Introducing a new way to review your PRs.

Read the announcement

combodo / itop

A simple, web based CMDB & IT Service Management tool

View on GitHub

17 documents · Updated Nov 20, 2026

docs / query-and-oql

Querying and OQL

Querying turns a class-based OQL request into a model-aware search and then into database rows or CMDB objects. The path keeps class rules, relationships, visibility, and object mapping together so callers can retrieve CMDB data without writing table-level SQL.

This page extends CMDB and data model. For object changes and persistence, see CMDB object lifecycle. For the class families commonly queried, see ITIL and infrastructure data models.

Query lifecycle

The query lifecycle moves from OQL text to a validated search definition and then to a result access layer. OQL describes classes, selected aliases, conditions, joins, parameters, functions, and unions. The search definition holds that meaning in a form that other parts of the system can refine before execution.

This diagram shows how an OQL request becomes CMDB objects or scalar rows.

flowchart LR
    A[OQL text] --> B[Parser]
    B --> C[Parsed query]
    C --> D[Model checks]
    D --> E[DB search]
    E --> F[Class tree and query context]
    F --> G[Structured SQL]
    G --> H[SQL rendering]
    H --> I[Database result]
    I --> J[Object set and iterator]
    J --> K[CMDB objects or rows]

DBSearch::FromOQL() is the normal entry point in core/dbsearch.class.php. It parses the request, checks it against model reflection, creates a search, binds supplied parameters, and sets its default data state. The resulting search can be reused for SQL generation, composition with other searches, object loading, or conversion back to OQL.

References: core/dbsearch.class.php• L637-716 core/…/oqlinterpreter.class.inc.php• L69-117 core/…/oqlquery.class.inc.php• L359-374

OQL language model

OQL is the class-facing query language for CMDB reads. A query selects one or more class aliases, joins related classes, and limits the result with expressions such as comparisons, logical operators, lists, functions, parameters, and nested queries.

The parser builds a query tree. OqlObjectQuery represents one object query, while OqlUnionQuery represents a UNION. Expression nodes keep fields, values, variables, functions, joins, and source positions so later checks can identify the part of the request that is invalid.

OQL conceptRole in retrieval
Class and aliasIdentifies a CMDB class and the name used by fields and joins
Selected classesDefines the objects returned in each result row
JoinConnects classes through an external key or related key path
ConditionRestricts rows with fields, values, parameters, and expressions
Nested querySupplies a query result inside an expression such as IN
UNIONCombines compatible result columns from several object queries

References: core/…/oql-parser.y• L37-100 core/…/oql-parser.y• L102-183 core/…/oqlquery.class.inc.php• L359-425

Query validation

Validation checks the parsed meaning against the CMDB model before SQL is built. It confirms that classes and aliases are known, selected aliases exist, fields belong to the available classes, and join keys point to compatible class families. It also checks that union branches expose compatible columns and class roots.

The check uses ModelReflection, which allows the same OQL shape to be checked against the active model or another model view. Unknown classes are reported with only classes the caller may read, so error suggestions follow access rules.

References: core/…/oqlquery.class.inc.php• L435-559 core/…/oqlquery.class.inc.php• L606-655 core/…/oqlinterpreter.class.inc.php• L28-62

DB search definitions

DBSearch is the editable, model-level representation of a validated query. It carries selected classes, conditions, aliases, relationship filters, parameters, archive and obsolete-data modes, modifier properties, and the data access policy without requiring callers to know database tables.

DBObjectSearch represents one class-oriented search. DBUnionSearch groups compatible object searches and exposes their shared result shape. A search is a definition, not a database result, so callers can change or combine it before SQL generation.

References: core/dbsearch.class.php• L14-26 core/dbsearch.class.php• L247-359 core/dbobjectsearch.class.php• L24-70 core/dbunionsearch.class.php• L25-57

Search composition

Search composition lets higher-level features build a request from smaller model-aware filters. A search can add conditions, connect a filter in the pointing-to or referenced-by direction, filter a selected alias, intersect results, specialize a class within its family, and rename aliases when query trees are combined.

These operations update or return search definitions. They do not fetch data at the time of composition. Alias translation and parameter merging keep attached searches valid when their trees share a namespace.

References: core/dbsearch.class.php• L321-432 core/dbobjectsearch.class.php• L648-727 core/dbobjectsearch.class.php• L834-988 core/dbobjectsearch.class.php• L1093-1157

Access and record state

