Introducing a new way to review your PRs.

Read the announcement

getnao / nao

👾 nao is the #1 open source agentic BI. (1) Create context with nao-core cli, (2) deploy nao chat interface for everyone

View on GitHub

23 documents · Updated Nov 23, 2026

docs / sql-and-warehouse-execution

SQL execution and warehouse connectivity

Nao connects projects to external warehouses, checks that access is safe, and turns SQL results into reusable data objects. It also provides a local DuckDB path for files and earlier results, plus isolated code execution for analysis that needs a full runtime. Read Data access and semantic queries for the wider query model and Semantic layer workflows for metric-query behavior.

Warehouse credentials

Warehouse credentials support both an initial connection and later query execution. The system keeps secret values out of normal project and chat views, while giving setup and query services the values they need at run time.

Credential entry and storage

The user first selects a supported warehouse provider and enters provider-specific connection fields. The form supports provider-specific defaults and authentication choices such as Snowflake password, key pair, or programmatic access token. It maps the form values to the shared warehouse contract before the backend validates them. apps/…/warehouse_provisioning.py accepts only approved provider fields, requires the needed secret fields, pins server-controlled authentication modes, and returns configuration that holds secret values in environment references rather than plain text.

The backend then wraps the values in a versioned record and stores the record in encrypted form. A credential summary exposes only the provider, update time, and field names, so settings can describe the connection without revealing secrets.

Credential updates must keep the existing field set and value types. This lets a user replace a password or token without changing the shape of the stored connection.

Warehouse access can also use the signed-in user's identity. For a project with the SSO feature, the system first tries an Azure access token and then an OIDC access token for that user. It forwards the available token to warehouses that support user-based queries. Open-source builds do not provide this token.

References: apps/…/warehouse-credentials-form.tsx• L31-48 apps/…/warehouse-credentials.ts• L100-243 apps/…/warehouse_provisioning.py• L148-201 apps/…/warehouse_provisioning.py• L291-359 apps/…/warehouse-credentials.ts• L8-29 apps/…/warehouse-credentials.ts• L31-74 apps/…/warehouse-access-token.service.ts• L7-16 apps/…/tools.ts• L60-63

Connection checks

Connection checks are a separate, fast test before full project setup. The backend normalizes provider credentials, rejects missing or extra fields, connects to the warehouse, and checks that schemas can be read. It records one of three outcomes: a working connection, missing credentials, or a connection error.

A failed check is useful to onboarding but must not block the recording of that check if the tracking store is unavailable. The check returns a user-facing message that points to likely fields when the provider rejects the request. A timeout is treated as a connection problem rather than as proof that the credentials are wrong.

References: apps/…/warehouse-provisioning.ts• L178-240 apps/…/warehouse-provisioning.ts• L242-257 apps/…/warehouse_provisioning.py• L204-273 apps/…/test_warehouse_provisioning.py• L469-574 apps/…/warehouse.ts• L29-31

Warehouse provisioning

Provisioning turns a working connection into a usable project. It is an asynchronous job because it must prepare the connector, inspect the warehouse, register project data, and complete project setup without holding the user request open.

Setup lifecycle

The setup job moves through clear checkpoints. It prepares the provider configuration, runs project initialization and checks, syncs warehouse metadata, registers the project, and then waits for business context before finalization and publishing.

flowchart LR
    A[Credentials] --> B[Prepare connection]
    B --> C[Initialize project]
    C --> D[Debug connection]
    D --> E[Sync warehouse metadata]
    E --> F[Register project]
    F --> G[Await business context]
    G --> H[Finalize project]
    H --> I[Publish project]
    I --> J[Ready]
    C -. failure or cancel .-> K[Rollback]
    D -. failure or cancel .-> K
    E -. failure or cancel .-> K
    H -. failure or cancel .-> K
    I -. failure or cancel .-> K

The agent can wait for a meaningful checkpoint instead of guessing from a running job. The important outcomes are not started, running, connection verified, ready, failed, and cancelled. Setup logs are shown for diagnosis after secret values are redacted. A successful metadata sync can report a verified connection while the job waits for business context. Publishing failures tell the user that the warehouse connection works and roll back the project that was created for the setup.

