> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oleria.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Execute

> Validates and executes the SQL query. If the query completes within the server-side sync threshold, the response is `200` with inline rows. If not, the response is `202` with a job_id for polling. Clients must always handle both `200` and `202`.
Both responses carry a `job_id`; pass it to `GET /v1/query/jobs/{job_id}` to obtain a download URL for the result file — the same path for synchronous and asynchronous results.
Setting `Prefer: respond-async` (RFC 7240) skips the sync threshold and returns `202` immediately.
**Idempotency:** The optional `X-Oleria-Request-Id` header is used as the execution idempotency key — see the parameter description for semantics and constraints.




## OpenAPI

````yaml /developer-docs/api-reference/trustfusion-openapi-schema-1.0.0.yaml post /v1/query/execute
openapi: 3.0.3
info:
  title: TrustFusion Facets API
  description: >
    API for all facets exposed by TrustFusion, including:


    - **Query**: Validate queries against validation rules, execute governed
    semantic queries

    - **Schema**: Discover semantic models, datasets, fields, relationships, and
    metrics

    - **Threats**: Discover threats and fetch a threat's investigation template
    or advisory by ID


    All endpoints require a valid Cognito JWT token.
  version: 1.0.0
servers:
  - url: https://devx.{environment}.oleria.io
    description: Oleria DevX Server
    variables:
      environment:
        default: prod
        description: Environment name (prod, staging, dev)
        enum:
          - prod
          - staging
          - dev
security:
  - clientCredentials: []
paths:
  /v1/query/execute:
    post:
      tags:
        - Query
      summary: Execute
      description: >
        Validates and executes the SQL query. If the query completes within the
        server-side sync threshold, the response is `200` with inline rows. If
        not, the response is `202` with a job_id for polling. Clients must
        always handle both `200` and `202`.

        Both responses carry a `job_id`; pass it to `GET
        /v1/query/jobs/{job_id}` to obtain a download URL for the result file —
        the same path for synchronous and asynchronous results.

        Setting `Prefer: respond-async` (RFC 7240) skips the sync threshold and
        returns `202` immediately.

        **Idempotency:** The optional `X-Oleria-Request-Id` header is used as
        the execution idempotency key — see the parameter description for
        semantics and constraints.
      operationId: ExecuteQuery
      parameters:
        - name: Prefer
          in: header
          required: false
          schema:
            type: string
            enum:
              - respond-async
          description: >
            Set to `respond-async` to request asynchronous execution (RFC 7240,
            Section 4.1). The response will return immediately with a job_id and
            status: pending.
        - name: X-Oleria-Request-Id
          in: header
          required: false
          schema:
            type: string
            format: uuid
          description: >
            Correlation ID and execution idempotency key. Must be a canonical
            36-char hyphenated UUID, case-insensitive (e.g.,
            `3bce7950-12a5-4b70-aeb9-270f1a9dec6e`). Sending the same UUID on a
            retry returns the original execution rather than starting a
            duplicate. When omitted, the server generates a UUID for the request
            — safe, but the caller has no way to retry idempotently. A header
            value that is not a valid UUID is rejected with `400`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/QueryRequest'
            examples:
              simple_query:
                summary: Simple query with named parameter
                value:
                  query: >-
                    SELECT account_id, mfa_status FROM oleria_account WHERE
                    mfa_status = :status
                  model: oleria_identity
                  dialect: trino
                  parameters:
                    status: disabled
      responses:
        '200':
          description: >
            Query executed successfully within the sync threshold. Contains
            inline rows and execution statistics.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResult'
              example:
                job_id: athn_a1b2c3d4-e5f6-7890-abcd-ef1234567890
                rows:
                  - account_id: acc-001
                    mfa_status: disabled
                  - account_id: acc-002
                    mfa_status: disabled
                statistics:
                  row_count: 2
                  execution_time_ms: 125
                  data_scanned_bytes: 52428800
        '202':
          description: >
            Query accepted for asynchronous execution. Returned when `Prefer:
            respond-async` is set, or when the query does not complete within
            the server-side sync threshold. Poll the returned job_id for status
            and results.
          headers:
            Preference-Applied:
              description: >
                Present when the server honored the `Prefer: respond-async`
                header (RFC 7240, Section 3). Absent when `202` was returned due
                to sync threshold expiry.
              schema:
                type: string
                enum:
                  - respond-async
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryJobResponse'
              example:
                job_id: athn_a1b2c3d4-e5f6-7890-abcd-ef1234567890
                status: pending
                retry_after: 5
        '400':
          description: SQL parsing failed or request is malformed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Missing or invalid authentication token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Valid token but insufficient permissions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                code: FORBIDDEN
                message: Token lacks required scope for query execution
        '422':
          description: >
            Query denied by validation rules. The query is syntactically valid
            but violates one or more governance policies. The query was not
            submitted to the execution engine.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                code: POLICY_VIOLATION
                message: Query denied by validation rules
                reasons:
                  - code: MUTATION_NOT_ALLOWED
                    message: >-
                      Only SELECT queries are permitted. Mutation statements are
                      not allowed.
        '429':
          description: >
            Rate limit exceeded. Retry after the duration specified in the
            Retry-After header.
          headers:
            Retry-After:
              description: Seconds to wait before retrying.
              schema:
                type: integer
                minimum: 0
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                code: TOO_MANY_REQUESTS
                message: >-
                  Query engine rate limit exceeded. Retry after the specified
                  interval.
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                code: INTERNAL_ERROR
                message: An unexpected error occurred
      security:
        - clientCredentials:
            - ClientCredentialsResourceServer/client_credentials_base_scope