Search execution applies visibility rules unless the search explicitly allows all data. The search also carries archive mode and obsolete-data behavior. These settings affect the search before SQL is rendered and therefore control which records can reach the result layer.

Normal searches use the current user's select filters. A trusted internal flow can use all-data mode when it must evaluate access rules or inspect records outside normal visibility. Joined classes can also receive visibility filters unless configuration disables that behavior. A union applies the same data policy to its branches.

References: core/dbsearch.class.php• L61-123 core/dbsearch.class.php• L1515-1543 core/dbobjectsearch.class.php• L1714-1729 core/dbobjectsearch.class.php• L1941-1968

Query building and optimization

SQL generation translates a DBSearch into a class tree and then into a structured SQL query. The builder uses model metadata to map CMDB attributes to stored fields, add joins for relationships and inherited classes, and select only the data needed by the request.

The search first applies data filters. It then builds or reuses a SQL structure. The final renderer produces a select, count, group, update, or delete statement with prepared query arguments.

References: core/dbsearch.class.php• L924-985 core/dbsearch.class.php• L1049-1087 core/dbobjectsearch.class.php• L1652-1714

Class tree construction

The class tree bridges a model query and its physical tables. It starts with the searched class and develops nodes for explicit joins, external keys, referenced objects, polymorphic fields, and inherited attributes. Each node records the class and alias needed by the final query.

The tree is optimized before physical table resolution. Unused outbound joins can be folded or removed when they do not provide selected data or filtering. Inbound joins remain when they express a reference-based filter. Alias translation keeps conditions and selected classes aligned after this work.

References: core/dbobjectsearch.class.php• L834-917 core/dbobjectsearch.class.php• L927-988 core/oqlclasstreebuilder.class.inc.php• L45-83 core/oqlclasstreeoptimizer.class.inc.php• L27-69 core/oqlactualclasstreeresolver.class.inc.php• L36-153

SQL query structures

SQLObjectQuery is the structured form of one SQL query. It holds selected expressions, conditions, grouping, and nested joins before rendering. SQLUnionQuery holds the branches of a union and applies shared result operations at the union level.

The structure is built before values are rendered. This separation lets the system add required object fields, order fields, counts, group expressions, and data filters without making each caller assemble SQL.

References: core/sqlquery.class.inc.php• L37-72 core/sqlobjectquery.class.inc.php• L35-80 core/sqlobjectquery.class.inc.php• L128-160 core/sqlunionquery.class.inc.php• L35-51 core/sqlunionquery.class.inc.php• L102-136

Query caches

The system can cache both the search created from OQL and the SQL structure built from a search. Cache keys include the query shape and relevant context such as selected fields, modifiers, grouping, selected classes, count mode, archive mode, obsolete-data mode, and language.

Cached searches and SQL structures are copied before reuse. This prevents later parameter or composition changes from modifying the cached definition. Requests with large, changing ID lists are excluded from SQL-structure caching because their shape is not useful to reuse.

References: core/dbsearch.class.php• L659-715 core/dbobjectsearch.class.php• L1732-1854

Result sets and iterators

DBObjectSet is the main result abstraction for object retrieval. It adds ordering, parameters, selected attributes, extended data, limits, and cursor state to a DBSearch. DBObjectIterator provides the small cursor contract used to rewind, seek, count, and fetch results.

The set supports one selected object per row and rows with several selected aliases. Fetch() returns the object for the main alias. FetchAssoc() returns the full row as an alias-to-object map. Count() can run a separate count query when the total is not already known.

References: core/dbobjectset.class.php• L18-26 core/dbobjectset.class.php• L86-118 core/dbobjectset.class.php• L789-821 core/dbobjectiterator.php• L27-63

Lazy loading and cursor access

Result loading is lazy. Creating a set does not run the database query. Load() builds and executes SQL only when a fetch, seek, or count operation needs data.

The cursor can rewind, seek to a zero-based row, and fetch until the set returns null. A limit controls the rows loaded from the database, while the total count remains available through the count path. If the database cannot accept the full join shape, the set has a reduced-column fallback that still identifies concrete objects.

References: core/dbobjectset.class.php• L680-744 core/dbobjectset.class.php• L1042-1070 core/dbobjectiterator.php• L27-63

Column and row mapping

Column selection controls how much data the set asks the SQL builder to return. The set adds fields needed to create objects, including friendly names, state flags, and the concrete class marker when the selected class has descendants.