References: apps/…/warehouse-provisioning.ts• L349-465 apps/…/warehouse-provisioning.ts• L695-863 apps/…/warehouse-setup.ts• L6-43 apps/…/wait-for-warehouse-setup.ts• L5-47

Retry and rollback

A failed or cancelled setup can be retried while its encrypted connection details remain available. The worker uses a lease and a periodic reconciliation pass so an interrupted process can recover or clean up its temporary project and files. Cancellation stops a running command and rolls back the resources created by that setup.

Rollback removes registered project state and related published resources. When setup reaches ready, the job clears its temporary credential copy. Failed jobs keep credentials only for the limited retry window. A retry carries forward saved business context when it is available.

References: apps/…/warehouse-provisioning.ts• L378-443 apps/…/warehouse-provisioning.ts• L1064-1177 apps/…/warehouse-provisioning.ts• L1179-1217 apps/…/warehouse-provisioning.test.ts• L1035-1073 apps/…/warehouse-provisioning.test.ts• L1190-1273

SQL execution paths

SQL requests share one result contract but can use different data sources. The route depends on the request mode, the selected database, and the project access policy.

Request routing

The primary entry point is apps/…/execute-sql.ts. Admin requests can query the application database. A request for duckdb_local runs against local files and cached results. Other database IDs go to the warehouse, unless the project semantic mode forbids direct warehouse SQL.

Semantic queries follow the same warehouse route after the semantic layer compiles metrics and dimensions into SQL. This keeps connection checks, table access, row rules, and result handling in one path rather than creating a second warehouse executor.

flowchart TD
    A[SQL or semantic request] --> B{Request source}
    B -->|Admin SQL| C[Application database]
    B -->|duckdb_local| D[Local DuckDB]
    B -->|Semantic query| E[Compile to SQL]
    E --> F[Warehouse SQL path]
    B -->|Direct warehouse SQL| G{Project mode permits it?}
    G -->|No| H[Reject request]
    G -->|Yes| F
    F --> I[Warehouse result]
    C --> J[Query result]
    D --> J
    I --> J

By default, SQL must be read-only. An administrator can enable write SQL for the permitted route, but server-passthrough functions remain blocked because they can open a separate database connection outside the intended access boundary.

References: apps/…/execute-sql.ts• L32-112 apps/…/execute-sql.ts• L141-165 apps/…/execute-sql.ts• L219-227 apps/…/execute-semantic-query.ts• L24-36 apps/…/sql-filter.ts• L6-73

Warehouse access controls

apps/…/warehouse-sql.service.ts is the boundary between the backend and the warehouse service. It sends the project folder, selected database, environment values, optional signed-in-user token, and the query's access context with each SQL request.

The warehouse service applies table access, excluded-column rules, and row security before or during execution. SQL validation also supplies the warehouse dialect for callers that need it, while row-predicate validation checks and normalizes policy expressions before they are saved. These controls apply to both direct SQL and SQL compiled from semantic queries.

References: apps/…/warehouse-sql.service.ts• L6-20 apps/…/warehouse-sql.service.ts• L38-72 apps/…/warehouse-sql.service.ts• L74-105 apps/…/warehouse-sql.service.ts• L108-153 apps/…/execute-sql.ts• L82-100 apps/…/user-group.routes.ts• L700-715

Local DuckDB work

Local DuckDB handles data that does not need a warehouse connection. It lets the agent query project files, saved files, and earlier query results together while keeping the source data on the local machine.

File and result queries

apps/…/local-query.service.ts rewrites saved-file paths to their real storage paths and exposes earlier query results as tables named by query ID. It also limits project files to paths allowed by the current project context. This supports joins between a warehouse result and a CSV, JSON, Parquet, or Excel file without sending either side through the model.

The local query is read-only. If the caller asks for save_to, DuckDB writes CSV or Parquet to a private staging directory. The system checks the file size and then moves the file into the user's /home storage space.

