Query utilities
The query utility layer turns a saved Insights query into a safe, executable analytical request. It supports operation-based query building, native SQL handling, dependency checks, source-table lineage, and result access for the Insights APIs. It is the server-side companion to the query editor and execution workflow and supports search flows such as AI-assisted search and resource discovery within the wider data exploration system.
Query lifecycle
An Insights query stores an ordered set of operations. The backend reads that set, builds a common query expression, and uses the expression for previews, execution, counts, distinct values, alerts, and downloads.
flowchart LR
A[Saved query operations] --> B[Query builder]
B --> C[Backend query expression]
C --> D[Preview and result APIs]
C --> E[Execution service]
E --> F[Rows and metadata]
A --> G[Dependency and source references]
Operation translation
The query builder processes operations in order. A source can be a data table or another saved query. Later operations can shape that source through joins, unions, filters, selections, calculated columns, summaries, sorting, limits, pivots, native SQL, or code. The result stays as a backend query expression until an API asks for data.
The builder can stop at an active operation. This gives the editor a view of the schema at an intermediate step without changing the saved query. It can also add request-specific filters for a single call. A query records whether it came from the builder, SQL editor, or script editor so execution and failure reporting can describe the source surface.
References: insights/…/ibis_utils.py• L53-155 insights/…/ibis_utils.py• L157-235 insights/…/ibis_utils.py• L338-571 insights/…/insights_query_v3.py• L167-192
Execution-facing results
The query document exposes one build path to several API behaviors. Normal execution returns generated SQL, column types, rows, currency symbols, and elapsed time. It also tells callers when native SQL contains aggregation. Related requests reuse the same built query to return a row count, distinct values, available columns, alert matches, or a bounded CSV or Excel download.
The execution entry point serves builder queries, native SQL, script queries, and queries created from chart settings. It reports a failed run once and keeps the failure details inside the site while recording the query interface, source type, execution mode, and error kind for telemetry.
When a run stops at an active operation, the response can also include record links for the columns visible at that step. This keeps chart drill links aligned with the result after a reader changes the query pipeline.
Chart-created queries can run through this same path without their own saved query identity. Their execution records use the source query identity so data-store read tracking remains attached to the real query.
This shared path keeps previews and final results aligned. The execution helper applies pagination when requested and records the SQL and timing after the backend runs the expression.
References: insights/…/insights_query_v3.py• L148-179 insights/…/insights_query_v3.py• L216-230 insights/…/insights_query_v3.py• L234-303 insights/…/insights_query_v3.py• L322-347 insights/…/insights_query_v3.py• L492-504 insights/…/ibis_utils.py• L911-981
Query dependency graph
Saved queries can use other saved queries as sources. The utility layer records these links beside table links so the system can validate edits and discover the physical data needed by a query and its children.
Reference extraction
Reference extraction converts operation data into two kinds of edges: a query edge for a saved query used as a source and a table edge for a data source plus table pair. Native SQL receives the same treatment through SQL parsing. Common table expressions are excluded because they are temporary names inside the statement rather than physical source tables.
The parser keeps database and catalog qualifiers when it identifies SQL tables and removes duplicate references. If a SQL statement cannot be parsed, extraction returns no table references so the query can still be saved. This can leave lineage incomplete for SQL forms that the parser does not support.
When a query changes, the system rebuilds all of its outgoing reference rows. This replaces stale lineage with the current set of dependencies. A migration helper can perform the same rebuild for existing query records.
References: insights/…/query_utils.py• L8-37 insights/…/query_utils.py• L40-49 insights/…/query_utils.py• L56-72 insights/…/query_utils.py• L75-99 insights/…/query_utils.py• L102-118 insights/…/query_utils.py• L121-152 insights/…/backfill_query_references.py• L5-14 insights/…/insights_query_v3.py• L87-129
Dependency validation
Before a query is saved, the backend checks whether its new direct query links would lead back to itself. It reads direct dependencies from each query's saved operations rather than from reference rows, because those rows rebuild after the save and can lag behind the latest write. The check follows those dependencies and returns a cycle path when one exists. The save is rejected before the invalid graph is stored.
The builder repeats the protection while it expands nested queries. This request-local check protects execution even when a graph changes outside the normal save path or contains older data. New query links also require the author to have read access to the referenced query.
References: insights/…/query_utils.py• L154-209 insights/…/insights_query_v3.py• L91-120 insights/…/ibis_utils.py• L90-118
Source table discovery
Source discovery walks the query graph and collects distinct table references from the current query and all reachable query dependencies. The result supports data-store refresh work by telling the system which source tables must be available for the whole query tree.
An administrator can use this source set to refresh the tables needed by the query. A query that has no discovered table cannot start that refresh operation.
References: insights/…/insights_query_v3.py• L148-154 insights/…/insights_query_v3.py• L551-571 insights/…/query_utils.py• L102-118 insights/…/query_utils.py• L154-182
Native SQL boundary
Native SQL enters the same query pipeline as builder operations, but it must cross a boundary between a source database and the Insights data store. The utility layer identifies its sources, applies the needed table bindings, and checks which SQL forms the selected execution mode can support.
SQL parsing and source binding
The SQL parser extracts physical table names with optional database and catalog parts. The query builder uses the data source database type to select the SQL dialect. When permissions or data-store execution require it, each source table is replaced with a controlled table expression before the SQL runs.
For data-store execution, source SQL can be translated to the store dialect. Schema-qualified names are rejected in this mode because the store binding expects the table name to belong to the selected Insights data source.
References: insights/…/query_utils.py• L8-37 insights/…/query_utils.py• L75-99 insights/…/ibis_utils.py• L578-639 insights/…/ibis_utils.py• L641-747 insights/…/insights_data_source_v3.py• L506-518
Execution modes
The same built expression can run against a live data-source connection or the managed data store. The selected mode affects table resolution and native SQL checks, while the query API keeps the result shape consistent for callers.
Live execution is subject to a concurrency limit so a burst of requests does not consume every web worker. Data-store execution runs through the store backend and can use cached results when the request permits it. Query failures report which mode ran without exposing SQL or data values in telemetry.
References: insights/…/ibis_utils.py• L578-639 insights/…/ibis_utils.py• L911-991 insights/…/insights_query_v3.py• L216-230
Query result contracts
The utility layer gives Insights APIs stable result information even when a query uses different source types or operation paths. Column metadata maps backend data types to Insights types such as String, Integer, Decimal, Date, Datetime, Time, JSON, and Array.
Result access
Result callers receive rows as records plus the columns needed to render or inspect them. Pagination limits normal requests. Count and distinct-value calls create focused queries from the same built expression instead of asking the client to process the full result set. Authoring helpers can also return a numeric column range, visible selectable columns, or whether an alert expression matches a row.
Downloads use a separate permission check and a hard row limit. They build the selected query step, remove hidden columns, and return a fresh CSV or Excel result. The access check can use the document that owns the request, which lets an unsaved chart-derived query enforce read access on the chart rather than on a query document that does not exist.
References: insights/…/ibis_utils.py• L911-981 insights/…/ibis_utils.py• L994-1023 insights/…/insights_query_v3.py• L304-400 insights/…/insights_query_v3.py• L402-490 insights/…/insights_query_v3.py• L492-504 insights/…/insights_query_v3.py• L610-633
Cache and request controls
Execution caching keys results from the generated SQL and the backend identity. A forced request bypasses a matching cached result. The query APIs choose shorter cache periods for changing result sets and longer periods for distinct-value lookups.
Ad hoc filters apply only within the request that supplies them. The builder adds them to the operation stream while it builds the expression, then the request context is cleared. Row requests and count requests must use the same filter and freshness choices when a caller needs one consistent total and page.
References: insights/…/ibis_utils.py• L911-981 insights/…/ibis_utils.py• L1026-1045 insights/…/ibis_utils.py• L62-88 insights/…/insights_query_v3.py• L253-338 insights/…/insights_query_v3.py• L403-443 insights/…/insights_query_v3.py• L654-661
Change checklist
When these files or sections are changed, remember to consider these:
- Keep operation source shapes aligned with dependency extraction. A new source form that builds correctly but is not recorded can break cycle checks and source-table refresh.
- Keep native SQL parsing dialects aligned with data-source database types. A mismatch can change table discovery or cause valid source SQL to fail during data-store translation.
- Preserve the shared build path when adding an API result mode. Count, preview, distinct-value, alert, and download behavior must apply the same request filters and operation cutoff rules.
- Keep cache identity tied to both generated SQL and backend identity. Otherwise a result from one data source or execution mode can be reused for another.
- Update reference rows after changing query operation persistence or import behavior. Lineage and nested-query validation depend on those rows.
- Keep query interface flags aligned with the surface that starts execution. Failure telemetry and query diagnostics use those flags to distinguish builder, SQL, script, and chart-created runs.
- Keep row and count freshness controls aligned. A forced row request paired with a cached count can show fresh data with an old total.
- Preserve the execution reference for unsaved chart-created queries. Logs and data-store read tracking must point to the source query rather than an unresolvable temporary document.
- Keep record-link generation aligned with the operation cutoff and returned columns. A drill response for an edited pipeline must describe the result level that the user sees.
- Keep export access checks separate from query execution identity. Chart-derived exports must authorize the chart while still applying the query export policy.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A query points to itself through one or more nested query sources | Save or build fails with a circular-reference error instead of recursing forever | Save-time graph check and request-local build guard |
| Native SQL cannot be parsed for table references | The query can be saved without complete table lineage | SQL extraction returns no references on parse failure; supported SQL forms should be used for reliable lineage |
| Native SQL contains more than one statement in data-store mode | The query is rejected before data-store execution | Native SQL validation permits one statement only in this mode |
| Native SQL uses a schema-qualified table in data-store mode | The query cannot be bound to the managed store table | SQL source extraction rejects database- or catalog-qualified names |
| A requested column does not exist after an operation | Query building fails or the operation is skipped when the operation allows a missing column | Column resolution checks exact, sanitized, and safe unique suffix matches |
| A live-query burst exceeds the concurrency limit | The request is rejected instead of waiting and starving web workers | Live execution uses a zero-wait concurrency limit |
| A query exceeds the configured database time limit | The caller receives a query-timeout error and the SQL is logged | Execution maps the database timeout to the configured Insights limit |
| Rows are forced fresh but the related count remains cached | Pagination can show a fresh page with a stale total | Use the same filters and force choice for row and count requests |
| A chart or edited pipeline receives record links for the wrong operation level | Drill actions can point to fields that are not present in the displayed result | Generate links from the operations through the active step and the returned columns |
| An export uses the wrong owning document for authorization | A chart download can be denied or allowed against the wrong resource | Apply the shared export policy with the caller's document as the read-permission target |
Key files
| File | Why to read it |
|---|---|
| insights/…/query_utils.py | Defines SQL table extraction, operation dependency extraction, reference-row rebuilds, graph traversal, and cycle detection. |
| insights/…/insights_query_v3.py | Shows how query validation, reference refresh, building, execution-facing API methods, result contracts, source discovery, record links, exports, and chart execution identity are exposed from the query document. |
| insights/…/ibis_utils.py | Defines the shared builder and execution boundary for operations, native SQL, backend selection, pagination, caching, and result type mapping. |
| insights/…/insights_query_reference.json | Describes the stored table and query edge model used for dependency and lineage data. |
| insights/…/backfill_query_references.py | Shows how reference rows are populated for query records that existed before the reference model. |
| insights/…/test_querying.py | Demonstrates the supported high-level contracts for building, filtering, joining, summarizing, nesting queries, and blocking cycles. |