When a row is fetched, the set maps each selected alias to a CMDB object through model metadata. A left-joined object can be null. A row with several aliases can therefore contain a different object or null for each alias.

References: core/dbobjectset.class.php• L203-285 core/dbobjectset.class.php• L965-988 core/dbobjectset.class.php• L1012-1032

Array retrieval

When object behavior is not needed, a search can return mapped arrays instead of creating objects. This path supports bulk reads and export work while keeping attribute mapping and SQL generation model-aware.

References: core/dbsearch.class.php• L718-772 core/dbsearch.class.php• L775-819

Saved OQL queries

The Query model stores reusable query definitions as CMDB data. QueryOQL stores the OQL text and an optional field description, so features such as exports can load a saved query, bind named parameters, and build a request-specific result.

Saved OQL uses the same DBSearch::FromOQL() path as a live request. It does not create a separate query engine. The saved text passes through the normal parser, model check, search, SQL, and result layers.

References: application/query.class.inc.php• L27-46 application/query.class.inc.php• L214-262 application/query.class.inc.php• L264-287

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to OQL grammar or expression names must stay aligned with lexer tokens, parser node types, expression conversion, and validation errors.
  • Changes to selected aliases or union columns must stay aligned across OQL validation, search composition, SQL union columns, and FetchAssoc() row mapping.
  • Changes to model attribute storage or inheritance must be checked against class-tree resolution, relationship joins, polymorphic expressions, and object row construction.
  • Changes to visibility, archive, or obsolete-data rules must be checked in both search filtering and SQL-structure cache keys.
  • Changes to query parameters must preserve the contract between OQL variables, search parameter discovery, saved-query binding, and SQL argument preparation.
  • Changes to join-folding or alias translation must be checked against nested conditions, selected aliases, and both pointing-to and referenced-by joins.

Important failure modes

TriggerConsequenceGuard
OQL names an unknown class, field, alias, or incompatible joinParsing or model validation stops before SQL is builtValidate with DBSearch::FromOQL() and use the reported source position
A union branch selects a different number of columns or unrelated class rootsThe union cannot expose one result shapeKeep branch selections aligned and within one model family
A required OQL parameter is not suppliedSQL rendering raises a missing-argument errorRead the search parameter list and bind every named value before execution
A query requests data hidden by user rightsThe result is reduced or becomes an empty searchUse the normal search path for user data and reserve all-data mode for trusted internal flows
A joined class is filtered with a stale or incomplete alias mapConditions can target the wrong class or fail during SQL buildingPreserve alias translation when searches are joined, merged, or intersected
A result set is fetched after its database result is exhausted or after a null left joinThe caller receives null for that positionCheck the fetch result and use FetchAssoc() when several aliases matter
A query creates more joins than the database allowsInitial execution fails and the set must use its reduced-column fallbackSelect only needed fields and avoid unnecessary relationship paths

Key files

FileWhy to read it
core/dbsearch.class.phpMain OQL entry point, search contract, access filtering, SQL handoff, rendering, and cache context
core/…/oqlinterpreter.class.inc.phpParser entry point for OQL queries and expressions
core/oql/oql-parser.yGrammar for selects, joins, conditions, nested queries, and unions
core/…/oqlquery.class.inc.phpParsed query objects, model checks, and conversion to database searches
core/dbobjectsearch.class.phpSingle-class search tree, OQL-to-search conversion, relationship composition, join optimization, and SQL structure handoff
core/dbunionsearch.class.phpShared result shape and composition for union searches
core/querybuildercontext.class.inc.phpShared context for class aliases, selected fields, conditions, and table aliases
core/oqlclasstreebuilder.class.inc.phpDevelopment of model joins and required fields into a class tree
core/oqlclasstreeoptimizer.class.inc.phpRemoval or folding of joins that do not affect the result
core/oqlactualclasstreeresolver.class.inc.phpPlacement of fields and joins on concrete model tables and ancestors
core/sqlobjectquerybuilder.class.inc.phpConversion from the class tree to structured SQL queries
core/sqlobjectquery.class.inc.phpStructured SQL object query and select or mutation rendering
core/sqlunionquery.class.inc.phpSQL rendering for union result sets and union counts
core/dbobjectset.class.phpLazy database load, object mapping, count, limits, and cursor access
core/dbobjectiterator.phpIterator contract for count, rewind, seek, and fetch
application/query.class.inc.phpSaved OQL query records and their use in export flows