References: apps/…/execute-sql.ts• L6-25 apps/…/execute-sql.ts• L27-41 apps/…/local-query.service.ts• L32-63 apps/…/local-query.service.ts• L213-265

Local query sandboxing

The local path treats SQL as untrusted input. Before DuckDB runs it, the system limits file access to approved paths and directories, disables external access, and locks the configuration. A query over earlier results has an additional table allowlist, so it cannot name an unrelated table or reach the network.

The result conversion keeps safe integer and decimal values numeric when they can pass through JavaScript without loss. Values that could lose precision remain strings.

References: apps/…/duckdb.service.ts• L35-86 apps/…/duckdb.service.ts• L118-136 apps/…/duckdb.service.ts• L179-209 apps/…/duckdb.service.ts• L212-263 apps/…/duckdb.service.ts• L372-375

Query results

Every successful SQL or semantic query produces a common result with columns, rows, a row count, and a query ID. That ID is the link between execution, chat history, charts, stories, paging, local follow-up, and sandbox analysis.

Query identity and reuse

The result is first available in the current agent run and can later be recovered from the chat's stored tool output. This lets a later turn use the same rows without rerunning the warehouse query. The cache also lets local DuckDB and sandbox tools consume results by ID.

Passing an existing query_id reruns a query in place. The newest result becomes authoritative, while older message parts are treated as superseded. A semantic result keeps its metric request and cannot be edited as raw SQL; it must be run again through the semantic query path.

References: apps/…/query-result.service.ts• L5-22 apps/…/execute-sql.ts• L92-112 apps/…/execute-sql.ts• L167-217 apps/…/execute-sql-parts.ts• L5-16 apps/…/execute-sql-parts.ts• L19-87

Result paging

The agent uses page_query_result when the first tool response does not show all rows. Paging reads the cached result by query ID and returns an offset, a bounded page, the columns, and the total row count. It does not rerun SQL.

The web client has a related chat query that can request a larger page and sort the cached rows for display. Both paths require chat access checks before rows leave the backend.

References: apps/…/page-query-result.ts• L5-25 apps/…/page-query-result.ts• L8-45 apps/…/query-rows.service.ts• L7-40 apps/…/chat.routes.ts• L55-77

Sandboxed analysis

Sandboxed code is the path for Python, shell, package-based analysis, visual output, and file formats that SQL alone does not handle well. It is separate from local DuckDB and runs code in an isolated micro-VM with explicit data and file inputs.

Sandbox data exchange

The sandbox can receive project context, chat images, saved /home files, and query results. Query results are copied in as CSV files named by the caller. Files that code should keep must be written to the sandbox output directory and listed for copying back to permanent storage.

This exchange is one-way by default. The sandbox is temporary, so files not copied to /home disappear when the sandbox expires.

References: apps/…/execute-sandboxed-code.ts• L15-40 apps/…/execute-sandboxed-code.ts• L42-54 apps/…/execute-sandboxed-code.ts• L290-376 apps/…/execute-sandboxed-code.ts• L471-501

Sandbox isolation and secrets

Each sandbox belongs to one user and project. The runtime limits the VM size, supports a short idle lifetime, and serializes reuse of the same sandbox. Project files are filtered before they are copied in, and sandbox output is redacted for configured secret values.

Secrets travel into the sandbox as environment variables. Their values are removed from standard output and error before the agent can read them. A timeout or runtime failure evicts the sandbox rather than reusing its state.

References: apps/…/execute-sandboxed-code.ts• L44-128 apps/…/execute-sandboxed-code.ts• L147-175 apps/…/execute-sandboxed-code.ts• L391-410 apps/…/execute-sandboxed-code.ts• L502-529 apps/…/execute-sandboxed-code.ts• L102-110