components:
  schemas:
    QueryRequest:
      type: object
      required:
        - query
      properties:
        query:
          type: string
          minLength: 1
          maxLength: 100000
          description: >-
            The query string to validate and/or execute. Queries above the
            maximum length are rejected before parsing; real-world queries sit
            well below the bound.
          example: >-
            SELECT account_id, mfa_status FROM oleria_account WHERE mfa_status =
            :status
        model:
          type: string
          default: oleria_identity
          description: >
            Name of the semantic model to use for query resolution. Defaults to
            oleria_identity.
          example: oleria_identity
        dialect:
          type: string
          default: trino
          description: >
            The SQL dialect used for parsing. Currently only `trino` is
            supported. Additional dialects may be added in future versions.
          enum:
            - trino
          example: trino
        format:
          type: string
          default: json
          enum:
            - json
            - csv
          description: >
            Result format of the downloadable file, fixed at submission. `json`
            (default) delivers large results as JSON Lines (NDJSON); best for
            programmatic and AI consumers. `csv` produces a single
            comma-separated file with a header row and renders every value as
            text; best for spreadsheet export and tabular UIs. The inline `rows`
            preview is JSON either way (scalar values keep their type). Ignored
            by `/v1/query/validate`, which does not execute.
          example: csv
        parameters:
          type: object
          additionalProperties:
            oneOf:
              - type: string
              - type: number
                format: double
              - type: boolean
          description: >
            Named parameter values for query placeholders. Use `:name` syntax in
            the SQL query (e.g., `:status`, `:created_after`). Parameter names
            must match exactly (case-sensitive). Type coercion is automatic:
            strings are quoted, numbers and booleans are used as-is.
          example:
            status: disabled
            created_after: '2026-01-01'
            limit: 100
            include_inactive: true
    QueryResult:
      type: object
      required:
        - job_id
        - rows
      description: >
        Synchronous query result: the complete row set inline plus a job
        identifier for downloading the same result as a file. Column types can
        be obtained from the semantic model.
      properties:
        job_id:
          type: string
          description: >
            Identifier for this execution. `rows` already holds the complete
            result (bounded by the row-limit policy); pass this id to `GET
            /v1/query/jobs/{job_id}` to download the same result as a file
            without re-running the query.
          example: athn_a1b2c3d4-e5f6-7890-abcd-ef1234567890
        rows:
          type: array
          description: >
            Query results as an array of records. Each record is a map of column
            name to value.
          items:
            type: object
            additionalProperties: true
        statistics:
          $ref: '#/components/schemas/QueryStatistics'
    QueryJobResponse:
      type: object
      required:
        - job_id
        - status
      description: >
        Status and results for a query job. A `completed` job carries
        `statistics` and, when the engine exposes a downloadable artifact,
        `downloads`. When status is `failed`, the error field describes the
        failure.
      properties:
        job_id:
          type: string
          description: >
            Unique identifier for the query job. Use this value to poll for
            status via the jobs endpoint.
        status:
          type: string
          enum:
            - pending
            - running
            - completed
            - failed
          description: >
            Current job state. `pending` = queued, `running` = executing,
            `completed` = results available, `failed` = execution error.
        retry_after:
          type: integer
          description: >
            Recommended polling interval in seconds. Present when status is
            `pending` or `running`. Clients should wait at least this long
            before polling again.
          example: 5
        downloads:
          type: array
          description: >
            Download references for the query result, present once `status` is
            `completed` and the engine exposes a downloadable artifact (omitted
            otherwise). A csv result is a single reference; a json result may be
            several references that together hold the complete result set.
          items:
            $ref: '#/components/schemas/Download'
        download:
          description: >
            Convenience reference to the single result file. Present only when
            the result is exactly one file — always so for `csv` — and identical
            to the sole `downloads` entry when present. A result delivered as
            multiple files populates only `downloads`, so a client that must
            handle any result should read `downloads`.
          allOf:
            - $ref: '#/components/schemas/Download'
        rows:
          type: array
          description: >
            An initial page of results, inline, so a client can render a preview
            without fetching the file. Present when `status` is `completed`. The
            complete result set is delivered via `downloads` when present.
          items:
            type: object
            additionalProperties: true
        statistics:
          description: >
            Execution statistics. Reported when status is `completed` and the
            engine returns statistics for the execution; absent when none are
            available.
          allOf:
            - $ref: '#/components/schemas/QueryStatistics'
        error:
          description: Error details when status is `failed`.
          allOf:
            - $ref: '#/components/schemas/ErrorResponse'
    ErrorResponse:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: string
          description: Machine-readable error code for programmatic handling.
          example: QUERY_PARSE_ERROR
        message:
          type: string
          description: Human-readable error description.
          example: Failed to parse SQL query
        details:
          type: object
          additionalProperties: true
          description: Additional context for debugging (optional, free-form).
          example:
            line: 3
            column: 15
            hint: Unexpected token near 'SELCT'
        reasons:
          type: array
          description: >
            Policy violation details. Present when `code` is `POLICY_VIOLATION`.
            Each entry identifies a governance policy that the query violated.
          items:
            $ref: '#/components/schemas/Reason'
    QueryStatistics:
      type: object
      description: >
        Execution statistics for the query. Reported together when the engine
        returns statistics for an execution; absent when no statistics are
        available.
      required:
        - execution_time_ms
        - data_scanned_bytes
      properties:
        row_count:
          type: integer
          format: int64
          description: >
            Total number of rows in the result set. Present only when the inline
            `rows` hold the complete result; omitted when `rows` is a truncated
            preview, where the full count is available only from the downloaded
            result file.
          example: 1500
        execution_time_ms:
          type: integer
          format: int64
          description: Query execution time in milliseconds.
          example: 2340
        data_scanned_bytes:
          type: integer
          format: int64
          description: >
            Total bytes scanned by the query engine. Useful for cost visibility
            and budget attribution.
          example: 104857600
    Download:
      type: object
      required:
        - url
        - format
      description: >
        A download reference for a query result file. A csv result is a single
        file; a json result may be delivered as more than one JSON Lines file,
        which together hold the complete result set.
      properties:
        url:
          type: string
          format: uri
          description: >
            Short-lived pre-signed URL to fetch the result file directly, valid
            for a few minutes. After it expires, re-poll the job to obtain a
            fresh link.
          example: >-
            https://downloads.prod.oleria.io/acme/qr/athena/results/exec.csv?Policy=eyJTdGF0ZW1lbnQ&Signature=Gr8tSignatureExample&Key-Pair-Id=K2EXAMPLE
        format:
          type: string
          enum:
            - json
            - csv
          description: >
            File format. `csv` is a single comma-separated file with a header
            row. `json` is JSON Lines (NDJSON) — one JSON object per line.
          example: csv
    Reason:
      type: object
      required:
        - code
        - message
      description: A single policy violation identified during query validation.
      properties:
        code:
          type: string
          description: >
            Stable, machine-readable identifier for the denial reason.
            SCREAMING_SNAKE_CASE; declared on the violated policy.
          example: MUTATION_NOT_ALLOWED
        message:
          type: string
          description: Human-readable explanation of the denial.
          example: >-
            Only SELECT queries are permitted. Mutation statements are not
            allowed.
  securitySchemes:
    clientCredentials:
      type: oauth2
      description: >
        OAuth 2.0 Client Credentials flow. The tokenUrl shown is for the
        production environment. For other environments, replace `prod` with the
        target environment name (e.g., `auth.staging.oleria.io` for staging).
      flows:
        clientCredentials:
          tokenUrl: https://auth.prod.oleria.io/oauth/token
          scopes:
            ClientCredentialsResourceServer/client_credentials_base_scope: >-
              Default scope used for all client credentials (RBAC is controlled
              via permissions in the bearer token)

````