Change checklist

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

  • Keep provider names, credential fields, validation labels, encrypted payloads, server-pinned authentication modes, and runtime environment loading aligned.
  • Keep identity-provider token availability aligned with SSO licensing, agent context creation, and warehouse request forwarding.
  • Keep setup status and outcome names aligned between the provisioning job, shared tools, onboarding waits, retry state, and client displays.
  • Keep rollback ownership aligned with project registration and publishing so a failed or cancelled setup cannot remove another project.
  • Keep secret redaction aligned with every credential environment name and with streamed command output before logs reach the agent or UI.
  • Keep the SQL and semantic result schemas aligned so one query ID remains usable by charts, stories, paging, local DuckDB, and sandboxes.
  • Keep warehouse access controls, row-predicate validation, and passthrough-function checks active for both direct SQL and compiled semantic SQL.
  • Keep local file allowlists, /home storage paths, save_to formats, and sandbox file exchange rules consistent.
  • Keep in-place query replacement aligned with superseded-result handling so old chart and story references do not show stale rows.

Important failure modes

TriggerConsequenceGuard
Provider credentials are missing, contain an unsupported field, or the validation service times outSetup cannot verify the warehouse and shows a targeted connection errorValidate the provider contract, report the affected fields, and treat timeout as a connection error
A provisioning worker stops during setupA partial project or managed repository may remain unless the job is recovered or rolled backUse job leases, reconciliation, ownership-aware rollback, and a retry budget
A project in exclusive semantic mode receives direct warehouse SQLThe request is rejected even though semantic queries can reach the warehouseUse execute_semantic_query for warehouse work and duckdb_local for reshaping
SQL writes or passthrough functions are sent to a read-only routeThe request is denied before it can open an unintended write or server connectionApply the read-only check and unconditional passthrough denylist
A user-based warehouse requires an identity token that is unavailableThe warehouse cannot authenticate the query as the signed-in userEnable the required SSO feature and pass the optional token through the warehouse context
A local query names a file or table outside its allowlistDuckDB cannot read the objectResolve project and storage paths before locking external access
A query ID is missing or supersededPaging, local joins, or sandbox mounts cannot find the intended resultUse the ID from the latest query output and preserve in-place update rules
Code writes outside the sandbox output directoryThe file is lost when the sandbox endsWrite to out/ and list the file in save_files

Key files

FileWhy to read it
apps/…/warehouse-provider-config.tsDefines the supported warehouse choices and the fields shown for each provider.
apps/…/warehouse-credentials.tsShows how form values become provider credential payloads and authentication choices.
apps/…/warehouse-credentials-form.tsxShows the user flow for entering, checking, and retaining warehouse credentials.
apps/…/warehouse_provisioning.pyDefines provider validation and secret-safe warehouse configuration preparation.
apps/…/warehouse-credentials.tsDefines encrypted project credential storage and safe summaries.
apps/…/warehouse-access-token.service.tsDefines optional identity-provider tokens for user-based warehouse access.
apps/…/warehouse-provisioning.tsDefines connection checks, setup states, retries, leases, rollback, finalization, and publishing.
apps/…/warehouse-setup.tsDefines setup status text and redaction of secrets from command logs.
apps/…/warehouse.tsDefines shared provider, setup status, and connection outcome contracts.
apps/…/execute-sql.tsShows the main routing and policy decisions for SQL execution.
apps/…/warehouse-sql.service.tsShows the warehouse access boundary and security context sent with SQL.
apps/…/context-access.tsShows how allowed warehouse tables are represented and checked.
apps/…/local-query.service.tsShows how files and earlier results become local DuckDB inputs and saved outputs.
apps/…/duckdb.service.tsShows local read-only execution and filesystem lockdown.
apps/…/execute-sql.tsDefines the SQL input, local database ID, save formats, and result contract.
apps/…/query-result.service.tsShows in-memory and chat-history lookup for reusable results.
apps/…/page-query-result.tsDefines agent paging without query reruns.
apps/…/query-rows.service.tsDefines web-facing row paging and sorting.
apps/…/execute-sandboxed-code.tsShows sandbox data exchange, secret handling, reuse, and saved files.
apps/…/execute-sandboxed-code.tsDefines sandbox inputs, output handling, images, and resource choices.