## AI Reference # StackQL AI Reference > Machine-readable reference content covering StackQL concepts, comparisons, how-tos, FAQs, architecture, and troubleshooting - structured for AI agents and answer engines. Source: https://stackql.io/ai This section is a parallel content surface for AI agents, answer engines, and LLM crawlers. Pages here are written to answer specific questions cleanly, with deterministic examples and explicit schema. Humans can read them too, but the human-facing site is at the top-level navigation. ## Sections - [Canonical definitions](/ai/canonical-definitions) - what StackQL and adjacent concepts are - [Comparisons](/ai/comparisons) - StackQL versus other tools in the IaC, cloud-query, and AI-tooling space - [How-tos](/ai/how-tos) - step-by-step task guides for authentication, querying, mutation, and AI integration - [Concepts](/ai/concepts) - deeper explanations of why StackQL works the way it does - [FAQs](/ai/faqs) - common questions, grouped by topic - [Architecture](/ai/architecture) - StackQL internals, server mode, MCP, control vs data plane - [Troubleshooting](/ai/troubleshooting) - common errors and resolutions - [Industry positioning](/ai/industry-positioning) - where StackQL fits in the agentic-infrastructure landscape - [Tutorials](/ai/tutorials) - longer end-to-end walkthroughs - [Providers](/ai/providers) - per-provider, per-resource reference (auto-generated) --- # Architecture > StackQL internals - server mode, MCP support, control-plane vs data-plane handling, provider architecture, query execution. Source: https://stackql.io/ai/architecture Pages here describe how StackQL is built and how its parts fit together. ## Pages - [StackQL Architecture Overview](/ai/architecture/stackql-architecture-overview) - entry points, parser, query engine, provider SDK, SQL backend - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, tools, safety modes, and audit logging --- # StackQL Architecture Overview > StackQL is a Go-based SQL engine with three entry points (CLI/shell, PostgreSQL wire protocol, MCP server), a Yacc-based SQL parser, a query engine that orchestrates live provider API calls, and an embedded SQLite (or external PostgreSQL) backend for relational post-processing. Source: https://stackql.io/ai/architecture/stackql-architecture-overview StackQL is a single Go binary implementing a SQL engine over cloud and SaaS provider APIs. Architecturally it is four layers: entry points that accept SQL, a parser and query engine that plan it, a provider SDK that executes live API calls described by declarative provider specs, and a SQL backend that performs relational operations on the materialized results. ## Components **Entry points.** Three ways in, all converging on the same parser: - **CLI / shell** (`stackql shell`, `stackql exec`) for interactive and batch use. - **PostgreSQL wire protocol server** (`stackql srv`, built on psql-wire) so any Postgres client - psql, DBeaver, BI tools, pandas - can connect. - **MCP server** (`stackql mcp`) exposing discovery, validation, and gated execution tools to AI agents (detailed in [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture)). **SQL parser.** A Yacc-based grammar (`stackql-parser`) producing an AST. The dialect covers the standard verbs plus StackQL meta-commands (`SHOW`, `DESCRIBE`, `REGISTRY`) and the `EXEC` verb for non-CRUD lifecycle operations. **Query engine.** Plans the AST: decides what is pushed down to the provider API (routing parameters, supported predicates) versus what is processed locally, coordinates API execution - including parallel fan-out when a query spans regions or multiple calls - and aggregates results. **Provider SDK (omnisdk).** The generic API client, which replaced any-sdk in StackQL v1.0. It loads provider specifications from the registry, handles per-provider authentication, plans each statement as a graph of provider exchanges, builds HTTP requests from query parameters, pushes supported predicates and limits into those requests, walks paginated responses regardless of pagination scheme (cursor, offset, token), and relationalizes JSON responses into rows as they arrive. **SQL backend.** Materialized API results land in an embedded SQLite database by default (an external PostgreSQL can be configured instead), where joins - including cross-provider joins - aggregates, sorting, subqueries, and expressions execute with full SQL semantics. ## The defining design decision: providers as data StackQL has no compiled, provider-specific plugins. A provider is a versioned document set - an extended OpenAPI specification in the open [StackQL provider registry](https://github.com/stackql/stackql-provider-registry) - mapping API operations to resources, SQL verbs, and parameters. `REGISTRY PULL aws` downloads the spec; the SDK interprets it at runtime. Consequences: provider coverage tracks the documented API surface rather than plugin development effort; data plane and lifecycle operations are mappable the same way control plane CRUD is; and the entire surface is introspectable at runtime (`SHOW PROVIDERS`, `SHOW METHODS IN aws.ec2.instances`, `DESCRIBE github.repos.repos`) - the property that makes StackQL self-describing for AI agents. ## Query execution flow For `SELECT instance_id, instance_type FROM aws.ec2.instances WHERE region = 'us-east-1';`: 1. The parser produces the AST; the engine resolves `aws.ec2.instances` against the provider spec and selects the `describe` access method, with `region` satisfying its required parameter. 2. The SDK authenticates (from environment variables), issues the EC2 API call(s), and walks pagination. 3. Responses are flattened to rows and materialized into the SQL backend. 4. The backend applies the projection and any residual relational work; results return to the caller in the requested format. A `region IN (...)` predicate at step 2 becomes parallel per-region calls; a join at step 4 operates across whatever providers contributed tables. ## Related concepts - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - the agent-facing entry point in depth - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - the mapping the provider specs encode - [Why SQL is a Strong Interface for Cloud APIs](/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis) - the rationale for the dialect - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the operating model this architecture serves - [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe) - an FDW-based architecture contrasted --- # StackQL MCP Architecture > StackQL's built-in MCP server exposes provider discovery, schema description, query validation, and gated query execution as Model Context Protocol tools, over stdio, HTTP, or reverse-proxy transports, governed by four safety modes and an always-on JSONL audit log. Source: https://stackql.io/ai/architecture/stackql-mcp-architecture StackQL's MCP server is built into the engine binary and publishes the StackQL capability surface - discovery, description, validation, execution - as Model Context Protocol tools. Its design centers on three things: a small generic tool set instead of per-operation tools, a graduated safety contract for mutations, and an audit trail that records everything an agent does. ## Transports and deployment modes | Mode | Command | Use | |---|---|---| | stdio | `stackql mcp --mcp.server.type=stdio` | Editor-embedded clients (Claude Desktop, Cursor, Continue) that launch the process directly | | HTTP (standalone) | `stackql mcp --mcp.server.type=http` | Long-running server for standalone agents | | Dual-server, in-memory | `stackql srv --mcp.server.type=http --pgsrv.port ` | MCP and PostgreSQL wire protocol from one process | | Reverse proxy | `stackql srv --mcp.server.type=reverse_proxy` | MCP requests dispatched to a backing StackQL Postgres server via DSN; supports workload separation and TLS | Configuration is a JSON (or YAML) object passed via `--mcp.config`, covering transport, address, TLS certificate paths, client authentication, mode, audit settings, and optional `enabled_tools` / `enabled_prompts` allowlists for publishing a narrowed surface (for example, a read-only inventory server exposing only `server_info` and `list_providers`). From `v0.12.742` the HTTP transport requires either a pre-shared bearer token (`server.auth_token_env_var`) or the explicit `server.allow_unauthenticated` opt-in; cross-origin browser requests are refused. ## The tool surface Fourteen tools, each returning a rendered text view for the LLM plus a typed structured payload: - **Discovery**: `list_providers`, `list_services`, `list_resources`, `list_methods`, `describe_method` - the hierarchy walk that reveals required `WHERE` parameters before any query is written. - **Registry**: `list_registry` (available providers and versions), `pull_provider` (install into the local cache). - **Validation**: `validate_select_query` - parse and plan a `SELECT` without executing. - **Execution**: `run_select_query` (reads), `run_mutation_query` (`INSERT`/`UPDATE`/`REPLACE`/`DELETE` - real side effects), `run_lifecycle_operation` (`EXEC`). - **Identity**: `server_info` - version, backend, registry, mode; called once at session start. - **Credentials**: `reload_credentials` - re-sources the `--env.file` dotenv file into the process environment mid-session and reports per-provider credential resolution status; names and statuses only, never secret values (available in releases after v0.10.542). One static prompt, `write_safe_select`, teaches the method-discovery workflow. ## The safety contract `server.mode` selects one of four contracts; all allow `SELECT` and metadata, differing on writes: | Mode | INSERT / UPDATE / REPLACE | DELETE | EXEC | |---|---|---|---| | `read_only` | refuse | refuse | refuse | | `safe` (default) | needs approval | needs approval | needs approval | | `delete_safe` | allow | needs approval | needs approval | | `full_access` | allow | allow | allow | "Needs approval" is implemented with MCP elicitation: the server sends the pending action - tool, query class, SQL - to the client, and a human accepts or declines. Clients that do not advertise elicitation get a refusal pointing the operator at `full_access`, which makes unattended mutation an explicit opt-in rather than a default. The mode is global per server; there are no per-tool overrides. A payload holding several statements is gated by its most privileged statement (from `v0.12.742`), and `validate_select_query` accepts exactly one statement. ## The audit subsystem Every tool call writes one JSONL record - timestamp, tool, mode, decision (`allow`, `refuse_immediate`, `needs_approval_accepted`, and so on), query class, SQL, arguments, duration, error - to a file sink with size/age/backup rotation. The log answers "what did the agent do", deliberately not "what did the agent see": `SELECT` result rows are excluded as potentially large and sensitive. The write happens after execution but before the response returns; under the default `strict` failure mode, an audit failure on a successful mutation returns an error to the client - an intentional choice that no `DELETE` completes unaudited. ## Related concepts - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - operational setup - [How to use StackQL with Claude](/ai/how-tos/use-stackql-with-claude) - Claude Desktop specifics - [StackQL vs Custom MCP Servers](/ai/comparisons/stackql-vs-custom-mcp-servers) - the design trade-off - [StackQL Architecture Overview](/ai/architecture/stackql-architecture-overview) - where the MCP server sits in the engine - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this implements --- # Canonical definitions > Authoritative definitions for StackQL and adjacent infrastructure concepts - each term as a citable answer. Source: https://stackql.io/ai/canonical-definitions Each page in this section defines one term. Pages are written as direct answers to "What is X?" questions, with consistent structure: a one-sentence definition, a longer explanation, an example where useful, and links to related concepts. ## Pages - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - the canonical definition of StackQL - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - cloud resources as live, queryable data - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - the design pattern mapping API operations to SQL verbs - [Control Plane vs Data Plane](/ai/canonical-definitions/control-plane-vs-data-plane) - the two API surfaces of cloud services - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - infrastructure AI agents can discover, query, and operate - [What is Infrastructure Drift?](/ai/canonical-definitions/what-is-infrastructure-drift) - divergence between recorded and actual state A `glossary.md` index page covering all terms in one place is planned but not yet written. --- # Control Plane vs Data Plane > The control plane is the API surface that manages the lifecycle and configuration of cloud resources; the data plane is the surface through which those resources do their actual work, such as serving objects or executing queries. Source: https://stackql.io/ai/canonical-definitions/control-plane-vs-data-plane The control plane is the API surface that manages the lifecycle and configuration of cloud resources; the data plane is the surface through which those resources do their actual work. Creating an S3 bucket, resizing a virtual machine, or attaching an IAM policy are control plane operations. Reading an object from that bucket, serving a request from that virtual machine, or executing a SQL statement in a warehouse are data plane operations. ## The distinction in practice | Aspect | Control plane | Data plane | |---|---|---| | Purpose | Manage resources (create, configure, delete) | Use resources (read, write, execute) | | Example (S3) | `CreateBucket`, `PutBucketPolicy` | `GetObject`, `PutObject` | | Example (Databricks) | Create a cluster or job | Run a query, execute a notebook | | Typical caller | Operators, IaC tools, governance systems | Applications, end users | | Call volume | Low | High | | Shape | Uniform CRUD lifecycle | Service-specific operations | The boundary matters because tooling has historically split along it. Infrastructure-as-code tools (Terraform, CloudFormation, Pulumi) operate almost exclusively on the control plane. Application SDKs and drivers operate on the data plane. The result is two disjoint toolchains, two credential models, and no single place to ask questions that span both. ## Why unification matters Many real operational questions cross the boundary. "Which warehouses exist, and what did they execute last week?" is a control plane question joined to a data plane question. "Which buckets are public, and which of those contain objects?" is the same. A tool that stops at the control plane can enumerate the resources but cannot inspect what they are doing. StackQL treats both planes uniformly: any operation documented in a provider's API specification can be projected into the same SQL model - resources as tables, reads as `SELECT`, writes as `INSERT`/`UPDATE`/`DELETE`, and other actions as `EXEC` methods. A single query session, with a single authentication context per provider, can traverse from configuration to activity. For AI agents this matters more: an agent given one interface to both planes can diagnose ("the job failed"), inspect configuration ("the cluster is undersized"), and remediate ("resize it") without switching toolchains. See [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure). ## Example A control plane query - enumerate virtual machines in an Azure subscription: ```sql SELECT name, location FROM azure.compute.virtual_machines WHERE subscriptionId = '00000000-1111-2222-3333-444444444444'; ``` A lifecycle action against one of those resources is an `EXEC` of a documented method on the same table (for example `restart` or `power_off`), discoverable via `SHOW METHODS IN azure.compute.virtual_machines`. ## Related concepts - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - one SQL surface for both planes - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the operating model - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - how operations on either plane map to SQL verbs - [StackQL Architecture Overview](/ai/architecture/stackql-architecture-overview) - how provider specs drive the mapping - [StackQL vs Terraform](/ai/comparisons/stackql-vs-terraform) - a control-plane-only tool compared --- # What is Agentic Infrastructure? > Agentic infrastructure is cloud infrastructure that AI agents can discover, query, and operate directly through structured, self-describing interfaces, with safety controls appropriate for autonomous callers. Source: https://stackql.io/ai/canonical-definitions/what-is-agentic-infrastructure Agentic infrastructure is cloud infrastructure that AI agents can discover, query, and operate directly through structured, self-describing interfaces, with safety controls designed for autonomous callers. It is the infrastructure-side counterpart of agentic software engineering: rather than a human translating an agent's recommendation into console clicks or Terraform edits, the agent holds a governed credential to the control plane and acts through it. ## What it requires Four properties separate agentic infrastructure from ordinary automation: 1. **Runtime discoverability.** The agent must be able to learn the API surface at runtime - what providers, services, resources, and operations exist, and what parameters they require - without pre-trained, provider-specific SDK knowledge. In StackQL, `SHOW PROVIDERS`, `SHOW METHODS IN aws.ec2.instances`, and `DESCRIBE aws.ec2.instances` make the entire surface self-describing, and the same metadata is exposed as MCP tools (`list_providers`, `list_methods`, `describe_method`). 2. **Live state.** Agents reason from current facts. Interfaces built on cached snapshots or state files feed the agent stale premises; conclusions drawn from them are wrong by the time they are acted on. See [Why State Files Break Down for AI Agents](/ai/concepts/why-state-files-break-down-for-ai-agents). 3. **A uniform action model.** An agent that needs different code paths for every provider accumulates errors at each seam. A single grammar - SQL `SELECT`/`INSERT`/`UPDATE`/`DELETE` across all providers - means one competence covers the whole estate. 4. **Graduated safety.** Autonomous callers need contracts, not trust. StackQL's MCP server enforces one of four modes (`read_only`, `safe`, `delete_safe`, `full_access`): in the default `safe` mode, reads proceed and every mutation requires human approval through the MCP elicitation flow. Every tool call is recorded in a JSONL audit log. ## Example An agent connected to StackQL's MCP server answering "what is running in our AWS account?" issues: ```sql SELECT instance_id, instance_type, launch_time FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` The agent did not need an AWS SDK, boto3 knowledge, or pagination handling - it needed SQL and the discoverable schema. If asked to remediate something it found, the resulting `DELETE` or `UPDATE` is held for human approval under the default server mode. ## Why it exists Infrastructure tooling assumed a human in the loop at every step: read the plan, review the diff, click apply. Agents change the economics - they can watch continuously, correlate across providers, and act in seconds - but only if the interface fits how they work: declarative queries, structured results, explicit contracts. Agentic infrastructure is the redesign of the control plane interface around that caller. ## Related concepts - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the data layer agentic infrastructure depends on - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - the server modes, tools, and audit log in detail - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - practical setup - [Why State Files Break Down for AI Agents](/ai/concepts/why-state-files-break-down-for-ai-agents) - why existing IaC interfaces do not transfer - [From IaC to Agentic Infrastructure](/ai/industry-positioning/from-iac-to-agentic-infrastructure) - how the category evolved --- # What is Infrastructure Drift? > Infrastructure drift is the divergence between the declared or recorded state of cloud resources and their actual state in the provider, caused by out-of-band changes, partial failures, or autonomous platform behavior. Source: https://stackql.io/ai/canonical-definitions/what-is-infrastructure-drift Infrastructure drift is the divergence between the declared or recorded state of cloud resources and their actual state in the provider. A Terraform state file says a security group has three rules; the live security group has five, because someone added two in the console during an incident. The two extra rules are drift. ## How drift happens Drift is structural, not accidental. Any system that keeps a copy of state - a state file, a CMDB, an inventory export - drifts from reality at the rate that reality changes outside it. Typical sources: - **Out-of-band changes**: console edits, ad-hoc CLI commands, emergency fixes. - **Concurrent tooling**: two pipelines or teams managing overlapping resources. - **Provider automation**: auto-scaling, managed upgrades, key and certificate rotation. - **Partial failures**: an apply that created four of six resources and recorded none. The IaC model treats drift as an anomaly to be corrected at the next plan/apply cycle. In environments with autonomous actors - auto-scalers, incident responders, AI agents - drift is better treated as a normal, continuous condition to be observed and reconciled. ## Detecting drift with live queries Because StackQL computes results from live provider APIs, a StackQL result set is the actual state. Drift detection reduces to comparing that result set against a baseline. For example, retrieving the live inventory of EC2 instances per region: ```sql SELECT region, COUNT(*) as num_instances FROM aws.ec2.instances WHERE region IN ('us-east-1','us-west-2','eu-west-1') GROUP BY region; ``` Comparing this against the counts implied by the desired-state definition reveals unmanaged or missing resources immediately, regardless of whether the IaC tool's own state file is current. The same pattern applies at attribute level: query the live configuration of a resource and diff it against the declared configuration. ## Drift vs reconciliation Detection answers "what diverged?"; reconciliation answers "what should be done about it?" - import the change into the desired state, revert it, or accept it as intentional. Reconciliation requires write access to the control plane, which is why read-and-write query tools can close the loop that read-only inventory tools can only report on. StackQL expresses the corrective actions as `UPDATE` or `DELETE` statements against the same tables used for detection. ## Related concepts - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the model that makes live-state comparison possible - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - read-and-write access to live state - [Why State Files Break Down for AI Agents](/ai/concepts/why-state-files-break-down-for-ai-agents) - drift as a structural property of state copies - [StackQL vs Terraform](/ai/comparisons/stackql-vs-terraform) - state-file and live-query models compared - [How to query AWS EC2 instances with StackQL](/ai/how-tos/query-aws-ec2-instances-with-stackql) - the inventory queries used in drift baselines --- # What is Queryable Infrastructure? > Queryable infrastructure is an operating model in which cloud resources are exposed as live, structured data that can be interrogated on demand with a query language, rather than reconstructed from state files or per-service consoles. Source: https://stackql.io/ai/canonical-definitions/what-is-queryable-infrastructure Queryable infrastructure is an operating model in which cloud resources are exposed as live, structured data that can be interrogated on demand with a query language. Instead of reconstructing the state of an environment from state files, exported snapshots, or per-service consoles, an operator (or an AI agent) asks a question - in SQL or a similar declarative language - and the answer is computed against the provider APIs at query time. ## How it works A queryable infrastructure system maps the provider's API surface onto a relational model: - A **provider** (AWS, Azure, Google Cloud, GitHub) becomes a schema namespace. - A **service** (EC2, Compute, Storage) becomes a sub-schema. - A **resource type** (instances, buckets, repositories) becomes a table. - Each **resource instance** becomes a row, with its configuration attributes as columns. A query planner translates SQL into the underlying API calls, handles pagination and authentication, and normalizes the responses into rows. In StackQL, the query ```sql SELECT instance_id, instance_type, public_ip_address FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` is executed as live calls to the EC2 API; nothing is read from a cache or a state file. Multi-region and multi-provider queries fan out as parallel API calls and aggregate the results into a single result set. ## Why it exists Three pressures created the category: 1. **Multi-cloud sprawl.** Organizations run resources across multiple clouds and dozens of SaaS platforms. Each has its own console, CLI, and SDK. A uniform query interface is the only practical way to answer cross-provider questions such as "list every compute instance we run, anywhere." 2. **Stale-copy problems.** Inventory databases, CMDBs, and IaC state files are copies, and copies drift from reality. Querying the control plane directly eliminates the gap between recorded state and actual state. 3. **AI agents.** Agents reason over structured, current data. A SQL surface over live APIs gives an agent one stable interface to discover, inspect, and act on infrastructure without provider-specific SDK code. This is the basis of [agentic infrastructure](/ai/canonical-definitions/what-is-agentic-infrastructure). ## Read and write Queryable infrastructure is read-oriented by definition, but the model extends naturally to writes: if a resource is a row, creating one is an `INSERT`, changing its configuration is an `UPDATE`, and decommissioning it is a `DELETE`. StackQL implements both sides; read-only tools such as Steampipe implement the query side only. The write side is covered in [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis). ## Related concepts - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - the reference implementation of queryable infrastructure with reads and writes - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - the design pattern underneath queryable infrastructure - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - what queryable infrastructure enables for AI agents - [What is Infrastructure Drift?](/ai/canonical-definitions/what-is-infrastructure-drift) - the failure mode queryable infrastructure detects - [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe) - two implementations of the model compared --- # What is SQL for APIs? > SQL for APIs is a design pattern that projects REST or RPC API operations onto relational semantics - list and get operations become SELECT, create becomes INSERT, modify becomes UPDATE, and remove becomes DELETE. Source: https://stackql.io/ai/canonical-definitions/what-is-sql-for-apis SQL for APIs is a design pattern that projects API operations onto relational semantics: list and get operations become `SELECT`, create operations become `INSERT`, modify operations become `UPDATE` or `REPLACE`, and remove operations become `DELETE`. The API's response objects become rows; their attributes become columns. The pattern gives any REST or RPC API the ergonomics of a database without requiring the API provider to change anything. ## How it works The mapping is mechanical, which is what makes it generalizable: | API concept | Relational concept | |---|---| | Provider (AWS, GitHub) | Schema namespace | | Service (EC2, repos) | Sub-schema | | Resource collection | Table | | List / get operation | `SELECT` method | | Create operation | `INSERT` method | | Patch / put operation | `UPDATE` / `REPLACE` method | | Delete operation | `DELETE` method | | Other lifecycle actions (start, stop, reboot) | `EXEC` method | | Required path or query parameters | Required `WHERE` clause predicates | | Request body fields | `data__` prefixed insert/update columns | In StackQL, this mapping is generated from extended OpenAPI specifications held in the open [StackQL provider registry](https://github.com/stackql/stackql-provider-registry). The required API parameters are discoverable at runtime: `SHOW METHODS IN aws.ec2.instances` returns each method's SQL verb and its required parameters, so a human or an AI agent can derive a correct query without reading provider documentation. ## Example A read is a `SELECT` whose `WHERE` clause carries the API's required parameters: ```sql SELECT name, language, stargazers_count FROM github.repos.repos WHERE org = 'stackql'; ``` A create is an `INSERT` whose columns carry the request body (prefixed `data__`) and routing parameters: ```sql INSERT INTO google.storage.buckets( project, data__name, data__location ) SELECT 'my-project', 'my-new-bucket', 'US'; ``` `SHOW INSERT INTO google.storage.buckets` generates this template mechanically, including all writable fields. ## Why it exists SQL is the most widely deployed query language in existence, with fifty years of tooling: drivers, ORMs, BI platforms, notebooks, and - increasingly important - LLM training data. Every mainstream AI model can already read and write competent SQL. Projecting APIs into SQL means all of that tooling and model capability applies to any API surface immediately. The alternative - one SDK per provider per language - multiplies integration work and gives agents nothing reusable. The argument is developed further in [Why SQL is a Strong Interface for Cloud APIs](/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis). ## Related concepts - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - the reference implementation of this pattern for cloud and SaaS APIs - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the operating model the pattern enables - [Why SQL is a Strong Interface for Cloud APIs](/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis) - the design rationale in depth - [StackQL Architecture Overview](/ai/architecture/stackql-architecture-overview) - how the mapping is implemented - [How to query GitHub repositories with StackQL](/ai/how-tos/query-github-repositories-with-stackql) - the pattern applied to a SaaS API --- # What is StackQL? > StackQL is an open-source query language and runtime that exposes cloud and SaaS provider APIs as relational tables, queryable with standard SQL. Source: https://stackql.io/ai/canonical-definitions/what-is-stackql StackQL is an open-source query language and runtime that exposes cloud and SaaS provider APIs as relational tables, queryable with standard SQL. It treats every cloud resource - virtual machines, storage buckets, IAM policies, GitHub repositories, Snowflake warehouses - as a row in a table, and every API operation as a SELECT, INSERT, UPDATE, or DELETE. ## How it works A typical infrastructure tool reads cloud state into a local file (Terraform's state file), generates a plan, and applies it. StackQL skips the state file entirely. When you run a query, StackQL issues live API calls to the relevant provider, normalizes the response shape, and returns the result as rows. Nothing is cached between invocations unless the user asks for it. The interface is SQL because SQL is a stable, well-understood query language with mature tooling - clients, drivers, BI integrations, AI agent toolkits - that all "just work" against StackQL. StackQL implements the PostgreSQL wire protocol in server mode, which means anything that can talk to Postgres (psql, DBeaver, Tableau, Power BI, pandas, LangChain SQL agents, an MCP server) can talk to StackQL. ## Example List all EC2 instances in a region with their type and public IP address: ```sql SELECT instance_id, instance_type, public_ip_address FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` That query runs against the live AWS EC2 API. There is no state file to refresh, no cached snapshot to invalidate, and no provider-specific SDK to learn. The same shape works for any provider - swap `aws.ec2.instances` for `github.repos.repos` or `azure.compute.virtual_machines` and the query model is identical. ## Why it exists StackQL was built on the premise that cloud infrastructure should be a queryable surface, not a static artifact. The state-file model that dominated infrastructure-as-code for the last decade was designed for human-driven, change-controlled workflows: write code, plan, review, apply. That model strains under two pressures: 1. **Multi-cloud reality.** Every major organization runs workloads across multiple providers. State files are per-provider, per-tool, per-team. Asking "what do we run in production?" across AWS, Azure, GitHub, and Snowflake is a manual aggregation exercise. 2. **AI agents.** Agents need live, structured access to infrastructure state to reason about it. A state file is the wrong primitive - it is stale by the second it is written, and its format is tool-specific. A SQL interface against live APIs is the right primitive: agents know SQL, the schema is stable, and the data is always current. StackQL exists to make cloud infrastructure as queryable as a database, across providers, for both human operators and AI agents. ## Related concepts - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the broader category StackQL belongs to - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - the design pattern StackQL implements - [Control Plane vs Data Plane](/ai/canonical-definitions/control-plane-vs-data-plane) - how StackQL unifies both - [StackQL vs Terraform](/ai/comparisons/stackql-vs-terraform) - comparison with the dominant IaC tool - [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe) - comparison with the closest peer - [Getting started with StackQL](/ai/tutorials/getting-started-with-stackql) - install to first query --- # Comparisons > How StackQL relates to other tools across IaC, cloud-query, data/API, and AI/agentic categories. Source: https://stackql.io/ai/comparisons Each page in this section compares StackQL with one other tool or one architectural approach. Comparisons lead with honest "when to use which" framing before making the affirmative case for StackQL. ## Pages - [StackQL vs Terraform](/ai/comparisons/stackql-vs-terraform) - live query/mutation engine vs state-file IaC - [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe) - read-and-write vs read-only cloud SQL - [StackQL vs CloudQuery](/ai/comparisons/stackql-vs-cloudquery) - live queries vs scheduled ELT snapshots - [StackQL vs Custom MCP Servers](/ai/comparisons/stackql-vs-custom-mcp-servers) - one generic agent interface vs hand-built tool sets --- # StackQL vs CloudQuery > CloudQuery is an ELT framework that syncs cloud asset data into a database on a schedule for later analysis; StackQL queries provider APIs live at execution time and can also mutate resources. The core trade-off is historical snapshots versus current state. Source: https://stackql.io/ai/comparisons/stackql-vs-cloudquery CloudQuery is an open-source ELT framework for cloud assets: source plugins extract resource data from providers and load it into a destination database on a schedule, where you query the snapshots with that database's SQL. StackQL inverts the architecture: SQL is executed directly against the provider APIs at query time, with no sync step and no stored copy - and the same engine can mutate resources, not just read them. ## When to use which Use **CloudQuery** when: - You need **history**: point-in-time snapshots retained across syncs for trend analysis, forensics, or compliance evidence. - You want asset data co-located with other warehouse data for joins in an existing BI/analytics stack (BigQuery, Snowflake, Postgres). - Query latency matters more than freshness - querying a local database is faster than fanning out API calls. Use **StackQL** when: - You need **current state**: security checks, drift detection, operational queries, and any decision an automation or AI agent will act on immediately. - You do not want to operate a sync pipeline and a destination database to answer questions. - You need write operations - creating, updating, or deleting resources - in the same tool and language as the queries. - Agents are the consumer: StackQL's MCP server exposes discovery, validation, and gated execution directly; a CloudQuery destination database knows nothing about the provider API surface. The two are complementary at scale: StackQL for live interrogation and action, CloudQuery (or StackQL results materialized on a schedule) for longitudinal storage. ## Architectural comparison | Dimension | CloudQuery | StackQL | |---|---|---| | Model | Extract-load, query the copy | Query the source live | | Freshness | As of last sync | As of query execution | | History | Native (retained snapshots) | Not retained (materialize manually) | | Infrastructure required | Sync scheduler + destination database | Single binary | | Writes to cloud | No | INSERT / UPDATE / DELETE / EXEC | | Provider definition | Go source plugins | Declarative extended-OpenAPI specs | | Query dialect | Destination database's SQL | StackQL SQL (Postgres-compatible wire in server mode) | | Agent interface | None (query the destination DB) | Built-in MCP server with safety modes | ## Example The freshness difference in one query - this StackQL statement reflects instances launched seconds ago, which a sync-based copy will not contain until the next sync completes: ```sql SELECT instance_id, instance_type, launch_time FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` For longitudinal needs, the equivalent StackQL pattern is scheduling this query (via cron, CI, or pystackql) and appending results to your own store - the same outcome as ELT, but the live query path remains available for time-sensitive questions. ## Related concepts - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - live query as an operating model - [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe) - the other live-query peer - [What is Infrastructure Drift?](/ai/canonical-definitions/what-is-infrastructure-drift) - why freshness matters - [How to query AWS EC2 instances with StackQL](/ai/how-tos/query-aws-ec2-instances-with-stackql) - the example expanded - [StackQL Architecture Overview](/ai/architecture/stackql-architecture-overview) - how live execution works --- # StackQL vs Custom MCP Servers > Building a custom MCP server gives an AI agent a hand-curated tool set for one domain; StackQL's built-in MCP server gives agents one generic, self-describing tool set covering every resource of every supported cloud and SaaS provider, with gated mutations and audit logging. Source: https://stackql.io/ai/comparisons/stackql-vs-custom-mcp-servers A custom MCP server wraps a specific API or workflow in hand-written tools for AI agents; StackQL's built-in MCP server exposes the entire surface of every supported cloud and SaaS provider through a small set of generic, self-describing tools plus SQL. The comparison is between curating tools per domain and giving the agent one queryable abstraction over all domains. ## When to use which Build a **custom MCP server** when: - The domain is narrow and the operations are few - a dozen well-named tools with tight schemas can outperform a general interface on reliability for that specific workflow. - You need heavy business logic between the agent and the API: approvals, enrichment, multi-step transactions that should appear to the agent as one atomic tool. - The target API is internal or proprietary and not described by a public specification. Use **StackQL's MCP server** when: - The domain is cloud and SaaS infrastructure - AWS, Azure, Google Cloud, GitHub, Databricks, Snowflake, Okta, and the rest of the provider registry - where the operation count makes per-operation tools impractical. - You want the agent to discover capability at runtime (`list_providers` -> `list_services` -> `list_resources` -> `list_methods` -> `describe_method`) instead of being limited to tools someone anticipated. - You need governed writes: the four-mode safety contract (`read_only`, `safe`, `delete_safe`, `full_access`) with elicitation-based human approval and an always-on audit log, rather than safety logic you write and maintain yourself. - You want one credential and policy surface for the whole estate instead of one bespoke server per provider. The approaches compose: teams commonly run StackQL MCP for general infrastructure access alongside small custom MCP servers for proprietary internal systems. ## The token economics The practical constraint on agent tooling is context. Tool definitions consume the agent's context window before any work happens, and tool-selection accuracy degrades as the tool count grows. Publishing AWS alone as per-operation tools would mean thousands of definitions. StackQL's design keeps the published tool set under fifteen (discovery, description, validation, execution, registry management) and moves the expressive power into SQL - a language every current model already writes fluently. The agent's per-task token cost is a short SQL string, not a tool schema negotiation. This argument is developed in [Why SQL is a Strong Interface for Cloud APIs](/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis). ## Example An agent session against StackQL's MCP server, after discovering required parameters with `list_methods`: ```sql SELECT name, visibility, default_branch FROM github.repos.repos WHERE org = 'stackql'; ``` The same tool (`run_select_query`) serves this query and any other read against any provider; mutation requests route through `run_mutation_query`, where the server mode decides whether they proceed, require approval, or are refused. ## Related concepts - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, tools, and audit in detail - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - setup walkthrough - [How to use StackQL with Claude](/ai/how-tos/use-stackql-with-claude) - Claude Desktop configuration - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the broader pattern - [Why SQL is a Strong Interface for Cloud APIs](/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis) - the design rationale --- # StackQL vs Steampipe > Steampipe and StackQL both expose cloud APIs as SQL-queryable tables; Steampipe is read-only and built on PostgreSQL foreign data wrappers, while StackQL adds write operations (INSERT, UPDATE, DELETE), lifecycle actions, and a built-in MCP server for AI agents. Source: https://stackql.io/ai/comparisons/stackql-vs-steampipe Steampipe and StackQL implement the same core idea - cloud and SaaS APIs exposed as SQL tables - with one decisive difference: Steampipe is read-only, while StackQL also writes. Steampipe embeds PostgreSQL and maps APIs through foreign data wrappers fed by Go plugins; StackQL implements its own SQL engine over declarative, OpenAPI-derived provider specs, and maps the full verb set: `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and `EXEC` for lifecycle actions. ## When to use which Use **Steampipe** when: - Your use case is purely read: inventory, compliance dashboards, security posture. - You want its mature ecosystem of compliance mods (CIS, SOC 2, and similar prebuilt benchmark packs). - You are already invested in PostgreSQL FDW-based tooling and the Turbot ecosystem around it. Use **StackQL** when: - You need reads and writes in one tool - query a misconfiguration, then fix it with an `UPDATE` in the same session. - You are building for AI agents: StackQL ships a built-in MCP server with discovery tools, query validation, gated mutation modes, and an audit log. - You want provider coverage driven by API specifications rather than plugin development, including data plane and lifecycle operations. - You want a deterministic, dependency-light single binary that also speaks the PostgreSQL wire protocol in server mode. Both are open source, both run locally or in pipelines, and for read-only inventory queries they are genuinely interchangeable in capability; the choice there comes down to schema preference and ecosystem. ## Architectural comparison | Dimension | Steampipe | StackQL | |---|---|---| | SQL verbs | SELECT only | SELECT, INSERT, UPDATE, REPLACE, DELETE, EXEC | | Engine | Embedded PostgreSQL + foreign data wrappers | Native SQL engine (embedded SQLite or PostgreSQL backend) | | Provider definition | Compiled Go plugins | Declarative extended-OpenAPI specs in an open registry | | Plane coverage | Control plane reads | Control and data plane, reads and writes | | AI agent interface | Generic Postgres connectivity | Built-in MCP server with safety modes and audit logging | | Server mode | Postgres wire (steampipe service) | Postgres wire (stackql srv) plus MCP (stackql mcp) | | Compliance content | Extensive mod library | Query-based; no packaged benchmark library | The provider-definition difference compounds over time: a Steampipe table exists when someone writes plugin code for it, while a StackQL table exists when the API operation is described in the provider spec. The write capability difference is categorical: closed-loop workflows - detect, decide, remediate - fit in one StackQL session, whereas Steampipe hands off remediation to another tool. ## Example Identical intent in both tools - but in StackQL, the follow-up remediation stays in the same language. Query EC2 instances: ```sql SELECT instance_id, instance_type, launch_time FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` A remediation in StackQL is then a `DELETE` or `EXEC` (for example, terminating or stopping an instance) against the same table, subject to the credential's permissions and - when running as an MCP server - the configured safety mode. ## Related concepts - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the category both tools implement - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - full definition - [StackQL vs CloudQuery](/ai/comparisons/stackql-vs-cloudquery) - the ELT-based alternative - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - the agent interface in detail - [Control Plane vs Data Plane](/ai/canonical-definitions/control-plane-vs-data-plane) - the coverage boundary explained --- # StackQL vs Terraform > Terraform is a declarative provisioning tool that converges infrastructure toward code-defined desired state via a state file; StackQL is a SQL engine that queries and mutates live cloud resources with no state file. They overlap on provisioning and are frequently used together. Source: https://stackql.io/ai/comparisons/stackql-vs-terraform Terraform is a declarative provisioning tool: you write HCL describing desired state, and Terraform plans and applies changes to converge reality toward it, tracking what it manages in a state file. StackQL is a SQL query and mutation engine for cloud APIs: it reads and writes live provider state directly and keeps no state file. The two tools answer different primary questions - Terraform answers "how do I declare and converge this environment?", StackQL answers "what exists right now, and how do I change it?" ## When to use which Use **Terraform** when: - You are provisioning environments with deep dependency graphs (VPCs, subnets, gateways, instances) where plan-time ordering matters. - You want infrastructure changes to flow through code review on HCL diffs. - You rely on the Terraform module ecosystem and existing organizational workflows around it. Use **StackQL** when: - You need to ask questions of live infrastructure - inventory, audit, security posture, cost inputs - with filtering, aggregation, and joins, including across providers. - You need to detect drift independently of any tool's recorded state. - An AI agent or automation pipeline needs a self-describing, runtime-discoverable interface to the control plane rather than a compiled plan/apply workflow. - You want provisioning without state-file operations overhead (locking, backends, state surgery), accepting a simpler dependency model in exchange. Use **both** when a platform team provisions with Terraform and audits, reconciles, and reports with StackQL. This is the most common pattern in practice. ## Architectural comparison | Dimension | Terraform | StackQL | |---|---|---| | Primary operation | Plan/apply convergence | Query and mutation | | Source of truth | State file + refresh | Live provider APIs | | Language | HCL | SQL | | Query capability | Minimal (data sources) | Full SELECT with WHERE, GROUP BY, JOIN, including cross-provider | | Mutation model | Diff-driven apply | Direct INSERT / UPDATE / DELETE / EXEC | | Dependency planning | Graph-based, plan-time | Query-ordered; stack orchestration via stackql-deploy | | Drift handling | Detected at refresh/plan against managed resources | Any live query is current state; compares against any baseline | | Provider model | Compiled Go plugins | Declarative OpenAPI-based specs from an open registry | | Agent accessibility | CLI and HCL, designed for humans | Self-describing SQL surface plus built-in MCP server | | State file | Required | None | Two of these differences do the most work. First, the provider model: Terraform providers are compiled programs, so coverage depends on plugin development; StackQL providers are data (extended OpenAPI specs), so any documented API operation - control plane or data plane - can be mapped. Second, the source of truth: Terraform's state file only describes resources Terraform manages, while StackQL sees everything the credential can see, managed or not. Unmanaged resources are exactly the ones that audits and incident response need to find. ## Example The kind of question Terraform cannot ask and StackQL is built for - a live regional inventory: ```sql SELECT region, COUNT(*) as num_functions FROM aws.lambda.functions WHERE region IN ('us-east-1','us-west-2','eu-west-1','ap-southeast-2') GROUP BY region; ``` StackQL executes this as parallel regional API calls and aggregates the results - no state to refresh, and it counts every function in the account, not just those under IaC management. ## Related concepts - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - full definition - [What is Infrastructure Drift?](/ai/canonical-definitions/what-is-infrastructure-drift) - the failure mode of recorded state - [Why State Files Break Down for AI Agents](/ai/concepts/why-state-files-break-down-for-ai-agents) - the agent-era argument - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the category StackQL occupies - [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe) - comparison with a closer peer --- # Concepts > Deep explanations of StackQL design decisions, best practices, and the reasoning behind the architecture. Source: https://stackql.io/ai/concepts Pages here explain *why* StackQL works the way it does, and what good usage patterns look like. Combines what would elsewhere be called best practices and conceptual deep-dives. ## Pages - [Why State Files Break Down for AI Agents](/ai/concepts/why-state-files-break-down-for-ai-agents) - the assumptions agents violate - [Why SQL is a Strong Interface for Cloud APIs](/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis) - the design rationale for the SQL surface --- # Why SQL is a Strong Interface for Cloud APIs > SQL fits cloud APIs because it is declarative, set-oriented, universally tooled, and - decisively in the agent era - the query language every AI model already writes fluently, making it the cheapest reliable interface between agents and infrastructure. Source: https://stackql.io/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis SQL fits cloud APIs for four reasons: it is declarative (callers state what, not how), set-oriented (cloud estates are sets of resources), universally tooled (every driver, BI platform, and notebook speaks it), and - the decisive reason in the agent era - it is the query language every AI model already writes fluently. Choosing SQL as the control plane interface means the integration cost of the entire toolchain and model ecosystem has already been paid. ## The structural fit Cloud resources are naturally relational. Every provider organizes its estate as typed collections (instances, buckets, repositories) of attributed objects, with identity and cross-references between them. That is a schema, and providers already publish it - as OpenAPI specifications. Operations on those collections come in exactly the shapes SQL names: enumerate and filter (`SELECT ... WHERE`), create (`INSERT`), modify (`UPDATE`), remove (`DELETE`). The mapping StackQL applies is mechanical, not metaphorical - which is what makes it generatable from specs across hundreds of services. See [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis). Set-orientation matters more than it first appears. Infrastructure questions are set questions: "all instances without this tag", "buckets grouped by region", "repositories where branch protection is off". Imperative SDK code answers them with loops, pagination handling, and accumulation. The SQL form is one expression: ```sql SELECT region, COUNT(*) as num_functions FROM aws.lambda.functions WHERE region IN ('us-east-1','us-west-2','eu-west-1') GROUP BY region; ``` StackQL executes this as parallel regional API calls; the caller never wrote the fan-out. ## The agent-era argument For AI agents, interface choice is a token-economics and reliability decision: - **Zero-shot competence.** SQL is among the densest competencies in every model's training distribution. An agent writes a correct filtered, aggregated, joined query with no in-context teaching. A bespoke DSL or per-provider SDK must be explained in the prompt, repeatedly, at a cost in tokens and errors. - **A small, closed grammar over a huge surface.** Cloud providers expose tens of thousands of operations. Published as individual tools or functions, they overwhelm tool selection. Expressed as SQL over discoverable schemas, the grammar stays constant while `SHOW PROVIDERS`, `SHOW METHODS`, and `DESCRIBE` let the agent learn the surface at runtime - paying for what it needs, when it needs it. - **Verifiability.** SQL's declarative form is auditable before execution. A human (or a gating policy, like StackQL's MCP safe mode) can read the statement and know exactly what it will touch - far harder with a script of imperative SDK calls. ## What SQL buys beyond agents The same choice connects infrastructure to the analytical stack: in server mode StackQL speaks the PostgreSQL wire protocol, so psql, DBeaver, Tableau, Power BI, Superset, pandas, and Jupyter address live cloud state as if it were a database. Inventory dashboards, security reporting, and FinOps analysis reuse existing skills and tools with no exporter or ETL pipeline in between. ## Related concepts - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - the mapping itself - [StackQL vs Custom MCP Servers](/ai/comparisons/stackql-vs-custom-mcp-servers) - the token-economics argument applied - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the requirements that favor SQL - [StackQL Architecture Overview](/ai/architecture/stackql-architecture-overview) - how the SQL engine executes against APIs - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the operating model --- # Why State Files Break Down for AI Agents > State files assume a single, slow, human-coordinated writer; AI agents are concurrent, fast, and continuous, which violates every assumption the state-file model depends on - live querying of the control plane is the replacement primitive. Source: https://stackql.io/ai/concepts/why-state-files-break-down-for-ai-agents State files were designed around assumptions that AI agents violate: one writer at a time, changes batched into infrequent human-reviewed applies, and a workflow that tolerates the state being stale between refreshes. Agents are concurrent, act continuously, and reason from whatever facts they are given - if those facts come from a state file, the agent reasons from a stale, partial copy of reality. ## The assumptions, made explicit The state-file model works when: 1. **Writes are serialized.** State locking assumes contention is rare. Human teams apply a few times a day; lock contention is an edge case. 2. **Reads happen at plan time.** State is refreshed when a human runs plan; staleness in between is invisible because nobody is looking. 3. **The managed set is the relevant set.** The state file describes only resources the tool created. The workflow assumes nothing important exists outside it. 4. **Errors are repaired by experts.** Corrupted or divergent state is fixed by a practitioner doing state surgery (imports, moves, manual edits). Each assumption fails under agentic operation. Agents act in seconds, so serialized writes become a throughput ceiling and lock contention the norm. Agents observe continuously, so between-refresh staleness becomes a stream of false premises. Agents are routinely asked about the whole environment ("is anything publicly exposed?"), and the answer outside the managed set is precisely what matters. And an agent that corrupts state cannot reliably perform its own state surgery - the repair loop assumed human judgment. ## The deeper problem: the copy is the interface All of these reduce to one design decision: the state file makes a *copy* of infrastructure state the system's working interface. Every copy has a synchronization problem, and every consumer of the copy inherits it. [Infrastructure drift](/ai/canonical-definitions/what-is-infrastructure-drift) is not an operational accident; it is the steady-state behavior of a copy in an environment where reality changes through other channels - consoles, autoscalers, other tools, other agents. Human workflows absorb this with process: change freezes, single-tool mandates, periodic reconciliation. Agentic environments cannot - the value of agents is that they act often and independently, which is exactly the traffic pattern that makes a coordinated copy unmaintainable. ## The replacement primitive The control plane itself is already a consistent, authoritative, concurrent-safe state store - the providers run it. What agents need is an interface to it that fits how they work: declarative queries over current state, uniform across providers, with mutations expressed in the same grammar and gated by policy. That is the model StackQL implements: ```sql SELECT instance_id, instance_type, launch_time FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` The result is true at execution time, includes unmanaged resources, requires no lock, and needs no repair workflow - there is nothing to corrupt. Identifier mapping and dependency ordering (the state file's legitimate jobs) move into the query engine and deployment orchestration (stackql-deploy) rather than into a mutable artifact the agent must keep consistent. ## Related concepts - [What is Infrastructure Drift?](/ai/canonical-definitions/what-is-infrastructure-drift) - drift as a property of copies - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the requirements agents impose - [StackQL vs Terraform](/ai/comparisons/stackql-vs-terraform) - the two models side by side - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the live-query operating model - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the practical setup --- # FAQs > Common questions about StackQL, grouped by topic. Source: https://stackql.io/ai/faqs Each page covers one topic with multiple question/answer pairs, emitted as `FAQPage` structured data so answer engines can lift individual Q&As. ## Pages - [StackQL FAQ](/ai/faqs/stackql-faq) - what StackQL is, what it supports, and how it is deployed --- # StackQL FAQ > Frequently asked questions about StackQL - what it is, what it supports (joins, mutations, providers, MCP), how it compares to other tools, and how it is deployed. Source: https://stackql.io/ai/faqs/stackql-faq Answers to the most common questions about StackQL. Each answer is self-contained; follow the links for fuller treatments. ## Scope and capability **What StackQL is.** An open-source SQL engine over cloud and SaaS provider APIs: providers become schemas, resources become tables, and the full SQL verb set applies - `SELECT` for reads, `INSERT`/`UPDATE`/`DELETE` for resource lifecycle, `EXEC` for other operations. See [What is StackQL?](/ai/canonical-definitions/what-is-stackql). **What StackQL is not.** It is not a database (no stored state), not a CMDB (no synced copy), and not a state-file IaC tool (no plan/apply convergence loop). The differences are covered in [StackQL vs Terraform](/ai/comparisons/stackql-vs-terraform), [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe), and [StackQL vs CloudQuery](/ai/comparisons/stackql-vs-cloudquery). **The shape of a query.** Required API parameters surface as required `WHERE` predicates, discoverable at runtime: ```sql SELECT name, language, stargazers_count FROM github.repos.repos WHERE org = 'stackql'; ``` `SHOW METHODS IN github.repos.repos` lists every operation and its required parameters - the same discovery mechanism AI agents use through the MCP tools. ## Deployment StackQL runs as an interactive shell (`stackql shell`), a batch executor (`stackql exec`), a PostgreSQL wire protocol server (`stackql srv`), and an MCP server for AI agents (`stackql mcp`). Authentication is per provider via environment variables; metadata operations work unauthenticated. See the how-to series starting at [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws). ## License and support StackQL is open source under the [MIT License](https://github.com/stackql/stackql/blob/main/LICENSE) and free to use for any purpose. Community support is through [GitHub Discussions](https://github.com/orgs/stackql/discussions) and [Discord](https://discord.com/invite/xVXZ9d5NxN); bugs and feature requests go to [GitHub Issues](https://github.com/stackql/stackql/issues). For commercial support enquiries, [contact StackQL Studios](/contact-us). ## Related concepts - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - the canonical definition - [Getting started with StackQL](/ai/tutorials/getting-started-with-stackql) - install to first query - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP server - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the category - [Common StackQL errors](/ai/troubleshooting/common-stackql-errors) - troubleshooting --- # How-tos > Step-by-step guides for using StackQL - authentication, querying, mutation, AI integration, and governance. Source: https://stackql.io/ai/how-tos Each page is one task. Pages follow a consistent shape: prerequisites, the steps, a working example, and "what to check if it didn't work." ## Authentication - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - [How to authenticate StackQL to Azure](/ai/how-tos/authenticate-stackql-to-azure) - [How to authenticate StackQL to Google Cloud](/ai/how-tos/authenticate-stackql-to-google-cloud) - [How to authenticate StackQL to GitHub](/ai/how-tos/authenticate-stackql-to-github) ## Querying - [How to query AWS EC2 instances with StackQL](/ai/how-tos/query-aws-ec2-instances-with-stackql) - [How to query S3 buckets with StackQL](/ai/how-tos/query-s3-buckets-with-stackql) - [How to query GitHub repositories with StackQL](/ai/how-tos/query-github-repositories-with-stackql) ## AI agents - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - [How to use StackQL with Claude](/ai/how-tos/use-stackql-with-claude) ## Embedded MCP - [How to embed the StackQL MCP server in a Go application](/ai/how-tos/embed-stackql-mcp-server-in-go) - [How to embed the StackQL MCP server in a Rust application](/ai/how-tos/embed-stackql-mcp-server-in-rust) - [How to embed the StackQL MCP server in a macOS Swift application](/ai/how-tos/embed-stackql-mcp-server-in-swift) - [How to embed the StackQL MCP server in a Kotlin or JVM application](/ai/how-tos/embed-stackql-mcp-server-in-kotlin) - [How to embed the StackQL MCP server in a .NET application](/ai/how-tos/embed-stackql-mcp-server-in-dotnet) - [How to embed the StackQL MCP server in a Gleam application](/ai/how-tos/embed-stackql-mcp-server-in-gleam) --- # How to authenticate StackQL to AWS > StackQL authenticates to AWS using the standard AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, with session tokens supported for assumed roles and AWS CloudShell. Source: https://stackql.io/ai/how-tos/authenticate-stackql-to-aws StackQL authenticates to AWS using the standard AWS credential environment variables. Set them before starting a StackQL shell, `exec` command, server, or MCP server; no configuration file is required. ## Steps 1. Create or identify an IAM principal (user or role) with the permissions your queries need. For read-only querying, the `ReadOnlyAccess` managed policy or a narrower equivalent is sufficient. 2. Export the credentials as environment variables: ```bash export AWS_ACCESS_KEY_ID=YOURACCESSKEYID export AWS_SECRET_ACCESS_KEY=YOURSECRETACCESSKEY ``` For temporary credentials (an assumed role via `sts assume-role`, or an AWS CloudShell session, which sets these automatically), the session token is exported as well: ```bash export AWS_SESSION_TOKEN=YOURSESSIONTOKEN ``` 3. Pull the AWS provider (first use only): ```sql REGISTRY PULL aws; ``` 4. Verify with a query: ```sql SELECT instance_id, instance_type FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` A successful result set confirms authentication. Note that AWS queries require a `region` predicate in the `WHERE` clause - this is a routing parameter, not a credential setting. ## Where the variables apply The same environment variables work in every StackQL execution mode: - **Interactive shell**: `stackql shell` - **Batch**: `stackql exec "..."` - **Server mode**: `stackql srv` (PostgreSQL wire protocol) - **MCP server**: `stackql mcp`, or via the `env` block of an MCP client configuration such as `claude_desktop_config.json` In CI systems, source the variables from the platform's secret store rather than hardcoding them. Metadata operations (`SHOW`, `DESCRIBE`, `REGISTRY`) work without credentials; only data operations (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, `EXEC`) require an authenticated session. ## Related concepts - [How to query AWS EC2 instances with StackQL](/ai/how-tos/query-aws-ec2-instances-with-stackql) - first queries after authenticating - [How to query S3 buckets with StackQL](/ai/how-tos/query-s3-buckets-with-stackql) - the S3 query pattern - [How to authenticate StackQL to Azure](/ai/how-tos/authenticate-stackql-to-azure) - the Azure equivalent - [How to authenticate StackQL to Google Cloud](/ai/how-tos/authenticate-stackql-to-google-cloud) - the GCP equivalent - [Common StackQL errors](/ai/troubleshooting/common-stackql-errors) - including authentication failures --- # How to authenticate StackQL to Azure > StackQL authenticates to Azure using a Microsoft Entra ID service principal via the AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET environment variables. Source: https://stackql.io/ai/how-tos/authenticate-stackql-to-azure StackQL authenticates to Azure with a Microsoft Entra ID (formerly Azure AD) service principal, supplied through three environment variables: `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET`. ## Steps 1. Create a service principal and grant it a role on the target subscription (the `Reader` role suffices for read-only querying): ```bash az ad sp create-for-rbac --name stackql-sp --role Reader \ --scopes /subscriptions/ ``` 2. Export the credentials it returns: ```bash export AZURE_TENANT_ID=your-tenant-id export AZURE_CLIENT_ID=your-client-id export AZURE_CLIENT_SECRET=your-client-secret ``` 3. Pull the Azure provider (first use only): ```sql REGISTRY PULL azure; ``` 4. Verify with a query: ```sql SELECT name, location FROM azure.compute.virtual_machines WHERE subscriptionId = '00000000-1111-2222-3333-444444444444'; ``` The `subscriptionId` predicate is a required routing parameter of the Azure API, not part of authentication. Methods scoped to a resource group additionally require `resourceGroupName`; run `SHOW METHODS IN azure.compute.virtual_machines` to see the required parameters for each access method (`list_all` needs only `subscriptionId`; `list` needs `resourceGroupName` as well; `get` needs `vmName`). ## Where the variables apply The variables work identically across `stackql shell`, `stackql exec`, `stackql srv` (PostgreSQL wire server), and `stackql mcp`. For MCP clients such as Claude Desktop, place them in the `env` block of the server entry in `claude_desktop_config.json`. In CI, source them from the pipeline's secret store. ## Related concepts - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - the AWS equivalent - [How to authenticate StackQL to Google Cloud](/ai/how-tos/authenticate-stackql-to-google-cloud) - the GCP equivalent - [How to use StackQL with Claude](/ai/how-tos/use-stackql-with-claude) - passing Azure credentials to an MCP session - [Control Plane vs Data Plane](/ai/canonical-definitions/control-plane-vs-data-plane) - what the Resource Manager APIs cover - [Common StackQL errors](/ai/troubleshooting/common-stackql-errors) - including authentication failures --- # How to authenticate StackQL to GitHub > StackQL authenticates to GitHub using basic authentication with a personal access token, supplied via the STACKQL_GITHUB_USERNAME and STACKQL_GITHUB_PASSWORD environment variables; public data can be queried without authentication at lower rate limits. Source: https://stackql.io/ai/how-tos/authenticate-stackql-to-github StackQL authenticates to GitHub with basic authentication: your GitHub username and a personal access token (PAT), supplied as `STACKQL_GITHUB_USERNAME` and `STACKQL_GITHUB_PASSWORD`. Public data is queryable without any credentials at GitHub's unauthenticated rate limits. ## Steps 1. Create a personal access token in GitHub (Settings -> Developer settings). Grant only the scopes your queries need - none for public data at higher rate limits, `repo` for private repositories. 2. Export the credentials: ```bash export STACKQL_GITHUB_USERNAME=yourghuser export STACKQL_GITHUB_PASSWORD=ghp_yourgithubpersonalaccesstoken ``` 3. Pull the GitHub provider (first use only): ```sql REGISTRY PULL github; ``` 4. Verify with a query: ```sql SELECT name, description, language, stargazers_count FROM github.repos.repos WHERE org = 'stackql'; ``` The `org` predicate selects the `list_for_org` access method; `WHERE username = '...'` selects `list_for_user` instead. `SHOW METHODS IN github.repos.repos` lists every method and its required parameters, including the mutation methods (`create_in_org`, `update`, `delete`). ## Unauthenticated access The query above works without credentials because the `stackql` organization is public - useful for evaluation and for agents exploring the query model before credentials are provisioned. GitHub's unauthenticated rate limit is low (60 requests per hour per IP), so any sustained use should authenticate. ## Related concepts - [How to query GitHub repositories with StackQL](/ai/how-tos/query-github-repositories-with-stackql) - the full query patterns - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - the AWS equivalent - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - how REST operations map to SQL verbs - [Getting started with StackQL](/ai/tutorials/getting-started-with-stackql) - GitHub is the fastest zero-credential start - [Common StackQL errors](/ai/troubleshooting/common-stackql-errors) - including rate-limit symptoms --- # How to authenticate StackQL to Google Cloud > StackQL authenticates to Google Cloud using a service account key supplied through the GOOGLE_CREDENTIALS environment variable, which holds the JSON key content. Source: https://stackql.io/ai/how-tos/authenticate-stackql-to-google-cloud StackQL authenticates to Google Cloud with a service account key, supplied as JSON content in the `GOOGLE_CREDENTIALS` environment variable. ## Steps 1. Create a service account and grant it a role on the target project (`roles/viewer` suffices for read-only querying), then create and download a JSON key: ```bash gcloud iam service-accounts keys create stackql-key.json \ --iam-account=stackql-sa@my-project.iam.gserviceaccount.com ``` 2. Export the key content: ```bash export GOOGLE_CREDENTIALS=$(cat ./stackql-key.json) ``` An alternative is passing the key by path with the `--auth` flag, which is useful for server and MCP deployments: ```bash stackql shell \ --auth='{"google": {"type": "service_account", "credentialsfilepath": "/path/to/stackql-key.json"}}' ``` 3. Pull the Google provider (first use only): ```sql REGISTRY PULL google; ``` 4. Verify with a query: ```sql SELECT name, status, machineType FROM google.compute.instances WHERE project = 'my-project'; ``` This uses the `aggregated_list` access method, which requires only `project` and returns instances across all zones. The zonal `list` method requires both `project` and `zone`; `SHOW METHODS IN google.compute.instances` shows each method's required parameters. ## Where the credentials apply The same variable (or `--auth` object) works across `stackql shell`, `stackql exec`, `stackql srv`, and `stackql mcp`. For Claude Desktop and similar MCP clients, set `GOOGLE_CREDENTIALS` in the `env` block of the server configuration. In CI, source the key from the platform's secret store - never commit it. ## Related concepts - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - the AWS equivalent - [How to authenticate StackQL to Azure](/ai/how-tos/authenticate-stackql-to-azure) - the Azure equivalent - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - credentials in MCP deployments - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - why required parameters surface in WHERE clauses - [Common StackQL errors](/ai/troubleshooting/common-stackql-errors) - including authentication failures --- # How to embed the StackQL MCP server in a .NET application > Embed the StackQL MCP server in a .NET / C# app as a sidecar or vendored bundle, so a worker service or agent can run cloud queries and drift checks over SQL with no runtime dependency. Source: https://stackql.io/ai/how-tos/embed-stackql-mcp-server-in-dotnet StackQL's MCP server can run inside a .NET application with no separate install and no runtime dependency. The `StackQL.Mcp` package spawns the signed StackQL binary over stdio behind the official C# MCP SDK client, so a worker service or agent gets a governed, self-describing SQL interface to every cloud and SaaS provider in the StackQL registry. This is the pattern behind **driftwatch**, a scheduled drift-check worker service. ## Steps 1. **Add the package:** ``` dotnet add package StackQL.Mcp ``` An optional `StackQL.Mcp.AgentFramework` package adds Agent Framework integration. Requires .NET 8 or later (the packages multi-target `net8.0` and `net9.0`). 2. **Start the server and call a tool.** The builder defaults to `StackqlMode.ReadOnly`: ```csharp using StackQL.Mcp; await using var server = await StackqlMcp.CreateBuilder() .WithMode(StackqlMode.ReadOnly) .WithAuth("github", "null_auth") .StartAsync(); var tools = await server.ListToolsAsync(); var result = await server.CallToolAsync("list_services", new() { ["provider"] = "github", ["row_limit"] = 5 }); ``` The builder also exposes `.WithBinary()`, `.WithBundlePath()`, `.WithApproot()`, and `.WithCommand()`. 3. **Choose a mode.** `.WithMode()` defaults to `StackqlMode.ReadOnly`. Set `StackqlMode.Safe`, `StackqlMode.DeleteSafe`, or `StackqlMode.FullAccess` only when the app needs to provision. Escalation is explicit. ## Ship a self-contained executable Two ways to source the binary: - **Sidecar (default)** - the platform bundle is downloaded on first run, sha256-verified, cached at `~/.stackql/mcp-server-bin///`, and spawned over stdio. - **Vendored** - embed the bundle as a build resource: ``` dotnet build -p:StackqlVendorBundle=/path/to/stackql-mcp-windows-x64.mcpb ``` Override the binary or bundle at runtime with the `STACKQL_MCP_BIN` or `STACKQL_MCP_BUNDLE` environment variables. ## Demo app **driftwatch** is a .NET Worker Service that embeds the read-only StackQL server and, on a schedule, runs a suite of SQL drift checks (public exposure, missing tags or licenses, baseline drift) and posts the findings to a Teams Adaptive Card. ## Related concepts - [Embedded MCP: .NET / C# reference](/mcp/embedded/dotnet) - install, API, and vendoring - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP model and safety modes - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables --- # How to embed the StackQL MCP server in a Gleam application > Embed the StackQL MCP server in a Gleam app on the Erlang/BEAM target, supervised by OTP, so a BEAM service can run cloud queries over SQL with no runtime dependency. Source: https://stackql.io/ai/how-tos/embed-stackql-mcp-server-in-gleam StackQL's MCP server can run inside a Gleam application on the Erlang/BEAM target with no separate install and no runtime dependency. The `stackql_mcp` library spawns the signed StackQL binary over stdio and integrates with OTP supervision, so a BEAM service gets a governed, self-describing SQL interface to every cloud and SaaS provider in the StackQL registry. The server is exposed as an OTP child via `child_spec()` so it can sit inside your own supervision tree. ## Steps 1. **Add the library:** ``` gleam add stackql_mcp ``` Targets Erlang/BEAM only (not the JavaScript target). 2. **Start the server and list tools.** `Config.mode` defaults to `read_only`: ```gleam import gleam/io import gleam/int import gleam/list import envoy import stackql_mcp pub fn main() { let config = stackql_mcp.Config( ..stackql_mcp.default_config(), auth: [stackql_mcp.auth_for("github", "null_auth")], ) let assert Ok(server) = stackql_mcp.start( config: config, home: "/home/u", os: "linux", arch: "x86_64", getenv: envoy.get, ) let assert Ok(tools) = stackql_mcp.list_tools(server) io.println(int.to_string(list.length(tools)) <> " tools available") stackql_mcp.stop(server) } ``` Use `child_spec()` to place the server under a supervisor, with `supervised_list_tools()` and `supervised_call_tool()` for supervised calls. 3. **Choose a mode.** `Config.mode` defaults to `read_only`. Build `stackql_mcp.Config(..stackql_mcp.default_config(), mode: stackql_mcp.safe)` to escalate to `safe`, `delete_safe`, or `full_access`. Escalation is explicit. ## Binary sourcing On start the library downloads the platform's StackQL bundle, verifies it against baked-in sha256 pins, and caches it in the shared family cache. Resolution precedence: explicit `Config.binary`, then `STACKQL_MCP_BIN`, then the shared cache at `~/.stackql/mcp-server-bin/`. For offline or air-gapped deployments, set `STACKQL_MCP_BUNDLE` to point at a local bundle. ## Demo app **pipewatch** is the planned demo for this library. It is on the roadmap and not yet implemented. ## Related concepts - [Embedded MCP: Gleam reference](/mcp/embedded/gleam) - install, API, and binary sourcing - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP model and safety modes - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables --- # How to embed the StackQL MCP server in a Go application > Embed the StackQL MCP server inside a compiled Go binary using go:embed or sidecar mode, so an agentic Go app can run cloud queries and provisioning over SQL with no runtime dependency. Source: https://stackql.io/ai/how-tos/embed-stackql-mcp-server-in-go StackQL's MCP server can run inside a compiled Go program with no `npx`, no separate install, and no runtime dependency. The `stackql-mcp-go` library spawns the signed StackQL binary over stdio behind the official Go MCP SDK client, so your Go app gets a governed, self-describing SQL interface to every cloud and SaaS provider in the StackQL registry. This is the pattern behind **sandboxctl**, an on-demand infrastructure concierge shipped as one binary. ## Steps 1. **Add the library:** ``` go get github.com/stackql/stackql-mcp-go ``` 2. **Start the embedded server and call a tool.** The server starts in `read_only` mode by default: ```go import ( "context" "github.com/modelcontextprotocol/go-sdk/mcp" stackqlmcp "github.com/stackql/stackql-mcp-go/embed" ) func main() { ctx := context.Background() client, err := stackqlmcp.StartServer(ctx, stackqlmcp.Options{ Binary: StackqlMCPBinary(), }) if err != nil { // handle error } defer client.Close() res, err := client.Session.CallTool(ctx, &mcp.CallToolParams{ Name: "run_select_query", Arguments: map[string]any{"sql": "SELECT name FROM google.compute.regions WHERE project = 'my-project'"}, }) _ = res } ``` 3. **Choose a mode.** `Options.Mode` defaults to `read_only`. Set it to `safe`, `delete_safe`, or `full_access` only when the app needs to provision. Escalation is explicit. ## Ship a single binary with go:embed For a self-contained executable, add a `go:generate` fetch step that downloads and sha256-verifies the platform binary, then `go:embed` it into the build: ``` //go:generate go run github.com/stackql/stackql-mcp-go/cmd/stackql-mcp-fetch -platform auto -package main ``` At runtime `StackqlMCPBinary()` returns the embedded binary, so there is no first-run download. Without vendoring, the binary is downloaded and verified into the shared cache at `~/.stackql/mcp-server-bin/` on first run. ## Demo app **sandboxctl** is an infrastructure concierge: an embedded StackQL MCP server plus a Claude agent loop in one Go binary that plans, cost-checks, and provisions ephemeral cloud sandboxes behind an approval gate. ## Related concepts - [Embedded MCP: Go reference](/mcp/embedded/go) - install, API, and modes - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP model and safety modes - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables --- # How to embed the StackQL MCP server in a Kotlin or JVM application > Embed the StackQL MCP server in a Kotlin/JVM app as a library or Gradle plugin, so a JVM service or CI/CD pipeline can run cloud queries and cost gates over SQL with no runtime dependency. Source: https://stackql.io/ai/how-tos/embed-stackql-mcp-server-in-kotlin StackQL's MCP server can run inside a Kotlin or JVM application with no `npx`, no separate install, and no runtime dependency. The `io.stackql:stackql-mcp` library spawns the signed StackQL binary over stdio behind the official Kotlin MCP SDK client, and a companion Gradle plugin wires the same launch into a build. This is the pattern behind **costgate**, a cost gate for CI/CD shipped as a CLI and a Gradle plugin. ## Steps 1. **Add the library** to your Gradle dependencies: ```kotlin dependencies { implementation("io.stackql:stackql-mcp:0.1.0") } ``` Requires JDK 17 and Kotlin 2.x. The client comes from the official Kotlin MCP SDK. 2. **Start the server and list tools.** The builder defaults to `Mode.ReadOnly`: ```kotlin import io.stackql.mcp.LaunchArgs import io.stackql.mcp.Mode import io.stackql.mcp.StackqlMcp suspend fun main() { val server = StackqlMcp.builder() .mode(Mode.ReadOnly) .auth(LaunchArgs.authFor("github", "null_auth")) .start() server.use { val tools = server.client.listTools().tools println("${tools.size} tools available") } } ``` 3. **Choose a mode.** `.mode()` defaults to `Mode.ReadOnly`. Set `Mode.Safe`, `Mode.DeleteSafe`, or `Mode.FullAccess` only when the app needs to provision. Escalation is explicit. ## Run StackQL queries from a Gradle build The Gradle plugin wires the embedded server into your build so CI tasks run StackQL queries without a separate install step. The **costgate** demo gates infrastructure deploys on cost budgets, as a CLI: ```bash costgate check --intent examples/costgate.yaml --explain ``` and as a Gradle plugin: ```kotlin plugins { id("io.stackql.costgate") version "0.1.0" } costgate { intent.set(layout.projectDirectory.file("costgate.yaml")) explain.set(true) } ``` ## Related concepts - [Embedded MCP: Kotlin / JVM reference](/mcp/embedded/kotlin) - install, API, and the Gradle plugin - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP model and safety modes - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables --- # How to embed the StackQL MCP server in a Rust application > Embed the StackQL MCP server inside a Rust binary using the sidecar feature or include_bytes! vendoring, so a Rust app can run cloud queries and provisioning over SQL with no runtime dependency. Source: https://stackql.io/ai/how-tos/embed-stackql-mcp-server-in-rust StackQL's MCP server can run inside a Rust binary with no `npx`, no separate install, and no runtime dependency. The `stackql-mcp` crate spawns the signed StackQL binary over stdio behind an `rmcp` client, so your Rust app gets a governed, self-describing SQL interface to every cloud and SaaS provider in the StackQL registry. This is the pattern behind **auditron**, a terminal compliance copilot shipped as one binary. ## Steps 1. **Add the crate** to `Cargo.toml`: ```toml stackql-mcp = "0.1" ``` 2. **Build the server and list tools.** The builder defaults to `Mode::ReadOnly`: ```rust use stackql_mcp::{Mode, StackqlMcp}; #[tokio::main] async fn main() -> Result<(), Box> { let server = StackqlMcp::builder() .mode(Mode::ReadOnly) .auth(serde_json::json!({"github": {"type": "null_auth"}})) .start() .await?; let tools = server.list_all_tools().await?; println!("{} tools available", tools.len()); server.shutdown().await?; Ok(()) } ``` The builder also exposes `.binary()`, `.bundle_path()`, `.approot()`, and `.command()`. MSRV is Rust 1.88. 3. **Choose a mode.** `.mode()` defaults to `Mode::ReadOnly`. Set `Mode::Safe`, `Mode::DeleteSafe`, or `Mode::FullAccess` only when the app needs to provision. Escalation is explicit. ## Ship a single binary with include_bytes! Two feature flags control how the binary is sourced: - `sidecar` (default) - download, verify, and cache the signed binary on first run. - `vendored` - embed the binary with `include_bytes!` for a single self-contained executable. The vendored binary adds roughly 80 MB to the build. ## Demo app **auditron** is a terminal compliance copilot: a TUI that streams pass/fail results with the SQL shown and Claude explanations, shipped as an ~80 MB vendored single binary. ## Related concepts - [Embedded MCP: Rust reference](/mcp/embedded/rust) - install, API, and feature flags - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP model and safety modes - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables --- # How to embed the StackQL MCP server in a macOS Swift application > Bundle the notarised StackQL MCP server binary inside a signed macOS Swift app, so a native menu-bar or desktop app can run cloud queries over SQL while keeping its notarisation valid. Source: https://stackql.io/ai/how-tos/embed-stackql-mcp-server-in-swift StackQL's MCP server can run inside a native macOS app with no separate install and no runtime dependency. The `stackql-mcp-swift` package spawns the signed StackQL binary over stdio behind the official Swift MCP SDK client. Because the `darwin-universal` binary is Developer ID signed and Apple-notarised, you can bundle it inside a signed `.app` and keep the app's notarisation valid - the pattern behind **CloudLens**, a menu-bar cloud sentinel. ## Steps 1. **Add the package** to `Package.swift`: ```swift .package(url: "https://github.com/stackql/stackql-mcp-swift.git", from: "0.1.0") ``` Requires macOS 13+ and Swift 6.1 (Xcode 16.3+). The single dependency is the official Swift MCP SDK. 2. **Start the server and call a tool.** `Options.mode` defaults to `.readOnly`: ```swift import StackQLMCP var options = Options() options.mode = .readOnly options.auth = ["github": ["type": "null_auth"]] let server = try await StackQLServer.start(options) let tools = try await server.listToolNames() print("\(tools.count) tools available") let services = try await server.call( "list_services", ["provider": "github", "row_limit": 5]) print(services.text) await server.stop() ``` For external harnesses, `StackQLServer.resolveCommand(_:)` returns the resolved launch command. 3. **Choose a mode.** `Options.mode` defaults to `.readOnly`. Set `.safe`, `.deleteSafe`, or `.fullAccess` only when the app needs to provision. Escalation is explicit. ## Bundle the notarised binary in a signed app The `darwin-universal` binary is Developer ID signed and Apple-notarised, so it can be bundled inside a signed macOS `.app` while keeping the app's own notarisation valid. Binary resolution order: 1. Explicit `binaryOverride`. 2. Bundled `.app` resources. 3. Shared cache at `~/.stackql/mcp-server-bin/`. 4. Download with sha256 verification (when `allowDownload` is set). Put the notarised binary in app resources and the bundled path wins - the app is fully self-contained with no first-run download. ## Demo app **CloudLens** is a menu-bar cloud sentinel that embeds the notarised binary and runs a `read_only` check suite. ## Related concepts - [Embedded MCP: Swift reference](/mcp/embedded/swift) - install, API, and binary resolution - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP model and safety modes - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables --- # How to query AWS EC2 instances with StackQL > Query EC2 instances as the SQL table aws.ec2.instances - filter by region, project attributes such as instance type and IP addresses, and aggregate across regions with GROUP BY. Source: https://stackql.io/ai/how-tos/query-aws-ec2-instances-with-stackql EC2 instances are exposed as the table `aws.ec2.instances`. Any field returned by the EC2 `DescribeInstances` API is a queryable column, and `region` is a required `WHERE` predicate because the API is regional. ## Prerequisites - AWS credentials exported as environment variables - see [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - The AWS provider installed: `REGISTRY PULL aws;` ## Basic query List instances in one region with their type and addressing: ```sql SELECT instance_id, instance_type, private_ip_address, public_ip_address, launch_time FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` ## Discover the schema first Two metadata commands make the resource self-describing - no AWS documentation required: ```sql DESCRIBE aws.ec2.instances; SHOW METHODS IN aws.ec2.instances; ``` `DESCRIBE` lists the available columns. `SHOW METHODS` lists the operations (the `describe` SELECT method, the `terminate` DELETE method, and EXEC lifecycle methods such as `start`, `stop`, and `reboot`) with the required parameters for each. These commands work without credentials. ## Multi-region aggregation A `region IN (...)` predicate runs one API call per region in parallel and aggregates the results - a regional service queried like a global table: ```sql SELECT region, instance_type, COUNT(*) as num_instances FROM aws.ec2.instances WHERE region IN ('us-east-1','us-west-2','eu-west-1','ap-southeast-2') GROUP BY region, instance_type; ``` This pattern is the basis of account-wide inventory and drift baselines: the result is the live answer, not a snapshot. ## Filtering on attributes Standard SQL predicates apply to any column. For example, instances exposed to the internet: ```sql SELECT instance_id, instance_type, public_ip_address FROM aws.ec2.instances WHERE region = 'us-east-1' AND public_ip_address IS NOT NULL; ``` Structured columns such as `state` and `tag_set` return JSON, which can be unpacked with the JSON functions of the configured SQL backend. ## Related concepts - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - credential setup - [How to query S3 buckets with StackQL](/ai/how-tos/query-s3-buckets-with-stackql) - the S3 pattern, which differs slightly - [What is Infrastructure Drift?](/ai/canonical-definitions/what-is-infrastructure-drift) - using these queries as baselines - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the model behind the table abstraction - [Getting started with StackQL](/ai/tutorials/getting-started-with-stackql) - end-to-end setup --- # How to query GitHub repositories with StackQL > Query GitHub repositories as the SQL table github.repos.repos - list repositories by organization or user, filter on language, visibility, and activity, and update repository settings with SQL. Source: https://stackql.io/ai/how-tos/query-github-repositories-with-stackql GitHub repositories are exposed as the table `github.repos.repos`. Listing by organization or user maps to the corresponding GitHub REST operations, selected by the `WHERE` clause: `org = '...'` uses the organization listing, `username = '...'` the user listing. ## Prerequisites - The GitHub provider installed: `REGISTRY PULL github;` - Optional credentials for private data and higher rate limits - see [How to authenticate StackQL to GitHub](/ai/how-tos/authenticate-stackql-to-github) ## List an organization's repositories ```sql SELECT name, description, language, stargazers_count FROM github.repos.repos WHERE org = 'stackql'; ``` Run against the public `stackql` organization, this returns rows such as the `stackql` engine repository (Go, 861 stars at the time of writing) and `stackql-provider-registry` - live API data, no snapshot involved. ## Filter on repository attributes Standard SQL predicates apply to any column: ```sql SELECT name, visibility, default_branch, archived FROM github.repos.repos WHERE org = 'my-org' AND archived = false AND visibility = 'public'; ``` Useful governance columns include `private`, `visibility`, `archived`, `fork`, `default_branch`, `delete_branch_on_merge`, `has_wiki`, `topics`, `created_at`, `pushed_at`, and `security_and_analysis`. `DESCRIBE github.repos.repos` lists all of them. ## Beyond the repository list The `github.repos` service exposes the rest of the repository surface as sibling tables - `github.repos.branches`, `github.repos.commits`, `github.repos.releases`, `github.repos.collaborators`, `github.repos.webhooks`, `github.repos.deployments`, and more. Discover them with: ```sql SHOW RESOURCES IN github.repos; ``` ## Updating repositories Repository settings changes are `UPDATE` statements; the method requires `owner` and `repo`, and body fields use the `data__` prefix: ```sql UPDATE github.repos.repos SET data__delete_branch_on_merge = true WHERE owner = 'my-org' AND repo = 'my-repo'; ``` Applied across a result set from the listing query, this is fleet-wide repository governance in two statements - a pattern that pairs naturally with cross-provider queries joining GitHub data to cloud resources. ## Related concepts - [How to authenticate StackQL to GitHub](/ai/how-tos/authenticate-stackql-to-github) - tokens and rate limits - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - the REST-to-SQL mapping used here - [Getting started with StackQL](/ai/tutorials/getting-started-with-stackql) - GitHub as the zero-credential first provider - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - agents running these queries via MCP - [StackQL vs Steampipe](/ai/comparisons/stackql-vs-steampipe) - read-only alternatives compared --- # How to query S3 buckets with StackQL > List S3 buckets with the aws.s3.buckets table and retrieve per-bucket configuration - encryption, versioning, public access blocks - with the aws.s3.bucket detail table keyed by data__Identifier. Source: https://stackql.io/ai/how-tos/query-s3-buckets-with-stackql S3 buckets are exposed as two related tables: `aws.s3.buckets` lists the buckets in the account, and `aws.s3.bucket` (singular) returns the full configuration of one bucket identified by `data__Identifier`. This list/detail split mirrors the AWS Cloud Control API the tables are built on. ## Prerequisites - AWS credentials exported - see [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - The AWS provider installed: `REGISTRY PULL aws;` ## List buckets ```sql SELECT bucket_name FROM aws.s3.buckets WHERE region = 'us-east-1'; ``` The `region` predicate is a required routing parameter of the underlying API call; `us-east-1` returns the account's buckets. ## Inspect one bucket The detail table returns configuration attributes for a named bucket: ```sql SELECT bucket_name, bucket_location, bucket_encryption, versioning_configuration, public_access_block_configuration FROM aws.s3.bucket WHERE region = 'us-east-1' AND data__Identifier = 'my-bucket-name'; ``` Configuration columns return structured JSON; `DESCRIBE aws.s3.bucket` lists everything available, including `logging_configuration`, `lifecycle_configuration`, `object_lock_configuration`, `tags`, and `arn`. ## Audit pattern: enumerate, then inspect Account-wide configuration audits combine the two tables: list the bucket names, then query the detail table per bucket. In scripted use (shell loops, or Python via pystackql), iterate over the list result and collect the detail rows - per-bucket checks such as "is versioning enabled?" or "is the public access block complete?" become row predicates over the collected results. This is the documented pattern for S3 inventory in the StackQL AWS tutorials. ## Creating buckets Writable properties are discoverable the same way readable ones are: ```sql SHOW INSERT INTO aws.s3.buckets; ``` This generates an `INSERT` template covering the resource's writable fields (the desired-state document and `region`). Restricting to mandatory fields only is done with the `/*+ REQUIRED */` query hint. ## Related concepts - [How to query AWS EC2 instances with StackQL](/ai/how-tos/query-aws-ec2-instances-with-stackql) - the regional-service pattern - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - credential setup - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - why list and detail are separate methods - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the audit use case in context - [Common StackQL errors](/ai/troubleshooting/common-stackql-errors) - missing required parameters explained --- # How to use StackQL with AI agents > Run StackQL as a Model Context Protocol (MCP) server so AI agents can discover cloud provider schemas, validate queries, and execute governed reads and mutations against live infrastructure. Source: https://stackql.io/ai/how-tos/use-stackql-with-ai-agents StackQL ships a built-in Model Context Protocol (MCP) server. Any MCP-capable agent - Claude, Cursor, Continue, or a custom agent framework - connects to it and gains a self-describing, governed SQL interface to every cloud and SaaS provider in the StackQL registry. ## Steps 1. **Set provider credentials** as environment variables before starting the server (the server inherits them): ```bash export AWS_ACCESS_KEY_ID=YOURACCESSKEYID export AWS_SECRET_ACCESS_KEY=YOURSECRETACCESSKEY ``` Alternatively (in StackQL releases after v0.10.542), nominate a dotenv-style credentials file with `--env.file`; the `reload_credentials` MCP tool re-sources it mid-session so rotated credentials reach a running server without a restart. 2. **Start the MCP server.** For a standalone HTTP server: ```bash stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true}}' ``` From `v0.12.742` the HTTP transport needs either `server.auth_token_env_var` (an environment variable holding a pre-shared bearer token that every request must carry) or the explicit `allow_unauthenticated` opt-in shown here, otherwise the server refuses to start; use the token for any listener other processes or hosts can reach. `stdio` is unaffected. For editor-embedded clients, use `--mcp.server.type=stdio` and let the client launch the process (see [How to use StackQL with Claude](/ai/how-tos/use-stackql-with-claude)). To serve MCP and the PostgreSQL wire protocol from one process, use `stackql srv` with the same MCP flags plus `--pgsrv.port`. 3. **Choose a safety mode.** The mode is set in the server config and gates what agents can do: | Mode | SELECT / metadata | INSERT / UPDATE | DELETE | EXEC | |---|---|---|---|---| | `read_only` | allow | refuse | refuse | refuse | | `safe` (default) | allow | needs approval | needs approval | needs approval | | `delete_safe` | allow | allow | needs approval | needs approval | | `full_access` | allow | allow | allow | allow | "Needs approval" uses the MCP elicitation flow: the client shows the user the pending SQL and the user accepts or declines. Pin `read_only` for inventory agents; reserve `full_access` for trusted pipelines with a reviewed audit log. A payload holding several statements is gated by its most privileged statement (from `v0.12.742`), so a mutation cannot ride behind a leading `SELECT`. 4. **Let the agent discover, then query.** A typical agent session: `server_info` once, then `list_providers` -> `list_methods` (which reveals required `WHERE` parameters) -> `validate_select_query` -> `run_select_query`: ```sql SELECT name, language, stargazers_count FROM github.repos.repos WHERE org = 'stackql'; ``` The agent never loads an SDK; the schema is discovered at runtime and the query is plain SQL. ## Auditing Every tool call writes one JSONL record - timestamp, tool, mode, decision, query class, SQL, duration - to a file sink with rotation. Audit is on by default and records what the agent did (not result rows). In the default `strict` failure mode, a failed audit write surfaces as an error rather than letting an unaudited mutation slip through. ## Related concepts - [How to use StackQL with Claude](/ai/how-tos/use-stackql-with-claude) - Claude Desktop configuration - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals - [StackQL vs Custom MCP Servers](/ai/comparisons/stackql-vs-custom-mcp-servers) - when to build instead - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables - [Why SQL is a Strong Interface for Cloud APIs](/ai/concepts/why-sql-is-a-strong-interface-for-cloud-apis) - why agents and SQL fit --- # How to use StackQL with Claude > Register StackQL as an MCP server in Claude Desktop or Claude Code so Claude can query and manage cloud infrastructure across AWS, Azure, Google Cloud, GitHub, and other providers using natural language. Source: https://stackql.io/ai/how-tos/use-stackql-with-claude Claude connects to StackQL through the Model Context Protocol: register `stackql` as an MCP server in Claude Desktop (or Claude Code), and Claude can inventory, audit, and - with your approval - modify cloud resources across every provider StackQL supports, driven by natural language. ## Steps 1. **Install StackQL** and verify it is on your PATH: ```bash stackql --version ``` 2. **Edit the Claude Desktop configuration file**: - Windows: `%APPDATA%\Claude\claude_desktop_config.json` - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` - Linux: `~/.config/Claude/claude_desktop_config.json` 3. **Add the server entry**, including credentials for the providers you use: ```json { "mcpServers": { "stackql": { "command": "stackql", "args": [ "mcp", "--mcp.server.type=stdio", "--mcp.config", "{\"server\": {\"transport\": \"stdio\", \"mode\": \"safe\"}}" ], "env": { "AWS_ACCESS_KEY_ID": "your-aws-access-key-id", "AWS_SECRET_ACCESS_KEY": "your-aws-secret-access-key", "STACKQL_GITHUB_USERNAME": "your-github-username", "STACKQL_GITHUB_PASSWORD": "your-github-personal-access-token" } } } } ``` Include only the providers you need (`AZURE_TENANT_ID`/`AZURE_CLIENT_ID`/`AZURE_CLIENT_SECRET` for Azure, `GOOGLE_CREDENTIALS` for Google Cloud, `DATABRICKS_CLIENT_ID`/`DATABRICKS_CLIENT_SECRET` for Databricks). Never commit this file to version control. 4. **Restart Claude Desktop.** The server starts automatically when a conversation begins. 5. **Ask in natural language.** Examples that map directly to StackQL operations: - "List all EC2 instances in us-east-1 with public IP addresses" - "Which repositories in our GitHub org have branch protection disabled?" - "Create an S3 bucket named analytics-data in us-west-2" For reads, Claude discovers the schema and runs `SELECT` statements immediately. For the bucket creation, `safe` mode triggers an approval prompt showing the exact `INSERT` before anything executes. ## Controlling what Claude can do The `mode` field in the config is the contract: `read_only` for inventory-only assistants, `safe` (default) for approval-gated changes, `delete_safe` to allow create/update but gate deletes, `full_access` only for trusted automation. Every call Claude makes is recorded in the server's JSONL audit log regardless of mode. ## Related concepts - [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the general MCP setup, including HTTP transport - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - modes, elicitation, and audit in detail - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - per-provider credential reference - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the broader pattern - [StackQL vs Custom MCP Servers](/ai/comparisons/stackql-vs-custom-mcp-servers) - why one generic server beats many bespoke ones --- # Industry positioning > Where StackQL fits in the agentic-infrastructure, AI-native IaC, and queryable-infrastructure landscape. Source: https://stackql.io/ai/industry-positioning Pages here describe the broader context StackQL operates in - the shift from state-file IaC to query-first infrastructure, the rise of AI agents needing live infrastructure state, and where StackQL sits in that landscape. ## Pages - [From IaC to Agentic Infrastructure](/ai/industry-positioning/from-iac-to-agentic-infrastructure) - the three eras of infrastructure tooling --- # From IaC to Agentic Infrastructure > Infrastructure tooling has moved through three eras - imperative scripts, declarative state-file IaC, and now agentic infrastructure, where AI agents operate the control plane through self-describing, governed interfaces over live state. Source: https://stackql.io/ai/industry-positioning/from-iac-to-agentic-infrastructure Infrastructure tooling has moved through three eras, each defined by who - or what - operates the control plane. Imperative scripting put humans at the keyboard; declarative IaC put humans in a review loop around a convergence engine; agentic infrastructure puts AI agents on the control plane directly, and the interface requirements change accordingly. ## Era one: imperative automation Shell scripts, CLI invocations, and configuration tools encoded *procedures*: do this, then this. The operator carried the model of desired state in their head. The approach scaled poorly - procedures drift, error handling multiplies, and nothing checks the result against intent. ## Era two: declarative IaC Terraform, CloudFormation, and their peers inverted the model: declare desired state, let the engine compute the procedure. This was a genuine advance - reviewable diffs, repeatable environments, modular reuse - and it built the workflows most platform teams run today. Its load-bearing artifact is the state file: the engine's record of what it manages, used to map declarations to real resources and compute plans. The model's assumptions are human-shaped: changes arrive in batches through code review; the state is refreshed when someone runs plan; everything that matters is inside the managed set. Within those assumptions it works well, which is why it persists. Outside them - continuous observation, cross-provider questions, resources nobody declared - it has little to offer: IaC tools cannot ask questions, and their records describe only what they manage. See [Why State Files Break Down for AI Agents](/ai/concepts/why-state-files-break-down-for-ai-agents). ## Era three: agentic infrastructure AI agents change the operating pattern, not just the operator. Agents act continuously rather than in release batches; they ask ad-hoc questions across the whole estate; they are concurrent; and they need machine-checkable guardrails rather than tribal process. The interface that serves them has four properties: 1. **Discoverable** - the agent learns providers, resources, operations, and required parameters at runtime (`SHOW METHODS`, MCP discovery tools), instead of shipping with hardcoded provider knowledge. 2. **Live** - answers reflect the control plane now, not a copy refreshed on a human cadence. 3. **Uniform** - one grammar (SQL: `SELECT`/`INSERT`/`UPDATE`/`DELETE`) across every provider, so agent competence transfers across the estate. 4. **Governed** - explicit contracts on what an autonomous caller may do (read-only through full access), human approval where required, and a complete audit trail. This is the interface StackQL implements: provider APIs as self-describing SQL tables over live state, mutations in the same grammar, exposed to agents through a built-in MCP server with graduated safety modes and always-on audit logging. ## What persists from the IaC era Desired-state definitions persist - intent must live somewhere, and version-controlled declarations remain the right home for it. What the agentic era replaces is the machinery between intent and reality: the periodic plan/apply loop against a private state record gives way to continuous query, comparison, and governed reconciliation against the live control plane. IaC defined the destination; agentic infrastructure changes how - and how often - the gap to it is measured and closed. ## Related concepts - [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the canonical definition - [Why State Files Break Down for AI Agents](/ai/concepts/why-state-files-break-down-for-ai-agents) - the era-two limits in detail - [StackQL vs Terraform](/ai/comparisons/stackql-vs-terraform) - era two and era three tools compared - [What is Queryable Infrastructure?](/ai/canonical-definitions/what-is-queryable-infrastructure) - the data layer of era three - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - the governance layer of era three --- # Providers reference > Per-provider, per-service, per-resource reference for StackQL - generated from provider specifications. Source: https://stackql.io/ai/providers This section is auto-generated from StackQL provider specifications. Each page documents one resource: its purpose, authentication requirements, supported methods (SELECT/INSERT/UPDATE/DELETE), a working SQL example, and related resources. Generation is not yet wired up - this is a placeholder for the generator described in the AEO content plan. --- # Troubleshooting > Common StackQL errors and resolutions - authentication, provider registry, server mode, PostgreSQL wire connections. Source: https://stackql.io/ai/troubleshooting Each page covers one error or symptom, with the root cause and the resolution. ## Pages - [Common StackQL Errors](/ai/troubleshooting/common-stackql-errors) - missing providers, required parameters, authentication, rate limits, and MCP gating --- # Common StackQL Errors > Resolutions for the most common StackQL failures - provider not installed, missing required WHERE parameters, authentication failures, GitHub rate limiting, empty results, and MCP mutation refusals. Source: https://stackql.io/ai/troubleshooting/common-stackql-errors Most StackQL failures fall into five categories: missing providers, missing required parameters, authentication problems, provider-side limits, and gated operations. Each has a fast diagnostic. ## Provider or table not found **Symptom**: a query references `aws.ec2.instances` (or any resource) and fails to resolve the provider or table. **Cause**: provider definitions are not bundled; they are pulled per machine from the registry. **Fix**: ```sql SHOW PROVIDERS; -- what is installed REGISTRY LIST; -- what is available REGISTRY PULL aws; -- install (repeat per provider) ``` Provider versions are also listed by `REGISTRY LIST` - re-pulling upgrades to the latest published spec. ## Missing required parameters **Symptom**: a syntactically valid `SELECT` fails or returns nothing because a required parameter (commonly `region`, `subscriptionId`, `project`, `org`, or a parent resource identifier) was not supplied. **Cause**: the underlying API operation has required routing parameters; StackQL surfaces them as required `WHERE` predicates. **Fix**: discover the requirements, then supply them as equality (or `IN`) predicates: ```sql SHOW METHODS IN aws.ec2.instances; ``` The `RequiredParams` column tells you, per access method, exactly what the `WHERE` clause must contain - for `aws.ec2.instances` the `describe` method requires `region`. This discovery step is the documented practice for both humans and agents (the MCP server publishes the same data through `list_methods`). ## Authentication failures **Symptom**: metadata commands (`SHOW`, `DESCRIBE`) work, but `SELECT` or mutations fail with provider 401/403 errors. **Cause**: metadata is served from local provider specs and needs no credentials; data operations call the provider. The credentials are absent from the process environment, misnamed, or insufficient. **Fix**: verify the variables are exported in the environment that launched StackQL (a server or MCP process inherits its launch environment - restarting it after setting variables is a common miss), the names match the provider convention (`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, `AZURE_TENANT_ID`/`AZURE_CLIENT_ID`/`AZURE_CLIENT_SECRET`, `GOOGLE_CREDENTIALS`, `STACKQL_GITHUB_USERNAME`/`STACKQL_GITHUB_PASSWORD`), and the principal has the permissions the operation needs. The per-provider how-tos under [/ai/how-tos](/ai/how-tos) cover each convention. ## GitHub rate limiting **Symptom**: unauthenticated GitHub queries work briefly, then fail. **Cause**: GitHub's unauthenticated limit is 60 requests per hour per IP, and one StackQL query can issue multiple paginated API calls. **Fix**: authenticate with a personal access token (even a no-scope token raises the limit substantially) - see [How to authenticate StackQL to GitHub](/ai/how-tos/authenticate-stackql-to-github). ## Empty results that should not be empty **Symptom**: the query succeeds but returns zero rows for resources you know exist. **Checklist**: the routing predicates point at the right scope (correct region, project, subscription, or org); the access method selected by your predicates is the one you intended (`SHOW METHODS` shows which predicate combinations select which method - for example `org =` versus `username =` on `github.repos.repos`); and the credential can see the resources (cloud IAM can filter list results silently). ## MCP mutation refused **Symptom**: an agent's `INSERT`/`UPDATE`/`DELETE` through the MCP server is refused, mentioning elicitation or the server mode. **Cause**: this is the safety contract working, not an error. The default `safe` mode requires human approval for mutations; clients that do not advertise the MCP elicitation capability cannot grant it. **Fix**: use an elicitation-capable client (Claude Desktop, Cursor, Continue) and approve the prompt, or - for trusted, non-interactive automation only - run the server with `"mode": "full_access"`. Details in [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture). ## Related concepts - [How to authenticate StackQL to AWS](/ai/how-tos/authenticate-stackql-to-aws) - and the Azure, Google Cloud, and GitHub equivalents - [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - modes and elicitation explained - [Getting started with StackQL](/ai/tutorials/getting-started-with-stackql) - a clean-room setup that avoids most of these - [What is SQL for APIs?](/ai/canonical-definitions/what-is-sql-for-apis) - why required parameters exist - [StackQL FAQ](/ai/faqs/stackql-faq) - broader questions --- # Tutorials > End-to-end walkthroughs - building multi-cloud inventory systems, AI infrastructure agents, governance dashboards, drift detection, and security audits with StackQL. Source: https://stackql.io/ai/tutorials Longer end-to-end walkthroughs that combine multiple StackQL features and providers to build something concrete. ## Pages - [Getting started with StackQL](/ai/tutorials/getting-started-with-stackql) - install, first unauthenticated query, schema discovery, first cloud query --- # Getting started with StackQL > Install StackQL, run your first query against live public GitHub data with no credentials, then authenticate to a cloud provider and explore the discoverable schema with SHOW and DESCRIBE. Source: https://stackql.io/ai/tutorials/getting-started-with-stackql This tutorial goes from installation to live queries in three stages: an unauthenticated query against public GitHub data (no credentials needed), schema discovery with the meta-commands, and an authenticated cloud query against AWS. ## 1. Install macOS (Homebrew): ```bash brew install stackql ``` Linux: ```bash curl -L https://bit.ly/stackql-zip -O && unzip stackql-zip ``` Windows, packages, and Docker images are covered on the [downloads page](https://stackql.io/downloads). Verify with `stackql --version`, then start the interactive shell: ```bash stackql shell ``` ## 2. First query - no credentials required Pull the GitHub provider and query a public organization: ```sql REGISTRY PULL github; SELECT name, description, language, stargazers_count FROM github.repos.repos WHERE org = 'stackql'; ``` The rows that come back - including the `stackql` engine repository itself - are live GitHub API responses relationalized at query time. Nothing was synced, cached, or imported. (Unauthenticated GitHub access is limited to 60 requests per hour; [a personal access token](/ai/how-tos/authenticate-stackql-to-github) raises this.) ## 3. Discover the schema The provider surface is self-describing - this is how you (or an AI agent) learn what is queryable without reading provider documentation: ```sql SHOW PROVIDERS; -- installed providers SHOW SERVICES IN github; -- services in a provider SHOW RESOURCES IN github.repos; -- tables in a service SHOW METHODS IN github.repos.repos; -- operations + required parameters DESCRIBE github.repos.repos; -- columns ``` `SHOW METHODS` is the one to remember: its `RequiredParams` column tells you exactly what each operation needs in the `WHERE` clause, and which SQL verb (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, `EXEC`) invokes it. ## 4. Query a cloud provider Export credentials (AWS shown; [Azure](/ai/how-tos/authenticate-stackql-to-azure) and [Google Cloud](/ai/how-tos/authenticate-stackql-to-google-cloud) are equivalent), pull the provider, and query: ```bash export AWS_ACCESS_KEY_ID=YOURACCESSKEYID export AWS_SECRET_ACCESS_KEY=YOURSECRETACCESSKEY ``` ```sql REGISTRY PULL aws; SELECT instance_id, instance_type, launch_time FROM aws.ec2.instances WHERE region = 'us-east-1'; ``` Aggregations fan out automatically - this runs as parallel per-region API calls: ```sql SELECT region, COUNT(*) as num_instances FROM aws.ec2.instances WHERE region IN ('us-east-1','us-west-2','eu-west-1') GROUP BY region; ``` ## 5. Where to go next - **Mutations**: `SHOW INSERT INTO ` generates creation templates; `INSERT`/`UPDATE`/`DELETE` operate on the same tables you query. - **Server mode**: `stackql srv` exposes the PostgreSQL wire protocol for psql, DBeaver, BI tools, and pandas. - **AI agents**: `stackql mcp` runs the built-in MCP server - see [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents). - **Python**: `pip install pystackql` for notebook and pipeline use. ## Related concepts - [What is StackQL?](/ai/canonical-definitions/what-is-stackql) - the canonical definition - [How to query GitHub repositories with StackQL](/ai/how-tos/query-github-repositories-with-stackql) - the first query, expanded - [How to query AWS EC2 instances with StackQL](/ai/how-tos/query-aws-ec2-instances-with-stackql) - the cloud query, expanded - [Common StackQL errors](/ai/troubleshooting/common-stackql-errors) - if something fails - [StackQL FAQ](/ai/faqs/stackql-faq) - common questions --- ## Documentation # SQL for cloud infrastructure, SaaS APIs and AI agents > StackQL is an open-source engine that lets humans and AI agents query, provision and operate cloud and SaaS services with SQL, with no state file and no per-cloud SDK. Source: https://stackql.io/ ### Agentic Platform Engineering A universal surface for agents and humans to author changes side by side, at machine speed. Multiple writers, live state, and policy-bounded execution as first-class concerns - the foundation autonomous systems need to operate safely. ### IaC for the Agentic Era Code is still intent. Reality is data. StackQL gives agents and operators one declarative interface to query live state across providers, assert desired state idempotently, and traverse control and data planes through a single grammar - no state file, no per-cloud SDK. ### Autonomous Observability Treat cloud APIs as your data layer, not your deployment target. Every read is live, every change is an event, and drift becomes a signal an agent can reason about - not an alarm a human has to chase. **Query** ```sql SELECT state, COUNT(*) as num_instances FROM aws.ec2.instances WHERE region = 'us-west-1' GROUP BY state; ``` **Results** ``` |---------------------------------| | state | num_instances | |---------------------------------| | running | 342 | |---------------------------------| | pending | 4 | |---------------------------------| | stopped | 38 | |---------------------------------| ``` Deploying resources using your cloud provider is as easy as writing an [`INSERT`](/language-spec/insert) statement... ```sql INSERT INTO google.compute.disks (project, zone, name, sizeGb) SELECT 'stackql-demo', 'australia-southeast1-a', 'test10gbdisk', 10; ``` Using StackQL you can develop your way: declarative or procedural. With an easy grammar to learn and no state file to manage, you can get started quickly and use StackQL interchangeably with other infrastructure as code tools, cloud native or otherwise. StackQL provides a universal interface for AI agents to interact with cloud infrastructure. Uses for StackQL include: - **AI Agent Integration** - Enable agents to provision and query cloud resources - **Control Plane Communication** - Programmatic infrastructure provisioning for agentic workflows - **Data Plane Observability** - Real-time monitoring and analytics for AI-driven operations - Cloud infrastructure deployment (using SQL) - Cloud asset inventory and reporting (using SQL) - Cloud compliance and control attestation (using SQL) - Configuration drift detection (using SQL) - and more, only limited by your imagination! ## Who StackQL is for StackQL is for platform engineering and SRE teams that operate cloud estates, security and FinOps teams that need live inventory, compliance and cost answers, data engineers who want cloud and SaaS APIs as queryable sources, and developers building AI agents that must query and change cloud and SaaS resources safely. It runs wherever the work is: as a single binary on macOS, Linux and Windows, in Docker, in CI with GitHub Actions, in the AWS, Azure and Google Cloud shells, embedded in applications, as a PostgreSQL-compatible server for BI tools and notebooks, and as an MCP server for AI agents. ## License and support StackQL is open source under the [MIT License](https://github.com/stackql/stackql/blob/main/LICENSE) and free to use, for any purpose. Community support is through [GitHub Discussions](https://github.com/orgs/stackql/discussions) and [Discord](https://discord.com/invite/xVXZ9d5NxN); bugs and feature requests go to [GitHub Issues](https://github.com/stackql/stackql/issues). For commercial support enquiries, [contact StackQL Studios](/contact-us). ## Get started - [Installation](/installing-stackql) - install the StackQL binary on macOS, Linux or Windows, or run it from Docker, a package manager or a cloud shell - [AI Agents](/ai-agents) - connect AI agents through MCP, embed the server, and explore queries and reference content - [Getting started](/getting-started) - the resource hierarchy, your first queries, using a provider, output modes, variables and templating - [Available providers](/providers) - the cloud and SaaS providers you can query and manage, each with its own reference site - [Blog](/blog) - product announcements, provider announcements and tutorials - [Command line usage](/command-line-usage) - `exec`, `shell`, `srv`, `mcp`, `registry` and the global flags - [MCP tools](/mcp) - the Model Context Protocol server and tools that give AI agents the same SQL interface - [Language specification](/language-spec/select) - `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `SHOW`, `DESCRIBE`, functions and data types --- # AI Agents > Connect AI agents to cloud and SaaS services with StackQL through MCP servers, tools, embedded integrations and SQL queries. Source: https://stackql.io/ai-agents StackQL gives AI agents the same SQL interface people use to query, provision and operate cloud and SaaS services. An agent discovers what a provider exposes, validates a query before it runs, reads live state with `SELECT` and changes it with `INSERT`, `UPDATE` and `DELETE`, with no state file and no per-cloud SDK. ## How agents connect - **MCP over stdio** for editor and desktop clients such as Claude Desktop, Cursor and Continue. The client launches `stackql mcp --mcp.server.type=stdio` itself. See [MCP Server](/command-line-usage/mcp). - **MCP over HTTP** for standalone agents and automation that connect to a long-running `stackql mcp` or `stackql srv` process, with bearer-token authentication and optional TLS. - **Embedded MCP** for compiled applications: the server runs in-process in Go, Rust, Swift, Kotlin, .NET and Gleam. See [Embedded MCP](/mcp/embedded). - **PostgreSQL wire protocol** via [`stackql srv`](/command-line-usage/srv) for agent frameworks, notebooks and BI tools that already speak Postgres. ## Quick start with Claude Desktop Install from the Anthropic Connector Directory (recommended) or the downloadable MCP Bundle, or register the server by hand in `claude_desktop_config.json`: ```json { "mcpServers": { "stackql": { "command": "stackql", "args": ["mcp", "--mcp.server.type=stdio", "--tls.allowInsecure"], "env": { "AWS_ACCESS_KEY_ID": "your-aws-access-key-id", "AWS_SECRET_ACCESS_KEY": "your-aws-secret-access-key" } } } } ``` Include only the credentials for the providers you plan to use. Full instructions, including the bundle downloads and using a credentials file, are in [Using StackQL with Claude Desktop](/getting-started/claude-desktop). ## What an agent can do The MCP server exposes a small, typed tool set. Each tool returns a rendered view for the model and a structured payload for programmatic clients. - **Discover**: `list_providers`, `list_services`, `list_resources`, `list_methods` and `describe_method` walk the provider hierarchy and return the inputs and output fields of each operation, so required `WHERE` parameters are known before a query is written. - **Validate and read**: `validate_select_query` parses and plans a `SELECT` without running it; `run_select_query` executes it. - **Change**: `run_mutation_query` runs `INSERT`, `UPDATE`, `REPLACE` and `DELETE`; `run_lifecycle_operation` runs `EXEC` lifecycle operations. Both are gated by the server mode below. - **Housekeeping**: `server_info`, `list_registry`, `pull_provider` and `reload_credentials`. The full reference, with inputs, gating behaviour and an example prompt per tool, is at [MCP Tools](/mcp). ## Guardrails The server mode sets the safety contract for the whole session: | Mode | `SELECT` / metadata | `INSERT` / `UPDATE` / `REPLACE` | `DELETE` / `EXEC` | |--|--|--|--| | `read_only` | allow | refuse | refuse | | `safe` (default) | allow | needs approval | needs approval | | `delete_safe` | allow | allow | needs approval | | `full_access` | allow | allow | allow | "Needs approval" uses MCP elicitation: clients that support it (Claude Desktop, Cursor, Continue) show the user the tool name, query class and SQL and wait for a decision before anything runs; clients that don't advertise it are refused. Every tool call is written to an audit log, HTTP listeners require a bearer token, and credentials are sourced from the environment or a dotenv file without secret values ever being returned to the client. Details are in [Server modes](/command-line-usage/mcp#server-modes), [HTTP client authentication](/command-line-usage/mcp#http-client-authentication) and [Audit log](/command-line-usage/mcp#audit-log). ## Next steps - [MCP Server](/command-line-usage/mcp) - deployment modes, configuration, server modes, audit log and flags. - [MCP Tools](/mcp) - the full tool reference with inputs, gating and example prompts. - [Embedded MCP](/mcp/embedded) - run the server inside your own Go, Rust, Swift, Kotlin, .NET or Gleam application. - [Query Library](pathname:///docs/query-library/) - ready-to-run SQL for common cloud operations questions, by provider. - [AI Reference](/ai) - concepts, how-tos, comparisons and troubleshooting written for agents and the people who build them. --- # Access Management > Opt-in caller access management for StackQL: authenticate callers with JWT, bearer tokens, mutual TLS or the local OS identity, map them to principals and groups in a directory, and authorise statements with policy rules. Source: https://stackql.io/command-line-usage/access-management Caller access management authenticates the caller of a StackQL session and authorises each statement against a policy. It is independent of provider credentials, which continue to be supplied through `--auth`, environment variables or [provider sessions](/getting-started/provider-sessions). It is disabled by default, and deployments that do not enable it behave as before. Available in StackQL `v1.0` and later. See also: [[ Global Flags ]](/command-line-usage/global-flags) [[` mcp `]](/command-line-usage/mcp) [[` whoami `]](/language-spec/functions/session/whoami) [[` groups `]](/language-spec/functions/session/groups) * * * ## Enabling access management Access management is switched on by starting StackQL with the `--access.config` global flag pointing at a JSON configuration file. The example starts an interactive shell in protected mode; `exec` and `mcp` are enabled the same way. ```bash stackql --access.config '{"path": "/etc/stackql/access.json"}' shell ``` `--access.config` takes a JSON envelope with a single `path` key; a bare file path is also accepted. The configuration is loaded once at startup, so rotate keys or policy through a controlled restart. While access management is enabled only `exec`, `shell`, `mcp` and `version` run; other commands, including `registry`, refuse rather than bypass the protected path. `srv` and the MCP `reverse_proxy` server type also refuse, because the PostgreSQL wire dependency does not yet expose per-connection authentication evidence. The SQL `AUTH` and `AUTH REVOKE` statements refuse in protected mode; provision provider credentials through host configuration instead. A protected `exec` that fails returns exit status `1` after presenting the error. ## Authentication modes The configuration file selects one `type`: `jwt` (the default when omitted), `bearer`, `mtls` or `local_os`. Configuration is strict JSON: unknown fields, and fields belonging to another mode, are rejected. All modes share the same `rules` and the same [principal directory](#principal-directory). ### JWT The caller presents a signed token, which is verified offline against the keys pinned in the configuration. A minimal configuration names the issuer and audience the token must carry, lists one public key, and grants the `readers` group read access: ```json { "type": "jwt", "issuer": "https://identity.example", "audience": "stackql", "keys": [ {"kid": "primary", "algorithm": "EdDSA", "public_key_pem": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n"} ], "rules": [ {"subject": "group:readers", "resource": "host/sql/read", "action": "execute"} ] } ``` The issuer, audience and public keys are pinned in the configuration; there is no OIDC discovery. Accepted algorithms are `EdDSA`, `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, `ES384` and `ES512`, and RSA keys must be at least 2048 bits. Each key is bound to its configured algorithm. Tokens with an unknown key ID, an invalid signature, a missing or past expiry, a future `nbf` or `iat`, or a wrong issuer or audience are rejected. Group claims and URLs carried in the token are not used for trust or directory membership. ### Static bearer token The caller presents an opaque token, and the configuration lists the SHA-256 digest of each accepted token with the subject it identifies. This suits a small, fixed set of service identities where running a token issuer is not warranted: ```json { "type": "bearer", "issuer": "local-tokens", "tokens": [{"subject": "alice", "sha256": "<64 hexadecimal characters: the SHA-256 of the token>"}], "rules": [{"subject": "group:readers", "resource": "host/sql/read", "action": "execute"}] } ``` Only the SHA-256 digest of each token is configured, and digests must be unique. Changing the configured digests requires a restart. ### Mutual TLS The caller is identified by the client certificate it presents on the HTTPS MCP transport. The configuration carries the CA that must have issued the certificate and says which subject alternative name holds the identity: ```json { "type": "mtls", "issuer": "client-certificates", "client_ca_pem": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n", "certificate_identity": "uri_san", "rules": [{"subject": "group:readers", "resource": "host/sql/read", "action": "execute"}] } ``` The client certificate chain is verified against `client_ca_pem` and the identity subject is taken from exactly one SAN of the configured kind, `uri_san` or `dns_san`. There is no Common Name fallback. Mutual TLS is available over the HTTPS MCP transport only. ### Local OS identity No credential is exchanged: the subject is the operating system identity that the StackQL process runs as. The configuration needs only an `issuer` label and the rules: ```json { "type": "local_os", "issuer": "this-host", "rules": [{"subject": "group:readers", "resource": "host/sql/read", "action": "execute"}] } ``` The identity subject is the effective Unix UID or Windows SID of the StackQL process, including numeric container UIDs with no passwd entry. No credential is presented and `STACKQL_CALLER_TOKEN` is ignored. This mode is local only: it is refused for HTTP callers. Operating system group membership does not grant access; only directory membership does. ### Session deadline Queries have no authentication-derived deadline by default. Credentials are verified and directory membership is refreshed for each new statement, so an expired credential cannot start new work, but expiry does not interrupt a statement that is already authorised. Set `"enforce_session_deadline": true` to cancel at `max_session_seconds` (default `300`, maximum `86400`), shortened by JWT or certificate expiry. This does not renew tokens. ## Principal directory Identities are mapped to principals, and principals to groups, in four tables in the configured SQLite or PostgreSQL backend: | Table | Contents | |--|--| | `stackql_access_principals` | Principal ID and a JSON object of string attributes. A `tenant` attribute namespaces preview IaC state. | | `stackql_access_identities` | Verified `(issuer, subject)` pair to principal ID. | | `stackql_access_groups` | Group IDs. | | `stackql_access_memberships` | Principal to group bindings. | Provision the tables, identities and memberships through a trusted database administration connection before serving protected queries: ```sql INSERT INTO stackql_access_principals (id, attributes) VALUES ('alice', '{}'); INSERT INTO stackql_access_groups (id) VALUES ('readers'); INSERT INTO stackql_access_identities (issuer, subject, principal_id) VALUES ('https://identity.example', 'alice', 'alice'); INSERT INTO stackql_access_memberships (principal_id, group_id) VALUES ('alice', 'readers'); ``` Use the mode's actual issuer and subject: for local OS identity this might be `('this-host', '1000')`, and for mutual TLS `('client-certificates', 'spiffe://example/alice')`. Select the backend explicitly: ```bash stackql --access.config '{"path":"/etc/stackql/access.json"}' \ --sqlBackend '{"dbEngine":"postgres_tcp","dsn":"postgres://runtime@localhost/stackql?sslmode=require","sqlDialect":"postgres"}' \ exec 'SELECT whoami(), groups();' ``` The directory produces an immutable snapshot for each statement. Revocation is a `DELETE FROM stackql_access_memberships` on the administration connection; the next statement sees the new snapshot. Unknown identities, an absent schema, malformed data and directory outages all deny access. Ordinary protected SQL cannot address the directory tables. Keep membership writes on the administration connection, protect the database file, and use separate administrative and runtime database privileges where the backend supports them. ## Policy rules Each rule grants one `action` on one `resource` to a `subject` of the form `group:`. Use the compiled method and operation identifiers from trusted provider documents; an operation wildcard grants mutation methods as well as reads. The `readers` group implicitly holds the host's safe-read SQL capability. Reads by principals outside that group require `host/sql/read`, and other statements require `execute` on `host/sql/`. Provider operations and credential use always require explicit rules, and a collection grant does not grant its underlying methods. Additional host checks: | Resource | Action | Scope | |--|--|--| | `host/sql/read` | `execute` | Read statements outside the implicit reader group | | `host/sql/exec` | `execute` | Native `EXEC`, including nested `EXEC` | | `host/iac/run`, `host/iac/destroy` | `execute` | The preview IaC relations, despite their `SELECT` syntax | | `host/function/` | `execute` | Functions outside the small allowlist of known-pure functions | | `host/backend` | `read` | Opaque stored and external backend relations | | `host/credentials` | `reload` | The MCP `reload_credentials` tool | | `session/variables` | `read` | Dereferencing [session variables](/getting-started/session-variables) and secrets | | `session/config` | `write` | `SET` and `UNSET` | Stored query expansion is checked before execution, and plan and row cache reuse is disabled on protected paths. ## Entry points | Authentication | `exec`, `shell`, MCP stdio | HTTPS MCP | |--|--|--| | JWT | `STACKQL_CALLER_TOKEN` environment variable | `Authorization: Bearer` request header | | Static bearer | `STACKQL_CALLER_TOKEN` environment variable | `Authorization: Bearer` request header | | Local OS | Effective process UID or SID; no credential | Refused | | Mutual TLS | Refused: no verified TLS connection | Verified client chain and one configured SAN | Supply local token credentials through the process environment, never as a SQL literal or a command-line argument. Over HTTPS the caller verifier replaces the shared `auth_token_env_var` bearer gate described in [HTTP client authentication](/command-line-usage/mcp#http-client-authentication); server TLS certificate and key configuration is mandatory, and a request without credentials never falls back to the server's environment token. ## Inspecting the caller In an authenticated session, `whoami()` returns the principal ID and `groups()` returns the directory groups as a JSON array: ```sql SELECT whoami() AS principal, groups() AS memberships; ``` ``` |-----------|-------------| | principal | memberships | |-----------|-------------| | alice | ["readers"] | |-----------|-------------| ``` Both functions require a session started with `--access.config`. ## Walkthroughs The StackQL repository ships [four executable walkthroughs](https://github.com/stackql/stackql/blob/main/docs/examples/access-management/README.md), one per authentication mode, driven by a Python script that provisions a demonstration directory and verifies a query. They need no cloud account and are run by the project's test suite. --- # exec > The stackql exec command runs one StackQL statement or a script of statements, with flags for output format, authentication and the provider registry. Source: https://stackql.io/command-line-usage/exec Command used to run a StackQL query, either as a statement or as a batch of statements from an StackQL script (IQL File). * * * ### Syntax `stackql exec [query] [flags]` * * * ### Arguments | Argument | Description | Example | |--|--|--| |`query`|StackQL query to be performed or command to be executed | `"SELECT * FROM google.compute.instances` `WHERE project = 'myproject' AND zone = 'us-east1-a'"` _Note that the query must be enclosed in single or double quotes_ | ### Flags | Flag | Description | |--|--| |`-o` `--output`|Output mode, valid values include: `table`(default) `json`, `jsonl` (newline delimited JSON, `ndjson` is accepted as an alias), `csv`, `text` and `otel` (OpenTelemetry log records, see [Output Modes](/getting-started/output-modes#otel-output)), example: `--output jsonl` | |`-i` `--infile`|Run query from the specified file if required, if specified any query provided as an argument will be ignored, example: `--infile myquery.iql` | |`-q` `--iqldata`|Source data for the command using a `json` or `jsonnet` file, example: `--iqldata vars.jsonnet`| |`--dryrun`|Dry run flag; preprocessor only will run and output will returned | |`--var`|External variables (can be environment vars or secrets) sourced by jsonnet files specified using the `--iqldata` flag, example `--var region=${AWS_REGION}`| |`-f` `--outfile`|File to output results to if required (default behavior is to output results to the console only), example `--outfile myoutput.csv`| |`-H` `--help`|Print help information| |`-v` `--verbose`|Run queries in verbose mode with additional output sent to stdout, if the `-f` option is selected this additional logging information will be written to the output file along with the query results| > see [Global Flags](/command-line-usage/global-flags) for additional options * * * ### Examples Output query results to the console in table format: ```shell stackql exec "SHOW services IN google" ``` Output query results to the console in json format: ```shell stackql exec "SHOW services IN google" -o json ``` Output query results to a file in json format: ```shell stackql exec "SHOW services IN google" -o json -f services.json ``` Execute query from an input file (IQL File) outputting the results to a file in json format: ```shell stackql exec -i getservices.iql -o json -f services.json ``` * * * ### Exit status `exec` exits with status `0` once the input has been processed; errors from individual statements are written to the console, so scripts should inspect the output. From `v1.0` it exits with status `1` when a [`SET`](/language-spec/set) or [`UNSET`](/language-spec/unset) configuration statement fails, when [access management](/command-line-usage/access-management) is enabled and a statement is refused, or when a preview IaC run reports a failed resource. --- # Global Flags > Global flags for the stackql binary: authentication, output format, registry location, logging and SQL backend settings, available on every command. Source: https://stackql.io/command-line-usage/global-flags Global flags specify runtime program behavior for the StackQL application, these flags are set at the command line when the StackQL application is launched (in either the interactive/shell mode or non-interactive exec mode) or are sourced from the StackQL initialization ([`.stackqlrc`](/getting-started/using-stackql#the-stackqlrc-initialization-file)) file. Flags include: | Flag | Data Type | Description | Default | | -- | -- | -- | -- | | `--access.config` | string | Caller access configuration, a JSON envelope `{"path": "/path/to/access.json"}` (a bare file path is also accepted). Enables [access management](/command-line-usage/access-management): callers are authenticated by JWT, static bearer token, mutual TLS or local OS identity and statements are authorised against policy rules. Local token credentials are read from `STACKQL_CALLER_TOKEN`. Available in StackQL releases from `v1.0`. | | | `--acid` | string | JSON / YAML string representing ACID config | `{}` | | `--allow-persistent-secrets` | flag | Allow a session to select a persistent OS secret store (macOS Keychain, Linux Secret Service or Windows Credential Manager) with `SET "$.secret_store"`. Flat-file stores are refused even with the flag. See [Provider Sessions and Secrets](/getting-started/provider-sessions#persistent-os-secret-stores). Available in StackQL releases from `v1.0`. | `false` | | `--allow-secret-dereference` | flag | Allow secret and credential values to be dereferenced in SQL expressions (`"$secrets.name"`, `"$auth.provider.field"`), with the consequence that they can enter results, logs and persisted query artefacts. Not needed for normal provider authentication. See [Secret values in SQL](/getting-started/provider-sessions#secret-values-in-sql). Available in StackQL releases from `v1.0`. | `false` | | `--apirequesttimeout` | integer | API request timeout in seconds, 0 for no timeout | `45` | | `--approot` | string | Application config and cache root path | `{cwd}/.stackql` | | `--approotfilemode` | uint32 | Application config and cache file mode | `493` | | `--auth` | string | `auth` context keyvals in json form | | | `--cachekeycount` | integer | Cache initial key count | `100` | | `--configfile` | string | Config file full path | `{cwd}/.stackqlrc` | | `--cpuprofile` | string | `cpuprofile` file, none if empty | `null` | | `--dataflow.dependency.max` | int | Maximum dataflow dependency depth for a given query | `50` | | `--dataflow.components.max` | int | Maximum dataflow weakly connected components for a given query | `50` | | `--dbInternal` | string | JSON / YAML string to configure DBMS housekeeping query handling | `{}` | | `-d`, `--delimiter` | string | Delimiter for csv output. Single char only.  Ignored for all non-csv output | `,` | | `--dryrun` | flag | `dryrun` flag; run preprocessor only, templated output will be returned | `false` | | `--env.file` | string | Optional dotenv-style file sourced into the process environment at startup (all commands); the MCP [`reload_credentials`](/mcp/reload_credentials) tool re-sources it on demand. A missing file is tolerated; keys with empty values are skipped; existing variables are overwritten. Not sourced from `.stackqlrc`. Available in StackQL releases after `v0.10.542`. | `null` | | `--execution.concurrency.limit` | int | Concurrency limit for query execution | `1` | | `--export.alias` | string | Export alias prefix (namespace or schema) | | | `--gc` | string | JSON / YAML string representing GC config | `{}` | | `-H`, `--hideheaders` | flag | Disables column headers, valid only with `--output csv` or `--output text` | `false` | | `--http.log.enabled` | flag | Display http request info in terminal | `false` | | `--http.proxy.host` | string | Proxy host (leave blank for no proxy) | `null` | | `--http.proxy.password` | string | Proxy password | `null` | | `--http.proxy.port` | integer | Proxy port, any number less than or equal to 0 will result in the default port for a given scheme (e.g. `http -> 80`) | `-1` | | `--http.proxy.scheme` | string | Proxy scheme, `http` or `https` | `http` | | `--http.proxy.user` | string | Proxy user | `null` | | `--http.response.maxResults` | integer | Maximum results per http request, any number less than or equal to 0 results in no limitation | `-1` | | `--http.response.pageLimit` | integer | Maximum pages of results that will be returned per resource, any number less than or equal to results in no limitation | `20` | | `--indirect.depth.max` | integer | Maximum depth for indirect queries: views and subqueries | `5` | | `-i`, `--infile` | string | Input file (IQL file) from which queries are read | `{stdin}` | | `-q`, `--iqldata` | string | Context (data) file for templating (`json` or `jsonnet` file)| | | `--loglevel` | string | Log level, must be one of | `fatal` | | `--mcp.config` | string | JSON / YAML configuration object for the [MCP server](/command-line-usage/mcp#mcp-configuration-object) (`stackql mcp` and `stackql srv`) | `{}` | | `--mcp.log.format` | string | MCP audit log encoding, `jsonl` or `otel` (OTLP/JSON log records); overrides `server.audit.format` in `--mcp.config`. See [Log format](/command-line-usage/mcp#log-format). Available in StackQL releases from `v0.11.660`. | `jsonl` | | `--mcp.protocol.version` | string | Newest MCP protocol revision advertised, `auto`, `2026-07-28` (sessionless only) or an older revision such as `2025-11-25`; overrides `server.protocol_version` in `--mcp.config`. See [Pinning the revision](/command-line-usage/mcp#pinning-the-revision). Available in StackQL releases from `v0.12.732`. | `auto` | | `--mcp.server.type` | string | MCP server type, one of . See [MCP server type](/command-line-usage/mcp#mcp-server-type). | `http` | | `--metadatattl` | integer | TTL for cached metadata documents, in seconds | `3600` | | `--namespaces` | string | JSON / YAML string representing namespaces for caching, views etc | `{}` | | `--offline` | flag | Work offline, using cached data | `false` | | `-f`, `--outfile` | string | Output file into which results are written | `{stdout}` | | `-o`, `--output` | string | Output format, must be one of (`ndjson` is accepted as an alias for `jsonl`). `otel` emits OpenTelemetry log records, see [Output Modes](/getting-started/output-modes#otel-output); available in StackQL releases from `v0.11.660`. With an exporter configured in `--otel.config`, `otel` records are also pushed to that endpoint | `table` | | `--otel.config` | string | JSON / YAML string configuring the `otel` output format; `exporter.endpoint`, `exporter.headers`, `exporter.timeout_ms` and `exporter.batch_size` push the records to an OTLP/HTTP logs endpoint, see [Pushing to an OTLP endpoint](/getting-started/output-modes#pushing-to-an-otlp-endpoint). Available in StackQL releases from `v0.12.732` | `{}` | | `--preview` | string | JSON string enabling preview functionality. `{"unstable": true}` exposes the document-driven `stackql_unstable_..` relations, which are resolved and run by `omnisdk` straight from the provider documents with rows streamed as they are produced; the remaining keys (`batchSize`, `flushInterval`, `endpoint`, `insecureSkipTLSVerify`) tune that backend. Preview functionality is not stable: behaviour, syntax and output may change or break between releases without notice, so do not rely on it in production. From `v1.0` the same opt-in exposes the `stackql_preview.iac.run` and `stackql_preview.iac.destroy` relations, which apply and tear down a declared resource set through `omnisdk` with state kept under the application root. See [Preview functionality](https://github.com/stackql/stackql/blob/main/docs/preview.md) | `{}` | | `--querycachesize` | integer | Size in number of entries of LRU cache for query plans | `10000` | | `--registry` | string | JSON / YAML string configuring the provider registry location and provider document signature verification | see [`--registry`](#--registry) | | `--session` | string | JSON / YAML string representing session config | `{}` | | `--sqlBackend` | string | JSON / YAML string representing SQL Backend System Config | see [`--sqlBackend`](#--sqlbackend) | | `--store.txn` | string | JSON / YAML string representing Txn store config | `{}` | | `--tls.CABundle` | string | Path to CA bundle, if not specified then system defaults used | | | `--tls.allowInsecure` | flag | Allow trust of insecure certificates (not recommended) | | | `--var` | string | External variables provided as key/value pairs for sourcing into StackQL queries through `jsonnet` data files | | | `-v`, `--verbose` | flag | Verbose output | `false` | | `-h`, `--help` | | Context specific help for stackql | | | `--version` | | Displays the version of the StackQL program | | ## `--registry` The `--registry` flag configures where provider documents are read from and whether their signatures are verified. The value is a JSON string with the following keys: | Key | Description | Default | | -- | -- | -- | | `url` | Registry URL. The public StackQL provider registry is used when omitted. | public registry | | `localDocRoot` | A local directory holding provider documents, read in place of downloading from the registry. Used when [developing a provider](/developers/developing-stackql-providers#testing-a-provider-locally). | | | `srcPrefix` | Path prefix under the registry root where provider source documents live. | `src` | | `verifyConfig.nopVerify` | `true` skips signature verification. Set to `false` to require an embedded ML-DSA-65 (FIPS 204) signature on every provider and service document read, including the document-backed preview relations. | `true` | | `verifyConfig.publicKeys` | A JSON object mapping key IDs to hex-encoded ML-DSA-65 public keys, for private registries. It replaces the embedded production keys; an explicit empty object is an error. | embedded keys | ### Example: Require signed provider documents Turns verification on for every provider and service document read from the public registry, checked against the embedded production keys: ```bash stackql --registry '{"verifyConfig": {"nopVerify": false}}' shell ``` ### Example: Read unsigned documents from a local directory Points the registry at a directory of provider documents under development. Those documents are unsigned, so verification stays off: ```bash stackql --registry '{"localDocRoot": "/path/to/provider-dev/openapi", "verifyConfig": {"nopVerify": true}}' shell ``` :::note Signature verification is available in StackQL releases from `v1.0` and is off by default. Signatures cover the exact YAML bytes of a document, so any edit, including a formatting or newline change, invalidates them; re-sign with the registry's `pqsig sign-doc` tool. Unsigned local development documents must keep `nopVerify: true`. The former certificate options and `.sig` sidecar files are no longer used, and archives published with sidecars only must be republished before verified use. Verification authenticates documents when they are read; archive download and extraction are not covered. ::: ## `--sqlBackend` The `--sqlBackend` flag configures an external SQL backend for StackQL, allowing you to use an external database engine (such as PostgreSQL) instead of the default embedded SQL engine. This is useful for leveraging an external database for query processing, persistent storage, or integration with existing database infrastructure. The value is a JSON string with the following keys: | Key | Description | Example Values | | -- | -- | -- | | `dbEngine` | The database engine type | `postgres_tcp` | | `sqlDialect` | The SQL dialect to use | `postgres` | | `dsn` | The data source name (connection string) for the database | See examples below | ### Example: Using a PostgreSQL Backend ```bash ./stackql \ --sqlBackend='{"dbEngine": "postgres_tcp", "sqlDialect": "postgres", "dsn": "postgres://user:password@hostname:port/dbname?sslmode=require"}' \ shell ``` ### Example: Using Databricks PostgreSQL Interface Databricks exposes a PostgreSQL-compatible interface that can be used as a StackQL SQL backend. The DSN uses the standard PostgreSQL connection string format with your Databricks credentials: ```bash ./stackql \ --sqlBackend='{"dbEngine": "postgres_tcp", "sqlDialect": "postgres", "dsn": "postgres://user%40domain.com:your-access-token@your-databricks-host.cloud.databricks.com/databricks_postgres?sslmode=require"}' \ shell ``` :::note Special characters in the username or password (such as `@`) must be URL-encoded in the DSN (e.g., `@` becomes `%40`). ::: --- # mcp > The stackql mcp command runs StackQL as a Model Context Protocol server for AI agents: deployment modes, safety modes, credential reloading and the audit log. Source: https://stackql.io/command-line-usage/mcp Command used to launch StackQL as a Model Context Protocol (MCP) server, enabling AI agents and assistants to interact with cloud infrastructure using StackQL's query capabilities. :::info[What is MCP?] The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) is an open protocol that standardizes how AI applications interact with external data sources and tools. By running StackQL as an MCP server, you can enable AI agents (Claude, Cursor, Continue, custom agents, etc) to query and manage cloud infrastructure across multiple providers using natural language. ::: * * * ### Syntax `stackql mcp [flags]` for a standalone MCP server. `stackql srv [flags]` to run the MCP server alongside the PostgreSQL wire-protocol server in the same process. * * * ### Deployment modes StackQL's MCP server can be deployed in three different configurations to suit various architectural requirements. The examples below opt into unauthenticated service with `"allow_unauthenticated": true`, which suits local development; for anything another process or host can reach, configure a bearer token instead (see [HTTP client authentication](#http-client-authentication)). #### 1. Standalone MCP server Run StackQL as a dedicated MCP server on a specified port. ```bash stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true}}' ``` **Use case:** when you only need MCP protocol access and don't require PostgreSQL wire protocol compatibility. #### 2. MCP + PostgreSQL server (in-memory) Run both MCP and PostgreSQL servers simultaneously with in-memory communication between them. ```bash stackql srv \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true}}' \ --pgsrv.port 5665 ``` **Use case:** when you need both MCP protocol access for AI agents and PostgreSQL wire protocol for traditional database clients, with maximum performance through in-memory communication. #### 3. MCP + PostgreSQL server (reverse proxy) Run both servers with TCP-based communication, supporting distributed deployments and TLS encryption. ```bash stackql srv \ --mcp.server.type=reverse_proxy \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9004", "allow_unauthenticated": true}, "backend": {"dsn": "postgres://stackql:stackql@127.0.0.1:5446?default_query_exec_mode=simple_protocol"}}' \ --pgsrv.port 5446 ``` **With TLS encryption:** ```bash stackql srv \ --mcp.server.type=reverse_proxy \ --mcp.config '{"server": {"tls_cert_file": "/path/to/server_cert.pem", "tls_key_file": "/path/to/server_key.pem", "transport": "http", "address": "127.0.0.1:9004", "auth_token_env_var": "STACKQL_MCP_TOKEN"}, "backend": {"dsn": "postgres://stackql:stackql@127.0.0.1:5446?default_query_exec_mode=simple_protocol"}}' \ --pgsrv.port 5446 ``` TLS encrypts the transport but does not authenticate the client, so this example also requires the bearer token held in `STACKQL_MCP_TOKEN`. **Use case:** when you need to separate MCP and PostgreSQL workloads across different processes or hosts, or when you require TLS encryption for the MCP endpoint. * * * ### Configuration options #### MCP server type | Type | Description | |--|--| |`http`|Direct HTTP server mode -- MCP requests are handled in-process by the StackQL engine.| |`reverse_proxy`|Reverse-proxy mode -- MCP requests are dispatched to a backing PostgreSQL server via the configured DSN. Used with `stackql srv`.| |`stdio`|Standard input/output transport -- the server reads requests from `stdin` and writes responses to `stdout`. Used by editor-embedded MCP clients (Claude Desktop, Cursor, etc).| #### MCP log format The `--mcp.log.format` flag selects the audit log encoding: `jsonl` (default) or `otel` (OpenTelemetry OTLP/JSON log records). It overrides `server.audit.format` in the configuration object. See [Log format](#log-format). #### MCP protocol version The `--mcp.protocol.version` flag sets the newest protocol revision the server advertises: `auto` (default, every supported revision), `2026-07-28` (sessionless only) or an older revision such as `2025-11-25` (that revision and earlier). It overrides `server.protocol_version` in the configuration object. See [Pinning the revision](#pinning-the-revision). #### MCP configuration object The `--mcp.config` flag accepts a JSON object with the following structure. ##### Server configuration | Field | Description | Required | |--|--|--| |`server.transport`|Transport protocol -- `http` or `stdio`.|Yes| |`server.address`|Address and port to bind the MCP server (e.g., `127.0.0.1:9912`). HTTP transport only.|For `http`| |`server.tls_cert_file`|Path to TLS certificate file for HTTPS.|No| |`server.tls_key_file`|Path to TLS private key file for HTTPS.|No| |`server.auth_token_env_var`|Name of an environment variable holding a pre-shared bearer token. When set, every HTTP request must carry `Authorization: Bearer `; the server refuses to start if the variable is unset or empty. See [HTTP client authentication](#http-client-authentication).|One of this or `allow_unauthenticated`, for `http`| |`server.allow_unauthenticated`|Explicit opt-in to serve the HTTP transport with no client authentication. Default `false`.|One of this or `auth_token_env_var`, for `http`| |`server.mode`|Safety contract that gates mutation and lifecycle operations. One of `read_only`, `safe` (default), `delete_safe`, `full_access`. See [Server modes](#server-modes).|No| |`server.read_only`|**Legacy** boolean alias for `mode: read_only`. When both fields are set, `mode` wins.|No| |`server.stateless`|Serve Streamable HTTP without sessions (no `Mcp-Session-Id`), which is how protocol revision `2026-07-28` is served over HTTP. Default `false`. Ignored for `stdio`. See [Protocol revision support](#protocol-revision-support).|No| |`server.protocol_version`|Newest protocol revision advertised: `auto` (default), `2026-07-28` or an older revision such as `2025-11-25`. `2026-07-28` implies `stateless` for Streamable HTTP. See [Pinning the revision](#pinning-the-revision).|No| |`server.audit`|Audit subsystem configuration, including `audit.format` (`jsonl` or `otel`). See [Audit log](#audit-log).|No| ##### Backend configuration (reverse-proxy mode only) | Field | Description | Required | |--|--|--| |`backend.dsn`|PostgreSQL connection string for the backend StackQL server.|Yes (for `reverse_proxy`)| :::info The backend DSN should include the `default_query_exec_mode=simple_protocol` parameter for optimal compatibility. ::: ##### Allowlists | Field | Description | |--|--| |`enabled_tools`|Array of tool names that the server is permitted to publish. When omitted or empty, every built-in tool is registered. Used to expose a narrow subset (e.g., a read-only inventory server).| |`enabled_prompts`|Array of prompt names. Same semantics as `enabled_tools` but for the prompt surface.| Example -- a server that publishes only `server_info` and `list_providers`: ```json { "server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true}, "enabled_tools": ["server_info", "list_providers"] } ``` * * * ### Protocol revision support Protocol revision `2026-07-28`, `server.stateless` and the `otel` audit log format are available in StackQL releases from `v0.11.660`. `server.protocol_version` and the `--mcp.protocol.version` flag are available in StackQL releases from `v0.12.732`. The server speaks every revision of the Model Context Protocol supported by the [Go MCP SDK](https://github.com/modelcontextprotocol/go-sdk) and negotiates per client, so a fleet of mixed clients works against one server. | Revision | Lifecycle | Approval prompt (`safe` / `delete_safe`) | |--|--|--| |`2026-07-28` (advertised)|No handshake: `server/discover`, then every request carries `io.modelcontextprotocol/protocolVersion` and `io.modelcontextprotocol/clientCapabilities` in `_meta` (plus the `Mcp-Protocol-Version`, `Mcp-Method` and `Mcp-Name` headers on HTTP).|`input_required` result, retried by the client with `inputResponses` (SEP-2322).| |`2025-11-25`, `2025-06-18`|`initialize` / `notifications/initialized` handshake.|Server-initiated `elicitation/create` request.| |`2025-03-26`, `2024-11-05`|As above.|As above.| **stdio** serves every revision on one process: a `2026-07-28` client's first request is served without a handshake and an older client's `initialize` still works. Nothing needs configuring for Claude Desktop, the npm / PyPI launchers or the Docker image. **Streamable HTTP** defaults to the stateful, session-per-client model (`Mcp-Session-Id`), which the SDK serves for revisions up to `2025-11-25`. A `2026-07-28` request is answered with JSON-RPC error `-32022` (unsupported protocol version; a plain HTTP 400 in releases up to `v0.12.718`) whose `data.supported` lists the handshake revisions, and `server/discover` advertises the same, so the client negotiates down and existing HTTP integrations keep their sessions and their approval prompts unchanged. Set `server.stateless` (or pin the revision to `2026-07-28`, [below](#pinning-the-revision)) to serve `2026-07-28` natively over HTTP: ```bash stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true, "stateless": true}}' ``` A sessionless server issues no `Mcp-Session-Id`, answers `GET` and `DELETE` with 405 (there is no session to tear down), keeps `tools/list`, `prompts/list` and `resources/list` connection-invariant, and runs the approval round trip through `input_required`. It still accepts an older client's `initialize` and serves reads to it, but it cannot retain the elicitation capability that client declared at initialise (each request gets an ephemeral session), so older clients cannot approve gated writes on a sessionless server. Choose `stateless` for current-revision hosts and the default for a fleet that still includes older clients. The server holds no cross-call state: mode, audit and provider credentials are process-level configuration, so nothing needs to move behind explicit handles. #### Pinning the revision By default the server advertises every supported revision and negotiates per client. The `--mcp.protocol.version` flag, or `server.protocol_version` in the configuration object (the flag wins), sets the newest revision advertised: ```bash # sessionless only; stateless Streamable HTTP is implied stackql mcp \ --mcp.server.type=http \ --mcp.protocol.version=2026-07-28 \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true}}' # handshake lifecycle only stackql mcp --mcp.server.type=stdio --mcp.protocol.version=2025-11-25 ``` | Value | Advertised | Effect | |--|--|--| |`auto` (default) or absent|Every supported revision.|Negotiation as above: the highest revision both sides speak.| |`2026-07-28`|`2026-07-28` only.|Sessionless only, and `stateless` is implied for Streamable HTTP. An older client's `initialize` is answered with `2025-11-25`, the cue for that client to disconnect rather than read the answer as the new lifecycle.| |`2025-11-25` (or any older revision)|That revision and everything before it.|Handshake lifecycle only: a `2026-07-28` request gets JSON-RPC error `-32022` with `data.supported` listing the advertised revisions, so the client can renegotiate. Older handshake clients keep their own revision.| Any other value fails configuration validation at startup, and the error names the legal values. #### Transport limits Streamable HTTP request bodies are capped at 4 MiB (HTTP 413 beyond it), JSON nested deeper than 1000 levels is rejected before parsing, and a single `stdio` frame is capped at 8 MiB. None of these limits is configurable; all sit far above any SQL statement the server accepts. * * * ### Credential (re)sourcing (`--env.file` + `reload_credentials`) :::note `--env.file` and the `reload_credentials` tool are available in StackQL releases after `v0.10.542`. ::: A process environment block is fixed at spawn. This creates two problems for MCP servers: - An MCP `stdio` server spawned by a desktop client (Claude Desktop, Cursor, etc) without the credential environment variables can never see them - the client passes its own environment to the subprocess. - Rotated short-lived credentials never reach a long-running server session. The `--env.file` flag bridges both gaps by nominating a dotenv-style file that acts as a mutable credential store: ```bash stackql mcp --mcp.server.type=stdio --env.file /path/to/stackql-credentials.env ``` #### Sourcing semantics The file is sourced into the process environment at startup for every entrypoint (`exec`, `shell`, `srv`, `registry`, `mcp`): - When the flag is empty or unset, nothing happens - credentials resolve lazily from the process environment at request time, exactly the historical behaviour. - A missing file at the given path is a tolerated no-op (the file may be created later). - A malformed or unreadable file is fatal at startup. - Only keys with non-empty values are set; existing process environment variables **are** overwritten (the file is the source of truth); nothing is ever unset. - The flag is command line only - it is not sourced from `.stackqlrc`. The file format is one `KEY=VALUE` per line. `#` comments, blank lines, an optional `export ` prefix, optional single or double quotes around the value, and CRLF line endings are all tolerated: ```bash # stackql-credentials.env export OKTA_SECRET_KEY="00abc...xyz" STACKQL_GITHUB_USERNAME=myuser STACKQL_GITHUB_PASSWORD='ghp_mytoken' ``` #### `reload_credentials` The [`reload_credentials`](/mcp/reload_credentials) tool re-sources the `--env.file` file into the process environment mid-session, then reports per-provider credential resolution status. Secret values are never returned, logged, or audited - names and statuses only. Without `--env.file` configured the tool degrades to a pure status probe. When a query fails on credential resolution, the MCP error carries a hint directing the agent to call `reload_credentials` and retry, so agentic clients self-heal: write the credential to the file, ask the agent to reload, and the failed query succeeds on retry - no server restart required. `reload_credentials` is not supported in `reverse_proxy` backend mode - queries execute in the remote stackql server process, so the tool returns an error directing the user to reload on the backing server. #### Windows and Claude Desktop `setx` writes the registry, not running processes, and Claude Desktop passes its own (stale) environment to MCP subprocesses - so credential changes normally require a full Claude Desktop restart. With `--env.file` the credentials file can be created or rotated at any time and `reload_credentials` picks it up without any restart. See [Using StackQL with Claude Desktop](/getting-started/claude-desktop) for a worked configuration. * * * ### HTTP client authentication :::note `server.auth_token_env_var` and `server.allow_unauthenticated` are available in StackQL releases from `v0.12.742`. ::: The HTTP transport requires client authentication. `server.auth_token_env_var` names an environment variable holding a pre-shared bearer token; every request must carry `Authorization: Bearer ` or it is answered with `401`. The token is read from the environment, so it never appears in `--mcp.config` or the process arguments. ```bash export STACKQL_MCP_TOKEN="$(openssl rand -hex 32)" stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "auth_token_env_var": "STACKQL_MCP_TOKEN"}}' ``` :::info[Server Authentication Required] Serving without a token is an explicit opt-in: set `"allow_unauthenticated": true` in `server`. With neither key the server exits at startup with a message naming both; it also exits if the token variable is unset or empty. As of the `v0.12.742` release you must add either `auth_token_env_var` or `"allow_unauthenticated": true` to `server` when using the `http` transport. ::: TLS (`tls_cert_file` / `tls_key_file`) encrypts the transport but does not authenticate the client; combine it with a token for any listener beyond loopback. Cross-origin browser requests (a mismatched `Origin`, or a cross-site `Sec-Fetch-Site`) are refused with `403` regardless of authentication. The bundled `stackql_mcp_client` sends no `Authorization` header, so a server it drives must opt into unauthenticated service. From `v1.0`, starting the server with [`--access.config`](/command-line-usage/access-management) replaces the shared token gate with per-caller authentication: each HTTPS request is verified with the configured JWT, static bearer or mutual TLS scheme and authorised against policy rules. Server TLS is mandatory in that case, `local_os` authentication is refused over HTTP, and a request without credentials never falls back to the server's environment token. Access management is not available with the `reverse_proxy` server type. * * * ### Server modes `server.mode` chooses one of four safety contracts. All four allow `SELECT` and metadata reads; they differ in how they handle mutations and lifecycle operations. | Mode | `SELECT` / metadata | `INSERT` / `UPDATE` / `REPLACE` | `DELETE` | `EXEC` (lifecycle) | |--|--|--|--|--| |`read_only`|allow|refuse|refuse|refuse| |`safe` (default)|allow|needs approval|needs approval|needs approval| |`delete_safe`|allow|allow|needs approval|needs approval| |`full_access`|allow|allow|allow|allow| **Refuse** returns an error immediately to the client. **Needs approval** uses the MCP elicitation flow, shaped by the negotiated [protocol revision](#protocol-revision-support): - If the client advertised the elicitation capability (at initialise, or in the per-request `_meta` client capabilities on `2026-07-28`), the server asks the user to approve the action with a short message (tool name, query class, SQL). On `2026-07-28` the prompt is returned as an `input_required` result carrying an `elicitation/create` input request under the id `stackql_approval`, and the client retries the call with the answer in `inputResponses`; on earlier revisions the server sends the `elicitation/create` request itself mid-call. The user accepts, declines, or cancels. - If the client did **not** advertise elicitation, the tool is refused with a message that explains the gap and points the operator at `full_access` mode. Approval is answered by the client, so it guards against an agent acting without its user, not against an untrusted caller. Pair the HTTP transport with [client authentication](#http-client-authentication) where callers are not trusted. The mode is global per server. There is no per-tool override. From `v1.0`, [`run_select_query`](/mcp/run_select_query) refuses `INSERT`, `UPDATE`, `REPLACE`, `DELETE` and `EXEC` in every mode, including `full_access`; the error names `run_mutation_query` or `run_lifecycle_operation`. Every tool also carries a `title` and the four MCP behavioural hints as explicit booleans (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`), derived from the same classification the policy gate enforces. `openWorldHint` is `true` for `list_registry`, `pull_provider`, `run_select_query`, `run_mutation_query` and `run_lifecycle_operation`, which reach registry or provider endpoints, and `false` for tools that read local state only. The hints are advisory for client UX; enforcement stays with the policy gate. :::info[Payload Gating] From release `v0.12.742`, a payload holding several statements is gated by its most privileged statement in every mode, so `SELECT 1; DELETE ...` is treated as a `DELETE` and the audit record carries `query_class` `mutation_delete`. `validate_select_query` accepts exactly one statement. ::: #### Default-mode behaviour change Prior releases enforced safety only through a single `read_only: true/false` flag whose default was "no enforcement". The current default (`mode: safe`) makes mutations require user approval out of the box. Operators running an elicitation-capable client (Claude Desktop, Cursor, Continue, etc) will see one approval prompt per mutation. Operators running automation, or the bundled `stackql_mcp_client` (which does not advertise elicitation), must explicitly opt into `mode: full_access` to run mutations and lifecycle operations. The legacy `read_only: true` JSON / YAML key is still accepted for back-compat and is treated as equivalent to `mode: read_only`. #### Examples ```bash # Read-only: SELECTs proceed; mutations and lifecycle refused immediately. stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true, "mode": "read_only"}}' # Delete-safe: INSERT/UPDATE proceed; DELETE and EXEC need approval. stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true, "mode": "delete_safe"}}' # Full access: everything proceeds without prompting. Use only with trusted # clients and operators. stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true, "mode": "full_access"}}' ``` * * * ### Audit log Every tool call writes one record to the configured audit sink, as JSONL by default or as OpenTelemetry log records (see [Log format](#log-format)). Audit is **on by default**. The audit answers "what did the agent do," not "what did the agent see" -- result rows from `SELECT` statements are intentionally not recorded, in either format. #### What gets recorded | Field | Description | |--|--| |`timestamp`|Start-of-call wall clock (RFC3339).| |`tool`|Tool name (e.g., `run_select_query`).| |`mode`|Server mode in effect at call time.| |`decision`|`allow` / `refuse_immediate` / `needs_approval_accepted` / `needs_approval_declined` / `needs_approval_cancelled` / `needs_approval_unavailable`.| |`query_class`|`select` / `mutation_create` / `mutation_delete` / `lifecycle` / `unknown`. For a payload holding several statements, the class of the most privileged one.| |`sql`|SQL string for query tools (`run_select_query`, `run_mutation_query`, `run_lifecycle_operation`, `validate_select_query`).| |`args`|Hierarchy fields for metadata tools (`list_*`, `describe_method`); SQL + `row_limit` for query tools.| |`duration_ms`|Wall-clock duration of the gate + handler.| |`error`|Error message if the tool errored or was refused.| Result rows from `SELECT` statements are deliberately excluded -- they can be very large and may carry sensitive data. #### File sink The only sink shipped today is `file`. One JSON object per line, fsynced after each record, lumberjack-style rotation by size / age / backup count. ```bash stackql mcp \ --mcp.server.type=http \ --mcp.config '{ "server": { "transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true, "audit": { "file": { "path": "/var/log/stackql-mcp.log", "max_size_mb": 100, "max_backups": 5, "max_age_days": 30 } } } }' ``` Two ways to specify the location: - `audit.file.path` -- a complete file path (absolute, or relative to cwd). - `audit.file.dir` -- a directory; the sink picks the basename `stackql_mcp_server_.log` inside it. When neither is set in `mcp.config`, the MCP server defaults `dir` to cwd so existing operators see the same behaviour as before. The underlying generic sink package itself refuses to silently pick a directory -- the "where do logs land" decision is always made by the caller. The resolved absolute path is logged to stderr at startup as `sink file: /path/to/file.log`. #### Log format The audit stream has two encodings, written to the same file sink: ```bash stackql mcp --mcp.server.type=stdio --mcp.log.format=jsonl # default, unchanged stackql mcp --mcp.server.type=stdio --mcp.log.format=otel # OTLP/JSON log records ``` The flag overrides `server.audit.format` in `mcp.config` (`"audit": {"format": "otel"}`). `jsonl` is byte-compatible with the records described above. `otel` writes one OTLP/JSON `LogsData` object per line, the shape the OpenTelemetry Collector's `otlp_json_file` receiver ingests as-is (verified against otelcol-contrib 0.160.0), so the stream reaches any OTLP pipeline with no transform processor: ```yaml receivers: otlp_json_file: include: [/var/log/stackql-mcp.log] exporters: debug: {} service: pipelines: logs: receivers: [otlp_json_file] exporters: [debug] ``` Each tool call produces one log record; a call that went through the approval gate produces a second record for the elicitation decision. Records of one call share `gen_ai.tool.call.id` and a trace id. A W3C `traceparent` supplied by the caller in `params._meta` is honoured; otherwise one trace id is generated per MCP session so an agent session's records correlate. The emitted attribute set is a versioned interface: the instrumentation scope is `github.com/stackql/stackql/pkg/mcp_server/audit` at version `1.0.0`, and `schemaUrl` pins the stable conventions to `https://opentelemetry.io/schemas/1.44.0`. The `gen_ai.*` and `mcp.*` attributes follow the [GenAI](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-spans.md#execute-tool-span) and [MCP](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/mcp.md) semantic conventions, which are Development status; the scope version is bumped when the set changes. | Attribute | Record | Value | |--|--|--| |`service.name`, `service.version`|resource|`stackql`, the StackQL version| |`gen_ai.operation.name`|tool call|`execute_tool`| |`mcp.method.name`|both|`tools/call` on the tool call record, `elicitation/create` on the decision record| |`gen_ai.tool.name`|both|Tool name| |`gen_ai.tool.call.id`|both|Generated per call, shared by both records| |`mcp.protocol.version`|both|Negotiated revision| |`mcp.session.id`|both|Session id (absent for sessionless HTTP requests)| |`stackql.mode`|both|Server mode| |`stackql.decision`|both|The `decision` value from the table above| |`stackql.query`|tool call|Verbatim SQL, for query tools| |`stackql.query_class`|tool call|The `query_class` value| |`stackql.provider`|tool call|Provider, for metadata tools| |`stackql.query.source`|tool call|Query library entry id, when supplied| |`stackql.duration_ms`|tool call|Wall-clock duration| |`stackql.rows_returned`|tool call|Row count, for row-returning tools| |`error.type`, `error.message`|tool call|On failure: the refusing decision, or `tool_error` past the gate| Body is `execute_tool ` / `elicitation `; severity is `INFO`, or `ERROR` when the call failed or was refused. The redaction contract is identical in both formats: result values are never serialised, only the statement that produced them. #### Failure modes When the sink returns an error, the response behaviour depends on `audit.failure_mode`. | failure_mode | Effect | |--|--| |`strict` (default)|The tool call returns the audit error to the client even if the underlying tool succeeded. Intentional: better an ambiguous client response than an undetected `DELETE`.| |`strict_mutations`|`SELECT` / metadata reads proceed with a stderr note; mutations and lifecycle ops surface the audit error.| |`best_effort`|Always log to stderr and proceed.| #### Sequencing The audit write happens **after** the tool executes (or is gated out) but **before** the response returns to the client. In strict mode, an audit-write failure on a successful DELETE means the row is gone but the client receives an error -- by design, so no mutation slips through unaudited. #### Disabling audit To turn audit off entirely (the pre-PR2 behaviour): ```bash stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true, "audit": {"disabled": true}}}' ``` * * * ### Available MCP tools When running as an MCP server, StackQL exposes the following tools, subject to the configured `enabled_tools` allowlist. Each returns both a rendered text view (for the LLM) and a typed structured payload (for programmatic clients). The default text rendering is a markdown table for uniform multi-row results or a markdown KV block for sparse / single-record results. Tools with arguments accept an optional `format` (`markdown` or `json`) override; otherwise the server's render setting is used. The inputs below list task-specific arguments; `?` marks optional inputs. Click any tool name for a full reference page, including inputs, gating behaviour, and an example prompt. | Tool | Renderer | Description | Inputs | |--|--|--|--| |[`server_info`](/mcp/server_info)|KV|Server identity and runtime: stackql version, backing SQL engine, provider registry location, mode, read-only flag. Call once at session start.|none| |[`list_providers`](/mcp/list_providers)|Table|Providers already pulled into the local cache -- top of the hierarchy.|none| |[`list_services`](/mcp/list_services)|Table|Services under a provider.|`provider`| |[`list_resources`](/mcp/list_resources)|Table|Resources under a `provider`.`service`.|`provider`, `service`| |[`list_methods`](/mcp/list_methods)|Table|Access methods (HTTP operations) for a resource, with the SQL verb each maps to and its required parameters. Call before writing any query -- this is where required `WHERE` parameters are inferred.|`provider`, `service`, `resource`| |[`describe_method`](/mcp/describe_method)|KV|Full I/O contract for one method (always EXTENDED): required and optional inputs, and the output fields a `SELECT` can reference.|`provider`, `service`, `resource`, `method`| |[`query_library_search`](/mcp/query_library_search)|Table|Find curated query templates by natural-language intent. Read-only; mutation entries require opt-in and are excluded in `read_only` mode.|`intent`, `provider?`, `service?`, `tags?`, `include_mutations?`, `limit?`| |[`query_library_get`](/mcp/query_library_get)|KV|Retrieve a template and its parameter declarations. With non-empty `params`, validate values and return rendered SQL plus `next_tool`, without executing.|`id`, `params?`| |[`validate_select_query`](/mcp/validate_select_query)|KV|Parse and plan a single `SELECT` without executing. Returns `{valid, errors}`. `SELECT` only; exactly one statement.|`sql`| |[`run_select_query`](/mcp/run_select_query)|Table|Execute a `SELECT`. Returns `{rows}`. Reads only.|`sql`, `row_limit?`| |[`run_mutation_query`](/mcp/run_mutation_query)|KV|Execute `INSERT`/`UPDATE`/`REPLACE`/`DELETE` against the provider. **Real side effects.** Returns `{messages, timestamp}`. Gated by the server [mode](#server-modes).|`sql`| |[`run_lifecycle_operation`](/mcp/run_lifecycle_operation)|KV|Execute a stackql `EXEC` lifecycle operation. Returns `{messages, timestamp}`. Gated by the server [mode](#server-modes).|`sql`| |[`list_registry`](/mcp/list_registry)|Table|Providers (and their versions) available in the configured registry. Distinct from `list_providers`, which lists only providers already pulled.|`provider?`| |[`pull_provider`](/mcp/pull_provider)|KV|Install a single provider from the registry into the local cache. Local cache state only -- no cloud control or data plane effect.|`provider`, `version?`| |[`reload_credentials`](/mcp/reload_credentials)|Table|Re-source credentials from the `--env.file` dotenv file into the process environment and report per-provider resolution status (`ok`, `unresolved`, `not_checked`). Never returns secret values. Allowed in every mode.|`provider?`| Consult `query_library_search` before authoring SQL from scratch, then use `query_library_get` to inspect and render a matching template. Query tools also accept an optional `source` containing the library entry ID for attribution only; execution remains subject to the normal server mode and approval policy. :::note `describe_resource` was retired in StackQL `v0.12.732`; MCP clients, prompts or agent instructions that called it should call [`list_methods`](/mcp/list_methods) followed by `describe_method` instead. A resource has no single field list, because each access method returns its own shape, so column names come from [`describe_method`](/mcp/describe_method) for the method a query routes to. The SQL [`DESCRIBE`](/language-spec/describe) statement is unchanged. ::: ### Available MCP prompts One static prompt is published. | Prompt | Description | |--|--| |`write_safe_select`|Guidance for writing safe `SELECT` queries against stackql resources. Explains how to use `SHOW METHODS IN ..` to discover the right read method and the required `WHERE` parameters.| * * * ### Flags | Flag | Description | |--|--| |`--mcp.server.type`|MCP server type: `http`, `stdio`, or `reverse_proxy` (the latter is used with `stackql srv`).| |`--mcp.config`|JSON configuration object for the MCP server. YAML is also accepted.| |`--mcp.protocol.version`|Newest protocol revision advertised: `auto` (default), `2026-07-28` or an older revision such as `2025-11-25`. See [Pinning the revision](#pinning-the-revision).| |`--env.file`|Dotenv-style credentials file sourced at startup and re-sourced on demand by the `reload_credentials` tool. See [Credential (re)sourcing](#credential-resourcing---envfile--reload_credentials).| |`--pgsrv.port`|TCP port for the PostgreSQL wire-protocol server (used with `stackql srv`).| |`-H`, `--help`|Print help information.| |`-v`, `--verbose`|Run in verbose mode with additional output.|     > see [Global Flags](/command-line-usage/global-flags) for additional options :::info You need to set environment variables required for provider authentication before starting the MCP server, or nominate a dotenv-style credentials file with [`--env.file`](#credential-resourcing---envfile--reload_credentials). See [Using a Provider](/getting-started/using-a-provider) for more information. ::: * * * ### Examples #### Basic standalone MCP server Launch a standalone MCP server with provider authentication and a bearer token for its clients: ```bash export GOOGLE_CREDENTIALS=$(cat /path/to/google-credentials.json) export STACKQL_MCP_TOKEN="$(openssl rand -hex 32)" stackql mcp \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "auth_token_env_var": "STACKQL_MCP_TOKEN"}}' \ --registry='{"url": "https://registry.stackql.io/providers"}' \ --auth='{"google": {"type": "service_account", "credentialsfilepath": "/path/to/google-credentials.json"}}' ``` #### MCP server with PostgreSQL server (in-memory) Run both MCP and PostgreSQL servers for dual-protocol access: ```bash export GOOGLE_CREDENTIALS=$(cat /path/to/google-credentials.json) stackql srv \ --mcp.server.type=http \ --mcp.config '{"server": {"transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true}}' \ --pgsrv.port 5665 \ --registry='{"url": "https://registry.stackql.io/providers"}' \ --auth='{"google": {"type": "service_account", "credentialsfilepath": "/path/to/google-credentials.json"}}' ``` #### Read-only inventory server with audit to a known path Useful for an inventory-scanning agent that should never mutate: ```bash stackql mcp \ --mcp.server.type=http \ --mcp.config '{ "server": { "transport": "http", "address": "127.0.0.1:9912", "allow_unauthenticated": true, "mode": "read_only", "audit": {"file": {"path": "/var/log/stackql-mcp-audit.log"}} } }' \ --registry='{"url": "https://registry.stackql.io/providers"}' \ --auth='{"google": {"type": "service_account", "credentialsfilepath": "/path/to/google-credentials.json"}}' ``` #### Full-access automation server For trusted automation pipelines that need mutations and can't respond to elicitation prompts. The pipeline presents the bearer token held in `STACKQL_MCP_TOKEN`: ```bash stackql mcp \ --mcp.server.type=http \ --mcp.config '{ "server": { "transport": "http", "address": "127.0.0.1:9912", "auth_token_env_var": "STACKQL_MCP_TOKEN", "mode": "full_access" } }' \ --registry='{"url": "https://registry.stackql.io/providers"}' \ --auth='{"google": {"type": "service_account", "credentialsfilepath": "/path/to/google-credentials.json"}}' ``` #### Secure MCP server with TLS Launch an MCP server with TLS encryption in reverse-proxy mode: First, generate TLS certificates (self-signed for development): ```bash openssl req -x509 -newkey rsa:4096 -keyout server_key.pem -out server_cert.pem -days 365 -nodes ``` Then start the server: ```bash stackql srv \ --mcp.server.type=reverse_proxy \ --mcp.config '{ "server": { "tls_cert_file": "server_cert.pem", "tls_key_file": "server_key.pem", "transport": "http", "address": "127.0.0.1:9004", "auth_token_env_var": "STACKQL_MCP_TOKEN" }, "backend": { "dsn": "postgres://stackql:stackql@127.0.0.1:5446?default_query_exec_mode=simple_protocol" } }' \ --pgsrv.port 5446 \ --registry='{"url": "https://registry.stackql.io/providers"}' \ --auth='{"google": {"type": "service_account", "credentialsfilepath": "/path/to/google-credentials.json"}}' ``` * * * ### Testing your MCP server The repository ships a development MCP client (`stackql_mcp_client`) for scripting and regression tests. Build it with: ```bash python cicd/python/build.py --build-mcp-client ``` This produces `./build/stackql_mcp_client`. Note that `stackql_mcp_client` sends no `Authorization` header, so the server it targets must set `"allow_unauthenticated": true` (as the examples above do); a token-protected server answers it with `401`. It also does **not** advertise the MCP elicitation capability -- it's for non-interactive scripting. Against a `safe` or `delete_safe` server it will receive the "client does not support elicitation" refusal on mutation and lifecycle calls. For interactive testing with elicitation prompts, use an editor-embedded MCP client (Claude Desktop, Cursor, Continue). ```bash # List all available tools ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 # Server identity, mode, audit / registry context ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action server_info # Re-source the --env.file credentials file and report per-provider # credential status - a good first diagnostic when queries fail on auth ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action reload_credentials # List providers already pulled into the local cache ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action list_providers # List providers (and versions) available in the registry ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action list_registry # Install a provider from the registry into the local cache ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action pull_provider \ --exec.args '{"provider": "kafka"}' # List services for a provider ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action list_services \ --exec.args '{"provider": "google"}' # List access methods for a resource (this is how an agent finds required # WHERE parameters before writing a query) ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action list_methods \ --exec.args '{"provider": "google", "service": "compute", "resource": "networks"}' # Validate a SELECT without executing ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action validate_select_query \ --exec.args '{"sql": "select name from google.compute.networks where project = '"'"'my-project'"'"';"}' # Execute a SELECT ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action run_select_query \ --exec.args '{"sql": "select name from google.compute.networks where project = '"'"'my-project'"'"';"}' # Mutation - succeeds only against a full_access server, or against # delete_safe (for INSERT/UPDATE) or safe with an elicitation-capable client. ./build/stackql_mcp_client exec \ --client-type=http \ --url=http://127.0.0.1:9912 \ --exec.action run_mutation_query \ --exec.args '{"sql": "delete from google.compute.firewalls where project = '"'"'my-project'"'"' and firewall = '"'"'old-rule'"'"';"}' ``` #### Example responses `server_info` (against a default-mode server): ```json { "version": "0.10.444", "commit": "abc1234", "build_date": "2026-05-16T10:47:33Z", "platform": "linux/amd64", "transport": "http", "sql_backend": "sqlite3", "provider_registry": "https://registry.stackql.io/providers", "mode": "safe", "is_read_only": false } ``` `run_select_query`: ```json { "rows": [ {"name": "default"}, {"name": "pathfinders-test-01"}, {"name": "returning-test-03"} ] } ``` `run_mutation_query` (against a `full_access` server): ```json { "messages": ["The operation was despatched successfully"], "timestamp": "2026-05-16T10:47:33+10:00 AEST" } ``` Sample audit log line for the same mutation: ```json {"timestamp":"2026-05-16T00:47:33Z","tool":"run_mutation_query","mode":"full_access","decision":"allow","query_class":"mutation_delete","sql":"delete from google.compute.firewalls where project = 'my-project' and firewall = 'old-rule';","args":{"sql":"delete from google.compute.firewalls where project = 'my-project' and firewall = 'old-rule';","row_limit":0},"duration_ms":42} ``` * * * ### Integration with AI assistants To integrate StackQL's MCP server with an AI assistant, register `stackql` as an MCP server in the assistant's configuration. Most editor-embedded MCP clients run the server over `stdio`; for those, use `--mcp.server.type=stdio` and the assistant launches the process directly. Standalone agents that speak HTTP can connect to a long-running `stackql mcp --mcp.server.type=http` process. For Claude Desktop - including the Anthropic Connector Directory listing (the recommended installation method), the downloadable MCP Bundle (`.mcpb`), and manual configuration - see [Using StackQL with Claude Desktop](/getting-started/claude-desktop). :::note Configuration file locations vary by operating system and AI assistant. Consult your AI assistant's documentation for the correct path and format. ::: * * * ### Architecture considerations When choosing a deployment mode, consider: 1. **Standalone (`stackql mcp`)**: simplest setup, ideal for development and for editor-embedded clients over `stdio`. 2. **In-memory dual-server (`stackql srv` with `mcp.server.type=http`)**: single process serves both MCP and PostgreSQL wire protocols. Best performance, suitable for most production deployments. 3. **Reverse proxy (`stackql srv` with `mcp.server.type=reverse_proxy`)**: - enables workload separation across processes or hosts - supports TLS encryption for secure MCP endpoints - allows independent scaling of MCP and PostgreSQL interfaces - provides flexibility for enterprise CA integration (note: enterprise CA support is experimental) And separately, on safety: - Start with the default `mode: safe`. Elicitation-capable clients (Claude Desktop, Cursor, Continue) will prompt the user before any mutation. - Pin `mode: read_only` for inventory or analytics agents that should never write. - Pin `mode: delete_safe` when you want create/update freedom but want a human in the loop for destructive operations. - Reserve `mode: full_access` for trusted automation pipelines, and only in conjunction with an audit log that someone reviews. - Set `server.auth_token_env_var` on any HTTP listener that other processes or hosts can reach; `allow_unauthenticated` is for local development. TLS alone does not authenticate clients. :::caution When using TLS with enterprise Certificate Authorities (CAs), additional configuration may be required. This functionality is experimental and may require adjustments based on your specific CA implementation. ::: * * * ### Further reading - The package-developer reference is the [`pkg/mcp_server` README](https://github.com/stackql/stackql/blob/main/pkg/mcp_server/README.md) in the stackql repo. - The contributor-facing technical doc lives at [`docs/mcp.md`](https://github.com/stackql/stackql/blob/main/docs/mcp.md) in the stackql repo and includes worked example responses for every tool. --- # registry > The stackql registry command lists, pulls and manages providers from the StackQL provider registry from the command line. Source: https://stackql.io/command-line-usage/registry Command used to interact with the StackQL Provider Registry. The registry location, and whether provider document signatures are verified, are configured with the [`--registry`](/command-line-usage/global-flags#--registry) global flag. The `registry` command is not available while [access management](/command-line-usage/access-management) is enabled; use `REGISTRY PULL` in a protected `exec` or `shell` session instead. * * * ### Syntax `stackql registry {subcommand} [{provider} [{version}]]` * * * ### Arguments | Argument | Description | Example | |--|--|--| |`subcommand`|Registry operation to be performed (either `list` or `pull`) | `list` or `pull` | |`provider`|Provider to be installed using `pull` subcommand| `okta` | |`version`|Optional provider version to be installed using `pull` subcommand *(StackQL Provider Document Version)* | `v23.03.00121` | ### Flags | Flag | Description | |--|--| |`-H, --help`|Print help information| > see [Global Flags](/command-line-usage/global-flags) for additional options * * * ### Examples List available providers in the public registry: ```shell stackql registry list ``` Pull the latest version of a provider from the public registry: ```shell stackql registry pull okta ``` --- # shell > The stackql shell command launches the interactive StackQL command shell for running queries and provider commands against your cloud and SaaS accounts. Source: https://stackql.io/command-line-usage/shell Command used to launch the interactive StackQL Command Shell. For more information see [Using the Interactive StackQL Shell](/getting-started/using-stackql#using-the-stackql-interactive-shell). * * * ### Syntax `stackql shell [flags]` * * * ### Flags | Flag | Description | |--|--| |`-H` `--help`|Print help information| |`-v` `--verbose`|Run queries in verbose mode with additional output sent to stdout, if the `-f` option is selected this additional logging information will be written to the output file along with the query results| > see [Global Flags](/command-line-usage/global-flags) for additional options * * * ### Examples Launch the StackQL shell, using a service account key file for authentication. ```shell stackql shell --keyfilepath /tmp/stackql-demo.json ``` --- # srv > The stackql srv command runs StackQL as a PostgreSQL wire protocol server, so psql, BI tools and language drivers can query cloud and SaaS APIs with SQL. Source: https://stackql.io/command-line-usage/srv Command used to launch StackQL as a service, which can then be accessed by clients using [Postgres wire protocol](https://www.postgresql.org/docs/current/protocol.html) clients authenticated using mTLS. The `srv` command can also run a [Model Context Protocol (MCP)](/command-line-usage/mcp) server alongside the PostgreSQL wire protocol server, enabling dual-protocol access for both traditional database clients and AI agents. * * * ### Syntax `stackql srv [server_options] [flags]` * * * :::note Although the StackQL server uses the Postgres wire protocol, it is not a Postgres server, nor does it require one. The wire protocol is used by the client to communicate with the server which uses StackQL to perform queries or DML operations against remote cloud and SaaS providers and return results back to the client. ::: Parameters sent over the extended query protocol (`Parse` / `Bind` / `Execute`, as used by `psycopg` 3, `pgx` and JDBC) are bound server side as string literals. From `v0.12.742` a `$n` placeholder inside a string literal, quoted identifier or comment is left alone, backslashes in parameter values are escaped, and a text value of `NULL` stays the string `NULL` (SQL `NULL` is carried separately). ### Server Options | Option | Description | |--|--| |`--pgsrv.address`|Address the server is listening on (typically `0.0.0.0`)| |`--pgsrv.port`|Port the server is listening on (e.g. `5444`)| |`--pgsrv.tls`|mTLS configuration object, see the [example](#examples) below| |`--pgsrv.loglevel`|Log level (default `WARN`)| > see [Global Flags](/command-line-usage/global-flags) for additional options ### MCP Server Options When running the `srv` command with MCP support, the following additional options are available: | Option | Description | |--|--| |`--mcp.server.type`|MCP server type: `http` (in-memory) or `reverse_proxy` (TCP-based)| |`--mcp.config`|JSON configuration object for the MCP server (see [MCP documentation](/command-line-usage/mcp))| |`--mcp.log.format`|MCP audit log encoding: `jsonl` (default) or `otel` (OTLP/JSON log records); overrides `server.audit.format` in the configuration object| |`--mcp.protocol.version`|Newest MCP protocol revision advertised: `auto` (default), `2026-07-28` (sessionless only) or an older revision such as `2025-11-25`; overrides `server.protocol_version` in the configuration object| :::info[Breaking change in v0.12.742] From `v0.12.742` the MCP HTTP transport (`--mcp.server.type=http` or `reverse_proxy`) refuses to start unless the configuration object names a bearer token with `server.auth_token_env_var` or opts out explicitly with `"allow_unauthenticated": true`. See [HTTP client authentication](/command-line-usage/mcp#http-client-authentication). ::: :::tip See the [MCP command documentation](/command-line-usage/mcp) for detailed information on configuring and using the MCP server, including deployment modes, configuration options, and integration with AI assistants. ::: :::info You need to set environment variables required for provider authentication before starting the server, see [Using a Provider](/getting-started/using-a-provider) for more information. ::: For long-running servers, the [`--env.file`](/command-line-usage/global-flags) flag lets you lay down or rotate credentials in a dotenv-style file on disk before startup rather than exporting variables into the shell: ```bash stackql srv --pgsrv.port 5444 --env.file /etc/stackql/credentials.env ``` For `stackql srv` the file is read once at startup; the mid-session re-source path is the MCP [`reload_credentials`](/mcp/reload_credentials) tool. ### Flags | Flag | Description | |--|--| |`-H,--help`|Print help information| |`-v,--verbose`|Run queries in verbose mode with additional output sent to stdout, if the `-f` option is selected this additional logging information will be written to the output file along with the query results| > see [Global Flags](/command-line-usage/global-flags) for additional options * * * ### Examples Launch a StackQL server process and connect using a `psql` command line client. First download the `openssl.cnf` configuration file from [stackql/stackql](https://raw.githubusercontent.com/stackql/stackql/main/test/server/mtls/openssl.cnf). Next generate the certificate and key files to be used by the server and client for mutual TLS authentication (mTLS). ```bash openssl req -x509 -keyout ~/stackqlcreds/server_key.pem -out ~/stackqlcreds/server_cert.pem -config ./openssl.cnf -days 365 openssl req -x509 -keyout ~/stackqlcreds/client_key.pem -out ~/stackqlcreds/client_cert.pem -config ./openssl.cnf -days 365 chmod 400 ~/stackqlcreds/client_key.pem ``` Now set environment variables, if the client and server are on the same host, these can be shared. ```bash export PGPORT=5444 export PGSSLCERT=~/stackqlcreds/client_cert.pem export PGSSLKEY=~/stackqlcreds/client_key.pem export PGSSLROOTCERT=~/stackqlcreds/server_cert.pem export PGSSLSRVKEY=~/stackqlcreds/server_key.pem export CLIENT_CERT=$(base64 -w 0 ~/stackqlcreds/client_cert.pem) export PGSSLMODE=allow ``` Set up an authentication object for whatever providers the server will need access to, for instance for GitHub. ```bash export STACKQL_GITHUB_USERNAME=youruser export STACKQL_GITHUB_PASSWORD=ghp_youraccesstoken ``` Now start the server in one terminal. ```bash stackql srv \ --pgsrv.address=0.0.0.0 \ --pgsrv.port=$PGPORT \ --pgsrv.tls='{ "keyFilePath": "'${PGSSLSRVKEY}'", "certFilePath": "'${PGSSLROOTCERT}'", "clientCAs": [ "'${CLIENT_CERT}'" ] }' ``` In another terminal, connect to the server using the `psql` command line client. ```bash psql 127.0.0.1 ``` Now run a StackQL query against an authenticated provider. ``` psql (12.11 (Ubuntu 12.11-0ubuntu0.20.04.1), server 0.0.0) Type "help" for help. 127.0.0.1=> SHOW SERVICES IN github LIKE '%repos%'; id | name | title --------------+-------+---------------------------- repos:v0.3.3 | repos | GitHub v3 REST API - repos (1 row) 127.0.0.1=> ``` --- # Architecture > How StackQL works internally: entry points, the query pipeline, the omnisdk provider SDK, the SQL backend, and how a statement reaches cloud providers. Source: https://stackql.io/developers/architecture See also: [[ Using StackQL ]](/getting-started/using-stackql) [[ Using Variables ]](/getting-started/variables) [[ Templating ]](/getting-started/templating) ## Overview StackQL is a unified SQL interface for querying and managing cloud infrastructure across multiple providers. The following container diagram illustrates the major components of the StackQL system and their interactions. ```mermaid flowchart TB subgraph User["User (DevOps, Analyst, or Automation)"] direction LR end subgraph StackQL["StackQL"] subgraph EntryPoints["Entry Points"] CLI["CLI / Shell
Go"] PGWire["PostgreSQL Wire Protocol
Go, psql-wire"] MCP["MCP Server
Go"] end subgraph Processing["Query Processing"] Parser["SQL Parser
Go, Yacc"] QueryEngine["Query Engine
Go"] SDK["Provider SDK
Go, omnisdk"] end subgraph Backend["SQL Backend"] SQLBackend["SQL Backend
Go"] SQLite[("SQLite
Embedded")] Postgres[("PostgreSQL
External, Optional")] end end subgraph External["External Systems"] Providers["Cloud Providers
AWS, GCP, Azure, K8s, GitHub..."] Registry["StackQL Registry
Provider definitions"] end User --> CLI User --> PGWire User --> MCP CLI --> Parser PGWire --> Parser MCP --> Parser Parser --> QueryEngine QueryEngine --> SDK QueryEngine --> SQLBackend SDK --> Providers SDK --> Registry SDK --> SQLBackend SQLBackend --> SQLite SQLBackend --> Postgres ``` ## Core Components ### Entry Points StackQL supports multiple entry points for executing SQL queries: - **CLI / Shell**: An interactive shell and command-line interface for executing SQL queries directly from the terminal. Users can run ad-hoc queries, scripts, or use the interactive shell for exploration. - **PostgreSQL Wire Protocol**: Enables connections from standard PostgreSQL clients such as `psql`, DBeaver, or any other PostgreSQL-compatible tool. This allows seamless integration with existing database workflows and BI tools. - **MCP Server**: A Model Context Protocol server that enables AI assistant integration, allowing large language models to query and manage infrastructure through natural language. ### Query Processing Pipeline 1. **SQL Parser**: Parses SQL input into an Abstract Syntax Tree (AST) using a custom grammar based on Yacc. The parser (implemented as `stackql-parser`) validates SQL syntax and prepares it for query planning. 2. **Query Engine**: The central orchestration layer that plans and executes queries. It determines which operations can be pushed down to the API layer versus which require local SQL processing. The query engine handles: - Query planning and optimization - Coordination between API calls and local SQL execution - Result aggregation and transformation ### Provider SDK (omnisdk) The Provider SDK, [omnisdk](https://github.com/stackql-labs/omnisdk), manages all interactions with cloud providers. It replaced `any-sdk` in StackQL `v1.0`. Key responsibilities include: - **Provider Discovery**: Fetches provider specifications from the StackQL Registry, which contains OpenAPI-based definitions for each supported cloud provider, and optionally verifies the ML-DSA-65 signature on each document before it is used. - **Authentication**: Handles authentication for each provider, supporting various auth methods including API keys, OAuth tokens, service account credentials, and more. Each provider definition specifies its authentication requirements; a session can bind the same provider under several aliases with separate credentials (see [Provider Sessions](/getting-started/provider-sessions)). - **Graph Planning**: Plans each statement as a graph of provider exchanges joined by data and control edges. Joins, subqueries, CTEs and views run through the same planner, and requests that fan out from a plan run concurrently within per-provider and per-host limits. - **API Request Building**: Transforms SQL queries into appropriate REST API calls for each provider, handling endpoint construction, parameter mapping, and request formatting. - **Pagination**: Automatically handles paginated API responses, abstracting away the complexity of different pagination schemes used by various providers (cursor-based, offset-based, token-based, etc.). - **Predicate Pushdown**: Pushes conditions that map to request parameters, and `LIMIT` where no ordering is required, into the provider requests to reduce the number of requests made and the data transferred. - **Response Transformation**: Converts API responses into rows as they arrive, for staging in the SQL backend or streaming to the client. SQL connections, staging and backend execution stay in StackQL. omnisdk contains no SQL staging and never receives a database connection; StackQL passes it relation handles and receives row cursors. ### SQL Backend The SQL Backend executes relational operations on materialized API data: - **SQLite**: An embedded database used for temporary table storage and relational processing. Ideal for ad-hoc queries and smaller datasets. - **PostgreSQL**: An optional external database for persistent storage, larger datasets, and advanced analytics workloads. The SQL backend handles operations such as: - JOIN operations across multiple providers or resources - Aggregate functions (COUNT, SUM, AVG, etc.) - Sorting and filtering on materialized data - Complex SQL expressions and subqueries ## External Systems ### Cloud Providers StackQL connects to cloud providers (AWS, GCP, Azure, Kubernetes, GitHub, and many more) via their REST APIs. All communication is over HTTPS, and the Provider SDK handles the specifics of each provider's API conventions. ### StackQL Registry The StackQL Registry hosts provider definitions - OpenAPI-based specifications that describe available resources, methods, and their mappings. Providers are versioned and can be pulled on-demand using the `REGISTRY PULL` command. ## Query Execution Flow 1. User submits a SQL query through one of the entry points (CLI, PostgreSQL protocol, or MCP) 2. The SQL Parser validates and converts the query into an AST 3. The Query Engine analyzes the AST and creates an execution plan 4. For provider operations, the Provider SDK: - Fetches the relevant provider specification from the Registry (if not cached) - Authenticates with the cloud provider - Builds and executes API requests, handling pagination automatically - Pushes predicates to the API where possible - Materializes results into the SQL backend 5. The SQL Backend executes any remaining relational operations 6. Results are returned to the user in the requested format --- # Developing StackQL Providers > How StackQL providers are structured, built from the provider template, tested locally, and published to the StackQL Provider Registry served from Cloudflare. Source: https://stackql.io/developers/developing-stackql-providers See also: [[ StackQL Provider Registry ]](/providers) [[ Using a Provider ]](/getting-started/using-a-provider) [[ REGISTRY ]](/language-spec/registry) [[ Architecture ]](/developers/architecture) ## Overview A StackQL provider is a versioned set of OpenAPI documents plus `x-stackQL-*` extensions that the [omnisdk](https://github.com/stackql-labs/omnisdk) engine turns into SQL tables: `SELECT` for reads, `INSERT`, `UPDATE`, `REPLACE` and `DELETE` for lifecycle operations, and `EXEC` for actions. Provider documents tell StackQL what a provider's API can do and how to invoke it with SQL semantics. They are plain YAML, so a provider can be built, tested and versioned like any other code. Three repositories and one distribution layer make up the provider ecosystem: | Component | Role | | --- | --- | | [__`stackql-provider-TEMPLATE`__](https://github.com/stackql-registry/stackql-provider-TEMPLATE) | The starting point for a new provider project: a deterministic `make` pipeline from a pinned upstream spec to a generated provider, credential-free test layers, a live smoke suite, a documentation microsite and CI. Bundles the Claude Code provider development skill. | | [__`omnisdk`__](https://github.com/stackql-labs/omnisdk) | The engine that reads provider documents and executes requests, from StackQL `v1.0`. Its predecessor, [`any-sdk`](https://github.com/stackql/any-sdk), still hosts the reference for the provider document contract, the `x-stackQL-*` extensions, authentication, pagination, transforms and pushdown, and the JSON Schemas linked below. | | [__`stackql-provider-registry`__](https://github.com/stackql/stackql-provider-registry) | The source of truth for published providers. Documents are versioned under `providers/src///`, then signed, packaged and published by GitHub Actions. | | __Cloudflare distribution layer__ | Packaged provider artifacts are served at the edge from Cloudflare R2 by a Cloudflare Worker at `registry.stackql.app` (production) and `registry-dev.stackql.app` (development). This is what `REGISTRY LIST` and `REGISTRY PULL` talk to. | The following diagram shows the path from a provider project to a StackQL installation: ```mermaid flowchart TB subgraph Dev["Provider project (from the template)"] direction LR Spec["Pinned upstream
OpenAPI spec"] --> Pipeline["make build
inventory, map, normalize, generate"] Pipeline --> Tests["make test
offline, mock integration, meta-route"] Tests --> Smoke["make smoke
live, dev account"] end subgraph Registry["stackql-provider-registry"] direction LR PR["PR to dev branch"] --> GA["GitHub Actions
validate, e2e test, sign, package"] GA --> S3[("AWS S3
artifact archive")] S3 --> R2[("Cloudflare R2
docs mirror")] R2 --> Worker["Cloudflare Worker
registry-dev.stackql.app
registry.stackql.app"] end Smoke -->|"push providers/src/name"| PR Worker -->|"REGISTRY LIST / REGISTRY PULL"| App["StackQL"] ``` ## Provider Document Structure StackQL objects follow the hierarchy `provider.service.resource.method`, for example `google.compute.instances.list`. The documents mirror that hierarchy: ``` provider.yaml # provider metadata, providerServices, provider-level config services/ .yaml # an OpenAPI 3 document per service, plus components.x-stackQL-resources # id, name, methods, sqlVerbs, optional config methods. # operation $ref, response, request, optional config ``` - __Provider document__ (`provider.yaml`): `id`, `name`, `title`, `version`, `providerServices` (each with a `service.$ref` to its service document and an optional `preferred` flag), optional `description`, `protocolType` (`http` is the default) and `config`. - __Service document__: a standard OpenAPI 3 document. The only required addition is `components.x-stackQL-resources`, which declares the resources exposed as tables. - __Resource__: `id`, `name`, `methods` and `sqlVerbs`. Each resource is a table; its columns come from the response schema of its primary `select` method. - __Method__: an `operation` that is a JSON pointer into `paths` (for example `$ref: '#/paths/~1orgs~1{org}~1repos/get'`), a `response` block (`mediaType`, `openAPIDocKey`, `objectKey`) that tells the engine where the rows are, and an optional `request` block and `config`. - __SQL verb mapping__: `sqlVerbs.select`, `insert`, `update`, `replace` and `delete` are ordered lists of method references. References are tried in the order written and the first whose required parameters are satisfied by the `WHERE` clause wins, so list `list` before `get`. Any method not referenced by a verb list is callable via `EXEC`. A minimal resource looks like this: ```yaml components: x-stackQL-resources: repos: id: github.repos.repos name: repos title: Repos methods: list_for_org: operation: $ref: '#/paths/~1orgs~1{org}~1repos/get' response: mediaType: application/json openAPIDocKey: '200' create_in_org: operation: $ref: '#/paths/~1orgs~1{org}~1repos/post' response: mediaType: application/json openAPIDocKey: '201' config: requestBodyTranslate: algorithm: naive sqlVerbs: select: - $ref: '#/components/x-stackQL-resources/repos/methods/list_for_org' insert: - $ref: '#/components/x-stackQL-resources/repos/methods/create_in_org' ``` The full contract, including every key and its meaning, is in the any-sdk [Provider Specification](https://github.com/stackql/any-sdk/blob/main/docs/provider_spec.md). JSON Schemas for `provider.yaml`, service documents and the config block live in [`any-sdk/cicd/schema-definitions`](https://github.com/stackql/any-sdk/tree/main/cicd/schema-definitions); the config schema rejects unknown keys, so a mistyped key fails validation rather than being silently ignored. ### OpenAPI extensions | Extension | Where | Purpose | | --- | --- | --- | | `x-stackQL-resources` | `components` | The resource dictionary for a service document (required) | | `x-stackQL-config` | service, resource, method or operation | A config block (see below) applied at that level | | `x-stackQL-envVar` | server variable | Names an environment variable that supplies the server variable when it is not given in the `WHERE` clause. Used to scope an API by tenant, org, project or deployment | | `x-stackQL-alias` | parameter or schema property | An alternative name accepted in SQL for a wire-level name | | `x-stackQL-stringOnly` | schema property | Serialize the property as a string regardless of its declared type | | `x-stackQL-graphQL` | operation | Backs a method with a GraphQL query where the REST API lacks the data | | `x-alwaysRequired` | parameter | Marks a parameter as always required | | `x-protocol` | `info` | Wire-protocol hint (`query`, `ec2`, `rest-xml`) for schema-driven XML response handling | ### The config block `config` in `provider.yaml` and `x-stackQL-config` in service documents share one schema. The allowed keys are `auth`, `pagination`, `queryParamPushdown`, `queryParamTranspose`, `requestTranslate`, `requestBodyTranslate`, `variations`, `views`, `sqlExternalTables`, `retry`, `minStackQLVersion` and `snake_case_aliases`. Config resolves from the most specific level outward, method -> resource -> service -> provider service -> provider, so a provider-wide default can be overridden for one resource or method. ## What Providers Handle Providers are responsible for the functions that abstract away API complexity, so users get a consistent SQL interface without managing the underlying HTTP conversation. ### Authentication Each provider ships a default `auth` block that names the environment variables holding its credentials, so a populated environment needs no runtime auth configuration. Only indirections (env var names, file paths) are accepted in a provider document; literal credential values belong exclusively in the runtime `--auth` context. Env var names should follow the vendor's Terraform provider where one exists. | `auth.type` | Typical fields | | --- | --- | | `bearer` | `credentialsenvvar` | | `api_key` | `credentialsenvvar`, `valuePrefix`, optional `location` (`header` or `query`) and `name` | | `basic` | `username_var`, `password_var` | | `custom` | `location`, `name`, `credentialsenvvar`, optional `valuePrefix`; chain a second credential with `successor` | | `oauth2` | `client_id_env_var`, `client_secret_env_var`, `grant_type: client_credentials`, `token_url`, `scopes` | | `service_account` | `credentialsenvvar` or `credentialsfilepathenvvar`, `scopes` | | `aws_signing_v4`, `aws_assume_role` | `keyIDenvvar`, `credentialsenvvar` | | `azure_default` | none | | `oci_signing_v1` | `tenancy_ocid_envvar`, `user_ocid_envvar`, `oci_fingerprint_envvar`, `oci_private_key_envvar`, `oci_region_envvar` | | `interactive` | none | | `null_auth` | none (explicitly unauthenticated) | For example: ```yaml config: auth: type: api_key credentialsenvvar: OKTA_API_TOKEN valuePrefix: 'SSWS ' ``` Users can override a provider's auth at runtime with `--auth='{"": {...}}'`. ### Pagination Providers declare the vendor's pagination scheme and the engine walks every page, so users receive complete result sets. Supported schemes: - __Token or cursor in the body__: `requestToken: {key: cursor, location: query}`, `responseToken: {key: $.cursor, location: body}`; stops when the token is absent or empty. - __Next-page URL in the body__: `requestToken: {key: '', location: request}`, `responseToken: {key: $.next, location: body}`; `algorithm: odata_next_link` for OData `@odata.nextLink`. - __RFC 5988 `Link` header__: `responseToken: {key: Link, location: header}`. - __Page number with a page count__: `algorithm: page_number` with `responseToken` (current page) and `responseTerminator` (total pages). Offset and limit APIs with no next marker are not a pagination scheme; expose `offset` and `limit` as `WHERE` parameters instead. The `--http.response.pageLimit` global flag bounds traversal. ### Predicate Pushdown `WHERE` keys are matched against the operation's declared parameters by name (path, then query, header and cookie) and sent to the API, so filtering happens at the source. Any leftover `WHERE` key with no matching parameter is appended as a query parameter. Beyond plain parameters, `queryParamPushdown` rewrites `SELECT` columns, `WHERE`, `ORDER BY`, `LIMIT`, `OFFSET` and `COUNT` into API parameters. `dialect: odata` fills the `$select`, `$filter`, `$orderby`, `$top`, `$skip` and `$count` defaults used by Microsoft Graph and Azure style APIs; `dialect: custom` uses `paramName` verbatim, most commonly `top: {paramName: limit, maxValue: 1000}` so `LIMIT n` becomes `?limit=n`. Predicates that cannot be pushed are still evaluated client-side. ### Response and Request Transformation - `response.objectKey` is a JSONPath (or XPath for XML APIs) that selects the row-bearing items from an envelope, for example `$.data[*]` or `$.value`. - `response.transform` applies a Go text template to a body before it is staged as rows; transform types cover JSON, XML and plain text, which is how AWS XML APIs and CLI output become tables. - `requestBodyTranslate: {algorithm: naive}` lets `INSERT` take request body fields as plain column names rather than the `data__` prefixed form. - `snake_case_aliases: true` at provider level exposes camelCase wire names as snake_case columns and parameters. - `retry` sets an exponential backoff policy (`max_attempts`, `initial_delay_ms`, `max_delay_ms`, `multiplier`, `jitter_fraction`, `retryable_methods`, `retryable_conditions.status_codes`). The first level that declares one wins; see the any-sdk [retry policy](https://github.com/stackql/any-sdk/blob/main/docs/retry_policy.md). Column types follow the OpenAPI schema: `string` -> text, `integer` -> integer, `number` -> numeric, `boolean` -> boolean. `object` and `array` properties are stored as JSON text, which is why nested fields are read with `json_extract` in queries and why providers often ship views (`config.views`, with per-dialect `ddl` and a `fallback`) for common nested projections. ### Non-HTTP Providers `protocolType: local_templated` in `provider.yaml` backs a provider with local commands instead of HTTP: methods carry an `inline` array of Go-template argv fragments, parameters use `in: inline`, and a `response.transform` turns command output into rows. The [`local_openssl`](https://github.com/stackql/any-sdk/tree/main/test/registry/src/local_openssl/v0.1.0) reference provider in any-sdk shows the shape. This is out of scope for the template pipeline, which targets HTTP APIs. ## Starting a Provider Project Start every new provider from [__`stackql-provider-TEMPLATE`__](https://github.com/stackql-registry/stackql-provider-TEMPLATE). It is a GitHub template repository that encodes the current standard for a provider: a pinned upstream spec, a deterministic build pipeline where every manual decision is a rule in a script rather than a hand edit to generated YAML, three credential-free test layers, a budgeted live smoke suite, a Docusaurus documentation site and CI. Published providers built this way live in the [stackql-registry](https://github.com/orgs/stackql-registry/repositories) GitHub organization, and are useful reference material alongside the template. Prerequisites: Node.js 20 or later, GNU make and bash (Linux, macOS or WSL), Python 3 for the smoke suite, and a `stackql` binary (`bin/start-server.sh` downloads one if none is found). 1. Create the repository from the template (GitHub "Use this template") and run `npm install`. 2. Run `bin/init-provider.sh "" [https://api.vendor.com]` to replace the placeholders across the repository. 3. Fill in the constants in `provider-dev/scripts/lib/spec_helpers.mjs` (spec URL, path version prefix, scope prefix for a tenant or project scoped API) and the config under `provider-dev/config/` (`servers.json`, `provider_config.json`, `service_names.json`). 4. Work the pipeline, either by hand through the `make` targets or by opening a Claude Code session in the repository (see below). 5. `grep -rn "TODO(template)"` lists what is still open. The pipeline is driven by `make` (`make help` lists every target): ```bash make fetch-spec # verify the upstream spec against the recorded pin (fails on drift) make inventory # one CSV row per operation with the proposed service, resource, method and verb make split # write provider-dev/source/<service>.yaml from the ordered path rules make mappings-report # print every derived operation -> resource.method mapping without writing make mappings # regenerate provider-dev/config/all_services.csv and validate it make normalize # flatten allOf, lower oneOf/anyOf, wrap bare arrays make generate # generate provider.yaml + services/*.yaml, then post-process and merge GraphQL/views make test # offline SHOW/DESCRIBE, mock API integration tests, meta-route walk (no credentials) make smoke # live smoke suite against a dedicated dev account (sources .env) make docs # generate the provider documentation site content make all # everything above except the live suites ``` Under the hood the pipeline uses [__`@stackql/provider-utils`__](https://github.com/stackql-registry/stackql-provider-utils) (`split`, `normalize`, `analyze`, `generate` and `docgen`) with provider-specific rules in `provider-dev/scripts/`. The generated provider lands in `provider-dev/openapi/src/<name>/v00.00.00000/`, which is the directory that is eventually published to the registry. `provider-dev/config/all_services.csv` is the committed contract of every operation to resource and method mapping. A diff on regeneration is a breaking change review, not noise. CI fails on uncommitted generation drift, so a regeneration must reproduce the committed artifacts byte for byte. For an existing provider repository that predates the template, copy the `.claude/skills` directory into it and start from the skill's `references/uplift-checklist.md`. ### Using Claude Code for Provider Development The template bundles the [__StackQL Provider Development skill__](https://github.com/stackql-registry/stackql-provider-TEMPLATE/blob/main/.claude/skills/stackql-provider-development/SKILL.md) for [Claude Code](https://docs.anthropic.com/en/docs/claude-code). Open a Claude Code session in a repository created from the template and ask it to build the provider; it picks up `CLAUDE.md` and the skill and works the steps in order. The skill is also the written procedure for doing the work by hand. The skill covers: - Choosing the archetype: a vendor-published OpenAPI, Swagger or discovery document (direct), or a spec derived from a vendor SDK where the SDK is the source of truth (derived) - Fetching, fixing, validating and pinning the upstream spec so every refresh is a reviewable diff - The endpoint inventory, the service split and the mapping rules that produce `all_services.csv` - Every provider document primitive and when to use it: `x-stackQL-envVar` scoping, `objectKey`, request and response transforms, pagination, query-parameter pushdown, lifecycle `EXEC` methods, the GraphQL merge and provider views - The three credential-free test layers and the live smoke suite - The documentation site, CI workflows and hand-over notes The skill's `references/` directory holds the detail for each step, and `scripts/find_extension_examples.sh` prints shipped YAML for any extension key from a clone of the provider registry, so a primitive can be seen in use before it is authored. ## Testing a Provider Locally StackQL reads providers from a registry described by the `--registry` global flag. During development point it at the generated provider directory on the local file system with signature verification disabled (documents are only signed when they are published): ```bash export LOCAL_REG='{ "url": "file:///path/to/provider-dev/openapi", "localDocRoot": "/path/to/provider-dev/openapi", "verifyConfig": { "nopVerify": true } }' stackql --registry="${LOCAL_REG}" shell ``` The directory under `localDocRoot` must contain `src/<provider>/<version>/provider.yaml` and `src/<provider>/<version>/services/*.yaml`, which is exactly what the template generates. From the shell, `SHOW SERVICES IN <provider>`, `SHOW RESOURCES IN <provider>.<service>`, `SHOW METHODS IN <provider>.<service>.<resource>` and `DESCRIBE EXTENDED <provider>.<service>.<resource>` confirm the surface before any query is run. The template's `tests/offline_validation.mjs` automates these assertions, and `npm run probe -- "SELECT ..."` runs ad-hoc SQL against the mock API and prints the wire calls. Providers pulled from a remote registry are cached under `<cwd>/.stackql` by default; use `--approot` to change the location. The [any-sdk CLI](https://github.com/stackql/any-sdk/blob/main/docs/cli.md) is useful for checking a document without StackQL in the loop: `anysdk aot <registry> <provider.yaml>` runs static analysis over a provider (unroutable `objectKey`, missing response schemas, incomplete pagination, adjacent path parameters and so on), and `anysdk query` executes a single method directly from the provider and service documents. [Automock testing](https://github.com/stackql/any-sdk/blob/main/docs/automock_testing.md) generates a mock API and expected results from the schemas in a provider for a full round trip without touching the live API. ### Testing Your Provider using the `dev` Registry Once a provider has been merged into the `dev` branch of the registry, it is available from the development registry. Point StackQL at it to verify the published artifact: ```bash export DEV_REG='{ "url": "https://registry-dev.stackql.app/providers" }' stackql --registry="${DEV_REG}" shell ``` ```sql REGISTRY PULL myprovider; ``` The template's `make smoke-live` target runs the smoke suite against the published provider for post-publish verification. ## Publishing a Provider Publishing is a separate, human-in-the-loop step and is not part of the template pipeline. 1. Fork [stackql-provider-registry](https://github.com/stackql/stackql-provider-registry) and copy the generated `provider-dev/openapi/src/<name>` directory to `providers/src/<name>` in a feature branch. 2. Raise a pull request against the `dev` branch with a description of the provider and the changes (see the registry [contribution guide](https://github.com/stackql/stackql-provider-registry/blob/main/.github/CONTRIBUTING.md)). 3. GitHub Actions validates and tests the provider using [stackql-provider-tests](https://github.com/stackql/stackql-provider-tests). The rules evaluated are: the document must be a valid OpenAPI specification, all services must be enumerable for resources, all resources must be enumerable for methods, methods callable via `SELECT` must have a valid response schema, and methods callable via `INSERT` must have a valid request schema. 4. On merge, the workflow allocates a version, signs the documents (Ed25519), packages them and publishes the artifact to the AWS S3 archive. The docs tree is then mirrored to Cloudflare R2 and the Cloudflare Worker serving `registry-dev.stackql.app` is deployed. The provider is immediately available to installations configured to use the `dev` registry. 5. After a period of monitoring, `dev` is promoted to `main`, which repeats the publish for `registry.stackql.app`. This is publication for default configured instances of StackQL. The same `stackql-provider-tests` harness can be run locally against a registry directory before raising a PR: ```bash test-provider.sh <provider_name> false /path/to/provider-dev/openapi ``` See [build and deployment](https://github.com/stackql/stackql-provider-registry/blob/main/docs/build-and-deployment.md) in the registry repository for the workflow in detail, including the provider delete guard that protects `providers/src`. --- # Using StackQL with Claude Desktop > Use StackQL with Claude Desktop to query and provision cloud resources using natural language Source: https://stackql.io/getting-started/claude-desktop StackQL integrates with Claude Desktop via the Model Context Protocol (MCP), enabling you to query and provision cloud resources across multiple cloud providers using natural language. This powerful combination allows you to interact with your cloud infrastructure conversationally while leveraging StackQL's SQL-based interface under the hood. There are three installation options, presented here in recommended order: install from the Anthropic Connector Directory, install from a downloaded bundle, or register a locally installed StackQL binary manually. ## Install from the Connector Directory (recommended) The easiest way to use the StackQL MCP server with Claude Desktop is to install it from the Anthropic Connector Directory. In Claude Desktop: **Settings -> Connectors -> Add -> Browse Connectors**, search for **StackQL**, and click **Install**. There is nothing to download and no separate StackQL installation is required. ![StackQL in the Anthropic Connector Directory](/img/stackql-anthropic-directory-listing.png) You can also view the listing directly at [claude.ai/directory](https://claude.ai/directory/connectors/ant.dir.gh.stackql.stackql). This installs the StackQL MCP server in-process for your platform: the listing serves a combined multiplatform bundle containing signed binaries for macOS universal, Windows x64, and Linux x64 and arm64, and Claude Desktop selects the right one for your machine automatically. For native Windows ARM64, install the separate `windows-arm64` bundle from the [downloads below](#install-from-a-downloaded-bundle). The Windows binaries are Authenticode-signed and the macOS binary is Apple-notarised - the same binaries as the standalone StackQL release. ![Installing the StackQL connector](/img/stackql-anthropic-directory-install.png) A directory-installed connector inherits Claude Desktop's environment, so set the environment variables for your providers at the operating-system level before launching Claude Desktop - see [Provider-Specific Credentials](#provider-specific-credentials). Claude Desktop captures its environment at launch: after changing variables you must fully quit Claude Desktop (including the tray icon on Windows) and relaunch. Asking the agent to run [`reload_credentials`](/mcp/reload_credentials) reports per-provider credential status and is the fastest way to confirm what the server can and cannot see. Claude Desktop advertises the MCP elicitation capability, so the default server mode (`safe`) will prompt you for approval on each mutation - see [Server modes](/command-line-usage/mcp#server-modes). ## Install from a downloaded bundle Use this installation option to pin a specific version, install without Connector Directory access, or verify checksums yourself before installing. The prebuilt MCP Bundle (`.mcpb`) is a one-click installable package containing the signed `stackql` binary and the server configuration. No separate StackQL installation is required. Download the bundle for your platform from the latest release: | Platform | Bundle | |---|---| | macOS (universal) | [stackql-mcp-darwin-universal.mcpb](https://github.com/stackql/stackql/releases/latest/download/stackql-mcp-darwin-universal.mcpb) | | Windows AMD64 (x64) | [stackql-mcp-windows-x64.mcpb](https://releases.stackql.io/stackql/latest/stackql-mcp-windows-x64.mcpb) | | Windows ARM64 (native) | [stackql-mcp-windows-arm64.mcpb](https://releases.stackql.io/stackql/latest/stackql-mcp-windows-arm64.mcpb) | | Linux x64 | [stackql-mcp-linux-x64.mcpb](https://github.com/stackql/stackql/releases/latest/download/stackql-mcp-linux-x64.mcpb) | | Linux arm64 | [stackql-mcp-linux-arm64.mcpb](https://github.com/stackql/stackql/releases/latest/download/stackql-mcp-linux-arm64.mcpb) | Then in Claude Desktop: **Settings -> Extensions -> Install Extension** and select the downloaded file. The embedded binary is Authenticode-signed (Windows) and Apple-notarised (macOS); each bundle has a `.sha256` checksum alongside it on the [release page](https://github.com/stackql/stackql/releases/latest). To verify before installing: ```bash # macOS / Linux shasum -a 256 -c stackql-mcp-darwin-universal.mcpb.sha256 ``` The server is also listed on the [Official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=stackql) as `io.github.stackql/stackql-mcp`, which pins these checksums. ## Manual Configuration If you already have StackQL installed, you can register the StackQL MCP server in Claude Desktop's configuration file directly. ### Prerequisites Before setting up StackQL with Claude Desktop, ensure you have: 1. **StackQL installed** - Download and install StackQL from [stackql.io](https://stackql.io/downloads) or use a package manager 2. **Claude Desktop** - Download from [Anthropic's website](https://claude.ai/desktop) 3. **Cloud provider credentials** - API keys or credentials for the cloud providers you want to work with Verify StackQL is in your system PATH by running: ```bash stackql --version ``` ### Setting Up the MCP Server To enable Claude Desktop to communicate with StackQL, you need to configure the MCP server in your Claude Desktop configuration file. #### Windows Edit the configuration file located at: ``` %APPDATA%\Claude\claude_desktop_config.json ``` #### macOS Edit the configuration file located at: ``` ~/Library/Application Support/Claude/claude_desktop_config.json ``` #### Linux Edit the configuration file located at: ``` ~/.config/Claude/claude_desktop_config.json ``` ### Configuration Example Add the following configuration to your `claude_desktop_config.json` file: ```json { "mcpServers": { "stackql": { "command": "stackql", "args": [ "mcp", "--mcp.server.type=stdio", "--tls.allowInsecure" ], "env": { "GOOGLE_CREDENTIALS": "/path/to/google-credentials.json", "AWS_ACCESS_KEY_ID": "your-aws-access-key-id", "AWS_SECRET_ACCESS_KEY": "your-aws-secret-access-key", "AZURE_CLIENT_ID": "your-azure-client-id", "AZURE_CLIENT_SECRET": "your-azure-client-secret", "AZURE_TENANT_ID": "your-azure-tenant-id", "DATABRICKS_CLIENT_ID": "your-databricks-client-id", "DATABRICKS_CLIENT_SECRET": "your-databricks-client-secret", "OPENAI_API_KEY": "your-openai-api-key" } } } } ``` :::tip You only need to include environment variables for the cloud providers you plan to use. Remove any unused provider credentials from the configuration. ::: :::warning Never commit your `claude_desktop_config.json` file with actual credentials to version control. Use secure credential management practices. ::: Claude Desktop advertises the MCP elicitation capability, so the default server mode (`safe`) will prompt you for approval on each mutation. Switch to `mode: read_only` for inventory-only access or `mode: full_access` to skip prompts - see [Server modes](/command-line-usage/mcp#server-modes). ### Using a Credentials File (`--env.file`) An alternative to the `env` block - and on Windows the recommended one - is to keep credentials in a dotenv-style file and pass it with the [`--env.file`](/command-line-usage/mcp#credential-resourcing---envfile--reload_credentials) flag: ```json { "mcpServers": { "stackql": { "command": "stackql", "args": [ "mcp", "--mcp.server.type=stdio", "--tls.allowInsecure", "--env.file=C:\\Users\\me\\stackql-credentials.env" ] } } } ``` With a minimal credentials file: ```bash # stackql-credentials.env GOOGLE_CREDENTIALS=/path/to/google-credentials.json AWS_ACCESS_KEY_ID=your-aws-access-key-id AWS_SECRET_ACCESS_KEY=your-aws-secret-access-key ``` Why this beats the `env` block: - Changes to the `env` block require a full Claude Desktop restart (including quitting the tray icon) before the MCP subprocess sees them, and on Windows `setx` writes the registry - it never reaches the running Desktop process. - The `--env.file` file can be created or rotated at any time - it does not even need to exist when the server starts - and asking the agent to run [`reload_credentials`](/mcp/reload_credentials) picks up the changes without any restart. :::note `--env.file` and `reload_credentials` are available in StackQL releases after `v0.10.542`. ::: ### Provider-Specific Credentials Different cloud providers require different authentication methods, see the provider docs ([https://stackql.io/providers](/providers))for the environment variables required for your desired provider(s). ### Restarting Claude Desktop After updating the configuration file, restart Claude Desktop to load the new MCP server configuration. The StackQL MCP server will be automatically started when you begin a new conversation. ## What You Can Do Once configured, you can use natural language in Claude Desktop to: ### Query Cloud Resources Ask Claude to retrieve information about your cloud infrastructure: - "Show me all my GCP compute instances in the us-central1 region" - "List all S3 buckets in my AWS account" - "What Azure virtual machines are running in my subscription?" - "Show me all Kubernetes pods in the default namespace" ### Provision Resources Create and deploy cloud resources using conversational commands: - "Create an S3 bucket named 'my-data-bucket' in us-west-2" - "Deploy a GCP Cloud Storage bucket with versioning enabled" - "Launch a small EC2 instance in us-east-1" - "Create an Azure resource group in westus2" ### Analyze and Audit Perform security audits and compliance checks: - "Show me all publicly accessible S3 buckets" - "List IAM users who haven't logged in for 90 days" - "Find all GCP instances without proper labels" - "Identify Azure VMs without backup enabled" ### Cross-Cloud Operations Query and compare resources across multiple cloud providers: - "Show me all compute instances across AWS, GCP, and Azure" - "Compare storage costs between AWS S3 and GCP Cloud Storage" - "List all databases across all cloud providers" ### Infrastructure as Code Generate and execute infrastructure deployment queries: - "Create a stack of resources including a VPC, subnet, and EC2 instance" - "Deploy a complete GKE cluster with node pools" - "Set up a multi-region deployment in AWS" ### Modify Resources Update existing cloud resources: - "Add tags to all untagged EC2 instances" - "Enable encryption for S3 bucket 'my-bucket'" - "Update the machine type of GCP instance 'web-server-1'" - "Change the ACL on my Cloud Storage bucket to private" ### Delete Resources Remove cloud resources when no longer needed: - "Delete the S3 bucket 'temp-bucket'" - "Remove all stopped EC2 instances" - "Clean up unused GCP disks" ## Example Conversation Here's an example of how you might interact with Claude Desktop using StackQL: **You:** "Can you show me all my GCP compute instances?" **Claude:** *Executes a StackQL query and returns results in a formatted table showing instance names, zones, machine types, and status* **You:** "Create a new Cloud Storage bucket named 'analytics-data-2025' in the us-central1 region with uniform bucket-level access" **Claude:** *Executes a StackQL INSERT statement to create the bucket and confirms the creation* **You:** "Now list all my Cloud Storage buckets" **Claude:** *Executes a SELECT query and shows all buckets including the newly created one* ## Tips and Best Practices 1. **Be Specific**: The more specific your request, the better results you'll get. Include resource names, regions, and specific attributes when possible. 2. **Use Natural Language**: You don't need to know SQL syntax - Claude translates your natural language requests into StackQL queries. 3. **Review Before Executing**: For destructive operations (DELETE, UPDATE), Claude will typically show you what will be executed before proceeding. 4. **Multi-Step Operations**: You can chain operations together in a single conversation. Claude maintains context throughout the session. 5. **Error Handling**: If a query fails, Claude can help troubleshoot and suggest corrections based on the error message. 6. **Explore Capabilities**: Ask Claude "What can I do with StackQL?" to get suggestions specific to your configured providers. ## Troubleshooting ### MCP Server Not Starting If Claude Desktop cannot connect to the StackQL MCP server: 1. Verify StackQL is in your PATH 2. Check that your `claude_desktop_config.json` file is valid JSON 3. Ensure the file path in the configuration is correct for your operating system 4. Review the Claude Desktop logs for error messages ### Authentication Errors If you receive authentication errors: 1. Verify your cloud provider credentials are correct 2. Ensure credential files exist at the specified paths 3. Check that environment variables are properly formatted in the configuration - asking the agent to run [`reload_credentials`](/mcp/reload_credentials) reports per-provider credential status and is the fastest way to see which variable is missing 4. Confirm your credentials have the necessary permissions ### Permission Errors If operations fail due to insufficient permissions: 1. Verify your service account or IAM user has the required permissions 2. Check provider-specific IAM policies 3. Ensure API services are enabled in your cloud projects ## Learn More - [StackQL MCP Command Reference](/command-line-usage/mcp) - [StackQL Provider Registry](/providers) - [Language Specification](/language-spec/select) - [Model Context Protocol Documentation](https://modelcontextprotocol.io) ## Security Considerations :::caution - Store credentials securely and never commit them to version control - Use least-privilege access principles for service accounts - Regularly rotate credentials and API keys - Monitor MCP server logs for unusual activity - Consider using cloud provider credential management tools (e.g., Secret Manager, Parameter Store) ::: --- # OTel Backend Recipes > Cloud inventory, drift and entitlement history from StackQL otel output in ClickHouse and Datadog, with a scheduled CI example Source: https://stackql.io/getting-started/otel-recipes See also: [[` Output Modes `]](/getting-started/output-modes#otel-output) [[` exec `]](/command-line-usage/exec) `stackql exec --output otel` turns a query into a timestamped snapshot: one OpenTelemetry log record per row, a completion record per statement, and the correlation keys `stackql.snapshot.id`, `stackql.query.hash` and `stackql.row.fingerprint` on every record (see [`otel` Output](/getting-started/output-modes#otel-output)). This page takes those records end to end in the two backends the format was designed for: a typed inventory table in ClickHouse (including ClickStack), and log queries and monitors in Datadog. The last section is a scheduled CI job that stamps each run with a trace id and resource attributes. The recipes use two recurring queries, an inventory of Compute Engine instances and the IAM bindings of a project unnested to one row per principal and role. Both project an `identity` column, the key the backend tracks a resource by (`id`, `arn`, `selfLink`, or a concatenation for a composite key); the fingerprint is the value. ```sql -- inventory: one row per instance select id as identity, name, status, machineType, zone from google.compute.instances where project = 'stackql-demo' and zone = 'australia-southeast1-a'; -- entitlements: one row per principal and role select iam.role || '/' || split_part(json_each.value, ':', 2) as identity, iam.role, split_part(json_each.value, ':', 2) as principal from google.cloudresourcemanager.projects_iam_policies iam, json_each(members) where projectsId = 'stackql-demo'; ``` Each query has a stable `stackql.query.hash`, and the recipes filter on it so a series is one recurring query and nothing else. Use `{query_hash:String}` as a query parameter in ClickHouse, or paste the hash from a completion record. ## ClickHouse The OpenTelemetry Collector's ClickHouse exporter, which ClickStack ships, lands log records in `otel_logs` with the attributes as string maps (`ResourceAttributes`, `LogAttributes`) alongside `Timestamp`, `Body`, `TraceId` and `ScopeName`. Point the exporter at ClickStack's OTLP intake or at a Collector: ```shell OTEL_RESOURCE_ATTRIBUTES=deployment.environment=prod,stackql.job=gce-inventory \ stackql exec --output otel -f instances.otlp.jsonl \ --otel.config '{ "exporter": { "endpoint": "http://clickstack.example:4318/v1/logs", "headers": { "authorization": "'"$CLICKSTACK_INGESTION_KEY"'" } } }\' \ "select id as identity, name, status, machineType, zone from google.compute.instances \ where project = 'stackql-demo' and zone = 'australia-southeast1-a'" ``` ### Typed inventory table Querying `otel_logs` directly works, but every question then pays for the map lookups. A materialized view lifts the row records into a typed table keyed by `(query_hash, identity, snapshot_time)`: ```sql CREATE TABLE stackql_inventory ( snapshot_time DateTime64(9), snapshot_id String, query_hash String, provider LowCardinality(String), service LowCardinality(String), resource LowCardinality(String), identity String, fingerprint String, attributes Map(LowCardinality(String), String), document String, environment LowCardinality(String), trace_id String ) ENGINE = MergeTree ORDER BY (query_hash, identity, snapshot_time); CREATE MATERIALIZED VIEW stackql_inventory_mv TO stackql_inventory AS SELECT Timestamp AS snapshot_time, LogAttributes['stackql.snapshot.id'] AS snapshot_id, LogAttributes['stackql.query.hash'] AS query_hash, LogAttributes['stackql.provider'] AS provider, LogAttributes['stackql.service'] AS service, LogAttributes['stackql.resource'] AS resource, LogAttributes['identity'] AS identity, LogAttributes['stackql.row.fingerprint'] AS fingerprint, LogAttributes AS attributes, Body AS document, ResourceAttributes['deployment.environment'] AS environment, TraceId AS trace_id FROM otel_logs WHERE ScopeName = 'github.com/stackql/stackql/internal/stackql/output' AND mapContains(LogAttributes, 'stackql.row.index'); ``` The completion records go to a small table of their own. It defines what "the latest snapshot" means in every recipe below: a snapshot counts once its completion record has arrived, so a run that fails part way is never mistaken for a smaller estate. ```sql CREATE TABLE stackql_snapshots ( snapshot_time DateTime64(9), snapshot_id String, query_hash String, query String, rows_returned UInt32, duration_ms UInt32, environment LowCardinality(String) ) ENGINE = MergeTree ORDER BY (query_hash, snapshot_time); CREATE MATERIALIZED VIEW stackql_snapshots_mv TO stackql_snapshots AS SELECT Timestamp AS snapshot_time, LogAttributes['stackql.snapshot.id'] AS snapshot_id, LogAttributes['stackql.query.hash'] AS query_hash, LogAttributes['stackql.query'] AS query, toUInt32OrZero(LogAttributes['stackql.rows_returned']) AS rows_returned, toUInt32OrZero(LogAttributes['stackql.duration_ms']) AS duration_ms, ResourceAttributes['deployment.environment'] AS environment FROM otel_logs WHERE ScopeName = 'github.com/stackql/stackql/internal/stackql/output' AND LogAttributes['stackql.snapshot.complete'] = 'true'; ``` A materialized view only sees rows inserted after it is created. Backfill records that landed earlier with an `INSERT INTO ... SELECT` using the same select as the view. ### Latest state per resource The current estate is the row set of the latest complete snapshot: ```sql WITH (SELECT snapshot_id FROM stackql_snapshots WHERE query_hash = {query_hash:String} ORDER BY snapshot_time DESC LIMIT 1) AS latest SELECT identity, attributes['name'] AS name, attributes['status'] AS status, document FROM stackql_inventory WHERE snapshot_id = latest ORDER BY identity; ``` For the last known state of every resource ever seen, including resources that have since disappeared, aggregate with `argMax`: ```sql SELECT identity, argMax(document, snapshot_time) AS document, argMax(fingerprint, snapshot_time) AS fingerprint, max(snapshot_time) AS last_seen FROM stackql_inventory WHERE query_hash = {query_hash:String} GROUP BY identity ORDER BY last_seen DESC; ``` ### Drift between two snapshots Join the two snapshots on identity. A fingerprint inequality is a change; a missing side is a resource that appeared or disappeared: ```sql WITH (SELECT snapshot_id FROM stackql_snapshots WHERE query_hash = {query_hash:String} ORDER BY snapshot_time DESC LIMIT 1) AS latest, (SELECT snapshot_id FROM stackql_snapshots WHERE query_hash = {query_hash:String} ORDER BY snapshot_time DESC LIMIT 1 OFFSET 1) AS previous SELECT if(n.identity != '', n.identity, p.identity) AS identity, multiIf(p.identity = '', 'appeared', n.identity = '', 'disappeared', 'changed') AS change, p.document AS before, n.document AS after FROM (SELECT identity, fingerprint, document FROM stackql_inventory WHERE snapshot_id = latest) AS n FULL OUTER JOIN (SELECT identity, fingerprint, document FROM stackql_inventory WHERE snapshot_id = previous) AS p ON n.identity = p.identity WHERE n.fingerprint != p.fingerprint ORDER BY change, identity; ``` Substitute any two snapshot ids to diff arbitrary points in time. When only one side is wanted, the same question is an anti-join: ```sql -- appeared since the previous snapshot SELECT n.identity, n.document FROM (SELECT identity, document FROM stackql_inventory WHERE snapshot_id = latest) AS n LEFT ANTI JOIN (SELECT identity FROM stackql_inventory WHERE snapshot_id = previous) AS p ON n.identity = p.identity; -- disappeared since the previous snapshot SELECT p.identity, p.document FROM (SELECT identity, document FROM stackql_inventory WHERE snapshot_id = previous) AS p LEFT ANTI JOIN (SELECT identity FROM stackql_inventory WHERE snapshot_id = latest) AS n ON p.identity = n.identity; ``` The `change` column is the drift scope of the projection: columns left out of the `SELECT` cannot cause a change, so a query that projects only `name` and `status` reports state changes and nothing else. ### Entitlement history For the entitlement query the identity is the principal and role pair, so a pair's timeline in the inventory table is the lifetime of that entitlement: ```sql WITH (SELECT max(snapshot_time) FROM stackql_snapshots WHERE query_hash = {query_hash:String}) AS latest_time SELECT attributes['principal'] AS principal, attributes['role'] AS role, min(snapshot_time) AS first_seen, max(snapshot_time) AS last_seen, max(snapshot_time) < latest_time AS revoked FROM stackql_inventory WHERE query_hash = {query_hash:String} GROUP BY principal, role ORDER BY last_seen DESC, principal, role; ``` `first_seen` and `last_seen` collapse a grant that was revoked and later re-granted into one span; `groupArray(snapshot_time)` on the same grouping lists every snapshot the pair was present in when the gaps matter. Everything else on this page applies unchanged: the drift recipe on the entitlement query lists grants and revocations between two runs. ## Datadog Send the records to the OTLP receiver of a Datadog Agent (enable the HTTP receiver in the Agent's `otlp_config`, port `4318`) or of an OpenTelemetry Collector running the Datadog exporter. Datadog's own OTLP intake takes the records directly with the API key as a header; take the regional URL from Datadog's OTLP ingestion documentation. ```shell OTEL_RESOURCE_ATTRIBUTES=deployment.environment=prod,stackql.job=gce-inventory \ stackql exec --output otel -f instances.otlp.jsonl \ --otel.config '{ "exporter": { "endpoint": "http://datadog-agent.example:4318/v1/logs" } }' \ "select id as identity, name, status, machineType, zone from google.compute.instances \ where project = 'stackql-demo' and zone = 'australia-southeast1-a'" ``` ```shell stackql exec --output otel ... \ --otel.config '{ "exporter": { "endpoint": "<regional OTLP logs intake URL>", "headers": { "dd-api-key": "'"$DD_API_KEY"'" } } }' ``` ### Attribute mapping | OpenTelemetry | Datadog | |--|--| |`service.name` resource attribute|`service` tag (`stackql`, or `OTEL_SERVICE_NAME`)| |`deployment.environment` resource attribute|`env` tag| |`cloud.provider`, `cloud.account.id`, `cloud.region`, `cloud.availability_zone` and other resource attributes|Log attributes, for example `@cloud.account.id`| |`stackql.*` log attributes|Log attributes, for example `@stackql.snapshot.id`; add facets for the ones you filter on| |Row columns (`identity`, `name`, `status`, ...)|Log attributes under the column name, for example `@status`| |Record body|`message`, the row as JSON| |`traceId`, `spanId`|`trace_id`, `span_id`, correlating every statement of one run| ### Log queries Datadog answers presence and history questions; joins between snapshots are done in ClickHouse, or by fanning the same stream out to both through a Collector. ``` # completion records of one recurring query, newest first: the latest snapshot id service:stackql @stackql.snapshot.complete:true @stackql.query.hash:<hash> # the rows of one snapshot service:stackql @stackql.query.hash:<hash> @stackql.snapshot.id:<snapshot id> # the timeline of one resource; a new fingerprint value is a change service:stackql @identity:<instance id> # every principal that has held a role, grouped by @principal in Log Analytics; # the first and last log in a group are first seen and last seen service:stackql @stackql.query.hash:<entitlements hash> @role:roles/owner ``` Monitors on the completion records watch the pipeline itself: a log monitor on `service:stackql @stackql.snapshot.complete:true @stackql.rows_returned:0` catches an inventory that came back empty, and a monitor with a "no data" condition on `service:stackql @stackql.snapshot.complete:true @stackql.job:gce-inventory` catches a scheduled run that did not happen. ## Scheduled CI A scheduled job makes the series. The example runs both queries hourly from GitHub Actions: the exporter is configured once in `OTEL_CONFIG` and passed to `--otel.config`, `TRACEPARENT` gives every statement of a run the same trace id, `OTEL_RESOURCE_ATTRIBUTES` stamps the environment, the job name and the run id on every record, and the `.otlp.jsonl` files are kept as artifacts so a failed push still leaves a copy. ```yaml name: cloud-inventory on: schedule: - cron: '0 * * * *' workflow_dispatch: jobs: snapshot: runs-on: ubuntu-latest env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }} OTEL_CONFIG: '{ "exporter": { "endpoint": "${{ vars.OTLP_LOGS_ENDPOINT }}", "headers": { "authorization": "${{ secrets.OTLP_INGESTION_KEY }}" } } }' OTEL_RESOURCE_ATTRIBUTES: deployment.environment=prod,stackql.job=cloud-inventory,stackql.run=${{ github.run_id }} steps: - uses: stackql/setup-stackql@v2 - name: snapshot run: | export TRACEPARENT="00-$(openssl rand -hex 16)-$(openssl rand -hex 8)-01" stackql exec --output otel -f instances.otlp.jsonl --otel.config "$OTEL_CONFIG" \ "select id as identity, name, status, machineType, zone from google.compute.instances \ where project = 'stackql-demo' and zone = 'australia-southeast1-a'" stackql exec --output otel -f entitlements.otlp.jsonl --otel.config "$OTEL_CONFIG" \ "select iam.role || '/' || split_part(json_each.value, ':', 2) as identity, \ iam.role, split_part(json_each.value, ':', 2) as principal \ from google.cloudresourcemanager.projects_iam_policies iam, json_each(members) \ where projectsId = 'stackql-demo'" - uses: actions/upload-artifact@v4 with: name: inventory-${{ github.run_id }} path: "*.otlp.jsonl" ``` The same job on any other scheduler needs only the flag and the two environment variables; `TRACEPARENT` is optional and is generated per process when absent, in which case the statements of one run still share a trace id. --- # Output Modes > StackQL output modes: table, json, jsonl, csv and otel, how to select them, and what each emits for shell, exec and server use. Source: https://stackql.io/getting-started/output-modes See also: [[` exec `]](/command-line-usage/exec) [[` shell `]](/command-line-usage/shell) Results returned from StackQL queries can be formatted in tabular (table) format, as well as json, jsonl (newline delimited JSON), csv, text or otel (OpenTelemetry log records) format. JSON, JSONL and CSV formats can be used to interchange data with other programs; the `otel` format ships a result set to an OpenTelemetry backend as a timestamped snapshot. The desired output format is configured using the `--output` StackQL flag. ### `table` Output Format Results can be formatted in a table format using the `table` value for the `--output` parameter as shown below (this is the default value for the StackQL interactive shell): ```shell stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' \ and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output table |---------------------|-----------------| | ID | NAME | |---------------------|-----------------| | 1257085253691867467 | demo-instance-1 | |---------------------|-----------------| | 2586731219281477960 | demo-instance-2 | |---------------------|-----------------| | 5584456226809282885 | demo-instance-3 | |---------------------|-----------------| ``` ### `json` Output Results can be returned in JSON format using the `json` value for the `--output` parameter as shown below, this output format is useful if the results of a query need to be passed to an external process or script: ```shell stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' \ and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output json [{"id":"5584456226809282885","name":"demo-instance-3"} ,{"id":"1257085253691867467","name":"demo-instance-1"} ,{"id":"2586731219281477960","name":"demo-instance-2"}] ``` ### `jsonl` Output Results can be returned in newline delimited JSON (JSON Lines) format using the `jsonl` value for the `--output` parameter as shown below (`ndjson` is accepted as an alias). Each row is written as a single JSON object on its own line and rows are flushed as they are written, making this output format useful for streaming results to line-oriented tools or piping large result sets to other programs: ```shell stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' \ and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output jsonl {"id":"5584456226809282885","name":"demo-instance-3"} {"id":"1257085253691867467","name":"demo-instance-1"} {"id":"2586731219281477960","name":"demo-instance-2"} ``` ### `csv` Output Results can be returned in JSON format using the `csv` value for the `--output` parameter as shown below, this output format is useful for parsing results in Excel or providing a data interface to another system: ```shell stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' \ and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output csv id,name 1257085253691867467,demo-instance-1 2586731219281477960,demo-instance-2 5584456226809282885,demo-instance-3 ``` #### Csv Output Example (with alternative delimiter) An alternatate delimiter can be specified for the `csv` output format using the `-d` switch as shown below: ```shell stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' \ and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output csv -d "|" id|name 1257085253691867467|demo-instance-1 2586731219281477960|demo-instance-2 5584456226809282885|demo-instance-3 ``` ### `otel` Output Results can be emitted as OpenTelemetry log records using the `otel` value for the `--output` parameter. Each row is written as one OTLP/JSON `LogsData` object on its own line, flushed as it is written like `jsonl`, followed by one completion record for the statement. This output format turns a query into a cloud configuration snapshot as telemetry: run an inventory query on a schedule, ship the records to an OTLP-capable backend (ClickHouse, Datadog, or an OpenTelemetry Collector in front of anything else), and answer "what does the estate look like now", "what changed since the last run", and "who has had which entitlement, and since when" there. Available in StackQL releases from `v0.11.660`. ```shell stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' \ and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output otel -f instances.otlp.jsonl ``` One row record, pretty-printed (the file holds each record on one line): ```json {"resourceLogs":[{"resource":{"attributes":[ {"key":"service.name","value":{"stringValue":"stackql"}}, {"key":"service.version","value":{"stringValue":"0.11.660"}}, {"key":"cloud.provider","value":{"stringValue":"gcp"}}, {"key":"cloud.account.id","value":{"stringValue":"stackql-demo"}}, {"key":"cloud.availability_zone","value":{"stringValue":"australia-southeast1-a"}} ]},"scopeLogs":[{"scope":{"name":"github.com/stackql/stackql/internal/stackql/output","version":"1.0.0"}, "logRecords":[{ "timeUnixNano":"1788739200000000000","observedTimeUnixNano":"1788739203412000000", "severityNumber":9,"severityText":"INFO", "body":{"stringValue":"{\"id\":\"1257085253691867467\",\"name\":\"demo-instance-1\"}"}, "attributes":[ {"key":"id","value":{"stringValue":"1257085253691867467"}}, {"key":"name","value":{"stringValue":"demo-instance-1"}}, {"key":"stackql.snapshot.id","value":{"stringValue":"1e0d4a6c-4b0f-4b4e-9f7d-2a6c9a1f3b21"}}, {"key":"stackql.query","value":{"stringValue":"select id, name from google.compute.instances where project = 'stackql-demo' and zone = 'australia-southeast1-a'"}}, {"key":"stackql.query.hash","value":{"stringValue":"9c1d2e..."}}, {"key":"stackql.provider","value":{"stringValue":"google"}}, {"key":"stackql.service","value":{"stringValue":"compute"}}, {"key":"stackql.resource","value":{"stringValue":"instances"}}, {"key":"stackql.row.index","value":{"intValue":"0"}}, {"key":"stackql.row.fingerprint","value":{"stringValue":"sha256:7f3a..."}} ], "traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"a1b2c3d4e5f60718" }],"schemaUrl":"https://opentelemetry.io/schemas/1.44.0"}],"schemaUrl":"https://opentelemetry.io/schemas/1.44.0"}]} ``` #### Snapshots One statement is one snapshot. Every record of the statement carries the same `timeUnixNano` (the statement start time), the same `stackql.snapshot.id` and the same `spanId`, so as-of queries, diffs and latest-state queries work even though rows arrive across pages over several seconds; `observedTimeUnixNano` records when each record was actually written. All statements of one invocation share a `traceId`, taken from a `TRACEPARENT` environment variable when one is set (the convention for CI pipelines) and generated otherwise. The last record of a statement is the completion record: body `snapshot complete <provider.service.resource>`, with `stackql.snapshot.complete=true`, `stackql.rows_returned` and `stackql.duration_ms`. It tells the backend the snapshot is whole, and a statement that returns no rows still emits it, so a resource that has disappeared shows up as drift rather than as silence. A failed statement produces an `ERROR` record carrying `error.type` and `error.message` when the error presentation is `record`; by default errors go to stderr as for every other output format. #### Record shape The body is the complete row as compact JSON, nested objects intact, and is the source of truth for the full document. The attributes carry each column under its own name, typed where the value is a scalar (`stringValue`, `intValue`, `doubleValue`, `boolValue`); nested columns are carried as JSON strings, which is portable across backends whose default attribute schema is string-valued, and null columns are omitted. The reserved `stackql.*` attributes are: | Attribute | Record | Value | |--|--|--| |`stackql.snapshot.id`|all|UUID generated per statement execution| |`stackql.query`|all|The submitted query text, verbatim| |`stackql.query.hash`|all|SHA-256 of the query text; a cheaper series key than the SQL for a recurring job| |`stackql.provider`, `stackql.service`, `stackql.resource`|all|The statement's primary table; omitted for joins and views that span tables| |`stackql.row.index`|row|Zero-based position in the result set| |`stackql.row.fingerprint`|row|`sha256:` of the canonical row JSON, so drift is one comparison per identity instead of a comparison over every attribute| |`stackql.snapshot.complete`|completion|`true`| |`stackql.rows_returned`|completion|Row count for the statement| |`stackql.duration_ms`|completion|Wall-clock duration from statement start| The emitted attribute set is a versioned interface: the instrumentation scope is `github.com/stackql/stackql/internal/stackql/output` at version `1.0.0`, and `schemaUrl` pins the stable conventions to `https://opentelemetry.io/schemas/1.44.0`. No resource identity is inferred: the fingerprint is the value and the backend chooses the key (`id`, `arn`, `selfLink`, or a tuple of columns). To track entitlements as entities, explode bindings to one row per principal and role in SQL; the telemetry follows the result grain. #### Resource attributes The resource carries `service.name` (`stackql`, or the value of `OTEL_SERVICE_NAME`) and `service.version`, the OpenTelemetry cloud conventions where they can be derived from a single-table `SELECT` (`cloud.provider` from the provider; `cloud.account.id` from a `project` or `subscriptionId` equality in the `WHERE` clause; `cloud.region` from `region`; `cloud.availability_zone` from `zone`), and every pair in the standard `OTEL_RESOURCE_ATTRIBUTES` environment variable, so a pipeline step can stamp `deployment.environment`, a job name or account tags with no additional flags: ```shell TRACEPARENT=00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 \ OTEL_RESOURCE_ATTRIBUTES=deployment.environment=prod,stackql.job=gce-inventory \ stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output otel -f instances.otlp.jsonl ``` #### Shipping the records The file is one `LogsData` per line, the shape the OpenTelemetry Collector's `otlp_json_file` receiver ingests with no transform processor: ```yaml receivers: otlp_json_file: include: [/var/lib/stackql/inventory/*.otlp.jsonl] exporters: otlphttp: endpoint: https://otlp.example.com service: pipelines: logs: receivers: [otlp_json_file] exporters: [otlphttp] ``` Each line is also, byte for byte, the body of an OTLP/HTTP `POST /v1/logs` request, which is what the built-in push exporter sends. #### Pushing to an OTLP endpoint The records can be pushed straight to an OTLP/HTTP logs endpoint, as well as being written to the file or stdout, by configuring an exporter in the `--otel.config` flag, a JSON or YAML string like the other configuration flags (available in StackQL releases from `v0.12.732`): ```shell stackql exec "select id, name from google.compute.instances \ where project = 'stackql-demo' and zone = 'australia-southeast1-a'" \ --keyfilepath stackql-demo.json --output otel -f instances.otlp.jsonl \ --otel.config '{ "exporter": { "endpoint": "http://clickstack.example:4318/v1/logs", "headers": { "authorization": "'"$CLICKSTACK_INGESTION_KEY"'" } } }\' ``` | Key | Purpose | |--|--| |`exporter.endpoint`|Full URL of the logs endpoint, for example `http://localhost:4318/v1/logs`; required to enable the exporter| |`exporter.headers`|Request headers sent with every export, typically an ingestion token or API key| |`exporter.timeout_ms`|Request timeout in milliseconds, default `10000`| |`exporter.batch_size`|Records per request, default `512`| Each statement is one batch: its row records and completion record are sent as a single OTLP/JSON `LogsData` (one resource and scope envelope, one entry in `logRecords` per record), and a large result set is split into requests of at most `batch_size` records as the rows stream, with the final request following the completion record. `429` and `5xx` responses and connection failures are retried up to four attempts with a doubling backoff from 500ms, honouring a delay-seconds `Retry-After` header (capped at 30 seconds) when the server sends one; other errors are not retried. The file or stream is written regardless, so a failed push leaves a local copy and an error line on stderr. The exporter speaks OTLP/JSON over HTTP; an endpoint that only accepts protobuf needs a Collector in front of it. No `OTEL_EXPORTER_OTLP_*` environment variables are read; every exporter setting comes from `--otel.config`. A malformed `--otel.config` value, or an `exporter` object without an `endpoint`, fails startup. This targets ClickStack's OTLP intake (`http://<host>:4318/v1/logs`, header `authorization: <ingestion API key>`), the OTLP receiver of a Datadog Agent or the Datadog OTLP intake (`dd-api-key: <key>`), and any OpenTelemetry Collector `otlp` receiver. See [OTel Backend Recipes](/getting-started/otel-recipes) for the inventory, drift and entitlement queries on the receiving side. --- # Provider Sessions and Secrets > Provider sessions in StackQL: bind provider aliases with their own credentials, tenancy and parameter defaults, override credential fields per session, and hold secrets in session memory or an OS secret store. Source: https://stackql.io/getting-started/provider-sessions See also: [[` SET `]](/language-spec/set) [[` UNSET `]](/language-spec/unset) [[ Session Variables ]](/getting-started/session-variables) [[ Global Flags ]](/command-line-usage/global-flags) A session can bind a provider under an alias with its own credentials, tenancy label, parameter defaults and request concurrency limits, so several accounts or tenants of the same provider can be queried in one session, and in one statement. Credential fields can also be overridden for the session, and secrets can be held in session memory or, with an operator opt-in, in the operating system's secret store. All of this is configured with [`SET`](/language-spec/set) and [`UNSET`](/language-spec/unset) and is available in StackQL `v1.0` and later. Everything described here is scoped to the current session. Independent connections to a `stackql srv` server do not share bindings or secrets, and each MCP request is its own session, so configure and query in one statement batch when using the MCP server. ## Provider aliases `SET "$.providers.<alias>"` binds an alias to a provider. The value is a JSON document held in a string: | Key | Required | Description | |--|--|--| | `provider` | Yes | The canonical provider the alias resolves to, for example `aws`. | | `tenancy` | Yes | A grouping label such as an account or tenant name. StackQL does not verify it against the provider. | | `auth` | One of `auth` or `auth_secret` | An authentication document with the same shape as the provider's entry in the [`--auth`](/command-line-usage/global-flags) object. The alias does not borrow the canonical provider's credentials. | | `auth_secret` | One of `auth` or `auth_secret` | The name of a [session secret](#session-secrets) holding the authentication document. | | `params` | No | Default values for declared provider parameters, including declared server parameters. A predicate in the query overrides a default. | | `tuning` | No | `max_concurrent` and `max_per_host` limits for the alias's requests. Aliases that share a provider and tenancy share these controls and must declare identical tuning. | The following binds two AWS accounts under separate aliases, each reading its keys from differently named environment variables, and queries both in one statement: ```sql SET "$.providers.production" = '{ "provider": "aws", "tenancy": "production-account", "auth": { "type": "aws_signing_v4", "access_key_id_env_var": "PRODUCTION_AWS_ACCESS_KEY_ID", "secret_access_key_env_var": "PRODUCTION_AWS_SECRET_ACCESS_KEY" }, "params": {"region": "ap-southeast-2"}, "tuning": {"max_concurrent": 4, "max_per_host": 4} }'; SET "$.providers.development" = '{ "provider": "aws", "tenancy": "development-account", "auth": { "type": "aws_signing_v4", "access_key_id_env_var": "DEVELOPMENT_AWS_ACCESS_KEY_ID", "secret_access_key_env_var": "DEVELOPMENT_AWS_SECRET_ACCESS_KEY" }, "params": {"region": "ap-southeast-2"}, "tuning": {"max_concurrent": 2} }'; SELECT name, 'production' AS account FROM production.s3.buckets UNION ALL SELECT name, 'development' AS account FROM development.s3.buckets; ``` Environment variable references are resolved from the StackQL process environment; there is no session-local environment. Temporary AWS credentials also need the session token field or environment variable reference. An alias behaves like its provider for metadata and data statements: `SHOW`, `DESCRIBE`, `SELECT`, `INSERT`, `UPDATE`, `DELETE` and `EXEC` all accept the alias in place of the provider name. Aliases do not extend to native built-in relations or to the preview IaC relations. `UNION ALL` branches that use different aliases run sequentially. Each query takes a detached snapshot of the alias's credentials. Changing a binding affects later queries, not one that is already running. `UNSET "$.providers.<alias>"` removes the binding. ## Overriding credential fields `SET "$.auth.<provider>.<field>"` changes one field of a provider's authentication context for the session, where the field names are the keys of the provider's `--auth` entry: ```sql SET "$.auth.github.credentialsenvvar" = 'GITHUB_TOKEN_READONLY'; SELECT name FROM github.repos.repos WHERE org = 'stackql'; UNSET "$.auth.github.credentialsenvvar"; ``` As with aliases, the change applies to queries started after the `SET`. Queries against a provider whose authentication has been unset, or whose alias has no usable `auth`, fail before any request is sent. ## Session secrets By default every session has a memory-only secret store, with no configuration needed. `SET "$.secrets.<name>"` stores a literal string, typically a JSON authentication document, and a provider alias references it with `auth_secret`: ```sql SET "$.secrets.production" = '{"type":"aws_signing_v4","access_key_id_env_var":"PRODUCTION_AWS_ACCESS_KEY_ID","secret_access_key_env_var":"PRODUCTION_AWS_SECRET_ACCESS_KEY"}'; SET "$.providers.production" = '{"provider":"aws","tenancy":"production-account","auth_secret":"production","params":{"region":"ap-southeast-2"}}'; SELECT name FROM production.s3.buckets; UNSET "$.secrets.production"; ``` Rotating a secret affects later queries; deleting it makes later uses fail. A new session receives a fresh, empty store, and ending the session releases it. `UNSET "$.secret_store"` discards the current store binding and starts again with empty session memory. Normal credential use, and `SET` statements that store variables or configuration, do not write secrets into the SQL backend. Putting sensitive data into an ordinary variable or table is the caller's responsibility. ## Persistent OS secret stores Persistent storage is disabled by default and can only be enabled by the operator starting StackQL with `--allow-persistent-secrets`; SQL cannot grant it. With the flag set, a session selects an OS store with: ```sql SET "$.secret_store" = '{"backend": "os", "namespace": "stackql/provider-auth"}'; ``` The store is the macOS Keychain, the Linux Secret Service (`secret-tool` with a working session service) or the Windows Credential Manager. Only the `os` backend is accepted: flat-file stores, file paths and any implicit file fallback are rejected even with the flag set, and an unavailable OS facility fails rather than falling back to a file. Values written to an OS store outlive the SQL session and are deleted explicitly with `UNSET "$.secrets.<name>"`. Resetting the store binding does not delete values already persisted. Access to the store is governed by the operating system identity of the StackQL process; a namespace is not a per-user access control, so do not treat this opt-in as a multi-user vault. ## Secret values in SQL Secret values are never dereferenced into SQL unless the operator starts StackQL with `--allow-secret-dereference`. With that flag, references such as `"$secrets.production"`, `"$secrets.production.credentials"`, `"$auth.github.password"` and `"$providers.production.auth.credentials"` resolve in expressions: ```sql SELECT upper("$secrets.production.credentials") AS credential; /* -- the same statement in a session started without --allow-secret-dereference SELECT upper("$secrets.production.credentials") AS credential; -- FAILS with secret variable dereferencing is disabled */ ``` Started without the flag, the same statement is refused before anything is evaluated, as the commented-out copy shows. The flag is an acknowledgement that explicitly dereferenced values can enter SQL staging, results, logs and persisted query artefacts. Normal provider authentication does not require it. ## Permissions With [access management](/command-line-usage/access-management) enabled, reading variables and secrets requires `session/variables:read`, and `SET` or `UNSET` requires `session/config:write`. A resolved alias is authorised as its canonical provider before execution. Per-variable and per-secret ownership and grants are not implemented. --- # Resource Heirarchy > The StackQL resource hierarchy: how providers, services, resources and methods map cloud and SaaS APIs onto queryable SQL tables. Source: https://stackql.io/getting-started/resource-hierarchy See also: [[` SHOW `]](/language-spec/show) [[` DESCRIBE `]](/language-spec/describe) * * * Objects in StackQL are represented in the following hierarchy, with an example using the Google Cloud provider shown: ### Using the StackQL Object Notation This hierarchy is expressed in the object notation `<provider>.<service>.<resource>` within the context of a given provider, an example of this object notation used in a [`SELECT`](/language-spec/select) statement is shown here: ```sql -- Selecting all resources deployed within a service using a basic SELECT statement SELECT * FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ```sql -- Selecting all resources deployed within a service using a basic SELECT statement SELECT * FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` :::note If a resource or service contains a period (`.`) in the name, use the backtick symbol (__`__) to encapsulate the resource name, for example: ```sql SELECT * FROM google.container.`projects.zones.clusters.nodePools`; ``` ::: ### Showing Services in a Provider Services within a provider can be listed using the [`SHOW SERVICES`](/language-spec/show) command as shown here: ```sql -- Returns all of the available services in a cloud provider SHOW SERVICES IN google; ``` ### Showing Resources within a Service Similarly resources within a service can be listed using the [`SHOW RESOURCES`](/language-spec/show) as shown here: ```sql -- Returns all of the available resources in a cloud provider service SHOW RESOURCES IN google.compute; ``` ### Showing Fields within a Resource Fields within a resource can be displayed using a [`DESCRIBE`](/language-spec/describe) statement as shown here: ```sql -- Returns all of the available fields in a resource DESCRIBE google.compute.instances; ``` ### Showing Executable Methods for a Resource Methods available for a resource can be displayed using a [`SHOW METHODS`](/language-spec/show) command as shown here: ```sql -- Show all of the available methods for a resource SHOW METHODS IN google.compute.instances; ``` --- # Session Variables > Session variables in StackQL: set typed scalar values with SET, dereference them with $name in predicates and expressions, and use them as relation and column names with IDENTIFIER. Source: https://stackql.io/getting-started/session-variables See also: [[` SET `]](/language-spec/set) [[` UNSET `]](/language-spec/unset) [[ Provider Sessions ]](/getting-started/provider-sessions) [[ Using Variables ]](/getting-started/variables) Session variables are scalar values held by the current session and referenced from later statements. They are available in StackQL `v1.0` and later, and work in the interactive shell, in `exec` scripts, over the PostgreSQL wire protocol and through the MCP server. Session variables are distinct from the templating variables described in [Using Variables](/getting-started/variables). Templating variables are supplied to `stackql exec` through `--iqldata` and `--var` and are rendered into the script text before it is parsed. Session variables are resolved inside the parsed statement, keep their type, and can be changed between statements. ## Setting and removing variables [`SET`](/language-spec/set) assigns a string, number, boolean or `null`. [`UNSET`](/language-spec/unset) removes a variable; `SET name = DEFAULT` is equivalent. An explicit `null` is a stored value, not a reset. ```sql SET region = 'ap-southeast-2'; SET minimum_count = 3; SET enabled = true; SET optional_value = null; UNSET region; ``` Arrays and objects are not scalar values. To hold a JSON document, store it as a string: ```sql SET "providers.saved" = '{"provider":"aws","tenancy":"production"}'; ``` ## Dereferencing a variable Use `$name`, without quotes, in any expression position. Strings are escaped as SQL literals; numbers, booleans and `null` keep their type. A single-quoted `'$name'` is the literal text `$name`, not a dereference. A reference to a variable that does not exist fails before any provider request is made. Resolved values can be used in ordinary SQL expressions, including `CAST`, `CONVERT`, concatenation with `||` and function calls: ```sql SET some_id = 42; SET suffix = 'East'; SELECT CAST($some_id AS TEXT) AS id_text, CONVERT($some_id, TEXT) || '-' || lower($suffix) AS label, md5(lower(CONVERT($some_id, TEXT) || '-' || $suffix)) AS digest, '$some_id' AS literal_text; ``` Assignments accept scalar literals or direct references only; apply conversions and other expressions where the variable is used, not in the `SET` statement. ## Variables in predicates A variable in a `WHERE` clause is resolved before the statement is planned, so it is routed to the provider API exactly as a literal would be. Required parameters can therefore be supplied from variables: ```sql SET project = 'stackql-demo'; SET zone = 'australia-southeast1-a'; SELECT name, status FROM google.compute.instances WHERE project = $project AND zone = $zone; ``` Typed values are compared with their type. `WHERE active = $enabled` with `SET enabled = false` filters on the boolean, and `WHERE id = CAST($some_id AS TEXT)` is the form to use when the provider column is a string and the variable is a number. ## Variables as object names Variables can name relations and columns as well as values. Names are converted to identifiers in the parsed statement and are never spliced into SQL text, so a value that contains a statement, is empty, or is not a string is rejected before any provider access. | Position | Form | |--|--| | `FROM` clause | `FROM $relation_name`, or by component, `FROM $provider.$service.$resource` | | Column in an expression | `IDENTIFIER($column_name)`, see [`IDENTIFIER`](/language-spec/functions/general/identifier) | | Column or table alias | `AS "$alias_name"` | | `ORDER BY` | `ORDER BY IDENTIFIER($column_name)` | | `LIMIT` | `LIMIT $row_count` | | DDL column names, `INSERT` column lists, `UPDATE` targets | the double-quoted `"$name"` form | ```sql SET relation_name = 'aws.s3.buckets'; SET column_name = 'name'; SET output_name = 'bucket'; SET row_count = 10; SELECT IDENTIFIER($column_name) AS "$output_name" FROM $relation_name WHERE region = 'ap-southeast-2' ORDER BY IDENTIFIER($column_name) LIMIT $row_count; ``` Joins, CTEs and subqueries resolve their relation variables in the same way. Dotted relation values have up to four components. Variables are not arbitrary SQL fragments: a keyword, a comma-separated column list or a whole `WHERE` clause cannot be substituted. ## Scope and isolation Variables belong to the session that set them. Separate connections to a `stackql srv` server have separate variables, as do separate `exec` invocations. Each MCP request is its own session, so a `SET` and the query that uses it must be sent in the same statement batch. New sessions start with no variables. The session is the only scope. `SET SESSION` and `UNSET SESSION` are accepted and mean exactly the same as `SET` and `UNSET`; the keyword is there for scripts that should read the same way as on databases where session and global settings differ. `GLOBAL` is rejected, because there is no state shared across sessions. Prepared statements resolve variables when they are executed, not when they are prepared, and a plan that contains bound session values is not reused across executions. With [access management](/command-line-usage/access-management) enabled, reading a variable requires `session/variables:read` and setting or resetting one requires `session/config:write`. Resolving a variable to an object name grants no permission on that object; the resolved relation is authorised before execution as usual. --- # Creating Infrastructure Templates > Generate INSERT templates for any resource with SHOW INSERT in StackQL, full or required parameters only, as the starting point for infrastructure definitions. Source: https://stackql.io/getting-started/templating See also: [[` exec `]](/command-line-usage/exec) [[` INSERT `]](/language-spec/insert) [[` SHOW `]](/language-spec/show) [[ Using Variables ]](/getting-started/variables) Cloud resources are deployed with StackQL using `INSERT` statements. `INSERT` templates for different cloud resources using the `SHOW INSERT` command. ### Generating an `INSERT` template using the `SHOW INSERT` command An example of generating a template is shown here: ```sql SHOW INSERT INTO google.compute.addresses; ``` This can be run through the `shell` or using an `exec` command as shown here: ```shell ./stackql exec 'show insert into google.compute.addresses' --output text --hideheaders ``` *__Returns :__* ```sql INSERT INTO google.compute.addresses( project, region, data__address, data__addressType, data__description, data__ipVersion, data__name, data__network, data__networkTier, data__prefixLength, data__purpose, data__subnetwork ) SELECT '{{ .values.project }}', '{{ .values.region }}', '{{ .values.data__address }}', '{{ .values.data__addressType }}', '{{ .values.data__description }}', '{{ .values.data__ipVersion }}', '{{ .values.data__name }}', '{{ .values.data__network }}', '{{ .values.data__networkTier }}', {{ .values.data__prefixLength }}, '{{ .values.data__purpose }}', '{{ .values.data__subnetwork }}' ``` > This template can then be used along with a `json` or `jsonnet` data file to supply values at run time,for more information see [Using Variables](/getting-started/variables). ### Generating an `INSERT` template with only required parameters To generate an StackQL `INSERT` template with only mandatory attributes use the `/*+ REQUIRED */` query hint as shown here: ```sql SHOW INSERT /*+ REQUIRED */ INTO google.compute.instances; ``` This can be run through the `shell` or using an `exec` command as shown here: ```shell ./stackql exec 'show insert /*+ REQUIRED */ into compute.instances' --output text -H ``` *__Returns :__* ```sql INSERT INTO google.compute.instances( project, zone, data__machineType, data__name ) SELECT '{{ .values.project }}', '{{ .values.zone }}', '{{ .values.data__machineType }}', '{{ .values.data__name }}' ; ``` --- # Using a Provider > Using a provider in StackQL: pull it from the registry, authenticate with environment variables or credentials, and query its services and resources. Source: https://stackql.io/getting-started/using-a-provider See also: [[` exec `]](/command-line-usage/exec) [[` shell `]](/command-line-usage/shell) [[ StackQL Provider Registry ]](/providers) StackQL queries can be run against a number of different cloud providers, including Google Cloud Platform, Amazon Web Services, Microsoft Azure, Digital Ocean, and more. StackQL provider specifications are pulled from the [__StackQL Provider Registry__](/providers), this can be done using the [__`REGISTRY PULL`__](/language-spec/registry) StackQL command, or by using the [__`stackql registry`__](/command-line-usage/registry) command line utility. ## Installing a Provider To see the list of available providers, run the following command: ```sql REGISTRY LIST; ``` To install a provider, run the following command: ```sql REGISTRY PULL okta; ``` To see providers installed on the current system, run the following command: ```sql SHOW PROVIDERS; ``` ## Authenticating to a Provider Authenticating to a cloud provider is often the first step in an StackQL routine. Meta commands such as [`SHOW`](/language-spec/show) and [`DESCRIBE`](/language-spec/describe) can be run against a provider without authenticating, but [`SELECT`](/language-spec/select), [`INSERT`](/language-spec/insert) and [`EXEC`](/language-spec/exec) commands generally require an authenticated session. Authentication is performed using environment variables set on the system (or sourced as secrets in a CI system), each provider will have it's own default unique variables used for authentication, so consult the documentation for your provider using the [StackQL Provider Registry documentation](/providers). The variables can also be sourced from a dotenv-style file at startup using the [`--env.file`](/command-line-usage/global-flags) global flag. :::tip You can authenticate to multiple providers in the same interactive shell or non-interactive batch routine by supplying multiple authentication objects, for example: ``` export AWS_ACCESS_KEY_ID=YOURACCESSKEYID export AWS_SECRET_ACCESS_KEY=YOURSECRETACCESSKEY export DIGITALOCEAN_TOKEN=dop_v1_yourdigitaloceantoken export STACKQL_GITHUB_USERNAME=yourghuser export STACKQL_GITHUB_PASSWORD=ghp_yourgithubpersonalaccesstoken ``` This is especially useful when you are joining data between multiple providers in a single query. ::: --- # Using StackQL > Using StackQL: run queries interactively in the shell, non-interactively with exec, or as a server, and discover providers, services and resources as you go. Source: https://stackql.io/getting-started/using-stackql See also: [[` exec `]](/command-line-usage/exec) [[` shell `]](/command-line-usage/shell) StackQL has several usage modes, these include: the StackQL interactive shell, the StackQL command line using StackQL statements, or executing one or more StackQL statements in an input file (IQL file). Each of the modes is described in more detail below: - Using the StackQL Interactive Shell ([`stackql shell`](/command-line-usage/shell)) - Using the StackQL Command Line Utility ([`stackql exec`](/command-line-usage/exec)) - Using an Input File (IQL File) ([`stackql exec -i`](/command-line-usage/exec)) ### Using the StackQL Interactive Shell The StackQL Shell provides an interactive programming environment for engineers to deploy and interact with cloud resources, as well as enabling interactive analysis (using [`SELECT`](/language-spec/select) statements) of their cloud environment. The shell is functionally similar to the MySQL shell or other REPL (Read Evaluate Print Loop) shells. The shell accepts valid StackQL statements, and returns results to the user. Statements can span multiple lines and are executed once a semicolon terminator is entered. The StackQL shell can be invoked using the `shell` command as shown below (see [StackQL Provider Registry](/providers)) for information about provider authentication: ```shell # Launching the StackQL Interactive Shell stackql shell --auth="${AUTH}" ``` Once in a shell authenticated to a cloud provider, you can begin running StackQL queries (`SELECT` queries or DDL - Infrastructure as Code - operations). By default the StackQL shell will return tabular results, however `json`, `jsonl`, `csv` and `text` output formats are available using the `--output` flag, see [Output Modes](/getting-started/output-modes). You can change the color scheme for the StackQL shell using the `--colorscheme` flag, as shown below: ```shell # Changing the Shell Color Scheme ./stackql shell --colorscheme light ``` ### The `.stackqlrc` Initialization File Defaults for StackQL command options, such as the output format and color scheme discussed previously, can be set using the `stackqlrc` initialization file. If this file exists in the current directory used by the StackQL executable it will be automatically loaded, or alternatively can be referenced using the `--configfile` flag as shown below: ```shell # Specifing a Initialization (.stackqlrc) File ./stackql shell --configfile /tmp/.stackqlrc ``` More information about command options is available in the Global Flags topic. ### Using the StackQL Command Line Utility StackQL commands can be executed non-interactively using the exec command of the StackQL executable. More than one command can be executed in a batch provided each discrete command is terminated with a semicolon (`;`). Command flags, such as the `--output` flag, can be specified at the command line or using the `.stackqlrc` initialization file discussed previously. The output from the StackQL executable is sent to stdout on the system being used, this output can be parsed within a BASH or PowerShell script. An example of a Windows PowerShell script including an StackQL command is shown here: ```shell $gcp_project = "stackql-demo" $gcp_zone = "australia-southeast1-a" $keyfilepath = "C:\tmp\stackql-demo.json" Write-Output "Selecting instances in ${gcp_zone}..." $query = "`"select id, name, machineType ` from compute.instances ` where project = '${gcp_project}' ` and zone = '${gcp_zone}';`"" $flags = "--keyfilepath ${keyfilepath} --output json" $cmd = "stackql.exe exec" $select = $cmd, $query, $flags -join " " (iex $select | ConvertFrom-Json) | Out-GridView -Title 'StackQL Query Results' ``` The above PowerShell command demonstrates selecting Compute Engine instances displaying the output using `Out-GridView`. ### Using an Input File (IQL File) StackQL input files can be used to execute several commands terminated by semicolons. This is another option for non-interactive or batch infrastructure programming. An input file is specified with the `-i` or `--infile` option as shown below: ```shell # create an iql file echo "select id, name from compute.instances \ where project = 'stackql-demo' \ and zone = 'australia-southeast1-a'" > listinstances.iql # execute an iql file ./stackql exec -i listinstances.iql \ --keyfilepath /mnt/c/tmp/stackql-demo.json \ --output json | jq '.[] | .name' ``` --- # Using Variables > Using variables in StackQL: supply values from Jsonnet or JSON data files, reference them in statements, source external values and preview with dry run. Source: https://stackql.io/getting-started/variables See also: [[` exec `]](/command-line-usage/exec) [[` INSERT `]](/language-spec/insert) Variables can be supplied in the form of configuration data to StackQL scripts. StackQL configuration data can be in the form of json or [jsonnet](https://jsonnet.org/ "Jsonnet"). Jsonnet provides additional features such as conditional logic, imports and inheritence, as well as loop structures. Data can be provided through `json` or `jsonnet` files referenced through the `--iqldata` parameter of the `stackql exec` command or can be included in an `iql` script using the following `<<<` and `>>>` decorators as shown here: ```sql <<<jsonnet // // jsonnet data // >>> /* stackql statements ... */ ``` ## Jsonnet Configuration Example The following example demonstrates the use of Jsonnet to supply configuration data to an StackQL script. Data is supplied using the `--iqldata` parameter to the `exec` command as shown below: ```shell stackql exec -i myscript.iql \ --iqldata vars.jsonnet \ --keyfilepath stackql-demo.json ``` ### Jsonnet Data Using jsonnet you can re-use variables and use arrays within loop structures in your StackQL code. The following jsonnet would be in the contents of the `vars.jsonnet` file referenced in the `--iqldata` parameter. ```json // variables local project = 'stackql-demo'; local region = 'australia-southeast1'; local name = 'myapp'; local nw_name = name + '-vpc'; local nw_self_link = 'https://compute.googleapis.com/compute/v1/projects/' + project + '/global/networks/' + nw_name + '/'; { // global config global: { project: project, }, // firewall rules firewalls: [ { allowed: [{IPProtocol: 'tcp'}, {IPProtocol: 'udp'}, {IPProtocol: 'icmp'}], direction: 'INGRESS', name: name + '-allow-internal-fw', network: nw_self_link, sourceRanges: ['10.240.0.0/24', '10.200.0.0/16'] }, { allowed: [{IPProtocol: 'tcp', ports: ['22']}, {IPProtocol: 'tcp', ports: ['6443']},{IPProtocol: 'icmp'}], direction: 'INGRESS', name: name + '-allow-external-fw', network: nw_self_link, sourceRanges: ['0.0.0.0/0'] } ], } ``` ### Referencing Jsonnet Data in an StackQL statement The following code snippet demonstrates how to reference jsonnet values from an StackQL command. ```sql -- -- create firewall rules -- {{range .firewalls}} INSERT /*+ AWAIT */ INTO google.compute.firewalls ( project, data__name, data__network, data__direction, data__sourceRanges, data__allowed ) SELECT '{{ .global.project }}', '{{.name}}', '{{.network}}', '{{.direction}}', '{{.sourceRanges}}', '{{.allowed}}'; {{end}} ``` ### Sourcing External Variables using Jsonnet The following code snippets demonstrate how to source external variables into a Jsonnet configuration file used to render a StackQL query. #### StackQL Query (`env-var-input.iql`) ```sql INSERT /*+ AWAIT */ INTO google.compute.networks ( project, data__name, data__autoCreateSubnetworks, data__routingConfig ) SELECT '{{ .global.project }}', '{{ .network.name }}', {{ .network.autoCreateSubnetworks }}, '{{ .network.routingConfig }}'; ``` #### Jsonnet Data File (`vars.jsonnet`) ```json // variables local name = 'env-var-input-demo'; local project = std.extVar("project"); { // global config global: { project: project, }, // network network: { autoCreateSubnetworks: false, name: name + '-vpc', routingConfig: {routingMode: 'REGIONAL'} }, } ``` #### Command Line Execution ``` /path/to/stackql exec -i $(pwd)/env-var-input.iql --var project=stackql-demo --iqldata $(pwd)/vars.jsonnet ``` ## Json Configuration Example Simple json can also be used to supply configuration data to an StackQL script as shown below: ```shell stackql exec -i myscript.iql \ --iqldata vars.json \ --keyfilepath stackql-demo.json ``` ### Json Data The following json data would be in the contents of the `vars.json` file referenced in the `--iqldata` parameter. ```json { "project": "stackql-demo", "firewalls": [ { "allowed": [{"IPProtocol": "tcp"}, {"IPProtocol": "udp"}, {"IPProtocol": "icmp"}], "direction": "INGRESS", "name": "myapp-allow-internal-fw", "network": "https://compute.googleapis.com/compute/v1/projects/stackql-demo/global/networks/myapp-vpc/", "sourceRanges": ["10.240.0.0/24", "10.200.0.0/16"] }, { "allowed": [{"IPProtocol": "tcp", "ports": ["22"]}, {"IPProtocol": "tcp", "ports": ["6443"]},{"IPProtocol": "icmp"}], "direction": "INGRESS", "name": "myapp-allow-external-fw", "network": "https://compute.googleapis.com/compute/v1/projects/stackql-demo/global/networks/myapp-vpc/", "sourceRanges": ["0.0.0.0/0"] } ], } ``` ### Referencing Json Data in an StackQL statement The data shown above would be referenced in an StackQL `INSERT` statement as shown here: ```sql INSERT /*+ AWAIT */ INTO google.compute.firewalls ( project, data__name, data__network, data__direction, data__sourceRanges, data__allowed ) SELECT '{{ project }}', '{{ firewalls[0].name }}', '{{ firewalls[0].network }}', '{{ firewalls[0].direction }}', '{{ firewalls[0].sourceRanges }}', '{{ firewalls[0].allowed }}'; INSERT /*+ AWAIT */ INTO compute.firewalls ( project, data__name, data__network, data__direction, data__sourceRanges, data__allowed ) SELECT '{{ project }}', '{{ firewalls[1].name }}', '{{ firewalls[1].network }}', '{{ firewalls[1].direction }}', '{{ firewalls[1].sourceRanges }}', '{{ firewalls[1].allowed }}'; ``` ## Dryrun Option to Preview Command You can use the `--dryrun` option to output a preprocessed StackQL script using your input script and `json` or `jsonnet` data file as shown below: ```shell ./stackql exec -i myscript.iql \ --iqldata vars.json \ --keyfilepath stackql-demo.json \ --dryrun \ --output text ``` --- # Installation > Install StackQL on macOS, Linux, Windows, Docker or a cloud shell, and use the StackQL MCP server from Claude Desktop, ChatGPT, Goose and other MCP clients, or via npx, uvx, pip, Docker and GitHub Actions. Source: https://stackql.io/installing-stackql Instructions for installing StackQL on various different platforms are provided here. **macOS** ## macOS StackQL is available on macOS via Homebrew and the `pkg` Installer, both ARM (M1/Apple Silicon) and AMD architectures are supported with a single multi-arch installer. **Homebrew** To install via Homebrew, run the following command in your terminal: ```bash brew install stackql ``` **curl (signed and notarized binary)** To install a signed and notarized `stackql` executable binary in the current directory, run the following command in your terminal: ```bash curl -fsSL https://get-stackql.io/install | sh ``` **Package download** StackQL is available as a signed and notarized, interactive `pkg` installer for MacOS. [Download macOS PKG](https://releases.stackql.io/stackql/latest/stackql_darwin_multiarch.pkg) **Linux** ## Linux StackQL is available for all Linux architectures. **curl** To install a `stackql` executable binary in the current directory for your linux architecture (amd64 or arm64), run the following command in your terminal: ```bash curl -fsSL https://get-stackql.io/install | sh ``` **Package download** Alternatively, you can download the binaries here: [Download Linux ZIP (amd64)](https://releases.stackql.io/stackql/latest/stackql_linux_amd64.zip) [Download Linux ZIP (arm64)](https://releases.stackql.io/stackql/latest/stackql_linux_arm64.zip) **Windows** ## Windows StackQL is available on Windows via Chocolatey, PowerShell install script, and the MSI installer. Native AMD64 (x64) and ARM64 builds are available as MSI installers and ZIP archives containing `stackql.exe`. The AMD64 build also runs on ARM64 via emulation. All executables are signed with an Authenticode code-signing certificate. **Chocolatey** To install via Chocolatey, run the following command in your PowerShell or `cmd` terminal: ```powershell choco install stackql ``` **Invoke-RestMethod** To install an Authenticode executable in the current directory, run the following in a Powershell terminal: ```powershell Invoke-RestMethod https://get-stackql.io/install | Invoke-Expression # or irm https://get-stackql.io/install | iex ``` **MSI/ZIP download** Download the signed Windows `stackql` installer or executable below. Clicking a download button selects AMD64 by default; use its dropdown to choose AMD64 or native ARM64. [Download Windows MSI](https://releases.stackql.io/stackql/latest/stackql_windows_amd64.msi) [Download Windows ZIP](https://releases.stackql.io/stackql/latest/stackql_windows_amd64.zip) **Docker** ## Docker StackQL builds are published to [DockerHub](https://hub.docker.com/u/stackql). __Docker Hub__ To pull the StackQL container image, run the following command: ```bash docker pull stackql/stackql ``` From `v1.0` the image is based on Ubuntu 26.04 LTS, and a variant with Python 3.13 preinstalled is published with the `-python3.13` tag suffix (alias `-python3`), for example: ```bash docker pull stackql/stackql:latest-python3.13 ``` **stackql-deploy** ## `stackql-deploy` `stackql-deploy` is a stateless IaC framework built on StackQL. For full documentation see [__StackQL Deploy Docs__](https://stackql-deploy.io/). __Linux / macOS__ Downloads and extracts the latest `stackql-deploy` binary in one step. The installer detects your OS and architecture (including Apple Silicon and Intel via a universal macOS binary) and fetches the correct release asset automatically. ```bash curl -fsSL https://get-stackql-deploy.io/install.sh | sh ``` __Windows__ Downloads and extracts the latest `stackql-deploy` binary into the current directory. The installer detects your platform and fetches the correct release asset automatically. ```powershell irm https://get-stackql-deploy.io/install.ps1 | iex ``` __cargo__ If you have the Rust toolchain installed, this builds and installs the binary directly from [__crates.io__](https://crates.io/crates/stackql-deploy). ```bash cargo install stackql-deploy ``` **Cloud Shells** ## Cloud Shells StackQL can be used directly from major cloud and data platforms' built-in cloud shells and web terminals. This provides a seamless experience as these environments are pre-authorized with the identity you're logged into, eliminating the need for separate authentication setup. **AWS** ### AWS Cloud Shell AWS CloudShell provides a browser-based shell with AWS CLI pre-installed and authenticated. Running StackQL in AWS CloudShell allows you to query and manage AWS resources without additional authentication steps. For detailed instructions, see our [AWS CloudShell tutorial](/quick-starts/aws/aws-cloud-shell). First, download the StackQL package: ```bash curl -fsSL https://get-stackql.io/install/aws | sh ``` Then run the StackQL AWS CloudShell script: ```bash ./stackql-aws-cloud-shell.sh ``` This script starts a StackQL command shell using your AWS CloudShell credentials, allowing you to immediately start querying AWS resources. **Azure** ### Azure Cloud Shell Azure Cloud Shell provides a browser-accessible shell environment with Azure CLI pre-authenticated with your Azure account. Using StackQL in Azure Cloud Shell enables seamless querying of your Azure resources without additional setup. For complete details, check our [Azure Cloud Shell guide](/blog/tutorials/using-stackql-in-native-cloud-shells-in-aws-azure-and-gcp#using-stackql-in-the-azure-cloud-shell). First, download the StackQL package: ```bash curl -fsSL https://get-stackql.io/install/azure | sh ``` Then run the StackQL Azure Cloud Shell script: ```bash ./stackql-azure-cloud-shell.sh ``` This script automatically configures a StackQL session to use your Azure Cloud Shell credentials, enabling immediate access to query your Azure resources. **Google** ### Google Cloud Shell Google Cloud Shell offers a development and operations environment with Google Cloud CLI already authenticated. Running StackQL in Google Cloud Shell lets you query GCP resources using your existing authentication. Learn more in our [Google Cloud Shell guide](/blog/tutorials/using-stackql-in-native-cloud-shells-in-aws-azure-and-gcp#using-stackql-in-the-google-cloud-shell). First, download the StackQL package: ```bash curl -fsSL https://get-stackql.io/install/google | sh ``` Then run the StackQL Google Cloud Shell script: ```bash ./stackql-google-cloud-shell.sh ``` The script sets up StackQL to use your Google Cloud Shell credentials, allowing you to immediately start querying your GCP resources using SQL syntax. **Databricks** ### Databricks Web Terminal Databricks workspaces include a web terminal that runs as the logged-in user. Running StackQL there lets you query your workspace using your Databricks identity, with no separate authentication setup. For example queries and account-level auth, see our [Databricks Web Terminal guide](/blog/tutorials/stackql-in-databricks-web-terminal). First, download the StackQL package: ```bash curl -fsSL https://get-stackql.io/install/databricks | sh ``` Then run the StackQL Databricks shell script: ```bash ./stackql-databricks-shell.sh ``` This starts a StackQL session using your Databricks workspace identity, so you can immediately query workspace-scoped resources such as `databricks_workspace.iam.vw_user_entitlements`. For account-level queries (provisioning, billing, account IAM), set the Databricks OAuth2 service principal variables as described in the guide. ## Using with MCP clients The StackQL MCP server runs locally over stdio, so provider credentials stay on your machine whichever client you use. Pick your client below: each tab gives the directory or one-click route first and the manual configuration as a fallback. For every distribution channel, including `npx`, Python, Docker and CI, see [Installing the MCP server](#installing-the-mcp-server). **Claude Desktop** ### Claude Desktop The recommended way to install the StackQL MCP server into Claude Desktop is from the [Anthropic Connector Directory](https://claude.ai/directory/connectors/ant.dir.gh.stackql.stackql) (**Settings -> Connectors -> Add -> Browse Connectors**, search for **StackQL**) - Claude Desktop selects the correct signed binary for your platform automatically. Alternatively, prebuilt MCP Bundles (`.mcpb`) are attached to every StackQL release for installation from a downloaded file - no separate StackQL installation is required either way. Bundles are available for macOS, Windows and Linux. Linux and Windows MCPB downloads default to **amd64** (x64). Use the dropdowns to select **amd64** or **arm64**. [Download macOS MCPB](https://releases.stackql.io/stackql/latest/stackql-mcp-darwin-universal.mcpb) [Download Linux MCPB](https://releases.stackql.io/stackql/latest/stackql-mcp-linux-x64.mcpb) [Download Windows MCPB](https://releases.stackql.io/stackql/latest/stackql-mcp-windows-x64.mcpb) :::info The StackQL MCP server is also listed on the [__Official MCP Registry__](https://registry.modelcontextprotocol.io/v0/servers?search=stackql) as `io.github.stackql/stackql-mcp`. ::: :::tip The bundle is one of several ways to run the StackQL MCP server. See [__Using StackQL with Claude Desktop__](/getting-started/claude-desktop) for the full Claude Desktop walkthrough, or [__Installing the MCP server__](#installing-the-mcp-server) for the npx, Docker, Python, CI and manual options. ::: **ChatGPT** ### ChatGPT and Codex StackQL ships as a local plugin for the ChatGPT desktop app and the Codex CLI. The plugin runs the StackQL MCP server over stdio on your machine, so provider credentials never leave it. Node.js 24.22.1 or later is required (22.23.4 or 26.12.1 on those release lines); the plugin needs only Node.js built-ins, downloads the signed `stackql` binary on first use and verifies its SHA-256. **ChatGPT desktop app (plugin directory):** open the plugin directory in the ChatGPT desktop app, search for **StackQL** and click **Install**, then run the plugin's setup; the bundled `stackql-setup` skill walks through credentials and a first query. The listing carries a **Desktop only** badge: the plugin installs only from the desktop app, not from ChatGPT web or mobile, and its tools are available in Work mode, in threads that run on your computer. If the listing is not visible in your directory yet, install from the repository marketplace instead. **ChatGPT desktop app (repository marketplace):** open **Settings -> Plugins -> Add -> Add from GitHub**, enter `stackql/stackql`, then install **StackQL** from the **Personal** section of the plugin directory and restart the app. **Codex CLI:** ```shell codex plugin marketplace add stackql/stackql --sparse .agents/plugins --sparse packaging/openai-plugin codex plugin add stackql@stackql ``` Restart ChatGPT desktop or Codex, then try: *Use StackQL to install the GitHub provider if needed, then list the first five GitHub services.* Provider credentials go in `~/.stackql/.env` using each provider's standard environment variable names (for example `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`); after editing the file, ask the agent to call `reload_credentials`. **Without the plugin:** under **Settings -> Plugins -> MCPs -> Connect to a custom MCP**, choose **STDIO**, set the command to `npx` and add the arguments `-y` and `@stackql/mcp-server`. Supply provider credentials as environment variables on that form. :::note ChatGPT web and mobile cannot run a local stdio server, so the plugin is desktop and Codex only. An open ChatGPT desktop bug ([openai/codex#38162](https://github.com/openai/codex/issues/38162)) can hide local MCP tools from **Chat** sessions; Work mode threads, Codex threads and the Codex CLI are unaffected. ::: **Goose** ### Goose Goose runs stdio extensions directly, so the `npx` launcher is all you need (Node.js 18 or later). **Goose Desktop:** click the button below. Goose opens, shows the command it is about to run and asks you to confirm, then adds StackQL as an extension. Install in Goose Desktop The button is a `goose://` deep link; you can also paste it into your browser's address bar, or open it from a terminal with `open` (macOS), `start` (Windows) or `xdg-open` (Linux): ``` goose://extension?cmd=npx&arg=-y&arg=%40stackql%2Fmcp-server&id=stackql&name=StackQL&description=Query%20and%20provision%20cloud%20and%20SaaS%20resources%20with%20SQL ``` **Goose CLI:** ```shell goose session --with-extension "npx -y @stackql/mcp-server" ``` or run `goose configure`, choose **Add Extension -> Command-line Extension**, and enter the same command. Provide provider credentials as the extension's environment variables when prompted. :::note Goose has retired its in-app extensions directory in favour of the [Official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=stackql), where StackQL is listed as `io.github.stackql/stackql-mcp`. Once Goose ships its registry import, StackQL will be discoverable there without any further action. ::: ## Installing the MCP server The StackQL MCP server lets AI agents query and provision cloud resources using StackQL. It ships through several channels - they all run the same server, so pick the channel that matches your client and your trust requirements. The options below are listed roughly in order of trust and ease. ### Marketplaces and directories The server is published to the Official MCP Registry as `io.github.stackql/stackql-mcp`; the package registries below carry the distributable artifacts, and downstream directories pick the listing up from there. **Registries** | Registry | Type | Published via | Listing | Notes | |---|---|---|---|---| | Official MCP Registry | Canonical metadata registry | `mcp-publisher` CLI + `server.json` | [`modelcontextprotocol.io/search`](https://registry.modelcontextprotocol.io/v0/servers?search=stackql) [`modelcontextprotocol.io/direct`](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.stackql/stackql-mcp) | advertises all 8 packages (`mcpb x5`, `oci`, `npm`, `pypi`) | | npm | Package registry | `npm publish` | [`@stackql/mcp-server`](https://www.npmjs.com/package/@stackql/mcp-server) | `npx` launcher | | PyPI | Package registry | `twine upload` | [`stackql-mcp-server`](https://pypi.org/project/stackql-mcp-server/) | `uvx` / `pip` launcher | | Docker Hub | Container registry | `docker buildx --push` | [`stackql/stackql-mcp`](https://hub.docker.com/r/stackql/stackql-mcp) | multi-arch `amd64` + `arm64` | | GitHub Actions Marketplace | CI marketplace (`setup-stackql-mcp` action) | Public repo + release + marketplace listing | [`setup-stackql-mcp-server`](https://github.com/marketplace/actions/setup-stackql-mcp-server) | Verified publisher; [`stackql/setup-stackql-mcp`](https://github.com/stackql/setup-stackql-mcp) | **Directories** Directory and aggregator listings, in rough order of significance for discovery: | Directory | Type | Listing | |---|---|---| | __Anthropic Connector Directory__ | Claude Desktop in-app directory | [claude.ai/directory](https://claude.ai/directory/connectors/ant.dir.gh.stackql.stackql) | | __OpenAI Plugin Directory__ | ChatGPT desktop in-app directory (Desktop only) | search for **StackQL** in the ChatGPT desktop app; see [ChatGPT and Codex](#using-with-mcp-clients) | | __Cursor Directory__ | IDE client directory | [cursor.directory](https://cursor.directory/plugins/stackql-mcp-server) | | __mcp.so__ | Largest aggregator | [mcp.so](https://mcp.so/server/stackql/stackql) | | __PulseMCP__ | Discovery, registry backer | [pulsemcp](https://www.pulsemcp.com/servers/stackql) | | __Glama.ai MCP__ | Searchable marketplace | [glama.ai](https://glama.ai/mcp/servers/stackql/stackql) | | __mcpmarket.com__ | Aggregator | [mcpmarket](https://mcpmarket.com/server/stackql) | | __mcpservers.org__ | Awesome-list site | [mcpservers.org](https://mcpservers.org/servers/stackql-mcp-server) | ### Prebuilt `.mcpb` bundle **When to use:** Claude Desktop without Connector Directory access, or when you want to pin a specific version or verify checksums yourself before installing. For most Claude Desktop users the [Anthropic Connector Directory](https://claude.ai/directory/connectors/ant.dir.gh.stackql.stackql) is the recommended installation method. A prebuilt MCP Bundle is attached to every StackQL release for each platform: ``` https://releases.stackql.io/stackql/latest/stackql-mcp-<platform>.mcpb ``` where `<platform>` is one of `darwin-universal`, `windows-x64` (AMD64), `windows-arm64`, `linux-x64`, or `linux-arm64`. Download buttons for each platform are in the **Claude Desktop** tab under [Using with MCP clients](#using-with-mcp-clients). Each bundle has a matching `.sha256` checksum on the [release page](https://github.com/stackql/stackql/releases/latest). Verify it, then install via **Settings -> Extensions** in Claude Desktop: ```bash shasum -a 256 -c stackql-mcp-darwin-universal.mcpb.sha256 ``` See [Using StackQL with Claude Desktop](/getting-started/claude-desktop#install-from-a-downloaded-bundle) for the full walkthrough. ### Manual `claude_desktop_config.json` **When to use:** you already have the `stackql` binary on your PATH and use Claude Desktop or any other stdio MCP client. ```json { "mcpServers": { "stackql": { "command": "stackql", "args": [ "mcp", "--mcp.server.type=stdio", "--approot", "/Users/you/.stackql", "--mcp.config", "{\"server\": {\"audit\": {\"disabled\": true}}}" ] } } } ``` All three arguments are load-bearing: - `--mcp.server.type=stdio` selects the stdio transport that editor-embedded clients speak. - `--approot` points the provider cache at a writable directory. MCP clients may launch the server with the working directory set to `/`, which is not writable. - `--mcp.config '{"server": {"audit": {"disabled": true}}}'` disables the audit log, which otherwise defaults its directory to the (possibly non-writable) working directory. Add provider credentials with an `"env"` block and tune the safety contract with `"mode"` - see [Server modes](/command-line-usage/mcp#server-modes). ### `npx` (no install) **When to use:** any Node environment, when you do not want a global StackQL install. ```json { "mcpServers": { "stackql": { "command": "npx", "args": ["-y", "@stackql/mcp-server"] } } } ``` The [`@stackql/mcp-server`](https://www.npmjs.com/package/@stackql/mcp-server) launcher downloads the signed `stackql` binary on first run, verifies its SHA-256, and caches it for subsequent runs. ### `uvx` / `pip` (Python) **When to use:** a Python environment - the same launcher packaged for Python, sharing the binary cache the npx launcher populates. ```json { "mcpServers": { "stackql": { "command": "uvx", "args": ["stackql-mcp-server"] } } } ``` Or install it into the current environment with `pip install stackql-mcp-server` (Python 3.9+). The package is [`stackql-mcp-server`](https://pypi.org/project/stackql-mcp-server/) on PyPI. ### Docker **When to use:** a containerised or otherwise isolated runtime. The image is multi-arch (amd64 and arm64). ```bash docker run -i --rm stackql/stackql-mcp ``` As a client configuration: ```json { "mcpServers": { "stackql": { "command": "docker", "args": ["run", "-i", "--rm", "stackql/stackql-mcp"] } } } ``` The image is [`stackql/stackql-mcp`](https://hub.docker.com/r/stackql/stackql-mcp) on Docker Hub. ### CI and agentic workflows (GitHub Actions) **When to use:** run the server inside a GitHub Actions job so an agent can query - and, if you allow it, act on - your cloud as part of CI. [`stackql/setup-stackql-mcp@v1`](https://github.com/marketplace/actions/setup-stackql-mcp-server) installs the binary and writes an MCP config (defaulting to `read_only` mode). Pass that config to [`anthropics/claude-code-action`](https://github.com/anthropics/claude-code-action) through `claude_args`: ```yaml - id: stackql uses: stackql/setup-stackql-mcp@v1 with: auth: '{"github":{"type":"null_auth"}}' - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: | Using stackql, list the public repositories in the stackql org and summarise them as a markdown table. claude_args: | --mcp-config ${{ steps.stackql.outputs.mcp-config-file }} --allowedTools 'mcp__stackql__*' ``` See the [action README](https://github.com/stackql/setup-stackql-mcp) for more agentic recipes (cloud audits, cost estimates, and so on). ### Embedded MCP **When to use:** you are building an agentic app and want to vendor the MCP server into your own binary - no `npx`, no separate install, no runtime dependency. Native libraries spawn the signed `stackql` binary over stdio behind each language's official MCP SDK client, so your app gets the same governed SQL interface to every provider in the registry. Each library defaults to `read_only` - escalation to a writable mode is always explicit - and can either download-and-verify the binary on first run or vendor it into your build for a single self-contained executable. The full per-language API is in the [Embedded MCP reference](/mcp/embedded). **Rust** The `stackql-mcp` crate spawns the binary behind an `rmcp` client. The default `sidecar` feature downloads and verifies the binary on first run; the `vendored` feature embeds it with `include_bytes!` for a single self-contained binary. MSRV Rust 1.88. ```toml # Cargo.toml stackql-mcp = "0.1" ``` ```rust use stackql_mcp::{Mode, StackqlMcp}; let server = StackqlMcp::builder() .mode(Mode::ReadOnly) .start() .await?; let tools = server.list_all_tools().await?; ``` [View on GitHub](https://github.com/stackql/stackql-mcp-rs) [View on crates.io](https://crates.io/crates/stackql-mcp) Full reference: [Embedded MCP: Rust](/mcp/embedded/rust). **Go** The `stackql-mcp-go` library spawns the binary behind the official Go MCP SDK client. Vendor the binary with `go:embed` for a single self-contained binary, or let it download and verify on first run. Starts in `read_only` mode by default. ```bash go get github.com/stackql/stackql-mcp-go ``` ```go import ( "context" stackqlmcp "github.com/stackql/stackql-mcp-go/embed" ) client, err := stackqlmcp.StartServer(ctx, stackqlmcp.Options{ Binary: StackqlMCPBinary(), }) defer client.Close() ``` [View on GitHub](https://github.com/stackql/stackql-mcp-go) [View on pkg.go.dev](https://pkg.go.dev/github.com/stackql/stackql-mcp-go) Full reference: [Embedded MCP: Go](/mcp/embedded/go). **Kotlin / JVM** The `io.stackql:stackql-mcp` library spawns the binary behind the official Kotlin MCP SDK client, and a companion Gradle plugin wires the same launch into a build. Requires JDK 17 and Kotlin 2.x. ```kotlin dependencies { implementation("io.stackql:stackql-mcp:0.1.0") } ``` ```kotlin import io.stackql.mcp.Mode import io.stackql.mcp.StackqlMcp val server = StackqlMcp.builder().mode(Mode.ReadOnly).start() server.use { val tools = server.client.listTools().tools } ``` [View on GitHub](https://github.com/stackql/stackql-mcp-kotlin) Full reference: [Embedded MCP: Kotlin / JVM](/mcp/embedded/kotlin). **.NET** The `StackQL.Mcp` package spawns the binary behind the official C# MCP SDK client. Sidecar by default, or vendor the bundle as a build resource for a self-contained executable. Requires .NET 8 or later. ```bash dotnet add package StackQL.Mcp ``` ```csharp using StackQL.Mcp; await using var server = await StackqlMcp.CreateBuilder() .WithMode(StackqlMode.ReadOnly) .StartAsync(); var tools = await server.ListToolsAsync(); ``` [View on GitHub](https://github.com/stackql/stackql-mcp-dotnet) Full reference: [Embedded MCP: .NET / C#](/mcp/embedded/dotnet). **Gleam** The `stackql_mcp` library targets the Erlang/BEAM runtime and exposes the server as an OTP child via `child_spec()`, so it can sit inside your own supervision tree. Starts in `read_only` mode by default. ```bash gleam add stackql_mcp ``` ```gleam import envoy import stackql_mcp let assert Ok(server) = stackql_mcp.start( config: stackql_mcp.default_config(), home: "/home/u", os: "linux", arch: "x86_64", getenv: envoy.get, ) let assert Ok(tools) = stackql_mcp.list_tools(server) ``` [View on GitHub](https://github.com/stackql/stackql-mcp-gleam) Full reference: [Embedded MCP: Gleam](/mcp/embedded/gleam). **Swift** The `stackql-mcp-swift` package spawns the binary behind the official Swift MCP SDK client. The `darwin-universal` binary is Developer ID signed and Apple-notarised, so you can bundle it inside a signed `.app` and keep the app's notarisation valid. Requires macOS 13+ and Swift 6.1 (Xcode 16.3+). ```swift // Package.swift .package(url: "https://github.com/stackql/stackql-mcp-swift.git", from: "0.1.0") ``` ```swift import StackQLMCP var options = Options() options.mode = .readOnly let server = try await StackQLServer.start(options) let tools = try await server.listToolNames() await server.stop() ``` [View on GitHub](https://github.com/stackql/stackql-mcp-swift) Full reference: [Embedded MCP: Swift](/mcp/embedded/swift). ### Trust model The same security properties hold across every channel: - The embedded `stackql` binary is Authenticode-signed (Windows) and Apple-notarised (macOS). - Every `.mcpb` bundle ships with a published SHA-256 checksum on the release page. - The `npx` and `uvx` launchers verify the downloaded binary's SHA-256 before first use. - The [MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=stackql) entry attests the per-platform hashes. ## Using GitHub Actions [StackQL GitHub Actions](https://github.com/stackql/stackql-actions-demo) are available for use in your GitHub Actions workflows. The following actions are available: **stackql-deploy** ### `stackql-deploy` Deploy or test infrastructure stacks using StackQL directly from your GitHub workflows. This action enables Infrastructure as Code (IaC) workflows using SQL-like syntax, allowing you to define, deploy, and manage cloud resources across multiple providers in a single workflow. [View on the GitHub Marketplace](https://github.com/marketplace/actions/stackql-deploy) [View on GitHub](https://github.com/stackql/stackql-deploy-action) __Example usage__ ```yaml ... jobs: stackql-actions-test: name: StackQL Actions Test runs-on: ubuntu-latest env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }} # add additional cloud provider creds here as needed steps: - name: Checkout uses: actions/checkout@v6 - name: Deploy a Stack uses: stackql/stackql-deploy-action@v2 with: command: 'build' stack_dir: 'examples/k8s-the-hard-way' stack_env: 'dev' env_vars: | GOOGLE_PROJECT=stackql-k8s-the-hard-way-demo GOOGLE_REGION=australia-southeast1 ``` **setup-stackql** ### `setup-stackql` Setup StackQL in your GitHub Actions workflow. [View on the GitHub Marketplace](https://github.com/marketplace/actions/setup-stackql) [View on GitHub](https://github.com/stackql/setup-stackql) __Example usage__ ```yaml - name: setup StackQL uses: stackql/setup-stackql@v2 with: use_wrapper: true - name: Use GitHub Provider run: | stackql exec -i ./examples/github-example.iql env: STACKQL_GITHUB_USERNAME: ${{ secrets.STACKQL_GITHUB_USERNAME }} STACKQL_GITHUB_PASSWORD: ${{ secrets.STACKQL_GITHUB_PASSWORD }} ``` **setup-stackql-mcp** ### `setup-stackql-mcp` Install the StackQL MCP server in your GitHub Actions workflow. The action installs the signed binary and writes an `mcpServers` config (defaulting to `read_only` mode) that an agentic step such as `anthropics/claude-code-action` consumes via `claude_args`. [View on the GitHub Marketplace](https://github.com/marketplace/actions/setup-stackql-mcp-server) [View on GitHub](https://github.com/stackql/setup-stackql-mcp) __Example usage__ ```yaml - id: stackql uses: stackql/setup-stackql-mcp@v1 with: auth: '{"github":{"type":"null_auth"}}' - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: | Using stackql, list the public repositories in the stackql org and summarise them as a markdown table. claude_args: | --mcp-config ${{ steps.stackql.outputs.mcp-config-file }} --allowedTools 'mcp__stackql__*' ``` **stackql-exec** ### `stackql-exec` Execute StackQL commands in your GitHub Actions workflow. Queries can be supplied in line or from a file in the repo. [View on the GitHub Marketplace](https://github.com/marketplace/actions/stackql-exec) [View on GitHub](https://github.com/stackql/stackql-exec) __Example usage__ ```yaml - name: exec github example uses: stackql/stackql-exec@v2 with: query: | select total_private_repos from github.orgs.orgs where org = 'stackql'" env: STACKQL_GITHUB_USERNAME: ${{ secrets.STACKQL_GITHUB_USERNAME }} STACKQL_GITHUB_PASSWORD: ${{ secrets.STACKQL_GITHUB_PASSWORD }} ``` **stackql-assert** ### `stackql-assert` Perform unit tests in your GitHub Actions workflow (for assurance, governance or cloud security checks). [View on the GitHub Marketplace](https://github.com/marketplace/actions/stackql-assert) [View on GitHub](https://github.com/stackql/stackql-assert) __Example usage__ ```yaml - name: Use test query string and expected rows uses: stackql/stackql-assert@v2 with: test_query: | SELECT name FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' AND name = 'stackql-demo-001'; expected_rows: 1 env: GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }} ``` ## Other Libraries StackQL provides several integration methods that allow you for use in different programming languages and environments. These libraries extend StackQL's functionality, making it easy to incorporate cloud resource querying and management into your existing applications and workflows. **pystackql** ### `pystackql` Python Package Python wrapper to use StackQL in your Python programs. The `pystackql` package is available on [__PyPi__](https://pypi.org/project/pystackql/), documentation for the `pystackql` package is available via [__Read the Docs__](https://pystackql.readthedocs.io/en/latest/). To install the `pystackql` package, run the following command: ```bash pip install pystackql ``` The following example shows the `pystackql` package used along with `pandas` to run StackQL queries and return the results to a `pandas.DataFrame`: ```python from pystackql import StackQL import pandas as pd region = "ap-southeast-2" stackql = StackQL() query = """ SELECT instance_type, COUNT(*) as num_instances FROM aws.ec2.instances WHERE region = '%s' GROUP BY instance_type """ % (region) res = stackql.execute(query) df = pd.read_json(res) print(df) ``` --- # CREATE VIEW > CREATE VIEW in StackQL: save a query, including cross-cloud UNIONs, as a named view, or as a materialized view whose results are stored for reuse. Source: https://stackql.io/language-spec/createview Creates a `view` or a `materialized view` within a session which can be used to represent a long or complex `stackql` query. See also: [[ `SELECT` ]](/language-spec/select) [[ `REFRESH` ]](/language-spec/refreshview) [[ `DROP` ]](/language-spec/dropview) * * * ## Syntax *createViewStatement::=*     ```sql CREATE [ OR REPLACE ] [ MATERIALIZED ] VIEW <viewName> AS <selectStatement> [ UNION | JOIN <selectStatement> ]; ``` * * * ## Examples ### Cross cloud `UNION` between `aws` and `google` ```sql CREATE VIEW dual_cloud_block_storage AS SELECT 'google' AS vendor, name, split_part(split_part(type, '/', 11), '-', 2) AS type, status, sizeGb AS size FROM google.compute.disks WHERE project = '<YOUR_GCP_PROJECT>' AND zone = 'australia-southeast1-a' UNION SELECT 'aws' AS vendor, volumeId AS name, volumeType AS type, status, size FROM aws.ec2.volumes WHERE region = 'ap-southeast-2'; ``` ### Create and use a Materialized View ```sql /* -------------------------- */ /* create a materialized view */ /* -------------------------- */ CREATE MATERIALIZED VIEW vw_ec2_instance_types AS SELECT memoryInfo, hypervisor, autoRecoverySupported, instanceType, SPLIT_PART(processorInfo, '\n', 3) as processorArch, currentGeneration, freeTierEligible, hibernationSupported, SPLIT_PART(vCpuInfo, '\n', 2) as vCPUs, bareMetal, burstablePerformanceSupported, dedicatedHostsSupported FROM aws.ec2.instance_types WHERE region = 'us-east-1'; /* ------------------------- */ /* use the materialized view */ /* ------------------------- */ SELECT i.instanceId, i.instanceType, it.vCPUs, it.memoryInfo FROM aws.ec2.instances i INNER JOIN vw_ec2_instance_types it ON i.instanceType = it.instanceType WHERE i.region = 'us-east-1'; ``` --- # Data Types > StackQL data types: the types used for resource properties and parameters in queries and results, and how they map to provider API schemas. Source: https://stackql.io/language-spec/data-types StackQL data types are used to represent values for input or output fields (properties or parameters) used within cloud resources. StackQL data types are listed in the table below: | StackQL type | Description | Example | |--|--|--| | `string` | sequence of Unicode characters enclosed by single quotes | `'mybucket'` | | `array` | ordered collection of values, surrounded by brackets `[ ]`, separated by a comma | `[0,1,2]` | | `object` | unordered set of zero or more name/value pairs inserted between `{ }` and separated by a comma | `{"name": "mydb"}` | | `boolean` | `true` or `false`, boolean values are not surrounded within quotes and will be treated as string values | `true` | | `integer` | a whole number that can be positive, negative, or zero | `2` | | `double` | double-precision floating-point number, can be positive or negative | `0.95` | > StackQL data types map to the data types exposed in the APIs for all major cloud providers. ## Type Conversion `CAST(expression AS type)` and `CONVERT(expression, type)` convert a value to another type. In addition to the conversion types inherited from the MySQL grammar (`CHAR`, `DATE`, `DATETIME`, `DECIMAL`, `SIGNED`, `UNSIGNED`, `TIME`, `JSON`), StackQL `v1.0` and later accept `TEXT`, `INTEGER`, `INT`, `BIGINT`, `BOOLEAN` and `BOOL`. The conversion is performed by the SQL backend, so its semantics are those of SQLite or PostgreSQL. Conversions are commonly used to compare a typed [session variable](/getting-started/session-variables) with a string column: ```sql SET some_id = 42; SELECT CAST($some_id AS TEXT) AS id_text, CONVERT($some_id, TEXT) || '-east' AS label; ``` Boolean fields served by XML providers such as AWS are reported as `true` and `false`; StackQL releases before `v1.0` reported them as `0` and `1`. --- # DELETE > DELETE in StackQL: remove an instance or instances of a cloud or SaaS resource with a SQL statement, taking the required parameters from the WHERE clause. Source: https://stackql.io/language-spec/delete Deletes an instance or instances of a resource. See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) * * * ## Syntax *deleteStatement::=*     ```sql DELETE FROM <multipartIdentifier> WHERE <expression> ; ``` * * * ## Examples ### Basic `DELETE` Statement Run a basic DELETE statement to remove a deployed resource in an authenticated session. ```sql -- Delete a Compute Engine resource instance by name DELETE FROM google.compute.instances WHERE instance = 'demo-instance-1' AND project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` --- # DESCRIBE > DESCRIBE in StackQL: list the fields of a resource, or the parameters and return type of a specific method, before you query or mutate it. Source: https://stackql.io/language-spec/describe Describes a resource or a specific method on a resource. See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) * * * ## Syntax *describeStatement::=*     ```sql DESCRIBE [ METHOD ] [ EXTENDED ] <multipartIdentifier> ; DESC [ EXTENDED ] <multipartIdentifier> ; ``` `DESC` is accepted as an alias for `DESCRIBE` when describing a resource; `DESCRIBE METHOD` requires the full keyword. ## Response **DESCRIBE** | Column | Description | | --- | --- | | `name` | Field name | | `type` | Datatype (`string`, `integer`, `boolean`, `number`, `object`, `array`) | | `description` | Field description (if `EXTENDED` is supplied) | **DESCRIBE METHOD** | Column | Description | | --- | --- | | `name` | Field name | | `type` | Datatype (`string`, `integer`, `boolean`, `number`, `object`, `array`) | | `param_type` | `input_required`, `input_optional`, or `output` | | `shape` | JSON Schema subset for object and array fields; empty for scalars. Includes nested `properties`, `items`, `required`, `enum`, `default`, `description`, and optionally includes booleans if made available by the provider (`readOnly`, `writeOnly`, `deprecated`) | | `description` | Field description (if `EXTENDED` is supplied) | * * * ## Examples ### Basic `DESCRIBE` Statement Run a basic `DESCRIBE` statement to list the fields in a resource from an authenticated session. ```sql -- Show the available fields in a Compute Engine resource DESCRIBE google.compute.instances; ``` ### Extended `DESCRIBE` Statement Run an extended `DESCRIBE` statement to list the fields in a resource and their descriptions from an authenticated session. ```sql -- Show the available fields in a Compute Engine resource DESCRIBE EXTENDED google.compute.instances; ``` ### `DESC` Alias `DESC` is shorthand for `DESCRIBE` on a resource, with or without `EXTENDED`. It is treated as a read-only statement everywhere `DESCRIBE` is, including the MCP server's `run_select_query` tool in `read_only` and `safe` modes. ```sql -- Same result as DESCRIBE EXTENDED google.compute.instances DESC EXTENDED google.compute.instances; ``` ### Basic `DESCRIBE METHOD` Statement Introspect a single method on a resource. The result includes input parameters and response fields, with nested structure rendered in the `shape` column. ```sql -- Show the inputs and outputs for the buckets.get method DESCRIBE METHOD google.storage.buckets.get; ``` ### Extended `DESCRIBE METHOD` Statement Run an extended `DESCRIBE METHOD` statement to include per-field descriptions alongside the shape. ```sql -- Show inputs, outputs, and descriptions for the buckets.insert method DESCRIBE METHOD EXTENDED google.storage.buckets.insert; ``` ### Discovering an `INSERT` Payload `DESCRIBE METHOD` is the canonical way to discover what fields an `INSERT` (or any mutating method) accepts. The `shape` column carries nested structure agents and humans can use to construct a payload in one query. ```sql -- See what google.compute.instances.insert requires DESCRIBE METHOD EXTENDED google.compute.instances.insert; ``` --- # DROP VIEW > DROP VIEW in StackQL: remove a view or materialized view created with CREATE VIEW. Source: https://stackql.io/language-spec/dropview Drops a `view` or `materialized view` within a session. See also: [[ `CREATE` ]](/language-spec/createview) [[ `REFRESH` ]](/language-spec/refreshview) * * * ## Syntax *dropViewStatement::=*     ```sql DROP [ MATERIALIZED ] VIEW <viewName>; ``` * * * ## Examples ### Drop a Materialized View ```sql DROP MATERIALIZED VIEW vw_ec2_instance_types; ``` --- # EXEC > EXEC in StackQL: call a provider resource method directly, with query hints to return results or await completion, such as starting or stopping an instance. Source: https://stackql.io/language-spec/exec Executes a provider resource method (built in procedure). See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) * * * ## Syntax *execStatement::=*     ```sql EXEC [ queryHint ] <multipartIdentifier>.<methodName> [ <methodArguments> ]; ``` ## Query Hints Query hints supported for the `EXEC` command are summarised below: | Hint | Description | |----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `/*+ SHOWRESULTS */` | Returns result set, designed for methods that return data, use `SELECT` however if possible. | | `/*+ AWAIT */` | Makes the operation blocking (synchronous), provides script control for long running operations (e.g. mutation operations). Note: this is not supported for all providers | * * * ## Examples ### Stopping a Google Compute Engine instance Run an `EXEC` statement to stop a running Compute Engine instance in an authenticated session. ```sql -- Stop a running Compute Engine resource instance EXEC google.compute.instances.stop @instance = 'demo-instance-1', @project = 'stackql-demo', @zone = 'australia-southeast1-a'; ``` ### Starting a Google Compute Engine instance (synchronous option) Run an `EXEC` statement to start a stopped Compute Engine instance in an authenticated session, uses the `/*+ AWAIT */` query hint to make the operation blocking (synchronous). ```sql -- Start a stopped Compute Engine resource instance EXEC /*+ AWAIT */ google.compute.instances.stop @instance = 'demo-instance-1', @project = 'stackql-demo', @zone = 'australia-southeast1-a'; ``` ### Starting and stopping an AWS EC2 instance Run an `EXEC` statement to start an AWS EC2 instance in an authenticated session. ```sql -- Start an EC2 instance EXEC aws.ec2.instances.start_instances @InstanceId = 'i-0fc989cf4efcd8b88', @region = 'ap-southeast-2'; -- Stop an EC2 instance EXEC aws.ec2.instances.stop_instances @InstanceId = 'i-0fc989cf4efcd8b88', @region = 'ap-southeast-2'; ``` ### Attach a Disk to a Google Compute Engine instance Run an `EXEC` statement to attach a Disk to a Compute Engine instance in an authenticated session. ```sql -- Attach a Disk resource to a Compute Engine instance EXEC google.compute.instances.attachDisk @zone='australia-southeast1-a', @project='stackql-demo', @instance='demo-instance-1' @@json= '{ "source": "projects/stackql-demo/zones/australia-southeast1-a/disks/test10gbdisk2", "boot": false }'; ``` ### Simulate Azure Spot VM eviction Run an `EXEC` statement to simulate eviction of Azure Spot VM Instance. ```sql exec azure.compute.virtual_machines.simulate_eviction @subscription_id = '0123456789', @resource_group_name = 'vmss-flex', @vm_name = 'vmss-flex-manual-1'; ``` --- # AVG > AVG aggregate function in StackQL: the average of the non-NULL values in a column or grouping. Source: https://stackql.io/language-spec/functions/aggregate/avg Returns the average value of all non `NULL` values within a column or grouping of columns. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT AVG(columnExpression) FROM <multipartIdentifier> [ GROUP BY groupByColumn ]; ``` ## Arguments __*columnExpression*__ A column or expression. > String and BLOB values which cannot be represented as numeric values are interpreted as `0`. > At least one value from the *columnExpression* must be non `NULL` otherwise `NULL` is returned. __*groupByColumn*__ A column or columns used to perform summary or aggregate operations against. The `GROUP BY` clause returns one row for each column grouping. ## Return Value(s) Returns a floating point value representing the average of the *columnExpression*. * * * ## Examples ### Return the average of a column expression over an entire resource ```sql SELECT avg(json_array_length(disks)) as avg_disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the average of a column expression grouped by another column expression ```sql SELECT tags, avg(json_array_length(disks)) as avg_disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' GROUP BY json_extract(tags, '$.instanceType'); ``` ### Use `AVG` as a window function to calculate moving averages ```sql -- Calculate moving average of commit activity WITH weekly_totals AS ( SELECT week, SUM(json_each.value) as commits_this_week FROM github.repos.stats_commit_activity, JSON_EACH(days) WHERE owner = 'stackql' AND repo = 'stackql' GROUP BY week ) SELECT week, commits_this_week, ROUND(AVG(commits_this_week) OVER (ORDER BY week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW), 1) as four_week_moving_avg FROM weekly_totals ORDER BY week; ``` For more information, see [https://www.sqlite.org/lang_aggfunc.html#avg](https://www.sqlite.org/lang_aggfunc.html#avg). --- # COUNT > COUNT aggregate function in StackQL: the number of rows in a resource, or the non-NULL values of a column within a grouping. Source: https://stackql.io/language-spec/functions/aggregate/count Returns the total number of records in a resource or a count of the non `NULL` instances of a column in a grouping. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT COUNT( * | columnExpression ) FROM <multipartIdentifier> [ GROUP BY groupByColumn ]; ``` ## Arguments __*columnExpression*__ or __*__ A column or expression. If __*__ is specified then all records in the resource or grouping are counted. > At least one value from the *columnExpression* must be non `NULL` otherwise `NULL` is returned. __*groupByColumn*__ A column or columns used to perform summary or aggregate operations against. The `GROUP BY` clause returns one row for each column grouping. ## Return Value(s) Returns an integer representing the count. * * * ## Examples ### Return the average of a column expression over an entire resource ```sql SELECT count(*) as num_instances FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the average of a column expression grouped by another column expression ```sql SELECT tags, count(*) as num_instances FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' GROUP BY json_extract(tags, '$.instanceType'); ``` ### Use `COUNT` as a window function to calculate cumulative counts ```sql -- Track cumulative issue counts over time SELECT number, title, state, created_at, COUNT(*) OVER (ORDER BY created_at) as cumulative_issues, COUNT(*) OVER (PARTITION BY state ORDER BY created_at) as cumulative_by_state FROM github.issues.issues WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY created_at; ``` For more information, see [https://www.sqlite.org/lang_aggfunc.html#count](https://www.sqlite.org/lang_aggfunc.html#count). --- # GROUP_CONCAT > GROUP_CONCAT aggregate function in StackQL: concatenate the non-NULL values of a column or grouping into one string with an optional separator. Source: https://stackql.io/language-spec/functions/aggregate/group_concat Returns a string which is the concatenation of all non `NULL` values of an input column or grouping. > The order of the concatenated elements is arbitrary. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT GROUP_CONCAT(columnExpression [, separator]) FROM <multipartIdentifier> [ GROUP BY groupByColumn ]; ``` ## Arguments __*columnExpression*__ A column or expression. If __*__ is specified then all records in the resource or grouping are counted. > At least one value from the *columnExpression* must be non `NULL` otherwise `NULL` is returned. __*separator*__ Seperator used for the concatenated result, the default of `,` is used if *separator* is not specified. __*groupByColumn*__ A column or columns used to perform summary or aggregate operations against. The `GROUP BY` clause returns one row for each column grouping. ## Return Value(s) Returns a string as a list of values seperated by the *separator* or `,`. * * * ## Examples ### Return a list of values for a column over an entire resource ```sql SELECT group_concat(name) as instance_list FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return a list of values for a column expression grouped by another column expression ```sql SELECT tags, group_concat(name) as instance_list FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' GROUP BY json_extract(tags, '$.instanceType'); ``` For more information, see [https://www.sqlite.org/lang_aggfunc.html#group_concat](https://www.sqlite.org/lang_aggfunc.html#group_concat). --- # MAX > MAX aggregate function in StackQL: the largest value in a column or grouping of columns. Source: https://stackql.io/language-spec/functions/aggregate/max Returns the maximum value based upon a column input or grouping of columns. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql /* aggregate function */ SELECT MAX(columnExpression) FROM <multipartIdentifier> [ GROUP BY groupByColumn ]; ``` ```sql /* scalar (multi-argument) function */ SELECT MAX(scalarExpression1, scalarExpressionN, ...) FROM <multipartIdentifier>; ``` ## Arguments ### Aggregate function __*columnExpression*__ A column or expression including operands (`+`, `-`, ...). > The `MAX` function will return the largest value for the given column based upon the column data type, for example a `MAX` operation on an integer column will return the largest integer for that column or column grouping, whereas a `MAX` operation on a string column or column grouping will return the largest ASCII value (generally the first value when sorted in lexographic order with some differences). __*groupByColumn*__ A column or columns used to perform summary or aggregate operations against. The `GROUP BY` clause returns one row for each column grouping. > The `MAX` function ignores `NULL` values. > The `MAX` function returns `NULL` if all the values in the group are `NULL`. ### Scalar function __*scalarExpression*__ A list columns or expressions (2 or more) from which the largest value is determined and returned. > The scalar `MAX` function returns `NULL` if any argument is `NULL`. > The scalar or multi-argument `MAX` function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. > If none of the arguments the scalar `MAX` function define a collating function, then the `BINARY` collating function is used. > If only one argument is provided, then the `MAX` aggregate function is invoked. ## Return Value(s) Returns the maximum value based upon the input data type (or grouping). * * * ## Examples ### Return the maximum value for a column ```sql SELECT name, location, max(timeCreated) FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Return the maximum value for each value in a column ```sql SELECT name, location, max(round(julianday('now')-julianday(timeCreated))) as age FROM google.storage.buckets WHERE project = 'stackql' GROUP BY location; ``` ### Return the maximum value from a list of values using the scalar `max` function ```sql SELECT max(json_extract(disks, '$[0].diskSizeGb'),json_extract(disks, '$[1].diskSizeGb')) as largest_disk FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Use `MAX` as a window function to find maximum values within partitions ```sql -- Find the most recent issue in each state SELECT number, title, state, created_at, MAX(created_at) OVER (PARTITION BY state) as latest_in_state FROM github.issues.issues WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY state, created_at DESC; ``` For more information, see [https://www.sqlite.org/lang_aggfunc.html#max_agg](https://www.sqlite.org/lang_aggfunc.html#max_agg) or [https://www.sqlite.org/lang_corefunc.html#max_scalar](https://www.sqlite.org/lang_corefunc.html#max_scalar) --- # MIN > MIN aggregate function in StackQL: the smallest value in a column or grouping of columns. Source: https://stackql.io/language-spec/functions/aggregate/min Returns the minimum value based upon a column input or grouping of columns. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql /* aggregate function */ SELECT MIN(columnExpression) FROM <multipartIdentifier> [ GROUP BY groupByColumn ]; ``` ```sql /* scalar (multi-argument) function */ SELECT MIN(scalarExpression1, scalarExpressionN, ...) FROM <multipartIdentifier>; ``` ## Arguments ### Aggregate function __*columnExpression*__ A column or expression including operands (`+`, `-`, ...). > The `MIN` function will return the smallest value for the given column based upon the column data type, for example a `MIN` operation on an integer column will return the smallest integer for that column or column grouping, whereas a `MIN` operation on a string column or column grouping will return the smallest ASCII value (generally the first value when sorted in reverse lexographic order with some differences). __*groupByColumn*__ A column or columns used to perform summary or aggregate operations against. The `GROUP BY` clause returns one row for each column grouping. > The `MIN` function ignores `NULL` values. > The `MIN` function returns `NULL` if all the values in the group are `NULL`. ### Scalar function __*scalarExpression*__ A list columns or expressions (2 or more) from which the smallest value is determined and returned. > The scalar `MIN` function returns `NULL` if any argument is `NULL`. > The scalar or multi-argument `MIN` function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. > If none of the arguments the scalar `MIN` function define a collating function, then the `BINARY` collating function is used. > If only one argument is provided, then the `MIN` aggregate function is invoked. ## Return Value(s) Returns the minimum value based upon the input data type (or grouping). * * * ## Examples ### Return the minimum value for a column ```sql SELECT name, location, min(timeCreated) FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Return the minimum value for each value in a column ```sql SELECT name, location, min(round(julianday('now')-julianday(timeCreated))) as age FROM google.storage.buckets WHERE project = 'stackql' GROUP BY location; ``` ### Return the minimum value from a list of values using the scalar `min` function ```sql SELECT min(json_extract(disks, '$[0].diskSizeGb'),json_extract(disks, '$[1].diskSizeGb')) as smallest_disk FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Use `MIN` as a window function to find minimum values within partitions ```sql -- Find the earliest issue in each state SELECT number, title, state, created_at, MIN(created_at) OVER (PARTITION BY state) as earliest_in_state FROM github.issues.issues WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY state, created_at; ``` For more information, see [https://www.sqlite.org/lang_aggfunc.html#min_agg](https://www.sqlite.org/lang_aggfunc.html#min_agg) or [https://www.sqlite.org/lang_corefunc.html#min_scalar](https://www.sqlite.org/lang_corefunc.html#min_scalar) --- # SUM > SUM aggregate function in StackQL: the total of the non-NULL values in a column or grouping, returned as an integer when every input is an integer. Source: https://stackql.io/language-spec/functions/aggregate/sum Returns the sum of all non `NULL` values in a column or grouping of columns. See also: [[` SELECT `]](/language-spec/select) [[` TOTAL `]](/language-spec/functions/aggregate/total) * * * :::tip Use the [**TOTAL**](/language-spec/functions/aggregate/total) function to sum floating point numbers or long values. ::: ## Syntax ```sql SELECT SUM(columnExpression) FROM <multipartIdentifier> [ GROUP BY groupByColumn ]; ``` ## Arguments __*columnExpression*__ A column or expression. > If all the values in the *columnExpression* are `NULL` then `SUM` returns `NULL`. > `SUM` will throw an "integer overflow" exception if an integer overflow occurs at any point during the computation. The [`TOTAL`]](/language-spec/functions/aggregate/total) function never throws an integer overflow. __*groupByColumn*__ A column or columns used to perform summary or aggregate operations against. The `GROUP BY` clause returns one row for each column grouping. ## Return Value(s) Returns an integer representing the sum of the *columnExpression* if all non `NULL` inputs are integers. If any inputs are not integers or are `NULL` then a floating point value which might be an approximation to the true sum is returned. * * * ## Examples ### Return the sum of a column expression over an entire resource ```sql SELECT sum(json_array_length(disks)) as sum_disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the sum of a column expression grouped by another column expression ```sql SELECT tags, sum(json_array_length(disks)) as sum_disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' GROUP BY json_extract(tags, '$.instanceType'); ``` ### Use `SUM` as a window function to calculate running totals ```sql -- Calculate running total and percentage of contributions SELECT login, contributions, SUM(contributions) OVER (ORDER BY contributions DESC) as running_total, SUM(contributions) OVER () as total_contributions, ROUND(100.0 * contributions / SUM(contributions) OVER (), 2) as pct_of_total FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` For more information, see [https://www.sqlite.org/lang_aggfunc.html#sumunc](https://www.sqlite.org/lang_aggfunc.html#sumunc). --- # TOTAL > TOTAL aggregate function in StackQL: the total of the non-NULL values in a column or grouping, always returned as a floating point number. Source: https://stackql.io/language-spec/functions/aggregate/total Returns the sum of all non `NULL` values in a column or grouping of columns. See also: [[` SELECT `]](/language-spec/select) [[` SUM `]](/language-spec/functions/aggregate/sum) * * * ## Syntax ```sql SELECT TOTAL(columnExpression) FROM <multipartIdentifier> [ GROUP BY groupByColumn ]; ``` ## Arguments __*columnExpression*__ A column or expression. > If all the values in the *columnExpression* are `NULL` then `TOTAL` returns `0.0`. __*groupByColumn*__ A column or columns used to perform summary or aggregate operations against. The `GROUP BY` clause returns one row for each column grouping. ## Return Value(s) Returns a floating point value representing the sum of the *columnExpression*. * * * ## Examples ### Return the sum of a column expression over an entire resource ```sql SELECT total(json_array_length(disks)) as total_disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the sum of a column expression grouped by another column expression ```sql SELECT tags, total(json_array_length(disks)) as total_disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' GROUP BY json_extract(tags, '$.instanceType'); ``` For more information, see [https://www.sqlite.org/lang_aggfunc.html#sumunc](https://www.sqlite.org/lang_aggfunc.html#sumunc). --- # DATE > DATE function in StackQL: return a date as a YYYY-MM-DD string from a time value and optional modifiers. Source: https://stackql.io/language-spec/functions/datetime/date Returns a date string in the format YYYY-MM-DD. See also: [[` SELECT `]](/language-spec/select) [[ Date Modifiers ]](/language-spec/functions/datetime/date_modifiers) * * * ## Syntax ```sql SELECT DATE(datetime_expression [, modifier, ...]) FROM <multipartIdentifier>; ``` ## Arguments __*datetime_expression*__ The datetime value. __*modifier*__ Zero or more modifiers to be applied to the *datetime_expression*. For more information about modifiers, see [**Date Modifiers**](/language-spec/functions/datetime/date_modifiers) ## Return Value(s) Returns a string representing the date component of the input *datetime_expression* with the *modifier* applied. * * * ## Examples ### Return the date component of a datetime value ```sql SELECT name, timeCreated, date(timeCreated) as date_only FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Return the local date component of a datetime value ```sql SELECT name, timeCreated, date(timeCreated, 'localtime') as local_date FROM google.storage.buckets WHERE project = 'stackql'; ``` For more information, see [https://www.sqlite.org/lang_datefunc.html](https://www.sqlite.org/lang_datefunc.html) --- # Date Modifiers > Date and time modifiers in StackQL: shift DATE, TIME, DATETIME, JULIANDAY and STRFTIME results by days, months or years, to a period start, a weekday and more. Source: https://stackql.io/language-spec/functions/datetime/date_modifiers ## Overview The date or time values datetime functions in StackQL can be followed by zero or more modifiers that alter the date and/or time. Each modifier is a transformation that is applied to the time value to its left. Modifiers are applied in order from left to right. The available modifiers are as follows: | Modifier | Description | |----------------------|-----------------------------------------------------------------------| | NNN day(s) | Add ±NNN days to a date and time | | NNN hour(s) | Add ±NNN hours to a date and time | | NNN minute(s) | Add ±NNN minutes to a date and time | | NNN[.NNNN] second(s) | Add ±NNN seconds to/from a date and time | | NNN month(s) | Add ±NNN months to a date and time | | NNN year(s) | Add ±NNN year to a date and time | | start of month | Backward to the beginning of the month | | start of year | Backward to the beginning of the year | | start of day | Backward to the beginning of the day | | weekday N | Advance a date forward to the next date where the weekday number is N | | localtime | Return local time | | utc | Return UTC time | | unixepoch | Unix time | ## Examples ### Return the current date and time using the `now` modifier ```sql SELECT name, date('now') as date, time('now') as time FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Convert UTC to localtime using the `localtime` modifier ```sql SELECT name, timeCreated, datetime(timeCreated, 'localtime') as local_time_created FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Covert datetime to UTC ```sql SELECT name, timeCreated, datetime('now', 'utc') as now_utc FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Calculate a date relative to another date ```sql SELECT name, timeCreated, datetime(timeCreated, '+24 hours') as a_day_later FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Get the next specified weekday after a given date ```sql SELECT name, timeCreated, datetime(timeCreated, 'weekday 0') as following_sunday FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Get the start of the month for a given date ```sql SELECT name, timeCreated, datetime(timeCreated, 'start of month') as start_of_month FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Covert a Unix timestamp to a datetime ```sql SELECT datetime(1576417943, 'unixepoch') as date_from_ts FROM google.storage.buckets WHERE project = 'stackql'; ``` :::tip To covert a datetime to a Unix epoch timestamp see [**STRFTIME**](/language-spec/functions/datetime/strftime). To calculate differences between two datetime objects see [**STRFTIME**](/language-spec/functions/datetime/strftime) or [**JULIANDAY**](/language-spec/functions/datetime/julianday). ::: --- # DATETIME > DATETIME function in StackQL: compute a datetime value from an input and one or more modifiers, returned as YYYY-MM-DD HH:MM:SS. Source: https://stackql.io/language-spec/functions/datetime/datetime-fn Returns a calculated datetime value from an input datetime and one or more modifiers. See also: [[` SELECT `]](/language-spec/select) [[ Date Modifiers ]](/language-spec/functions/datetime/date_modifiers) * * * ## Syntax ```sql SELECT DATETIME(datetime_expression , modifier, ...) FROM <multipartIdentifier>; ``` ## Arguments __*datetime_expression*__ The datetime value. __*modifier*__ Zero or more modifiers to be applied to the *datetime_expression*. For more information about modifiers, see [**Date Modifiers**](/language-spec/functions/datetime/date_modifiers) ## Return Value(s) Returns a string representing the datetime of the input *datetime_expression* with the *modifier* applied. * * * ## Examples ### Convert UTC to localtime using the `localtime` modifier ```sql SELECT name, timeCreated, datetime(timeCreated, 'localtime') as local_time_created FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Covert datetime to UTC ```sql SELECT name, timeCreated, datetime('now', 'utc') as now_utc FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Calculate a date relative to another date ```sql SELECT name, timeCreated, datetime(timeCreated, '+24 hours') as a_day_later FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Get the next specified weekday after a given date ```sql SELECT name, timeCreated, datetime(timeCreated, 'weekday 0') as following_sunday FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Get the start of the month for a given date ```sql SELECT name, timeCreated, datetime(timeCreated, 'start of month') as start_of_month FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Covert a Unix timestamp to a datetime ```sql SELECT datetime(1576417943, 'unixepoch') as date_from_ts FROM google.storage.buckets WHERE project = 'stackql'; ``` :::tip To covert a datetime to a Unix epoch timestamp see [**STRFTIME**](/language-spec/functions/datetime/strftime). To calculate differences between two datetime objects see [**STRFTIME**](/language-spec/functions/datetime/strftime) or [**JULIANDAY**](/language-spec/functions/datetime/julianday). ::: For more information, see [https://www.sqlite.org/lang_datefunc.html](https://www.sqlite.org/lang_datefunc.html) --- # JULIANDAY > JULIANDAY function in StackQL: the fractional number of days since noon on 24 November 4714 BC for a time value, useful for date arithmetic. Source: https://stackql.io/language-spec/functions/datetime/julianday Returns the Julian day - the number of days since noon in Greenwich on November 24, 4714 B.C. [(Proleptic Gregorian calendar)](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar). See also: [[` SELECT `]](/language-spec/select) [[ Date Modifiers ]](/language-spec/functions/datetime/date_modifiers) * * * ## Syntax ```sql SELECT JULIANDAY(datetime_expression [, modifier, ...]) FROM <multipartIdentifier>; ``` ## Arguments __*datetime_expression*__ The datetime value. __*modifier*__ Zero or more modifiers to be applied to the *datetime_expression*. For more information about modifiers, see [**Date Modifiers**](/language-spec/functions/datetime/date_modifiers) ## Return Value(s) Returns the [Julian Day](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar) representing the date component of the input *datetime_expression* with the *modifier* applied. * * * ## Examples ### Calculate the days between two dates ```sql SELECT name, timeCreated, round(julianday('now')-julianday(timeCreated)) as days_since FROM google.storage.buckets WHERE project = 'stackql'; ``` :::tip Use the [**ROUND**](/language-spec/functions/math/round) to convert floating point numbers to the nearest integer. ::: For more information, see [https://www.sqlite.org/lang_datefunc.html](https://www.sqlite.org/lang_datefunc.html) --- # STRFTIME > STRFTIME function in StackQL: format a datetime value with a format string, using the same substitutions as the C strftime function. Source: https://stackql.io/language-spec/functions/datetime/strftime Return a formatted datetime value based on a specified format. See also: [[` SELECT `]](/language-spec/select) [[ Date Modifiers ]](/language-spec/functions/datetime/date_modifiers) * * * ## Syntax ```sql SELECT STRFTIME(format, datetime_expression [, modifier, ...]) FROM <multipartIdentifier>; ``` ## Arguments __*format*__ The desired format for the datetime value specified by the *datetime_expression* value. See the table of formats below. __*datetime_expression*__ The date or time value to be formatted. __*modifier*__ Zero or more modifiers to be applied to the *datetime_expression*. For more information about modifiers, see [**Date Modifiers**](/language-spec/functions/datetime/date_modifiers) ### Formats | Format | Description | |--------|--------------------------------| | %d | day of the month: 01-31 | | %f | fractional seconds: SS.SSS | | %H | hour: 00-24 | | %j | day of the year: 001-366 | | %J | Julian day number | | %m | month: 01-12 | | %M | minute: 00-59 | | %s | seconds since 1970-01-01 | | %S | seconds: 00-59 | | %w | day of week 0-6 with Sunday==0 | | %W | week of the year: 00-53 | | %Y | year: 0000-9999 | | %% | escape a percent symbol: % | ## Return Value(s) Returns a formatted string representing the desired datetime format. * * * ## Examples ### Return a date in US format ```sql SELECT name, strftime('%m/%d/%Y', creationTimestamp) as created_at FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Convert a datetime to an epoch timestamp ```sql SELECT name, strftime('%s', creationTimestamp) as created_at FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Calculate the days between two dates ```sql SELECT name, (strftime('%s','now')-strftime('%s', creationTimestamp))/86400 as days_since_creation FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_datefunc.html](https://www.sqlite.org/lang_datefunc.html) --- # TIME > TIME function in StackQL: return a time as an HH:MM:SS string from a time value and optional modifiers. Source: https://stackql.io/language-spec/functions/datetime/time Returns a time string in the format HH:MM:SS. See also: [[` SELECT `]](/language-spec/select) [[ Date Modifiers ]](/language-spec/functions/datetime/date_modifiers) * * * ## Syntax ```sql SELECT TIME(datetime_expression [, modifier, ...]) FROM <multipartIdentifier>; ``` ## Arguments __*datetime_expression*__ The datetime value. __*modifier*__ Zero or more modifiers to be applied to the *datetime_expression*. For more information about modifiers, see [**Date Modifiers**](/language-spec/functions/datetime/date_modifiers) ## Return Value(s) Returns a string representing the time component of the input *datetime_expression* with the *modifier* applied. * * * ## Examples ### Return the time component of a datetime value ```sql SELECT name, timeCreated, time(timeCreated) as time_only FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Return the local time component of a datetime value ```sql SELECT name, timeCreated, time(timeCreated, 'localtime') as local_time FROM google.storage.buckets WHERE project = 'stackql'; ``` For more information, see [https://www.sqlite.org/lang_datefunc.html](https://www.sqlite.org/lang_datefunc.html) --- # COALESCE > COALESCE function in StackQL: return the first non-NULL argument from two or more, typically to substitute a default for a missing value. Source: https://stackql.io/language-spec/functions/general/coalesce Returns the first argument which is not `NULL` from a series of two or more arguments, can be used to substitute a default value for a `NULL` value. > The `COALESCE` function is equivalent to the `NVL` function in Oracle or the `IFNULL` function in MySQL. See also: [[` SELECT `]](/language-spec/select) [[` IFNULL `]](/language-spec/functions/general/ifnull) [[` NULLIF `]](/language-spec/functions/general/nullif) * * * ## Syntax ```sql SELECT COALESCE(expression1, expression2 [, ..]) FROM <multipartIdentifier>; ``` ## Arguments __*expression*__ Two or more expressions of any data type which resolve to a `NULL` or non `NULL` value. > If all of the *expression* arguments are `NULL`, the `COALESCE` function returns `NULL`. ## Return Value(s) Returns the first non `NULL` value from the series of *expression* arguments. * * * ## Examples ### Replace a `NULL` value with a default value ```sql SELECT name, coalesce(website, cors, 'not hosting shared resources') AS website_or_cors_config FROM google.storage.buckets where project = 'stackql'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#coalesce](https://www.sqlite.org/lang_corefunc.html#coalesce) --- # IDENTIFIER > IDENTIFIER function in StackQL: resolve a session variable holding a column name into a column reference, so variables can name columns in projections and ORDER BY. Source: https://stackql.io/language-spec/functions/general/identifier Resolves a string value, normally a session variable, into a column name. Use it where a bare `$variable` would otherwise be read as a scalar value. Available in StackQL `v1.0` and later. See also: [[` SET `]](/language-spec/set) [[ Session Variables ]](/getting-started/session-variables) * * * ## Syntax ```sql SELECT IDENTIFIER($variable) FROM <multipartIdentifier> ORDER BY IDENTIFIER($variable); ``` ## Arguments __*variable*__ A session variable, or a string literal, holding a column name. A qualified name such as `t.name` is accepted. Exactly one argument is accepted and it must be a single string value; a concatenation such as `'t.' || $column_name`, a second argument, or a numeric value is rejected with `IDENTIFIER requires one string value`. An empty value, or a value containing a statement, is rejected with `invalid identifier value`, and an undefined variable fails as undefined. All of these checks happen before any provider request is made. ## Return Value(s) The function is replaced in the parsed statement by a reference to the named column, so it returns that column's value. Names are converted to identifiers and never spliced into SQL text. The resulting column reference can be used anywhere a column can: the select list, `WHERE`, `GROUP BY` and `ORDER BY` clauses, function arguments, and inside CTEs and subqueries. * * * ## Examples ### Project and order by a column named in a variable The column to return and the column to sort on are both taken from `column_name`, and the output column is renamed from `output_name`. `IDENTIFIER` is needed in the select list and in `ORDER BY` because a bare `$column_name` in those positions would be the string `'name'`, not the column. The alias uses the double-quoted form instead. Once the variables are resolved, the statement is the same as `SELECT name AS bucket FROM aws.s3.buckets WHERE region = 'ap-southeast-2' ORDER BY name`. ```sql SET column_name = 'name'; SET output_name = 'bucket'; SELECT IDENTIFIER($column_name) AS "$output_name" FROM aws.s3.buckets WHERE region = 'ap-southeast-2' ORDER BY IDENTIFIER($column_name); ``` ### Filter on a column named in a variable The resolved reference works in a predicate as well as a projection. Here the field to filter on and the value to match both come from variables: `IDENTIFIER($filter_column)` becomes the column `status`, while `$filter_value` is passed as the string literal `'RUNNING'`. The two forms are deliberately different, because the first names a column and the second supplies a value. ```sql SET filter_column = 'status'; SET filter_value = 'RUNNING'; SELECT name, zone FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' AND IDENTIFIER($filter_column) = $filter_value; ``` ### Qualify the column with a table alias A dotted value resolves to a qualified column reference. The table is aliased as `w`, with the alias itself taken from a variable, and `IDENTIFIER($column_name)` becomes `w.name`. This is the form to use when the same column name exists on both sides of a join and the reference would otherwise be ambiguous. ```sql SET table_alias = 'w'; SET column_name = 'w.name'; SELECT IDENTIFIER($column_name) AS bucket FROM aws.s3.buckets AS "$table_alias" WHERE w.region = 'ap-southeast-2'; ``` ### Rejected values Because the value becomes a name rather than query text, anything that is not a usable name is refused before the statement is planned, and no request reaches the provider. The first two statements below fail with `invalid identifier value` and the third with `IDENTIFIER requires one string value`. ```sql /* SET column_name = ''; SELECT IDENTIFIER($column_name) FROM aws.s3.buckets; -- FAILS with invalid identifier value SET column_name = 'name; DROP TABLE imaginary'; SELECT IDENTIFIER($column_name) FROM aws.s3.buckets; -- FAILS with invalid identifier value SET column_name = 17; SELECT IDENTIFIER($column_name) FROM aws.s3.buckets; -- FAILS with IDENTIFIER requires one string value */ ``` > A `$variable` in a `FROM` clause resolves to a relation without `IDENTIFIER`, and a double-quoted `"$variable"` is used for aliases, DDL column names, `INSERT` column lists and `UPDATE` targets. --- # IFNULL > IFNULL function in StackQL: return the first of exactly two arguments that is not NULL, a two-argument form of COALESCE. Source: https://stackql.io/language-spec/functions/general/ifnull Accepts exactly two arguments and returns the first non `NULL` argument, can be used to substitute a default value for a `NULL` value. > The `IFNULL` function is equivalent to the [`COALESCE`](/language-spec/functions/general/coalesce) function with two arguments only, the [`COALESCE`](/language-spec/functions/general/coalesce) function can have more than two arguments. See also: [[` SELECT `]](/language-spec/select) [[` COALESCE `]](/language-spec/functions/general/coalesce) [[` NULLIF `]](/language-spec/functions/general/nullif) * * * ## Syntax ```sql SELECT IFNULL(expression1, expression2) FROM <multipartIdentifier>; ``` ## Arguments __*expression*__ Two expressions of any data type which resolve to a `NULL` or non `NULL` value. > If both *expression* arguments are `NULL`, the `IFNULL` function returns `NULL`. ## Return Value(s) Returns the first non `NULL` value from the two *expression* arguments. * * * ## Examples ### Replace a `NULL` value with a default value ```sql SELECT name, ifnull(website, 'Not hosting a website') AS website FROM google.storage.buckets where project = 'stackql'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#ifnull](https://www.sqlite.org/lang_corefunc.html#ifnull) --- # IIF > IIF function in StackQL: return one of two values depending on whether a condition is true, an inline if-then-else expression. Source: https://stackql.io/language-spec/functions/general/iif Returns a value based upon the evaluation of an input expression. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT IIF(expression, result_if_true, result_if_false) FROM <multipartIdentifier>; ``` > The `iif()` function is logically equivalent to the `CASE` expression `CASE WHEN expression THEN result_if_true ELSE result_if_false END` ## Arguments __*expression*__ A boolean expression to be evaluated. :::tip The *expression* argument can be a nested function such as `JSON_EXTRACT`. ::: __*result_if_true*__ The result to be returned if *expression* evaluates to `true`. __*result_if_false*__ The result to be returned if *expression* evaluates to `false`. ## Return Value(s) The datatype of the *result_if_true* or *result_if_false* arguments. * * * ## Examples ### Catgorize disk sizes of compute engine instances ```sql SELECT iif(json_extract(disks, '$[0].diskSizeGb') > 9, "> 10GB", "<= 10GB") as disk_size FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#iif](https://www.sqlite.org/lang_corefunc.html#iif) --- # NULLIF > NULLIF function in StackQL: return NULL when two arguments are equal, otherwise return the first argument. Source: https://stackql.io/language-spec/functions/general/nullif Accepts two arguments and returns a `NULL` value if they are equal, otherwise the first argument is returned. > The `NULLIF` function is equvalent to `CASE WHEN expression1 = expression2 THEN NULL ELSE expression1 END` > `NULLIF` is useful with aggregate functions such as [`AVG`](/language-spec/functions/aggregate/avg), [`MAX`](/language-spec/functions/aggregate/max), [`MIN`](/language-spec/functions/aggregate/min), [`SUM`](/language-spec/functions/aggregate/sum), and [`COUNT`](/language-spec/functions/aggregate/count), where the result set contains special values that are not `NULL`, but that you want to treat as `NULL` for the purposes of aggregation. See also: [[` SELECT `]](/language-spec/select) [[` COALESCE `]](/language-spec/functions/general/coalesce) [[` IFNULL `]](/language-spec/functions/general/ifnull) * * * ## Syntax ```sql SELECT NULLIF(expression1, expression2) FROM <multipartIdentifier>; ``` ## Arguments __*expression*__ Two expressions of any data type which resolve to a `NULL` or non `NULL` value. > The `NULLIF` function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If neither argument defines a collating function then `BINARY` collation is used. ## Return Value(s) Returns `NULL` if the two *expression* arguments resolve to the same value, otherwise the first value is returned. * * * ## Examples ### Count records where a field is not equal to a given value ```sql SELECT COUNT(NULLIF(name, 'controller-0')) FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; /* equivalent to: SELECT COUNT(*) FROM google.compute.instances WHERE name != 'controller-0'; */ ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#nullif](https://www.sqlite.org/lang_corefunc.html#nullif) --- # MD5 > MD5 function in StackQL: return the lowercase hexadecimal MD5 digest of a string, for fingerprinting and change detection rather than security. Source: https://stackql.io/language-spec/functions/hash/md5 Returns the MD5 digest of a string as 32 lowercase hexadecimal characters. Available in StackQL `v1.0` and later. See also: [[` SELECT `]](/language-spec/select) [[ Concatenation ]](/language-spec/functions/string/concatenation) * * * ## Syntax ```sql SELECT MD5(expression) FROM <multipartIdentifier>; ``` ## Arguments __*expression*__ A string, or a value coerced to text. A `NULL` argument returns `NULL`. ## Return Value(s) Returns a 32 character lowercase hexadecimal string. > `MD5` is provided for fingerprinting and change detection. It is not a password or security primitive. On the PostgreSQL backend the database's own `md5` function is used. * * * ## Examples ### Fingerprint a derived value The variables are substituted as typed values, the integer is converted to text and joined to the suffix, and the digest is taken over the lower-cased result. The same inputs always produce the same 32-character hexadecimal string, so the value can be used as a stable key. ```sql SET some_id = 42; SET suffix = 'East'; SELECT md5(lower(CONVERT($some_id, TEXT) || '-' || $suffix)) AS digest; ``` ### Detect configuration changes Hashing a serialised JSON column gives a short value to store and compare between runs. A bucket whose digest differs from the last run has a changed IAM configuration, without the whole document having to be stored or diffed. ```sql SELECT name, md5(json_extract(iamConfiguration, '$')) AS iam_digest FROM google.storage.buckets WHERE project = 'stackql-demo'; ``` --- # AWS_POLICY_EQUAL > Compare two AWS IAM policy documents or AWS tags arrays for semantic equivalence using SQL. Source: https://stackql.io/language-spec/functions/json/aws_policy_equal Compares two AWS IAM policy JSON strings (or AWS tags arrays) and returns `true` if they are semantically equivalent according to AWS policy evaluation rules, `false` otherwise. See also: [__[` SELECT `]__](/language-spec/select) [__[` DESCRIBE `]__](/language-spec/describe) [__[` JSON_EQUAL `]__](/language-spec/functions/json/json_equal) [__[` JSON_EXTRACT `]__](/language-spec/functions/json/json_extract) [[ Data Types ]](/language-spec/data-types) * * * :::tip The `aws_policy_equal` function is a custom StackQL extension function. It handles AWS IAM policy comparison according to AWS policy evaluation rules, where certain elements (like `Action`, `Resource`, `Principal`, and `Tags`) are treated as unordered sets. When both arguments are top-level JSON arrays (e.g. a raw AWS tags array), they are also compared as unordered sets. The `aws_policy_equal` function is available in StackQL versions `0.8.175` and above and is only supported with the default embedded, in-memory SQL backend for StackQL. ::: ## Syntax ```sql SELECT AWS_POLICY_EQUAL(policy1, policy2); ``` ## Arguments __*policy1*__ A JSON string representing an AWS IAM policy document, or a JSON array of AWS tags. __*policy2*__ Another JSON string representing an AWS IAM policy document or tags array to compare against the first. > Both arguments must be valid JSON. When comparing policy documents, both must be valid AWS IAM policy JSON. ## Return Value(s) An integer value: __1__ if the documents are semantically equivalent, __0__ if they are not. * * * ## Examples ### Compare AWS IAM Policies ```sql SELECT AssumeRolePolicyDocument as current_policy, '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}' as desired_policy, AWS_POLICY_EQUAL(AssumeRolePolicyDocument, '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}') as compliant FROM aws.iam.roles WHERE RoleName = 'my-lambda-role'; /* returns... |------------------------------------------------------------------|------------------------------------------------------------------|-----------| | current_policy | desired_policy | compliant | |------------------------------------------------------------------|------------------------------------------------------------------|-----------| | {"Version":"2012-10-17","Statement":[{"Effect":"Allow", | {"Version":"2012-10-17","Statement":[{"Effect":"Allow", | 1 | | "Principal":{"Service":"lambda.amazonaws.com"}, | "Principal":{"Service":"lambda.amazonaws.com"}, | | | "Action":"sts:AssumeRole"}]} | "Action":"sts:AssumeRole"}]} | | |------------------------------------------------------------------|------------------------------------------------------------------|-----------| */ ``` ### Compare Policies with Different Element Ordering ```sql SELECT aws_policy_equal( '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":"*"}]}', '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject"],"Resource":"*"}]}' ) as unordered_action_equal, aws_policy_equal( '{"Version":"2012-10-17","Statement":[{"Condition":{"StringEquals":{"sts:ExternalId":"0000"}},"Action":"sts:AssumeRole","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:role/role1"}}]}', '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:role/role1"},"Action":"sts:AssumeRole","Condition":{"StringEquals":{"sts:ExternalId":"0000"}}}]}' ) as reordered_elements_equal ; /* returns... |------------------------|--------------------------| | unordered_action_equal | reordered_elements_equal | |------------------------|--------------------------| | 1 | 1 | |------------------------|--------------------------| */ ``` ### Compare Different Policy Formats (Array vs String) ```sql SELECT aws_policy_equal( '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":"*"}]}', '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}' ) as array_string_equal ; /* returns... |--------------------| | array_string_equal | |--------------------| | 1 | |--------------------| */ ``` ### Compare AWS Tags Arrays AWS does not guarantee the order of tags returned by its APIs. Use `aws_policy_equal` to compare tags arrays without regard to element order. ```sql SELECT aws_policy_equal( tags, '[{"Key":"stackql:stack-name","Value":"stackql-serverless"},{"Key":"stackql:stack-env","Value":"dev"},{"Key":"stackql:resource-name","Value":"aws_s3_workspace_bucket"}]' ) as tags_match FROM aws.s3.buckets WHERE region = 'us-east-1' AND name = 'my-workspace-bucket'; /* returns... |------------| | tags_match | |------------| | 1 | |------------| -- Returns 1 regardless of the order AWS returns the tags array */ ``` ### Compare Resource Tags Nested in a Resource Object When tags are embedded inside a resource object as a `Tags` field, `aws_policy_equal` still treats the tags array as an unordered set. ```sql SELECT aws_policy_equal( '{"BucketName":"my-bucket","Tags":[{"Key":"env","Value":"prod"},{"Key":"team","Value":"platform"}]}', '{"BucketName":"my-bucket","Tags":[{"Key":"team","Value":"platform"},{"Key":"env","Value":"prod"}]}' ) as nested_tags_equal ; /* returns... |--------------------| | nested_tags_equal | |--------------------| | 1 | |--------------------| */ ``` For more information, see [aws_policy_equal](https://github.com/stackql/sqlite-ext-functions/blob/main/sqlpkg/aws_policy_equal.json). --- # JSON_ARRAY_LENGTH > JSON_ARRAY_LENGTH function in StackQL: the number of elements in a JSON array, at the top level or at a path within a JSON value. Source: https://stackql.io/language-spec/functions/json/json_array_length Returns the number of elements in a JSON array. See also: [[` SELECT `]](/language-spec/select) [[` DESCRIBE `]](/language-spec/describe) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[ Data Types ]](/language-spec/data-types) * * * :::tip Use the [**DESCRIBE**](/language-spec/describe) function to locate `array` or `object` datatypes which can be used with StackQL JSON functions. Use the [**JSON_TYPE**](/language-spec/functions/json/json_type) function to resolve the datatypes of nested objects or array elements. ::: ## Syntax ```sql SELECT JSON_ARRAY_LENGTH(json_array_or_object [, json_path]) FROM <multipartIdentifier>; ``` ## Arguments __*json_array_or_object*__ A JSON array or object. > If *json_array_or_object* is a JSON object (not an array) and *json_path* is not specified then `0` is returned. __*json_path*__ The optional JSON path to an array contained within an object. See [jsonpath.com](https://jsonpath.com/). > If *json_path* is supplied then the `json_array_length` function locates the path within *json_array_or_object* and returns the length of the array or `0` if *json_path* is an object (not an array). If *json_path* cannot be located within *json_array_or_object*, then `NULL` is returned. > If *json_array_or_object* or *json_path* are not JSON objects or are not well-formed, then an error is thrown. ## Return Value(s) Returns an integer. * * * ## Examples ### Return the number of disks attached to Google Compute Engine instances ```sql SELECT name, json_array_length(disks) as num_disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the number of network interfaces attached to Google Compute Engine instances ```sql SELECT name, json_array_length(networkInterfaces) as num_nics FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the number of ACLs associated with Google Storage Buckets ```sql SELECT name, json_array_length(acl) as num_acls FROM google.storage.buckets WHERE project = 'stackql'; ``` ### Return the number of scopes associated with a service account ```sql SELECT name, json_array_length(serviceAccounts, '$[0].scopes') as num_scopes FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/json1.html#jarraylen](https://www.sqlite.org/json1.html#jarraylen) --- # JSON_EACH > JSON_EACH table-valued function in StackQL: expand a JSON array or object into one row per element or member, to join and filter nested API responses. Source: https://stackql.io/language-spec/functions/json/json_each Table-valued function which returns a table consisting of one row for each array element or object member. See also: [[` SELECT `]](/language-spec/select) [[` DESCRIBE `]](/language-spec/describe) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[` JSON_ARRAY_LENGTH `]](/language-spec/functions/json/json_array_length) [[ Data Types ]](/language-spec/data-types) * * * :::tip Use the [**DESCRIBE**](/language-spec/describe) function to locate `array` datatypes which can be used with the `json_each` function. ::: :::note The `json_each` function is implemented as the `json_array_elements_text` function if you are using stackql with a `postgres` sql backend ::: ## Syntax ```sql SELECT <alias>.<projectedField>, ... , json_each.value FROM <multipartIdentifier> <alias>, JSON_EACH(json_array_or_object, json_path); ``` ## Arguments __*json_array_or_object*__ A JSON array or object. __*json_path*__ The JSON path to an array or object contained within an *json_array_or_object*. See [jsonpath.com](https://jsonpath.com/). > If *json_path* does not exist in *json_array_or_object*, then the function returns `NULL`. > The `json_type()` function throws an error if any of its arguments are not well-formed. ## Return Value(s) A table consisting of one row for each array element or object member. * * * ## Examples ### Unnest an array of strings into a table joined with associated fields for context: ```sql describe google.cloudresourcemanager.projects_iam_policies; ``` returns... ``` |-----------|--------| | name | type | |-----------|--------| | condition | object | |-----------|--------| | members | array | |-----------|--------| | role | string | |-----------|--------| ``` The following `stackql` query uses the `json_each` function to unnest the `members` array into a table joined with the `role` and optionally `condition` fields. ```sql select iam.role, SPLIT_PART(json_each.value, ':', 2) as member from google.cloudresourcemanager.projects_iam_policies iam, json_each(members) where projectsId = 'stackql'; ``` would return... ``` |--------------------------------------|-------------------------------------------------------| | role | member | |--------------------------------------|-------------------------------------------------------| | roles/cloudbuild.builds.builder | 1234567890@cloudbuild.gserviceaccount.com | |--------------------------------------|---------------------------------------------- --------| | roles/editor | 1234567890-compute@developer.gserviceaccount.com | |--------------------------------------|-------------------------------------------------------| | roles/editor | 1234567890@cloudservices.gserviceaccount.com | |--------------------------------------|-------------------------------------------------------| | roles/editor | stackql@appspot.gserviceaccount.com | |--------------------------------------|-------------------------------------------------------| | ... | ... | |--------------------------------------|-------------------------------------------------------| ``` For more information, see [https://www.sqlite.org/json1.html#jeach](https://www.sqlite.org/json1.html#jeach) --- # JSON_EQUAL > Compare two JSON strings for equivalence using SQL. Source: https://stackql.io/language-spec/functions/json/json_equal Compares two JSON strings and returns true if they are equivalent, false otherwise. See also: [[` SELECT `]](/language-spec/select) [[` DESCRIBE `]](/language-spec/describe) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[` JSON_ARRAY_LENGTH `]](/language-spec/functions/json/json_array_length) [[ Data Types ]](/language-spec/data-types) * * * :::tip The `json_equal` function is a custom StackQL extension function. It supports comparing JSON objects and arrays, treating objects with keys in different orders as equivalent according to the JSON specification. The `json_equal` function is available in StackQL versions `0.5.707` and above and is only supported with the default embedded, in-memory SQL backend for StackQL. ::: ## Syntax ```sql SELECT JSON_EQUAL(json1, json2); ``` ## Arguments __*json1*__ A JSON string representing an object or array. __*json2*__ Another JSON string to compare against the first. > Both arguments must be valid JSON strings. ## Return Value(s) An integer value: 1 if the JSON strings are equivalent, 0 if they are not. * * * ## Examples ### Compare JSON Objects ```sql SELECT public_access_block_configuration as current_state, '{"BlockPublicAcls": true, "BlockPublicPolicy": true, "IgnorePublicAcls": true, "RestrictPublicBuckets": true}' as desired_state, JSON_EQUAL(public_access_block_configuration, '{"BlockPublicAcls": true, "BlockPublicPolicy": true, "IgnorePublicAcls": true, "RestrictPublicBuckets": true}') as comp FROM awscc.s3.buckets WHERE region = 'ap-southeast-2' AND Identifier = 'my-bucket'; /* returns... |--------------------------------------------------------------------------------------------------------|--------------------------------|------| | current_state | desired_state | comp | |--------------------------------------------------------------------------------------------------------|--------------------------------|------| | {"RestrictPublicBuckets":true,"BlockPublicPolicy":true,"BlockPublicAcls":true,"IgnorePublicAcls":true} | {"BlockPublicAcls": true, | 1 | | | "BlockPublicPolicy": true, | | | | "IgnorePublicAcls": true, | | | | "RestrictPublicBuckets": true} | | |--------------------------------------------------------------------------------------------------------|--------------------------------|------| */ ``` ### Compare JSON Arrays ```sql SELECT json_equal('[1, 2, 3]', '[1, 2, 3]') as array_comp_1, json_equal('[1, 2, 3]', '[3, 2, 1]') as array_comp_2 ; /* returns... |--------------|--------------| | array_comp_1 | array_comp_2 | |--------------|--------------| | 1 | 0 | |--------------|--------------| */ ``` For more information, see [json_equal](https://github.com/stackql/sqlite-ext-functions/blob/main/docs/json_equal.md). --- # JSON_EXTRACT > JSON_EXTRACT function in StackQL: pull one or more values out of a JSON object or array by path, the main tool for flattening nested API response fields. Source: https://stackql.io/language-spec/functions/json/json_extract Returns one or more values from a well-formed JSON object or array. See also: [[` SELECT `]](/language-spec/select) [[` DESCRIBE `]](/language-spec/describe) [[` JSON_ARRAY_LENGTH `]](/language-spec/functions/json/json_array_length) [[ Data Types ]](/language-spec/data-types) * * * :::tip Use the [**DESCRIBE**](/language-spec/describe) function to locate `array` or `object` datatypes which can be used with StackQL JSON functions. Use the [**JSON_TYPE**](/language-spec/functions/json/json_type) function to resolve the datatypes of nested objects or array elements. ::: :::note The `json_extract` function is implemented as the `json_extract_path_text` function if you are using stackql with a `postgres` sql backend ::: ## Syntax ```sql SELECT JSON_EXTRACT(json_array_or_object, json_path[, json_path1, .. json_pathN]) FROM <multipartIdentifier>; ``` ## Arguments __*json_array_or_object*__ A JSON array or object. __*json_path*__ The JSON path to an array or object contained within an *json_array_or_object*. See [jsonpath.com](https://jsonpath.com/). > If a single *json_path* is provided then a scalar result is returned mapping to the datatype of the resolved path. > If multiple *json_path* arguments are provided, then the result will be an array composed of objects resolved by the respective paths. > Specifying `'$'` for the *json_path* argument will return the entire JSON object corresponding to the column represented by the *json_array_or_object* argument. > NOTE: You can use tools like [`json-viewer`](https://aarrange.com/json-viewer) to develop and test JSON Path expressions ## Return Value(s) A string, integer, object, array, boolean or null depending upon the *json_array_or_object* and *json_path* provided as input. * * * ## Examples ### Return the disk objects associated with each Google Compute Engine instance ```sql SELECT name, json_extract(disks, '$') as disks FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the device name and size of the first disk attached to each Google Compute Engine instance ```sql SELECT name, json_extract(disks, '$[0].deviceName') as device_name, json_extract(disks, '$[0].diskSizeGb') as disk_size FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the network tier of first NIC attached to each Google Compute Engine instances ```sql SELECT name, json_extract(networkInterfaces, '$[0].accessConfigs[0].networkTier') as network_tier FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return a list of scopes associated with the first service account associated with each Google Compute Engine instance ```sql SELECT name, json_extract(serviceAccounts, '$[0].scopes') as scopes FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; /* returns a list for each service account */ ``` For more information, see [https://www.sqlite.org/json1.html#jex](https://www.sqlite.org/json1.html#jex) --- # JSON_GROUP_ARRAY > Aggregate JSON objects into a JSON array using SQL in StackQL. Source: https://stackql.io/language-spec/functions/json/json_group_array Aggregates values as a JSON array. `JSON_GROUP_ARRAY()` collects all values for each group in a specified column and combines them into a JSON array. See also: [[`SELECT`]](/language-spec/select) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) * * * ## Syntax ```sql SELECT JSON_GROUP_ARRAY(column_name) FROM <multipartIdentifier> WHERE condition GROUP BY column_name; ``` ## Arguments __*column_name*__ The column from which values are aggregated into a JSON array. ## Return Value(s) Returns a JSON array containing all the aggregated values from the specified column. * * * ## Examples ### Aggregate Resource Group Names into a JSON Array ```sql -- Collects all resource group names into a JSON array SELECT JSON_GROUP_ARRAY(name) as res_groups FROM azure.resource.resource_groups WHERE subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468'; ``` This query returns a JSON array of resource group names such as `["stackqlenv1","stackqlenv2","stackqlenv3"]`. ### Aggregate Resource Groups by Location ```sql -- Collects resource group names into a JSON array grouped by location SELECT location, JSON_GROUP_ARRAY(name) AS resource_groups FROM azure.resource.resource_groups WHERE subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468' GROUP BY location; ``` This query organizes resource groups into JSON arrays based on their location, returning multiple arrays, one for each location, containing the names of resource groups in that location. --- # JSON_GROUP_OBJECT > Aggregate key-value pairs into a JSON object using SQL in StackQL. Source: https://stackql.io/language-spec/functions/json/json_group_object Aggregates key-value pairs into a JSON object, grouping by a specified column. `JSON_GROUP_OBJECT()` collects all key-value pairs for each group in specified columns and combines them into a single JSON object for each group. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT JSON_GROUP_OBJECT(key_column, value_column) FROM <multipartIdentifier> WHERE condition GROUP BY grouping_column; ``` ## Arguments __*key_column*__ The column that provides the keys for the JSON objects. __*value_column*__ The column that provides the values for the JSON objects. __*grouping_column*__ The column by which the results are grouped. ## Return Value(s) Returns a JSON object containing all the aggregated key-value pairs from the specified columns, grouped according to the `grouping_column`. * * * ## Examples ### Aggregate Repository Sizes by Programming Language ```sql -- Example: Group repository names with their corresponding sizes by programming language SELECT language, JSON_GROUP_OBJECT(name, size) AS language_index FROM github.repos.repos WHERE org = 'stackql' AND language IS NOT NULL GROUP BY language; ``` This query returns a JSON object for each programming language, where each object contains repository names and their corresponding sizes as key-value pairs. Here's a sample of the expected output: ```plaintext |-------------|-----------------------------------------------------------------------------------| | language | language_index | |-------------|-----------------------------------------------------------------------------------| | C | {"go-sqlite3":35667,"data-encryption-spike":50746} | |-------------|-----------------------------------------------------------------------------------| | C++ | {"expt-any-sdk":2399,"isqlang":9} | |-------------|-----------------------------------------------------------------------------------| | Dockerfile | {"stackql-compliance-checks-devel":8} | |-------------|-----------------------------------------------------------------------------------| | Go | {"stackql-provider-registry":115711, ...} | |-------------|-----------------------------------------------------------------------------------| ``` This output is useful for visualizing the distribution of repository sizes across different programming languages within an organization, providing clear and organized data grouped by language. --- # JSON_INSERT > Insert new values into a JSON document without overwriting existing data using SQL in StackQL. Source: https://stackql.io/language-spec/functions/json/json_insert Inserts new values into a JSON document at specified paths without overwriting existing values. See also: [[`SELECT`]](/language-spec/select) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[` JSON_SET `]](/language-spec/functions/json/json_set) [[` JSON_REPLACE `]](/language-spec/functions/json/json_replace) * * * ## Syntax ```sql SELECT JSON_INSERT(json_column, path, new_value) FROM <multipartIdentifier>; ``` ## Arguments __*json_column*__ The JSON column or expression to be modified. __*path*__ The JSON path expression where the new value should be inserted. If the path already exists, the original value at that path is not replaced. __*new_value*__ The value to insert at the specified path in the JSON document. ## Return Value(s) Returns the JSON document with the new value inserted if the specified path does not already exist; otherwise, the JSON document is returned unchanged. :::note Behavior If a Key Exists | Function | Overwrite if already exists? | Create if does not exist? | |--------------------------------------------------------------|------------------------------|---------------------------| | [`json_insert()`](/language-spec/functions/json/json_insert) | No | Yes | | [`json_replace()`](/language-spec/functions/json/json_replace) | Yes | No | | [`json_set()`](/language-spec/functions/json/json_set) | Yes | Yes | ::: * * * ## Examples ### Insert a new key-value pair into a JSON object ```sql -- Example: Insert a new 'region' key with the value 'Europe' into a JSON object SELECT JSON_INSERT(json_data, '$.region', 'Europe') as updated_object; /* expected output... |-------------------------------------------------------------| | updated_json | |-------------------------------------------------------------| | {"name":"ResourceOne", "type":"Storage", "region":"Europe"} | |-------------------------------------------------------------| */ ``` This query inserts a new key called 'region' with the value 'Europe' into the JSON document if the 'region' key does not already exist. If 'region' is already a key in the document, the original document is returned without changes. --- # JSON_OBJECT > JSON_OBJECT function in StackQL: build a JSON object from key and value arguments, for example to construct request bodies for INSERT and UPDATE. Source: https://stackql.io/language-spec/functions/json/json_object Returns an object constructred from arguments provided. See also: [[` SELECT `]](/language-spec/select) [[` DESCRIBE `]](/language-spec/describe) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[ Data Types ]](/language-spec/data-types) * * * :::tip Use the [**DESCRIBE**](/language-spec/describe) function to locate `array` or `object` datatypes which can be used with StackQL JSON functions. ::: :::note The `json_object` function as `jsonb_build_object` if you are using stackql with a `postgres` SQL backend. ::: ## Syntax ```sql SELECT JSON_OBJECT(key1, value1, key2, value2, ...) FROM <multipartIdentifier>; ``` ## Arguments __*key1, key2, ...*__ The labels for the JSON object. __*value1, value2, ...*__ The values corresponding to the labels in the JSON object. ## Return Value(s) A string representing the well-formed JSON object. * * * ## Examples ### Return the datatype of a field nested within a JSON object or array ```sql SELECT JSON_GROUP_ARRAY(json_object('instance', selfLink)) as instance_links FROM google.compute.instances WHERE project = 'stackql-k8s-the-hard-way-demo' AND zone = 'australia-southeast1-a' AND name like '%-dev-controller-%'; /* returns a data structure required for a targetPool in GCP */ ``` For more information, see [https://sqlite.org/json1.html#jobj](https://sqlite.org/json1.html#jobj) --- # JSON_PATCH > Apply a JSON MergePatch to a JSON document using SQL in StackQL, modifying or merging JSON objects. Source: https://stackql.io/language-spec/functions/json/json_patch Applies a JSON MergePatch (RFC-7396) to a JSON document, modifying it according to specified operations. This function is used to add, modify, or delete elements within JSON objects but treats JSON arrays as atomic units. See also: [[`SELECT`]](/language-spec/select) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) * * * ## Syntax ```sql SELECT JSON_PATCH(target_json, patch_json) FROM <multipartIdentifier>; ``` ## Arguments __*target_json*__ The JSON document to be patched. __*patch_json*__ A JSON document describing the changes to be applied according to the MergePatch algorithm. ## Return Value(s) Returns the modified JSON document after the patch has been applied. * * * ## Examples ### Simple MergePatch ```sql -- Example: Simple merge of new elements into the target JSON object SELECT JSON_PATCH('{"a":1,"b":2}', '{"c":3,"d":4}') AS patched_json; ``` Output: `{"a":1,"b":2,"c":3,"d":4}` ### Replace Element in Array ```sql -- Example: Replacing an array with a single value in the JSON object SELECT JSON_PATCH('{"a":[1,2],"b":2}', '{"a":9}') AS patched_json; ``` Output: `{"a":9,"b":2}` ### Remove Element Using Null ```sql -- Example: Removing an element by setting it to null SELECT JSON_PATCH('{"a":1,"b":2}', '{"a":9,"b":null,"c":8}') AS patched_json; ``` Output: `{"a":9,"c":8}` ### Nested MergePatch ```sql -- Example: Nested merge patch updating sub-keys within a nested JSON object SELECT JSON_PATCH('{"a":{"x":1,"y":2},"b":3}', '{"a":{"y":9},"c":8}') AS patched_json; ``` Output: `{"a":{"x":1,"y":9},"b":3,"c":8}` This functionality allows for flexible and dynamic updates to JSON stored in a database, particularly useful for applications requiring conditional modifications of data structures. --- # JSON_REMOVE > Remove elements from a JSON document by specifying paths using SQL in StackQL. Source: https://stackql.io/language-spec/functions/json/json_remove Removes specified elements from a JSON document using path expressions. If a specified path does not exist in the document, it is ignored. Sequential processing of paths can affect the structure for subsequent removals. See also: [[`SELECT`]](/language-spec/select) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) * * * ## Syntax ```sql SELECT JSON_REMOVE(json_document, path1, path2, ...) FROM <multipartIdentifier>; ``` ## Arguments __*json_document*__ The JSON document from which elements are to be removed. __*path1, path2, ...*__ One or more path expressions pointing to elements in the JSON document to be removed. ## Return Value(s) Returns a copy of the JSON document with the specified elements removed. If no paths are provided, returns the input JSON reformatted with excess whitespace removed. * * * ## Examples ### Remove an Element from a JSON Array ```sql -- Example: Remove the third element from a JSON array SELECT JSON_REMOVE('[0,1,2,3,4]', '$[2]') AS modified_json; ``` Output: `'[0,1,3,4]'` ### Remove Multiple Elements from a JSON Array ```sql -- Example: Remove the first and third elements from a JSON array SELECT JSON_REMOVE('[0,1,2,3,4]', '$[2]', '$[0]') AS modified_json; ``` Output: `'[1,3,4]'` ### Remove Last Element Using Negative Index ```sql -- Example: Remove the last and first elements from a JSON array SELECT JSON_REMOVE('[0,1,2,3,4]', '$[#-1]', '$[0]') AS modified_json; ``` Output: `'[1,2,3]'` ### Remove Non-existent Path ```sql -- Example: Attempt to remove a non-existent key from a JSON object SELECT JSON_REMOVE('{"x":25,"y":42}', '$.z') AS modified_json; ``` Output: `'{"x":25,"y":42}'` ### Remove Existing Key from JSON Object ```sql -- Example: Remove the 'y' key from a JSON object SELECT JSON_REMOVE('{"x":25,"y":42}', '$.y') AS modified_json; ``` Output: `'{"x":25}'` ### Edge Case: Removal with Root Path ```sql -- Example: Attempt to remove using the root path SELECT JSON_REMOVE('{"x":25,"y":42}', '$') AS modified_json; ``` Output: `NULL` These examples illustrate how `json_remove()` can be used to manipulate JSON data dynamically, addressing various scenarios from simple deletions to handling edge cases in data structure modifications. --- # JSON_REPLACE > Replace existing values in a JSON document using SQL in StackQL. Source: https://stackql.io/language-spec/functions/json/json_replace Updates existing values in a JSON object based on their path. `JSON_REPLACE` does not add new keys to the document; it only replaces the values of existing keys. See also: [[`SELECT`]](/language-spec/select) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[` JSON_SET `]](/language-spec/functions/json/json_set) [[` JSON_REPLACE `]](/language-spec/functions/json/json_replace) * * * ## Syntax ```sql SELECT JSON_REPLACE(json_column, path, new_value) FROM <multipartIdentifier>; ``` ## Arguments __*json_column*__ The JSON column or expression from which to replace values. __*path*__ The JSON path expression pointing to the location within the JSON document where the replacement should occur. The path must point to an existing key. __*new_value*__ The new value to replace at the specified path in the JSON document. ## Return Value(s) Returns a modified JSON document with the specified value replaced. If the specified path does not exist, the original JSON document is returned unchanged. :::note Behavior If a Key Exists | Function | Overwrite if already exists? | Create if does not exist? | |--------------------------------------------------------------|------------------------------|---------------------------| | [`json_insert()`](/language-spec/functions/json/json_insert) | No | Yes | | [`json_replace()`](/language-spec/functions/json/json_replace) | Yes | No | | [`json_set()`](/language-spec/functions/json/json_set) | Yes | Yes | ::: * * * ## Examples ### Replace a Single Value in a JSON Object ```sql SELECT sku as original, JSON_REPLACE(sku, '$.name', 'Standard_EU') as updated FROM azure.container_registry.registries WHERE registry_name = 'exampleRegistryProd' AND subscription_id = '12345678-abcd-1234-abcd-1234abcd5678' AND resource_group_name = 'exampleResourceGroupProd'; /* expected output... |---------------------------------------|------------------------------------------| | original | updated | |---------------------------------------|------------------------------------------| | {"name":"Standard","tier":"Standard"} | {"name":"Standard_EU","tier":"Standard"} | |---------------------------------------|------------------------------------------| */ ``` ### Replace Multiple Values in a JSON Object **Query** ```sql select properties beforechange, json_replace(json_remove(properties, '$.allowPort25Out', '$.auxiliarySku', '$.provisioningState', '$.resourceGuid', '$.macAddress', '$.vnetEncryptionSupported', '$.enableIPForwarding', '$.defaultOutboundAccess', '$.primary', '$.virtualMachine', '$.hostedWorkloads', '$.tapConfigurations', '$.nicType', '$.auxiliaryMode', '$.ipConfigurations[0].id', '$.ipConfigurations[0].etag', '$.ipConfigurations[0].type', '$.ipConfigurations[0].properties.provisioningState', '$.ipConfigurations[0].properties.privateIPAddress', '$.ipConfigurations[0].properties.privateIPAllocationMethod', '$.ipConfigurations[0].properties.primary', '$.ipConfigurations[0].properties.privateIPAddressVersion' ), '$.ipConfigurations[0].name', 'vmss-flex-vnet-nic01-defaultIpConfiguration' ) afterchange from azure.network.network_interfaces where subscription_id = '0123456789' and resource_group_name = 'vm-rg' and network_interface_name = 'vm1450_z1' ``` **Output (JSON)** ```json [{"afterchange": { "disableTcpStateTracking": false, "dnsSettings": { "appliedDnsServers": [], "dnsServers": [], "internalDomainNameSuffix": "02ylkvekgslelowidrppwubzmb.bx.internal.cloudapp.net" }, "enableAcceleratedNetworking": false, "ipConfigurations": [ { "name": "vmss-flex-vnet-nic01-defaultIpConfiguration", "properties": { "publicIPAddress": { "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Network/publicIPAddresses/vm1-ip", "properties": { "deleteOption": "Delete" } }, "subnet": { "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Network/virtualNetworks/vm1-vnet/subnets/default" } } } ], "networkSecurityGroup": { "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Network/networkSecurityGroups/vm1-nsg" } }, "beforechange": { "allowPort25Out": false, "auxiliaryMode": "None", "auxiliarySku": "None", "disableTcpStateTracking": false, "dnsSettings": { "appliedDnsServers": [], "dnsServers": [], "internalDomainNameSuffix": "123ylkvekgslelowidrppwubzmb.bx.internal.cloudapp.net" }, "enableAcceleratedNetworking": false, "enableIPForwarding": false, "hostedWorkloads": [], "ipConfigurations": [ { "etag": "123-bc7e-4609-9328-709fe04c69c3", "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Network/networkInterfaces/vm1450_z1/ipConfigurations/ipconfig1", "name": "ipconfig1", "properties": { "primary": true, "privateIPAddress": "10.0.0.4", "privateIPAddressVersion": "IPv4", "privateIPAllocationMethod": "Dynamic", "provisioningState": "Succeeded", "publicIPAddress": { "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Network/publicIPAddresses/vm1-ip", "properties": { "deleteOption": "Delete" } }, "subnet": { "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Network/virtualNetworks/vm1-vnet/subnets/default" } }, "type": "Microsoft.Network/networkInterfaces/ipConfigurations" } ], "macAddress": "23-0D-3A-1B-FF-91", "networkSecurityGroup": { "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Network/networkSecurityGroups/vm1-nsg" }, "nicType": "Standard", "primary": true, "provisioningState": "Succeeded", "resourceGuid": "566a1d71-923d-41e0-bbd5-d09bf64cbe7b", "tapConfigurations": [], "virtualMachine": { "id": "/subscriptions/0123456789/resourceGroups/vm-rg/providers/Microsoft.Compute/virtualMachines/vm1" }, "vnetEncryptionSupported": false } }] ``` --- # JSON_SET > Update or insert values in a JSON document using SQL in StackQL. Source: https://stackql.io/language-spec/functions/json/json_set Updates existing values or inserts new values in a JSON document at specified paths. See also: [[`SELECT`]](/language-spec/select) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[` JSON_SET `]](/language-spec/functions/json/json_set) [[` JSON_REPLACE `]](/language-spec/functions/json/json_replace) * * * ## Syntax ```sql SELECT JSON_SET(json_column, path, value_to_set) FROM <multipartIdentifier>; ``` ## Arguments __*json_column*__ The JSON column or expression to be modified. __*path*__ The JSON path expression indicating where to set the value. If the path exists, the value is updated; if the path does not exist, a new key-value pair is added. __*value_to_set*__ The value to be set at the specified path in the JSON document. ## Return Value(s) Returns a JSON document with the value set at the specified path. If the path exists, the existing value is updated; otherwise, a new key-value pair is added. :::note Behavior If a Key Exists | Function | Overwrite if already exists? | Create if does not exist? | |--------------------------------------------------------------|------------------------------|---------------------------| | [`json_insert()`](/language-spec/functions/json/json_insert) | No | Yes | | [`json_replace()`](/language-spec/functions/json/json_replace) | Yes | No | | [`json_set()`](/language-spec/functions/json/json_set) | Yes | Yes | ::: * * * ## Examples ### Update an existing value in a JSON object ```sql -- Example: Update the 'status' key's value to 'active' in a JSON object SELECT JSON_SET(json_data, '$.status', 'active') as updated_json FROM cloud_services WHERE service_id = 'service123'; -- Expected output: -- |---------------------------------------------------------| -- | updated_json | -- |---------------------------------------------------------| -- | {"name":"ServiceOne", "status":"active", "region":"US"} | -- |---------------------------------------------------------| ``` This query updates the 'status' key to 'active' in the JSON document if the 'status' key exists. If 'status' does not exist in the document, it is added with the value 'active'. ### Add a new key-value pair to a JSON object ```sql -- Example: Add a new key 'lastChecked' with the current date to a JSON object SELECT JSON_SET(json_data, '$.lastChecked', '2024-04-29') as updated_json FROM cloud_services WHERE service_id = 'service123'; /* expected output... |-----------------------------------------------------------------------| | updated_json | |-----------------------------------------------------------------------| | {"name":"ServiceOne", "status":"pending", "lastChecked":"2024-04-29"} | |-----------------------------------------------------------------------| */ ``` This query adds a new key 'lastChecked' with the value '2024-04-29' to the JSON document if 'lastChecked' does not already exist. If it does, the existing value is updated to '2024-04-29'. --- # JSON_TYPE > JSON_TYPE function in StackQL: the type (object, array, text, integer, real, true, false or null) of a JSON value's outermost element, or of a path within it. Source: https://stackql.io/language-spec/functions/json/json_type Returns the datatype of the outermost element of an input JSON object or array and path. See also: [[` SELECT `]](/language-spec/select) [[` DESCRIBE `]](/language-spec/describe) [[` JSON_EXTRACT `]](/language-spec/functions/json/json_extract) [[ Data Types ]](/language-spec/data-types) * * * :::tip Use the [**DESCRIBE**](/language-spec/describe) function to locate `array` or `object` datatypes which can be used with StackQL JSON functions. ::: :::note The `json_type` function is implemented as the `json_typeof` function if you are using stackql with a `postgres` sql backend ::: ## Syntax ```sql SELECT JSON_TYPE(json_array_or_object, json_path) FROM <multipartIdentifier>; ``` ## Arguments __*json_array_or_object*__ A JSON array or object. __*json_path*__ The JSON path to an array or object contained within an *json_array_or_object*. See [jsonpath.com](https://jsonpath.com/). > If *json_path* does not exist in *json_array_or_object*, then the function returns `NULL`. > The `json_type()` function throws an error if any of its arguments are not well-formed. ## Return Value(s) A string representing the resolved datatype. > Datatypes include `null`, `true`, `false`, `integer`, `real`, `text`, `array`, or `object`. * * * ## Examples ### Return the datatype of a field nested within a JSON object or array ```sql SELECT json_type(disks, '$[0].licenses[0]') as datatype FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; /* returns text */ ``` For more information, see [https://www.sqlite.org/json1.html#jtype](https://www.sqlite.org/json1.html#jtype) --- # ABS > ABS function in StackQL: the absolute value of a numeric argument. Source: https://stackql.io/language-spec/functions/math/abs Returns the absolute value of the numeric argument. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT ABS(numeric_expression) FROM <multipartIdentifier>; ``` > `abs(X)` returns `NULL` if `X` is `NULL`. `abs(X)` returns `0.0` if `X` is a string or blob that cannot be converted to a numeric value. If `X` is the integer -9223372036854775808 then `abs(X)` throws an integer overflow error since there is no equivalent positive 64-bit two complement value. ## Arguments __*numeric_expression*__ An expression of the exact numeric or approximate numeric data type category. ## Return Value(s) Returns a positive numeric value. * * * ## Examples ### Return the absolute value of a number ```sql SELECT name, abs(strftime('%s', creationTimestamp)-strftime('%s','now')) as abs_value FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_mathfunc.html](https://www.sqlite.org/lang_mathfunc.html) --- # CEIL > CEIL function in StackQL: round a numeric argument up to the nearest integer. Source: https://stackql.io/language-spec/functions/math/ceil Rounds a numeric argument up to the nearest integer. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT CEIL(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ An expression of the exact numeric or approximate numeric data type category. ## Return Value(s) Returns the smallest integer greater than or equal to the specified numeric expression. * * * ## Examples ### Round up a floating point number to the closest (larger) integer ```sql SELECT name, timeCreated, ceil(julianday('now')-julianday(timeCreated)) as days_since_ceiling FROM google.storage.buckets WHERE project = 'stackql'; ``` --- # FLOOR > FLOOR function in StackQL: round a numeric argument down to the nearest integer. Source: https://stackql.io/language-spec/functions/math/floor Rounds a numeric argument down to the nearest integer. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT FLOOR(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ An expression of the exact numeric or approximate numeric data type category. ## Return Value(s) Returns the largest integer less than or equal to the specified numeric expression. * * * ## Examples ### Round down a floating point number to the closest (smaller) integer ```sql SELECT name, timeCreated, floor(julianday('now')-julianday(timeCreated)) as days_since_ceiling FROM google.storage.buckets WHERE project = 'stackql'; ``` --- # LN > Calculate the natural logarithm of a number using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/logarithmic/ln Calculates the natural logarithm (logarithm to the base \(e\)) of a given number. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT LN(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ A positive numeric expression for which the natural logarithm is to be calculated. ## Return Value(s) Returns the natural logarithm of the specified positive numeric value. * * * ## Examples ### Calculate the natural logarithm of 2.71828 (approximately \(e\)) ```sql SELECT LN(2.71828) AS natural_log; ``` This query returns a value close to `1`, since the natural logarithm of \(e\) (approximately 2.71828) is 1. ### Calculate the natural logarithm of a larger number ```sql SELECT LN(10) AS natural_log; ``` This query calculates the natural logarithm of 10, providing the logarithmic value of 10 to the base \(e\). --- # LOG > Calculate the logarithm of a number for any base using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/logarithmic/log Calculates the logarithm of a number to a specified base, which is a more general form of logarithmic function compared to LN, which uses base \(e\). See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT LOG(base, numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*base*__ The base of the logarithm, a positive numeric expression other than 1. __*numeric_expression*__ A positive numeric expression for which the logarithm is to be calculated. ## Return Value(s) Returns the logarithm of the specified numeric value to the specified base. * * * ## Examples ### Calculate the logarithm of 1000 with base 10 ```sql SELECT LOG(10, 1000) AS log_result; ``` This query returns `3`, as \(10^3 = 1000\). ### Calculate the logarithm of 16 with base 2 ```sql SELECT LOG(2, 16) AS log_result; ``` This query calculates the logarithm of 16 with base 2, resulting in `4`, since \(2^4 = 16\). --- # LOG10 > Calculate the base-10 logarithm of a number using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/logarithmic/log10 Calculates the base-10 logarithm of a given number, determining the power to which the number 10 must be raised to achieve the value. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT LOG10(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ A positive numeric expression for which the base-10 logarithm is to be calculated. ## Return Value(s) Returns the base-10 logarithm of the specified numeric value. * * * ## Examples ### Calculate the base-10 logarithm of 100 ```sql SELECT LOG10(100) AS log_result; ``` This query returns `2`, as \(10^2 = 100\). ### Calculate the base-10 logarithm of 1000 ```sql SELECT LOG10(1000) AS log_result; ``` This query calculates the base-10 logarithm of 1000, resulting in `3`, since \(10^3 = 1000\). --- # LOG2 > Calculate the base-2 logarithm of a number using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/logarithmic/log2 Calculates the base-2 logarithm of a given number, returning the power to which the number 2 must be raised to obtain the value. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT LOG2(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ A positive numeric expression for which the base-2 logarithm is to be calculated. ## Return Value(s) Returns the base-2 logarithm of the specified numeric value. * * * ## Examples ### Calculate the base-2 logarithm of 16 ```sql SELECT LOG2(16) AS log_result; ``` This query returns `4`, as \(2^4 = 16\). ### Calculate the base-2 logarithm of 32 ```sql SELECT LOG2(32) AS log_result; ``` This query calculates the base-2 logarithm of 32, resulting in `5`, since \(2^5 = 32\). --- # MOD > Calculate the remainder of one number divided by another using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/mod Calculates the remainder of *x* divided by *y*, returning the modulus. This is similar to using the '%' operator but is compatible with non-integer arguments. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT MOD(x, y) FROM <multipartIdentifier>; ``` ## Arguments __*x*__ The dividend, which is a numeric expression. __*y*__ The divisor, also a numeric expression. ## Return Value(s) Returns the remainder of *x* divided by *y*. * * * ## Examples ### Calculate the modulus of 10 divided by 3 ```sql SELECT MOD(10, 3) AS remainder; ``` --- # POW > Calculate the power of one number raised to another using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/pow Calculates *x* raised to the power *y*. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT POW(x, y) FROM <multipartIdentifier>; -- or using the equivalent SELECT POWER(x, y) FROM <multipartIdentifier>; ``` ## Arguments __*x*__ The base number, which is a numeric expression. __*y*__ The exponent to which the base number *x* is raised, also a numeric expression. ## Return Value(s) Returns the result of *x* raised to the power *y*. * * * ## Examples ### Calculate x raised to the power y ```sql SELECT POW(2, 3) AS result; ``` --- # ROUND > ROUND function in StackQL: round a numeric argument to a given number of decimal places, defaulting to zero. Source: https://stackql.io/language-spec/functions/math/round Rounds a numeric argument. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT ROUND(numeric_expression [, precision]) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ An expression of the exact numeric or approximate numeric data type category. __*precision*__ The number of digits to the right of the decimal point to round the *numeric_expression* to. > If the *precision* argument is omitted, it is assumed to be 0. ## Return Value(s) Returns a numeric value. * * * ## Examples ### Round a floating point number to two decimal places ```sql SELECT name, timeCreated, round(julianday('now')-julianday(timeCreated), 2) as days_since FROM google.storage.buckets WHERE project = 'stackql'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#round](https://www.sqlite.org/lang_corefunc.html#round) --- # SIGN > SIGN function in StackQL: return -1, 0 or 1 depending on whether a numeric argument is negative, zero or positive. Source: https://stackql.io/language-spec/functions/math/sign Returns -1 if the input value is negative, 0 if the input value is 0, and 1 is the input value is positive. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT SIGN(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ An expression of the exact numeric or approximate numeric data type category. > If *numeric_expression* is `NULL` or is a `string` or BLOB that cannot be losslessly converted into a number, then the function will return `NULL`. ## Return Value(s) Returns `-1`, `0` or `1`. * * * ## Examples ### Determine the sign of a number ```sql SELECT name, sign(strftime('%s', creationTimestamp)-strftime('%s','now')) as sign FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#sign](https://www.sqlite.org/lang_corefunc.html#sign) --- # SQRT > Calculate the square root of a number using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/sqrt Calculates the square root of a non-negative numeric expression. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT SQRT(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ A non-negative numeric expression for which the square root is to be calculated. ## Return Value(s) Returns the square root of the specified non-negative numeric value. * * * ## Examples ### Calculate the square root of a number ```sql SELECT SQRT(9) AS square_root; ``` --- # ACOS > Calculate the arc cosine (inverse cosine) of a number, returning an angle in radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/acos Calculates the arc cosine (inverse cosine) of a number, which is the angle in radians whose cosine is the specified number. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT ACOS(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression within the range of -1 to 1, inclusive, for which the arc cosine is to be calculated. ## Return Value(s) Returns the arc cosine of the specified value in radians. * * * ## Examples ### Calculate the arc cosine of 0.5 ```sql SELECT ACOS(0.5) AS arc_cosine_value; ``` This query returns approximately `1.047`, as the arc cosine of 0.5 radians is π/3, which is about 1.047 radians. ### Calculate the arc cosine of 1 ```sql SELECT ACOS(1) AS arc_cosine_value; ``` This query calculates the arc cosine of 1, resulting in `0`, since the cosine of 0 radians is 1. --- # ACOSH > Calculate the hyperbolic arc cosine (inverse hyperbolic cosine) of a number, returning an angle in radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/acosh Calculates the hyperbolic arc cosine (inverse hyperbolic cosine) of a number, which is the non-negative value \( \theta \) in radians whose hyperbolic cosine is the specified number. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT ACOSH(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression greater than or equal to 1, for which the hyperbolic arc cosine is to be calculated. ## Return Value(s) Returns the hyperbolic arc cosine of the specified value in radians. * * * ## Examples ### Calculate the hyperbolic arc cosine of 1 ```sql SELECT ACOSH(1) AS hyperbolic_arc_cosine_value; ``` This query returns `0`, as the hyperbolic arc cosine of 1 is 0 radians. ### Calculate the hyperbolic arc cosine of 10 ```sql SELECT ACOSH(10) AS hyperbolic_arc_cosine_value; ``` This query calculates the hyperbolic arc cosine of 10, resulting in approximately `2.9932`, as this is the value in radians whose hyperbolic cosine is 10. --- # ASIN > Calculate the arc sine (inverse sine) of a number, returning an angle in radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/asin Calculates the arc sine (inverse sine) of a number, which is the angle in radians whose sine is the specified number. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT ASIN(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression within the range of -1 to 1, inclusive, for which the arc sine is to be calculated. ## Return Value(s) Returns the arc sine of the specified value in radians. * * * ## Examples ### Calculate the arc sine of 0.5 ```sql SELECT ASIN(0.5) AS arc_sine_value; ``` This query returns π/6 or approximately `0.5236`, as the arc sine of 0.5 corresponds to an angle of π/6 radians. ### Calculate the arc sine of -1 ```sql SELECT ASIN(-1) AS arc_sine_value; ``` This query calculates the arc sine of -1, resulting in -π/2 or approximately `-1.5708`, as the sine of -π/2 is -1. --- # ASINH > Calculate the hyperbolic arc sine (inverse hyperbolic sine) of a number, returning an angle in radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/asinh Calculates the hyperbolic arc sine (inverse hyperbolic sine) of a number, which is the value \( \theta \) in radians whose hyperbolic sine is the specified number. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT ASINH(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression for which the hyperbolic arc sine is to be calculated. ## Return Value(s) Returns the hyperbolic arc sine of the specified value in radians. * * * ## Examples ### Calculate the hyperbolic arc sine of 0.5 ```sql SELECT ASINH(0.5) AS hyperbolic_arc_sine_value; ``` This query returns approximately `0.4812`, as the hyperbolic arc sine of 0.5 is about 0.4812 radians. ### Calculate the hyperbolic arc sine of -1 ```sql SELECT ASINH(-1) AS hyperbolic_arc_sine_value; ``` This query calculates the hyperbolic arc sine of -1, resulting in approximately `-0.8814`, as this is the value in radians whose hyperbolic sine is -1. --- # ATAN > Calculate the arc tangent (inverse tangent) of a number, returning an angle in radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/atan Calculates the arc tangent (inverse tangent) of a number, which is the angle in radians whose tangent is the specified number. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT ATAN(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression for which the arc tangent is to be calculated. ## Return Value(s) Returns the arc tangent of the specified value in radians. * * * ## Examples ### Calculate the arc tangent of 1 ```sql SELECT ATAN(1) AS arc_tangent_value; ``` This query returns π/4 or approximately `0.785`, as the arc tangent of 1 is π/4 radians. ### Calculate the arc tangent of 0 ```sql SELECT ATAN(0) AS arc_tangent_value; ``` This query calculates the arc tangent of 0, resulting in `0`, since the tangent of 0 radians is 0. --- # ATAN2 > Calculate the arc tangent of two numbers (y/x), returning an angle in radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/atan2 Calculates the arc tangent of two numbers, specifically the angle \( \theta \) in radians for which the tangent is the ratio of two specified numbers (y divided by x), correctly handling the signs of the inputs to determine the correct quadrant. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT ATAN2(y, x) FROM <multipartIdentifier>; ``` ## Arguments __*y*__ The y-coordinate (numerator) of the point. __*x*__ The x-coordinate (denominator) of the point. ## Return Value(s) Returns the arc tangent of y/x in radians, accounting for the correct quadrant of the angle. * * * ## Examples ### Calculate the arc tangent of the point (1,1) ```sql SELECT ATAN2(1, 1) AS arc_tangent_value; ``` This query returns π/4 or approximately `0.785`, as the arc tangent of the point (1,1) corresponds to an angle of π/4 radians in the first quadrant. ### Calculate the arc tangent of the point (10, -10) ```sql SELECT ATAN2(10, -10) AS arc_tangent_value; ``` This query calculates the arc tangent of the point (10, -10), resulting in 3π/4 or approximately `2.356`, as the tangent of this angle is -1 in the second quadrant. --- # ATANH > Calculate the hyperbolic arc tangent (inverse hyperbolic tangent) of a number, returning an angle in radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/atanh Calculates the hyperbolic arc tangent (inverse hyperbolic tangent) of a number, which is the value \( \theta \) in radians whose hyperbolic tangent is the specified number. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT ATANH(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression within the range of -1 to 1 (exclusive), for which the hyperbolic arc tangent is to be calculated. ## Return Value(s) Returns the hyperbolic arc tangent of the specified value in radians. * * * ## Examples ### Calculate the hyperbolic arc tangent of 0.5 ```sql SELECT ATANH(0.5) AS hyperbolic_arc_tangent_value; ``` This query returns approximately `0.5493`, as the hyperbolic arc tangent of 0.5 is about 0.5493 radians. ### Calculate the hyperbolic arc tangent of -0.5 ```sql SELECT ATANH(-0.5) AS hyperbolic_arc_tangent_value; ``` This query calculates the hyperbolic arc tangent of -0.5, resulting in approximately `-0.5493`, as this is the value in radians whose hyperbolic tangent is -0.5. --- # COS > Calculate the cosine of an angle, provided in radians, using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/cos Calculates the cosine of a specified angle given in radians. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT COS(radian_value) FROM <multipartIdentifier>; ``` ## Arguments __*radian_value*__ A numeric expression that specifies the angle in radians for which the cosine is to be calculated. ## Return Value(s) Returns the cosine of the specified angle. * * * ## Examples ### Calculate the cosine of π/3 radians ```sql SELECT COS(PI() / 3) AS cosine_value; ``` This query returns `0.5`, as the cosine of π/3 radians is 0.5. ### Calculate the cosine of π radians ```sql SELECT COS(PI()) AS cosine_value; ``` This query calculates the cosine of π radians, resulting in `-1`, since the cosine of π is -1. --- # COSH > Calculate the hyperbolic cosine of a number, returning the result using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/cosh Calculates the hyperbolic cosine of a specified value. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT COSH(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression for which the hyperbolic cosine is to be calculated. ## Return Value(s) Returns the hyperbolic cosine of the specified value. * * * ## Examples ### Calculate the hyperbolic cosine of 1 ```sql SELECT COSH(1) AS hyperbolic_cosine_value; ``` This query returns approximately `1.5431`, as the hyperbolic cosine of 1 is about 1.5431. ### Calculate the hyperbolic cosine of 0 ```sql SELECT COSH(0) AS hyperbolic_cosine_value; ``` This query calculates the hyperbolic cosine of 0, resulting in `1`, since the hyperbolic cosine of 0 is exactly 1. --- # DEGREES > Convert an angle from radians to degrees using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/degrees Converts a specified angle from radians to degrees. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT DEGREES(angle_in_radians) FROM <multipartIdentifier>; ``` ## Arguments __*angle_in_radians*__ A numeric expression representing an angle in radians. ## Return Value(s) Returns the equivalent of the angle in degrees. * * * ## Examples ### Convert π radians to degrees ```sql SELECT DEGREES(3.14159) AS degrees_value; ``` This query will return approximately `180`, as converting π radians (approximately `3.14159`) results in about 180 degrees. ### Convert π/2 radians to degrees ```sql SELECT DEGREES(1.5708) AS degrees_value; ``` This query calculates the conversion of π/2 radians (approximately `1.5708`) to degrees, resulting in about `90`, since π/2 radians is the equivalent of a 90-degree angle. --- # PI > Retrieve the mathematical constant π (pi) using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/pi Returns the mathematical constant π (pi), which is the ratio of a circle's circumference to its diameter. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT PI() AS pi_value; ``` ## Arguments This function does not require any arguments. ## Return Value(s) Returns the constant π, approximately equal to 3.14159. * * * ## Examples ### Retrieve the value of π ```sql SELECT PI() AS pi_value; ``` This query will output the value of π, which is approximately `3.14159`, useful in various mathematical calculations involving circles and other geometric functions. --- # RADIANS > Convert an angle from degrees to radians using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/radians Converts a specified angle from degrees to radians. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT RADIANS(angle_in_degrees) FROM <multipartIdentifier>; ``` ## Arguments __*angle_in_degrees*__ A numeric expression representing an angle in degrees. ## Return Value(s) Returns the equivalent of the angle in radians. * * * ## Examples ### Convert 180 degrees to radians ```sql SELECT RADIANS(180) AS radians_value; ``` This query will return π (approximately `3.14159`), as converting 180 degrees to radians results in π radians. ### Convert 90 degrees to radians ```sql SELECT RADIANS(90) AS radians_value; ``` This query calculates the conversion of 90 degrees to radians, resulting in π/2 or approximately `1.5708`, since 90 degrees is half of 180 degrees. --- # SIN > Calculate the sine of an angle, provided in radians, using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/sin Calculates the sine of a specified angle given in radians. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT SIN(radian_value) FROM <multipartIdentifier>; ``` ## Arguments __*radian_value*__ A numeric expression that specifies the angle in radians for which the sine is to be calculated. ## Return Value(s) Returns the sine of the specified angle. * * * ## Examples ### Calculate the sine of π/2 radians ```sql SELECT SIN(PI() / 2) AS sine_value; ``` This query returns `1`, as the sine of π/2 radians is 1. ### Calculate the sine of π radians ```sql SELECT SIN(PI()) AS sine_value; ``` This query calculates the sine of π radians, resulting in approximately `0`, as the sine of π is 0. --- # SINH > Calculate the hyperbolic sine of a number, returning the result using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/sinh Calculates the hyperbolic sine of a specified value. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT SINH(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression for which the hyperbolic sine is to be calculated. ## Return Value(s) Returns the hyperbolic sine of the specified value. * * * ## Examples ### Calculate the hyperbolic sine of 1 ```sql SELECT SINH(1) AS hyperbolic_sine_value; ``` This query returns approximately `1.1752`, as the hyperbolic sine of 1 is about 1.1752. ### Calculate the hyperbolic sine of 0 ```sql SELECT SINH(0) AS hyperbolic_sine_value; ``` This query calculates the hyperbolic sine of 0, resulting in `0`, since the hyperbolic sine of 0 is exactly 0. --- # TAN > Calculate the tangent of an angle, provided in radians, using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/tan Calculates the tangent of a specified angle given in radians. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT TAN(radian_value) FROM <multipartIdentifier>; ``` ## Arguments __*radian_value*__ A numeric expression that specifies the angle in radians for which the tangent is to be calculated. ## Return Value(s) Returns the tangent of the specified angle. * * * ## Examples ### Calculate the tangent of π/4 radians ```sql SELECT TAN(PI() / 4) AS tangent_value; ``` This query returns `1`, as the tangent of π/4 radians is 1. ### Calculate the tangent of π radians ```sql SELECT TAN(PI()) AS tangent_value; ``` This query calculates the tangent of π radians, resulting in approximately `0`, since the tangent of π is very close to 0. --- # TANH > Calculate the hyperbolic tangent of a number, returning the result using SQL in StackQL. Source: https://stackql.io/language-spec/functions/math/trigonometric/tanh Calculates the hyperbolic tangent of a specified value. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT TANH(value) FROM <multipartIdentifier>; ``` ## Arguments __*value*__ A numeric expression for which the hyperbolic tangent is to be calculated. ## Return Value(s) Returns the hyperbolic tangent of the specified value. * * * ## Examples ### Calculate the hyperbolic tangent of 1 ```sql SELECT TANH(1) AS hyperbolic_tangent_value; ``` This query returns approximately `0.7616`, as the hyperbolic tangent of 1 is about 0.7616. ### Calculate the hyperbolic tangent of 0 ```sql SELECT TANH(0) AS hyperbolic_tangent_value; ``` This query calculates the hyperbolic tangent of 0, resulting in `0`, since the hyperbolic tangent of 0 is exactly 0. --- # TRUNC > TRUNC function in StackQL: the integer part of a number, rounding towards zero and discarding any fraction. Source: https://stackql.io/language-spec/functions/math/trunc Returns the integer part of a number by rounding towards zero, stripping away any fractional component. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT TRUNC(numeric_expression) FROM <multipartIdentifier>; ``` ## Arguments __*numeric_expression*__ An expression of the exact numeric or approximate numeric data type category. ## Return Value(s) Returns a numeric value truncated to its integer component. * * * ## Examples ### Truncate the number of days since creation of Google Cloud Storage buckets to two decimal places ```sql SELECT name, timeCreated, TRUNC(julianday('now') - julianday(timeCreated)) as days_since FROM google.storage.buckets WHERE project = 'stackql'; ``` --- # Regex Reference > Regular expression reference for StackQL: syntax, character classes, anchors, quantifiers and groups for REGEXP_LIKE, REGEXP_REPLACE and REGEXP_SUBSTR. Source: https://stackql.io/language-spec/functions/re/reference Reference for regular expressions used in StackQL. See also: [[` REGEXP_LIKE `]](/language-spec/functions/re/regexp_like) [[` REGEXP_SUBSTR `]](/language-spec/functions/re/regexp_substr) [[` REGEXP_REPLACE `]](/language-spec/functions/re/regexp_replace) * * * ## Supported syntax The following regular expression syntax is supported in StackQL: | Expression | Description | |------------|-------------| | `X*` | zero or more occurrences of `X` | | `X+` | one or more occurrences of `X` | | `X?` | zero or one occurrences of `X` | | `(X)` | match `X` | | `X`|`Y` | `X` or `Y` | | `^X` | `X` occurring at the beginning of the string | | `X$` | `X` occurring at the end of the string | | `.` | Match any single character | | `\c` | Character `c` where `c` is one of `\{}()[]`|`*+?.` | `\c` | C-language escapes for `c` in `afnrtv`. ex: `\t` or `\n` | | `[abc]` | Any single character from the set `abc` | | `[^abc]` | Any single character not in the set `abc` | | `[a-z]` | Any single character in the range `a-z` | | `[^a-z]` | Any single character not in the range `a-z` |     For more information, see [https://github.com/nalgeon/sqlean/blob/main/docs/re.md](https://github.com/nalgeon/sqlean/blob/main/docs/re.md) --- # REGEXP > Use regular expressions to match patterns in strings using SQL in StackQL. Source: https://stackql.io/language-spec/functions/re/regexp Checks if the source string matches the regular expression pattern provided. See also: [[`SELECT`]](/language-spec/select) * * * ## Syntax ```sql SELECT source_string REGEXP pattern_expression AS match_result FROM <multipartIdentifier>; ``` ## Arguments __*source_string*__ The string in which to search for the pattern. __*pattern_expression*__ The regular expression pattern to match against the source string. ## Return Value(s) Returns a boolean value: `TRUE` if the source string matches the regular expression pattern, otherwise `FALSE`. * * * ## Examples ### Check if a string contains numbers This example demonstrates checking whether the string 'the year is 2021' contains one or more numeric characters: ```sql SELECT 'the year is 2021' REGEXP '[0-9]+' AS match_result; ``` This query will return `TRUE` because the string contains the substring '2021', which matches the pattern `[0-9]+`, indicating one or more digits. ### Validate email format To check if a string is in a valid email format: ```sql SELECT 'user@example.com' REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$' AS match_result; ``` This query returns `TRUE`, indicating that 'user@example.com' is formatted like a typical email address, matching the specified regular expression pattern. --- # REGEXP_LIKE > REGEXP_LIKE function in StackQL: test whether a string matches a regular expression, returning true or false, for pattern filters in WHERE clauses. Source: https://stackql.io/language-spec/functions/re/regexp_like Checks if source string matches pattern and returns `true` or `false`. See also: [[` SELECT `]](/language-spec/select) [[ Regular Expression Reference ]](/language-spec/functions/re/reference) * * * ## Syntax ```sql SELECT REGEXP_LIKE(source, pattern) FROM <multipartIdentifier>; ``` ## Arguments __*source*__ A literal string or string column that you want to test for the existence of a pattern defined by a regular expression (`pattern`). __*pattern*__ The regular expression pattern to search for. ## Return Value(s) Returns a `0` if `false` and `1` if `true`. * * * ## Examples ### Determine if a string contains a pattern **StackQL** ```sql select name, regexp_like(name, 'vm[0-9]+') as name_starts_with_vm from azure.compute.virtual_machines WHERE subscription_id = '273769f6-545f-45b2-8ab8-2f14ec5768dc'; ``` **Results** ``` |------|---------------------| | name | name_starts_with_vm | |------|---------------------| | vm0 | 1 | |------|---------------------| | vm1 | 1 | |------|---------------------| | test | 0 | |------|---------------------| ``` For more information, see [https://github.com/nalgeon/sqlean/blob/main/docs/re.md](https://github.com/nalgeon/sqlean/blob/main/docs/re.md) --- # REGEXP_REPLACE > REGEXP_REPLACE function in StackQL: replace the parts of a string that match a regular expression with a replacement string. Source: https://stackql.io/language-spec/functions/re/regexp_replace Replaces a matching substring with replacement string. See also: [[` SELECT `]](/language-spec/select) [[ Regular Expression Reference ]](/language-spec/functions/re/reference) * * * ## Syntax ```sql SELECT REGEXP_REPLACE(source, pattern, replacement) FROM <multipartIdentifier>; ``` ## Arguments __*source*__ A literal string or string column from which you want to extract a substring based upon a pattern defined by a regular expression (`pattern`). __*pattern*__ The regular expression pattern to search for. __*replacement*__ The replacement string. > Supports backreferences to captured groups `\1` through `\9` in replacement string. ## Return Value(s) Returns a string. * * * ## Examples ### Replace a regular expression pattern in a column **StackQL** ```sql select name, regexp_replace(json_extract(properties, '$.timeCreated'), 'T.*', '') as date_created from azure.compute.virtual_machines WHERE subscription_id = '273769f6-545f-45b2-8ab8-2f14ec5768dc'; ``` **Results** ``` |------|--------------| | name | date_created | |------|--------------| | vm0 | 2022-09-14 | |------|--------------| | vm1 | 2022-09-14 | |------|--------------| | vm2 | 2022-09-14 | |------|--------------| ``` For more information, see [https://github.com/nalgeon/sqlean/blob/main/docs/re.md](https://github.com/nalgeon/sqlean/blob/main/docs/re.md) --- # REGEXP_SUBSTR > REGEXP_SUBSTR function in StackQL: extract the substring of an input that matches a regular expression. Source: https://stackql.io/language-spec/functions/re/regexp_substr Returns a substring from an input string matching a specified pattern. See also: [[` SELECT `]](/language-spec/select) [[ Regular Expression Reference ]](/language-spec/functions/re/reference) * * * ## Syntax ```sql SELECT REGEXP_SUBSTR(source, pattern) FROM <multipartIdentifier>; ``` ## Arguments __*source*__ A literal string or string column from which you want to extract a substring based upon a pattern defined by a regular expression (`pattern`). __*pattern*__ The regular expression pattern to search for. ## Return Value(s) Returns a string. * * * ## Examples ### Extract a substring based upon a regular expression **StackQL** ```sql select name, json_extract(properties, '$.storageProfile.imageReference.offer') as os, regexp_substr( json_extract(properties, '$.storageProfile.imageReference.exactVersion'), '[0-9][0-9]\.[0-9][0-9]') as os_version from azure.compute.virtual_machines WHERE subscription_id = '273769f6-545f-45b2-8ab8-2f14ec5768dc'; ``` **Results** ``` |------|---------------|------------| | name | os | os_version | |------|---------------|------------| | vm0 | UbuntuServer | 16.04 | |------|---------------|------------| | vm1 | UbuntuServer | 16.04 | |------|---------------|------------| | vm2 | UbuntuServer | 20.04 | |------|---------------|------------| ``` For more information, see [https://github.com/nalgeon/sqlean/blob/main/docs/re.md](https://github.com/nalgeon/sqlean/blob/main/docs/re.md) --- # GROUPS > GROUPS function in StackQL: return the directory groups of the authenticated caller as a JSON array when access management is enabled. Source: https://stackql.io/language-spec/functions/session/groups Returns the directory group memberships of the authenticated caller as a JSON array. Requires a session started with [access management](/command-line-usage/access-management) enabled. Available in StackQL `v1.0` and later. See also: [[` WHOAMI `]](/language-spec/functions/session/whoami) [[ Access Management ]](/command-line-usage/access-management) * * * ## Syntax ```sql SELECT GROUPS() [ AS <alias> ]; ``` ## Arguments None. ## Return Value(s) Returns a JSON array of group IDs from the principal directory snapshot taken for the current statement, for example `["readers"]`. Membership is refreshed for each statement, so a revocation is reflected by the next statement. The function fails in a session started without `--access.config`. * * * ## Examples ### Inspect the established identity The two functions together show the caller's principal ID and its current directory groups. Because membership is read afresh for every statement, running this after a directory change confirms that the change is visible to the session. ```sql SELECT whoami() AS principal, groups() AS memberships; ``` --- # WHOAMI > WHOAMI function in StackQL: return the principal ID of the authenticated caller when access management is enabled. Source: https://stackql.io/language-spec/functions/session/whoami Returns the principal ID of the authenticated caller. Requires a session started with [access management](/command-line-usage/access-management) enabled. Available in StackQL `v1.0` and later. See also: [[` GROUPS `]](/language-spec/functions/session/groups) [[ Access Management ]](/command-line-usage/access-management) * * * ## Syntax ```sql SELECT WHOAMI() [ AS <alias> ]; ``` ## Arguments None. ## Return Value(s) Returns the principal ID string established for the current statement. The function fails in a session started without `--access.config`. * * * ## Examples ### Inspect the established identity Both functions take no arguments and describe the caller that the server authenticated for this statement. `whoami()` returns the principal ID and `groups()` the caller's directory groups, so running them together is a quick check that a token or certificate maps to the expected principal before anything else is run. ```sql SELECT whoami() AS principal, groups() AS memberships; ``` --- # CHAR > CHAR function in StackQL: the characters for one or more character codes, for putting newlines, quotes, tabs and other control characters into strings. Source: https://stackql.io/language-spec/functions/string/char The `CHAR()` function returns the character corresponding to the specified ASCII code. See also: [[`SELECT`]](/language-spec/select) * * * :::note When using StackQL with a PostgreSQL backend, the equivalent function is `CHR()`. ::: ## Syntax ```sql SELECT CHAR(ascii_code) FROM <multipartIdentifier>; ``` > The `CHAR()` function returns the character associated with the given ASCII code. ## Arguments **_ascii_code_** An integer representing the ASCII code of the desired character. ## Return Value(s) Returns a single-character string corresponding to the specified ASCII code. * * * ## Common ASCII Codes | Character | Description | ASCII Code | Usage Example | |---------------|-----------------------|------------|---------------------------------| | `\n` | Newline | 10 | `CHAR(10)` | | `'` | Single Quote | 39 | `CHAR(39)` | | `"` | Double Quote | 34 | `CHAR(34)` | | (space) | Space | 32 | `CHAR(32)` | | `:` | Colon | 58 | `CHAR(58)` | | `;` | Semicolon | 59 | `CHAR(59)` | | `\t` | Horizontal Tab | 9 | `CHAR(9)` | | `\r` | Carriage Return | 13 | `CHAR(13)` | | `\b` | Backspace | 8 | `CHAR(8)` | | `\f` | Form Feed | 12 | `CHAR(12)` | * * * ## Examples ### Concatenate Strings with Special Characters To concatenate strings with a newline character between them: ```sql SELECT '/* ' || displayName || ' */' || CHAR(10) || 'DELETE FROM databricks_account.iam.account_users WHERE account_id = ' || CHAR(39) || account_id || CHAR(39) || ' AND id = ' || CHAR(39) || id || CHAR(39) FROM databricks_account.iam.account_users where account_id = 'abcd1234-1234-5678-90ab-abcdef123456' AND active = false; ``` **Result:** ``` He said "Hello" and left. ``` * * * --- # Concatenation Operator > The || concatenation operator in StackQL: join two or more string values into one string. Source: https://stackql.io/language-spec/functions/string/concatenation Returns the resultant string from the concatenation, or joining, of two or more string values. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT character_expression1 || character_expression2 FROM <multipartIdentifier>; ``` ## Arguments __*character_expression*__ A literal string or string column. ## Return Value(s) Returns a string. :::note From StackQL `v1.0` the parser treats `||` as the concatenation operator, binding more tightly than comparison operators, so `WHERE id = prefix || suffix` compares `id` with the joined string. Earlier releases tokenised `||` as boolean `OR`. Use `OR` for boolean disjunction. [Session variables](/getting-started/session-variables) can be concatenated too: `$prefix || '-' || $suffix`. ::: * * * ## Examples ### Concatenate two fields together ```sql SELECT name || ' (' || location || ')' as bucket_location FROM google.storage.buckets WHERE project = 'stackql-demo'; ``` For more information, see [https://sqlite.org/lang_expr.html](https://sqlite.org/lang_expr.html) --- # INSTR > INSTR function in StackQL: the one-based position of the first occurrence of one string inside another, or 0 when it is not found. Source: https://stackql.io/language-spec/functions/string/instr Returns the character position of first occurrence of string within another string, returns 0 if the string being searched for is not found. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT INSTR(string, searchstring) FROM <multipartIdentifier>; ``` ## Arguments __*string*__ The source string being searched. __*searchstring*__ The substring being searched for. > If *string* and *searchstring* are both BLOBs, then `instr(<string>, <searchstring>)` returns one more than the number bytes prior to the first occurrence of *searchstring*, or 0 if *searchstring* does not occur anywhere within *string*. If both arguments are not `NULL` and are not BLOBs then both are interpreted as strings. ## Return Value(s) Returns an integer. > If either the *string* or the *searchstring* values are `NULL`, then the result is `NULL`. * * * ## Examples ### Search a field for a string ```sql SELECT INSTR(name, 'worker') as charpos FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; /* returns 0 if the term 'worker' is not present in the 'name' column, otherwise returns the character position (starting from 1) of the first occurence of the term 'worker' in the 'name' column */ ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#instr](https://www.sqlite.org/lang_corefunc.html#instr) --- # LENGTH > LENGTH function in StackQL: the number of characters in a string, or the number of bytes in a BLOB. Source: https://stackql.io/language-spec/functions/string/length Returns the number of characters in a string input expression prior to the first `NULL` character, or the number of bytes in a BLOB expression. See also: [[` SELECT `]](/language-spec/select) * * * :::info To get the length of a JSON array use the [**JSON_ARRAY_LENGTH**](/language-spec/functions/json/json_array_length) function. ::: ## Syntax ```sql SELECT LENGTH(expression) FROM <multipartIdentifier>; ``` ## Arguments __*expression*__ An ASCII string or a BLOB. > Returns `NULL` if *expression* is `NULL`. > If *expression* is numeric then the length of a string representation of *expression* is returned. ## Return Value(s) Returns an integer. * * * ## Examples ### Return the length of a string column ```sql SELECT name, length(name) AS len FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#length](https://www.sqlite.org/lang_corefunc.html#length) --- # LOWER > LOWER function in StackQL: convert a string to lowercase. Source: https://stackql.io/language-spec/functions/string/lower Returns an input string in lowercase. See also: [[` SELECT `]](/language-spec/select) [[` UPPER `]](/language-spec/functions/string/upper) [[ Data Types ]](/language-spec/data-types) * * * ## Syntax ```sql SELECT LOWER(character_expression) FROM <multipartIdentifier>; ``` > The `lower()` function works for ASCII characters only. ## Arguments __*character_expression*__ An ASCII string. ## Return Value(s) Returns a string value. * * * ## Examples ### Return a string in lowercase ```sql SELECT name, LOWER(location) FROM google.storage.buckets WHERE project = 'stackql-demo'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#lower](https://www.sqlite.org/lang_corefunc.html#lower) --- # LTRIM > LTRIM function in StackQL: remove whitespace, or a given set of characters, from the left of a string. Source: https://stackql.io/language-spec/functions/string/ltrim Returns a string formed by removing white space or any characters that appear from the left side of an input string. See also: [[` SELECT `]](/language-spec/select) [[` RTRIM `]](/language-spec/functions/string/rtrim) [[` TRIM `]](/language-spec/functions/string/trim) * * * ## Syntax ```sql SELECT LTRIM(character_expression[, character ]) FROM <multipartIdentifier>; ``` ## Arguments __*character_expression*__ A literal string or string column. __*character*__ An optional character to remove if found at the beginning of the *character_expression*. ## Return Value(s) Returns a string. * * * ## Examples ### Remove leading whitespace from a string column ```sql SELECT ltrim(description) AS leading_whitespace_removed FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#ltrim](https://www.sqlite.org/lang_corefunc.html#ltrim) --- # REPLACE > REPLACE function in StackQL: substitute every occurrence of a substring within a string with another string. Source: https://stackql.io/language-spec/functions/string/replace Returns a string formed by substituting a portion of a string for every occurrence of another string. See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT REPLACE(character_expression, pattern, replacement) FROM <multipartIdentifier>; ``` ## Arguments __*character_expression*__ A literal string or string column that you want to perform the replacement on. __*pattern*__ The substring to be found in the original string. > If *pattern* is an empty string or is not found in *character_expression*, then *character_expression* will be returned unchanged. __*replacement*__ The replacement string. > If *replacement* is not initially a string, it is cast to a UTF-8 string prior to processing. > The `BINARY` collating sequence is used for comparisons. ## Return Value(s) Returns a string. * * * ## Examples ### Replace a string pattern in a column ```sql SELECT replace(name, 'prd', 'production') AS replacement_string FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#replace](https://www.sqlite.org/lang_corefunc.html#replace) --- # RTRIM > RTRIM function in StackQL: remove whitespace, or a given set of characters, from the right of a string. Source: https://stackql.io/language-spec/functions/string/rtrim Returns a string formed by removing white space or any characters that appear from the right side of an input string. See also: [[` SELECT `]](/language-spec/select) [[` LTRIM `]](/language-spec/functions/string/ltrim) [[` TRIM `]](/language-spec/functions/string/trim) * * * ## Syntax ```sql SELECT RTRIM(character_expression[, character ]) FROM <multipartIdentifier>; ``` ## Arguments __*character_expression*__ A literal string or string column. __*character*__ An optional character to remove if found at the end of the *character_expression*. ## Return Value(s) Returns a string. * * * ## Examples ### Remove trailing whitespace from a string column ```sql SELECT rtrim(description) AS trailing_whitespace_removed FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#rtrim](https://www.sqlite.org/lang_corefunc.html#rtrim) --- # SPLIT_PART > SPLIT_PART function in StackQL: split a string on a separator and return the part at a one-based position, handy for picking apart resource IDs and ARNs. Source: https://stackql.io/language-spec/functions/string/split_part Splits source string based upon a seperator and returns the given part (counting from one). See also: [[` SELECT `]](/language-spec/select) * * * ## Syntax ```sql SELECT SPLIT_PART(source, sep, part) FROM <multipartIdentifier>; ``` ## Arguments __*source*__ A literal string or string column that you want to perform the split on. __*sep*__ A character or characters you want to use as the separator. > If `sep` is composed of multiple characters, each character is treated as separator. > Only ASCII (1-byte) symbols are supported as separators. __*part*__ The element (one based) of the split string to return. Negative values are used to count backwards from the last element. ## Return Value(s) Returns a string. * * * ## Examples ### Extract elements from a string seperated by a forward slash **StackQL** ```sql SELECT name, split_part(id, '/', 3) as subscription, split_part(id, '/', 5) as resource_group, json_extract(properties, '$.hardwareProfile.vmSize') as vm_size FROM azure.compute.virtual_machines WHERE resource_group_name = 'stackql-ops-cicd-dev-01' AND subscription_id = '273769f6-545f-45b2-8ab8-2f14ec5768dc'; ``` **Results** ``` |------|--------------------------------------|-------------------------|-----------------| | name | subscription | resource_group | vm_size | |------|--------------------------------------|-------------------------|-----------------| | test | 273769f6-545f-45b2-8ab8-2f14ec5768dc | stackql-ops-cicd-dev-01 | Standard_D2s_v3 | |------|--------------------------------------|-------------------------|-----------------| ``` ### Extract the last element from a url **StackQL** ```sql SELECT name, SPLIT_PART(network, '/', -1) as network, SPLIT_PART(region, '/', -1) as region FROM google.compute.vpn_gateways WHERE project = 'stackql-demo'; ``` **Results** ``` +------------------------+-----------------------+----------------------+ | name | network | region | +------------------------+-----------------------+----------------------+ | gcp-aws-vpn-gateway | stackql-shrd-vpc-nw | australia-southeast1 | +------------------------+-----------------------+----------------------+ ``` For more information, see [https://github.com/nalgeon/sqlean/blob/main/docs/text.md](https://github.com/nalgeon/sqlean/blob/main/docs/text.md) --- # SUBSTRING > SUBSTRING function in StackQL (alias SUBSTR): return part of a string or binary value by start position and length. Source: https://stackql.io/language-spec/functions/string/substring Returns part of a character or binary expression. `SUBSTR` is an alias for `SUBSTRING`. See also: [[` SELECT `]](/language-spec/select) [[ Data Types ]](/language-spec/data-types) * * * :::info To extract a field from a JSON object use the [**JSON_EXTRACT**](/language-spec/functions/json/json_extract) function. ::: ## Syntax ```sql SELECT SUBSTRING(expression, start[, length]) FROM <multipartIdentifier>; SELECT SUBSTR(expression, start[, length]) FROM <multipartIdentifier>; ``` ## Arguments __*expression*__ An ASCII string or a BLOB. > If *expression* is a string then characters indices refer to actual UTF-8 characters. If *expression* is a BLOB then the indices refer to bytes. __*start*__ An integer representing the first character or byte of the sub sequence of the input expression to be returned. If *start* is negative then the first character of the substring is found by counting from the right rather than the left. > The left-most character of *expression* is number 1. __*length*__ An optional integer value representing the length of the sub sequence to be returned after the *start* value. If *length* is omitted then all characters through the end of the string or BLOB specified by the *expression* are returned. > If *length* is negative then the absolute value of *length* is used. ## Return Value(s) Returns a string or BLOB value depending upon the *expression* type. * * * ## Examples ### Return the first *n* characters from a column ```sql SELECT SUBSTRING(name, 1, 5) as "first five chars" FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Truncate the first *n* characters from a column ```sql SELECT SUBSTR(name, 5) as "from char 5" FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return the last *n* characters from a column ```sql SELECT SUBSTRING(name, -5) as "last five chars" FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#substr](https://www.sqlite.org/lang_corefunc.html#substr) --- # TRIM > TRIM function in StackQL: remove whitespace, or a given set of characters, from both ends of a string. Source: https://stackql.io/language-spec/functions/string/trim Returns a string formed by removing white space or any characters that appear from the left and right side of an input string. See also: [[` SELECT `]](/language-spec/select) [[` LTRIM `]](/language-spec/functions/string/ltrim) [[` RTRIM `]](/language-spec/functions/string/rtrim) * * * ## Syntax ```sql SELECT TRIM(character_expression[, character ]) FROM <multipartIdentifier>; ``` ## Arguments __*character_expression*__ A literal string or string column. __*character*__ An optional character to remove if found at the beginning or end of the *character_expression*. ## Return Value(s) Returns a string. * * * ## Examples ### Remove leading and trailing whitespace from a string column ```sql SELECT trim(description) AS leading_and_trailing_whitespace_removed FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#trim](https://www.sqlite.org/lang_corefunc.html#trim) --- # UPPER > UPPER function in StackQL: convert a string to uppercase. Source: https://stackql.io/language-spec/functions/string/upper Returns an input string in uppercase. See also: [[` SELECT `]](/language-spec/select) [[` LOWER `]](/language-spec/functions/string/lower) [[ Data Types ]](/language-spec/data-types) * * * ## Syntax ```sql SELECT UPPER(character_expression) FROM <multipartIdentifier>; ``` > The `upper()` function works for ASCII characters only. ## Arguments __*character_expression*__ An ASCII string. ## Return Value(s) Returns a string value. * * * ## Examples ### Return a string in uppercase ```sql SELECT UPPER(name), location FROM google.storage.buckets WHERE project = 'stackql-demo'; ``` For more information, see [https://www.sqlite.org/lang_corefunc.html#upper](https://www.sqlite.org/lang_corefunc.html#upper) --- # CUME_DIST > CUME_DIST window function in StackQL: the cumulative distribution of the current row within its partition, as row number divided by partition rows. Source: https://stackql.io/language-spec/functions/window/cume_dist Returns the cumulative distribution of a value within a partition. This is calculated as `row-number / partition-rows`, where `row-number` is the value returned by `ROW_NUMBER()` for the last peer in the group and `partition-rows` is the number of rows in the partition. See also: [[` SELECT `]](/language-spec/select) [[` PERCENT_RANK `]](/language-spec/functions/window/percent_rank) [[` RANK `]](/language-spec/functions/window/rank) * * * ## Syntax ```sql SELECT CUME_DIST() OVER ([PARTITION BY column] ORDER BY column [ASC|DESC]) FROM <multipartIdentifier>; ``` ## Arguments __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `CUME_DIST` function is applied to each partition separately. __*ORDER BY column*__ Specifies the order in which the cumulative distribution is calculated. ## Return Value(s) Returns a floating-point number between 0.0 and 1.0 representing the cumulative distribution value. * * * ## Examples ### Calculate cumulative distribution of contributors ```sql -- Calculate percentile ranking of contributors SELECT login, contributions, PERCENT_RANK() OVER (ORDER BY contributions) as percentile, CUME_DIST() OVER (ORDER BY contributions) as cumulative_dist FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY contributions DESC; ``` :::tip `CUME_DIST` returns the proportion of rows with values less than or equal to the current row's value. A value of 0.75 means 75% of the rows have values less than or equal to the current row. ::: For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # DENSE_RANK > DENSE_RANK window function in StackQL: the rank of the current row in its partition without gaps, so tied rows share a rank and the next rank follows at once. Source: https://stackql.io/language-spec/functions/window/dense_rank Returns the rank of the current row without gaps. This is the number of the current row's peer group within its partition. Rows with equal values for the ordering columns receive the same rank, and the next rank value is always incremented by 1 (no gaps). Rows are numbered starting from 1 in the order defined by the `ORDER BY` clause in the window definition. If there is no `ORDER BY` clause, then all rows are considered peers and this function always returns 1. See also: [[` SELECT `]](/language-spec/select) [[` ROW_NUMBER `]](/language-spec/functions/window/row_number) [[` RANK `]](/language-spec/functions/window/rank) * * * ## Syntax ```sql SELECT DENSE_RANK() OVER ([PARTITION BY column] ORDER BY column [ASC|DESC]) FROM <multipartIdentifier>; ``` ## Arguments __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `DENSE_RANK` function is applied to each partition separately. __*ORDER BY column*__ Specifies the order in which ranks are assigned. If there is no `ORDER BY` clause, all rows are considered peers and receive rank 1. ## Return Value(s) Returns an integer representing the dense rank of the current row within the partition, without gaps for tied values. * * * ## Examples ### Rank contributors by contributions (without gaps) ```sql -- Rank contributors without gaps for ties SELECT DENSE_RANK() OVER (ORDER BY contributions DESC) as rank, login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo IN ('stackql', 'stackql-deploy', 'stackql-provider-registry') ORDER BY contributions DESC; ``` ### Compare `DENSE_RANK` with `RANK` and `ROW_NUMBER` ```sql -- Compare RANK vs DENSE_RANK vs ROW_NUMBER for contributors SELECT login, contributions, RANK() OVER (ORDER BY contributions DESC) as rank, DENSE_RANK() OVER (ORDER BY contributions DESC) as dense_rank, ROW_NUMBER() OVER (ORDER BY contributions DESC) as row_num FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` ### Rank aggregated contributions across multiple repositories ```sql -- Rank total contributions across multiple repos WITH all_contributors AS ( SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql' UNION ALL SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-deploy' UNION ALL SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-provider-registry' ) SELECT DENSE_RANK() OVER (ORDER BY SUM(contributions) DESC) as rank, login, SUM(contributions) as total_contributions, MAX(html_url) as html_url FROM all_contributors GROUP BY login ORDER BY total_contributions DESC; ``` For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # FIRST_VALUE > FIRST_VALUE window function in StackQL: the value of an expression for the first row of the window frame. Source: https://stackql.io/language-spec/functions/window/first_value Returns the value of the expression evaluated against the first row in the window frame. This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value of the expression evaluated against the first row in the window frame for each row. See also: [[` SELECT `]](/language-spec/select) [[` LAST_VALUE `]](/language-spec/functions/window/last_value) [[` NTH_VALUE `]](/language-spec/functions/window/nth_value) * * * ## Syntax ```sql SELECT FIRST_VALUE(expr) OVER ( [PARTITION BY column] ORDER BY column [ROWS BETWEEN frame_start AND frame_end] ) FROM <multipartIdentifier>; ``` ## Arguments __*expr*__ The expression to evaluate against the first row in the window frame. __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `FIRST_VALUE` function is applied within each partition separately. __*ORDER BY column*__ Specifies the order in which rows are processed. __*ROWS BETWEEN frame_start AND frame_end*__ Optional. Defines the window frame. Common options include: - `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` (default) - `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING` ## Return Value(s) Returns the value of the expression evaluated against the first row in the window frame. * * * ## Examples ### Find the first release for context ```sql -- Find first and latest release for context SELECT tag_name, name, published_at, FIRST_VALUE(tag_name) OVER ( ORDER BY published_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) as first_release, LAST_VALUE(tag_name) OVER ( ORDER BY published_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) as latest_release FROM github.repos.releases WHERE owner = 'stackql' AND repo = 'stackql'; ``` :::tip By default, the window frame extends from the start of the partition to the current row. To include all rows in the partition, use `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`. ::: For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # LAG > LAG window function in StackQL: evaluate an expression against a previous row in the partition, with an optional offset and default. Source: https://stackql.io/language-spec/functions/window/lag Returns the result of evaluating an expression against a previous row in the partition. The first form of `LAG()` returns the result of evaluating the expression against the previous row in the partition. Or, if there is no previous row (because the current row is the first), `NULL` is returned. If the offset argument is provided, it must be a non-negative integer. The value returned is the result of evaluating the expression against the row *offset* rows before the current row within the partition. If offset is 0, the expression is evaluated against the current row. If there is no row *offset* rows before the current row, `NULL` is returned. If a default value is also provided, it is returned instead of `NULL` if the row identified by offset does not exist. See also: [[` SELECT `]](/language-spec/select) [[` LEAD `]](/language-spec/functions/window/lead) * * * ## Syntax ```sql SELECT LAG(expr) OVER ([PARTITION BY column] ORDER BY column) FROM <multipartIdentifier>; SELECT LAG(expr, offset) OVER ([PARTITION BY column] ORDER BY column) FROM <multipartIdentifier>; SELECT LAG(expr, offset, default) OVER ([PARTITION BY column] ORDER BY column) FROM <multipartIdentifier>; ``` ## Arguments __*expr*__ The expression to evaluate against the previous row. __*offset*__ Optional. A non-negative integer specifying how many rows back to look. Defaults to 1. __*default*__ Optional. The value to return if the offset row does not exist. Defaults to `NULL`. __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `LAG` function is applied within each partition separately. __*ORDER BY column*__ Specifies the order in which rows are processed. ## Return Value(s) Returns the value of the expression evaluated against the specified previous row, or `NULL` (or the default value) if no such row exists. * * * ## Examples ### Compare each release to the previous release ```sql -- Compare each release to previous and next release dates SELECT tag_name, name, published_at, LAG(tag_name, 1) OVER (ORDER BY published_at) as previous_release, LAG(published_at, 1) OVER (ORDER BY published_at) as previous_release_date, julianday(published_at) - julianday(LAG(published_at, 1) OVER (ORDER BY published_at)) as days_since_last_release FROM github.repos.releases WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY published_at; ``` ### Analyze gaps between issue creation ```sql -- Analyze gaps between issue creation SELECT number, title, created_at, LAG(created_at, 1) OVER (ORDER BY created_at) as prev_issue_date, julianday(created_at) - julianday(LAG(created_at, 1) OVER (ORDER BY created_at)) as days_since_prev_issue FROM github.issues.issues WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY created_at; ``` For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # LAST_VALUE > LAST_VALUE window function in StackQL: the value of an expression for the last row of the window frame. Source: https://stackql.io/language-spec/functions/window/last_value Returns the value of the expression evaluated against the last row in the window frame. This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value of the expression evaluated against the last row in the window frame for each row. See also: [[` SELECT `]](/language-spec/select) [[` FIRST_VALUE `]](/language-spec/functions/window/first_value) [[` NTH_VALUE `]](/language-spec/functions/window/nth_value) * * * ## Syntax ```sql SELECT LAST_VALUE(expr) OVER ( [PARTITION BY column] ORDER BY column [ROWS BETWEEN frame_start AND frame_end] ) FROM <multipartIdentifier>; ``` ## Arguments __*expr*__ The expression to evaluate against the last row in the window frame. __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `LAST_VALUE` function is applied within each partition separately. __*ORDER BY column*__ Specifies the order in which rows are processed. __*ROWS BETWEEN frame_start AND frame_end*__ Optional. Defines the window frame. Common options include: - `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` (default) - `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING` ## Return Value(s) Returns the value of the expression evaluated against the last row in the window frame. * * * ## Examples ### Find the latest release for context ```sql -- Find first and latest release for context SELECT tag_name, name, published_at, FIRST_VALUE(tag_name) OVER ( ORDER BY published_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) as first_release, LAST_VALUE(tag_name) OVER ( ORDER BY published_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) as latest_release FROM github.repos.releases WHERE owner = 'stackql' AND repo = 'stackql'; ``` :::tip By default, the window frame extends from the start of the partition to the current row, which means `LAST_VALUE` would return the current row's value. To get the actual last value in the partition, use `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`. ::: For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # LEAD > LEAD window function in StackQL: evaluate an expression against a following row in the partition, with an optional offset and default. Source: https://stackql.io/language-spec/functions/window/lead Returns the result of evaluating an expression against a subsequent row in the partition. The first form of `LEAD()` returns the result of evaluating the expression against the next row in the partition. Or, if there is no next row (because the current row is the last), `NULL` is returned. If the offset argument is provided, it must be a non-negative integer. The value returned is the result of evaluating the expression against the row *offset* rows after the current row within the partition. If offset is 0, the expression is evaluated against the current row. If there is no row *offset* rows after the current row, `NULL` is returned. If a default value is also provided, it is returned instead of `NULL` if the row identified by offset does not exist. See also: [[` SELECT `]](/language-spec/select) [[` LAG `]](/language-spec/functions/window/lag) * * * ## Syntax ```sql SELECT LEAD(expr) OVER ([PARTITION BY column] ORDER BY column) FROM <multipartIdentifier>; SELECT LEAD(expr, offset) OVER ([PARTITION BY column] ORDER BY column) FROM <multipartIdentifier>; SELECT LEAD(expr, offset, default) OVER ([PARTITION BY column] ORDER BY column) FROM <multipartIdentifier>; ``` ## Arguments __*expr*__ The expression to evaluate against the subsequent row. __*offset*__ Optional. A non-negative integer specifying how many rows forward to look. Defaults to 1. __*default*__ Optional. The value to return if the offset row does not exist. Defaults to `NULL`. __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `LEAD` function is applied within each partition separately. __*ORDER BY column*__ Specifies the order in which rows are processed. ## Return Value(s) Returns the value of the expression evaluated against the specified subsequent row, or `NULL` (or the default value) if no such row exists. * * * ## Examples ### Look ahead to the next release ```sql -- Compare each release to previous and next release dates SELECT tag_name, name, published_at, LAG(tag_name, 1) OVER (ORDER BY published_at) as previous_release, LEAD(tag_name, 1) OVER (ORDER BY published_at) as next_release FROM github.repos.releases WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY published_at; ``` For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # NTH_VALUE > NTH_VALUE window function in StackQL: the value of an expression for the Nth row of the window frame. Source: https://stackql.io/language-spec/functions/window/nth_value Returns the value of the expression evaluated against the Nth row in the window frame. This built-in window function calculates the window frame for each row in the same way as an aggregate window function. It returns the value of the expression evaluated against row N of the window frame. Rows are numbered within the window frame starting from 1 in the order defined by the `ORDER BY` clause if present, or in arbitrary order otherwise. If there is no Nth row in the partition, then `NULL` is returned. See also: [[` SELECT `]](/language-spec/select) [[` FIRST_VALUE `]](/language-spec/functions/window/first_value) [[` LAST_VALUE `]](/language-spec/functions/window/last_value) * * * ## Syntax ```sql SELECT NTH_VALUE(expr, N) OVER ( [PARTITION BY column] ORDER BY column [ROWS BETWEEN frame_start AND frame_end] ) FROM <multipartIdentifier>; ``` ## Arguments __*expr*__ The expression to evaluate against the Nth row in the window frame. __*N*__ A positive integer specifying which row number to retrieve (1-indexed). __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `NTH_VALUE` function is applied within each partition separately. __*ORDER BY column*__ Specifies the order in which rows are processed. __*ROWS BETWEEN frame_start AND frame_end*__ Optional. Defines the window frame. ## Return Value(s) Returns the value of the expression evaluated against the Nth row in the window frame, or `NULL` if the Nth row does not exist. * * * ## Examples ### Get the second-highest contributor ```sql -- Get the top 3 contributors by name for comparison SELECT login, contributions, NTH_VALUE(login, 1) OVER (ORDER BY contributions DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as top_contributor, NTH_VALUE(login, 2) OVER (ORDER BY contributions DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as second_contributor, NTH_VALUE(login, 3) OVER (ORDER BY contributions DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as third_contributor FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # NTILE > NTILE window function in StackQL: split a partition into N groups as evenly as possible and number each row's group from 1 to N. Source: https://stackql.io/language-spec/functions/window/ntile Divides the partition into N groups as evenly as possible and assigns an integer between 1 and N to each group, in the order defined by the `ORDER BY` clause, or in arbitrary order otherwise. If necessary, larger groups occur first. See also: [[` SELECT `]](/language-spec/select) [[` RANK `]](/language-spec/functions/window/rank) * * * ## Syntax ```sql SELECT NTILE(N) OVER ([PARTITION BY column] ORDER BY column [ASC|DESC]) FROM <multipartIdentifier>; ``` ## Arguments __*N*__ A positive integer specifying the number of groups (tiles) to divide the partition into. __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `NTILE` function is applied to each partition separately. __*ORDER BY column*__ Specifies the order in which rows are assigned to tiles. ## Return Value(s) Returns an integer between 1 and N indicating which tile (group) the current row belongs to. * * * ## Examples ### Group contributors into quartiles by contribution level ```sql -- Group contributors into quartiles by contribution level SELECT login, contributions, NTILE(4) OVER (ORDER BY contributions DESC) as contribution_quartile, CASE NTILE(4) OVER (ORDER BY contributions DESC) WHEN 1 THEN 'Top Contributors' WHEN 2 THEN 'Active Contributors' WHEN 3 THEN 'Moderate Contributors' WHEN 4 THEN 'Occasional Contributors' END as contributor_tier FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` :::tip Use `NTILE` to create segments or tiers in your data. Common use cases include dividing data into quartiles (N=4), deciles (N=10), or percentiles (N=100). ::: For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # PERCENT_RANK > PERCENT_RANK window function in StackQL: the relative rank of the current row within its partition as a value between 0.0 and 1.0. Source: https://stackql.io/language-spec/functions/window/percent_rank Returns a value between 0.0 and 1.0 representing the relative rank of the current row within its partition. Despite the name, this function returns a value equal to `(rank - 1) / (partition-rows - 1)`, where `rank` is the value returned by the built-in window function `RANK()` and `partition-rows` is the total number of rows in the partition. If the partition contains only one row, this function returns 0.0. See also: [[` SELECT `]](/language-spec/select) [[` RANK `]](/language-spec/functions/window/rank) [[` CUME_DIST `]](/language-spec/functions/window/cume_dist) * * * ## Syntax ```sql SELECT PERCENT_RANK() OVER ([PARTITION BY column] ORDER BY column [ASC|DESC]) FROM <multipartIdentifier>; ``` ## Arguments __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `PERCENT_RANK` function is applied to each partition separately. __*ORDER BY column*__ Specifies the order in which the percentile ranks are calculated. ## Return Value(s) Returns a floating-point number between 0.0 and 1.0 representing the percentile rank. * * * ## Examples ### Calculate percentile ranking of contributors ```sql -- Calculate percentile ranking of contributors SELECT login, contributions, PERCENT_RANK() OVER (ORDER BY contributions) as percentile, CUME_DIST() OVER (ORDER BY contributions) as cumulative_dist FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY contributions DESC; ``` :::tip The `PERCENT_RANK` value of 0.0 indicates the lowest-ranked row, while 1.0 indicates the highest-ranked row. Use this function to identify where a particular value falls within a distribution. ::: For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # RANK > RANK window function in StackQL: the rank of the current row within its partition with gaps, so tied rows share a rank and the following ranks are skipped. Source: https://stackql.io/language-spec/functions/window/rank Returns the rank of the current row with gaps. This is the `ROW_NUMBER` of the first peer in each group. Rows with equal values for the ordering columns receive the same rank, and the next rank value is incremented by the number of tied rows (leaving gaps). If there is no `ORDER BY` clause, then all rows are considered peers and this function always returns 1. See also: [[` SELECT `]](/language-spec/select) [[` ROW_NUMBER `]](/language-spec/functions/window/row_number) [[` DENSE_RANK `]](/language-spec/functions/window/dense_rank) * * * ## Syntax ```sql SELECT RANK() OVER ([PARTITION BY column] ORDER BY column [ASC|DESC]) FROM <multipartIdentifier>; ``` ## Arguments __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `RANK` function is applied to each partition separately. __*ORDER BY column*__ Specifies the order in which ranks are assigned. If there is no `ORDER BY` clause, all rows are considered peers and receive rank 1. ## Return Value(s) Returns an integer representing the rank of the current row within the partition, with gaps for tied values. * * * ## Examples ### Rank contributors by contributions (with gaps) ```sql -- Rank contributors with gaps for ties SELECT login, contributions, RANK() OVER (ORDER BY contributions DESC) as rank FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` ### Compare `RANK` with `DENSE_RANK` and `ROW_NUMBER` ```sql -- Compare RANK vs DENSE_RANK vs ROW_NUMBER for contributors SELECT login, contributions, RANK() OVER (ORDER BY contributions DESC) as rank, DENSE_RANK() OVER (ORDER BY contributions DESC) as dense_rank, ROW_NUMBER() OVER (ORDER BY contributions DESC) as row_num FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` ### Rank contributors within each repository using `PARTITION BY` ```sql -- Rank contributors within each repo WITH repo_contributors AS ( SELECT repo, login, contributions, RANK() OVER (PARTITION BY repo ORDER BY contributions DESC) as rank_in_repo FROM ( SELECT 'stackql' as repo, login, contributions FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql' UNION ALL SELECT 'stackql-provider-registry' as repo, login, contributions FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-provider-registry' ) t ) SELECT repo, login, contributions, rank_in_repo FROM repo_contributors ORDER BY repo, rank_in_repo; ``` For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # ROW_NUMBER > ROW_NUMBER window function in StackQL: number the rows within a partition from 1 in the order given by the window's ORDER BY clause. Source: https://stackql.io/language-spec/functions/window/row_number Returns the number of the row within the current partition. Rows are numbered starting from 1 in the order defined by the `ORDER BY` clause in the window definition, or in arbitrary order otherwise. See also: [[` SELECT `]](/language-spec/select) [[` RANK `]](/language-spec/functions/window/rank) [[` DENSE_RANK `]](/language-spec/functions/window/dense_rank) * * * ## Syntax ```sql SELECT ROW_NUMBER() OVER ([PARTITION BY column] ORDER BY column [ASC|DESC]) FROM <multipartIdentifier>; ``` ## Arguments __*PARTITION BY column*__ Optional. Divides the result set into partitions. The `ROW_NUMBER` function is applied to each partition separately and resets the row number for each partition. __*ORDER BY column*__ Specifies the order in which the row numbers are assigned. Required for meaningful results. ## Return Value(s) Returns an integer representing the sequential row number within the partition, starting at 1. * * * ## Examples ### Rank contributors within a repository ```sql -- Rank contributors within a repository SELECT login, contributions, ROW_NUMBER() OVER (ORDER BY contributions DESC) as contribution_rank FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` ### Track issue sequence over time ```sql -- Track issue growth over time SELECT number, title, state, created_at, ROW_NUMBER() OVER (ORDER BY created_at) as issue_sequence FROM github.issues.issues WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY created_at; ``` ### Compare `ROW_NUMBER` with `RANK` and `DENSE_RANK` ```sql -- Compare RANK vs DENSE_RANK vs ROW_NUMBER for contributors SELECT login, contributions, RANK() OVER (ORDER BY contributions DESC) as rank, DENSE_RANK() OVER (ORDER BY contributions DESC) as dense_rank, ROW_NUMBER() OVER (ORDER BY contributions DESC) as row_num FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` For more information, see [https://sqlite.org/windowfunctions.html#built-in_window_functions](https://sqlite.org/windowfunctions.html#built-in_window_functions). --- # INSERT > INSERT in StackQL: create one or more instances of a cloud or SaaS resource with a SQL statement, passing required and optional fields as columns and values. Source: https://stackql.io/language-spec/insert Creates a new instance or instances of a resource. See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) * * * ## Syntax *insertStatement::=*     ```sql INSERT [ /*+ AWAIT */ ] [ IGNORE ] [ INTO ] <multipartIdentifier> ( field_name [, field_name] ... ) { VALUES ( value [, value] ... ) | <selectExpression> } [ RETURNING field_name [, field_name] ... ]; ``` * * * ## `RETURNING` Clause The `RETURNING` clause allows you to retrieve data from the `INSERT` operation response. This is particularly useful when: - The API returns important information like generated IDs, status codes, or other metadata - You need to capture the response data for further processing - You want to verify the operation result The fields specified in the `RETURNING` clause will be deserialized from the API response and displayed in the result set. * * * ## Examples ### Basic `INSERT` statement Run an INSERT statement to create a Compute Engine Disk resource. This is a non blocking (asynchronous) invocation. ```sql -- Create a Compute Engine Disk resource INSERT INTO google.compute.disks (project, zone, name, sizeGb) SELECT 'stackql-demo', 'australia-southeast1-a', 'test10gbdisk', 10; ``` ### `INSERT` statement (blocking) Run an INSERT statement to create a Compute Engine Disk resource. This is a blocking (synchronous) invocation. ```sql -- Create a Compute Engine Disk resource INSERT /*+ AWAIT */ INTO google.compute.disks (project, zone, name, sizeGb) SELECT 'stackql-demo', 'australia-southeast1-a', 'test10gbdisk', 10; ``` ### `INSERT` statement with `SELECT` Run an INSERT statement with SELECT. ```sql -- Create a Azure Network Interface INSERT INTO azure.network.network_interfaces ( resource_group_name, subscription_id, network_interface_name, data__location, data__properties ) SELECT 'vmss-flex', '0123456789', 'vmss-flex-vnet-nic01-manual-' || '1', 'eastus', json_replace(json_remove(properties, '$.allowPort25Out', '$.auxiliarySku', '$.provisioningState', '$.resourceGuid', '$.macAddress', '$.vnetEncryptionSupported', '$.enableIPForwarding', '$.defaultOutboundAccess', '$.primary', '$.virtualMachine', '$.hostedWorkloads', '$.tapConfigurations', '$.nicType', '$.auxiliaryMode', '$.ipConfigurations[0].id', '$.ipConfigurations[0].etag', '$.ipConfigurations[0].type', '$.ipConfigurations[0].properties.provisioningState', '$.ipConfigurations[0].properties.privateIPAddress', '$.ipConfigurations[0].properties.privateIPAllocationMethod', '$.ipConfigurations[0].properties.primary', '$.ipConfigurations[0].properties.privateIPAddressVersion' ), '$.ipConfigurations[0].name', 'vmss-flex-vnet-nic01-defaultIpConfiguration' ) FROM azure.network.network_interfaces WHERE subscription_id = '0123456789' AND resource_group_name = 'vmss-flex' AND network_interface_name = 'vmss-nic-01'; ``` ### `INSERT` statement with `RETURNING` clause Run an `INSERT` statement and retrieve specific fields from the API response. ```sql -- Execute a Snowflake SQL statement and return the response data INSERT INTO snowflake.sqlapi.statements ( data__statement, data__timeout, data__database, data__schema, "User-Agent", endpoint ) SELECT 'SELECT customer_id, customer_name, email, credit_card_number, purchase_amount, purchase_date FROM CUSTOMER_DATA', 10, 'MY_DATABASE', 'MY_SCHEMA', 'User-Agent', 'ABCDEF-XY12345' RETURNING code, sqlState, message, data; ``` Result: ``` |--------|----------|--------------------------------|-----------------------------------------------------------------------------| | code | sqlState | message | data | |--------|----------|--------------------------------|-----------------------------------------------------------------------------| | 090001 | 00000 | Statement executed | [["1","John | | | | successfully. | Smith","john.smith@example.com","***MASKED***","199.99","20262"],["1","John | | | | | Smith","john.smith@example.com","***MASKED***","199.99","20263"]] | |--------|----------|--------------------------------|-----------------------------------------------------------------------------| ``` --- # Keywords > StackQL keywords: the reserved words of the StackQL grammar, which can be written in any case and must be quoted when used as identifiers. Source: https://stackql.io/language-spec/keywords Keywords are reserved words that have significance in the StackQL grammar. Keywords can be entered in any case (upper, lower or mixed), they are capitalized in all of the examples by convention. Keywords in StackQL include: `ADD`, `AND`, `AS`, `ASC`, `BETWEEN`, `BINARY`, `BY`, `CASE`, `COLLATE`, `CONVERT`, `CREATE`, `CROSS`, `CURRENT_DATE`, `CURRENT_TIME`, `CURRENT_TIMESTAMP`, `DATABASE`, `DATABASES`, `DELETE`, `DESC`, `DESCRIBE`, `DISTINCT`, `DIV`, `DROP`, `ELSE`, `END`, `ESCAPE`, `EXEC`, `EXISTS`, `EXPLAIN`, `FALSE`, `FOR`, `FROM`, `GROUP`, `HAVING`, `IF`, `IGNORE`, `IN`, `INDEX`, `INNER`, `INSERT`, `INTERVAL`, `INTO`, `IS`, `JOIN`, `LEFT`, `LIKE`, `LIMIT`, `LOCALTIME`, `LOCALTIMESTAMP`, `LOCK`, `MOD`, `NATURAL`, `NEXT`, `NOT`, `NULL`, `OFF`, `ON`, `OR`, `ORDER`, `OUTER`, `OVER`, `RECURSIVE`, `REGEXP`, `REPLACE`, `RETURNING`, `RIGHT`, `SCHEMA`, `SELECT`, `SEPARATOR`, `SESSION`, `SET`, `SHOW`, `SUBSTR`, `SUBSTRING`, `TABLE`, `THEN`, `TIMESTAMPADD`, `TIMESTAMPDIFF`, `TO`, `TRUE`, `UNION`, `UNSET`, `UPDATE`, `USE`, `USING`, `UTC_DATE`, `UTC_TIME`, `UTC_TIMESTAMP`, `VALUES`, `WHEN`, `WHERE`, `XOR` --- # Lexical Structure > The lexical structure of StackQL: how statements, identifiers, quoting, literals, comments and whitespace are tokenised by the parser. Source: https://stackql.io/language-spec/lexical-structure See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) [[ Keywords ]](/language-spec/keywords) [[ Data Types ]](/language-spec/data-types) [[ DESCRIBE ]](/language-spec/describe) StackQL’s lexical structure and grammar is modelled upon MySQL’s language implementation (an adaptation of the ANSI SQL-92 standard) with some extensions. StackQL statements are used to query cloud resources (using `SELECT` grammar) or create, modify or delete infrastructure using standard Data Manipulation Language (DML) statements such as `INSERT`, `UPDATE`, `REPLACE` and `DELETE`. Additionally, non DML operations such as starting an instance, or getting or putting an object into a bucket in AWS S3 for example are implemented as built-in provider procedures (akin to Stored Procedures in a DBMS). Built-in provider procedures are invoked using the `EXEC` statement. StackQL’s SQL domain-specific language allows for declarative as well as procedural infrastructure programming. * * * ## Syntax StackQL operations are comprised of one or more semicolon (`;`) terminated statements. Statements include keywords, identifiers, parameters and values, an example StackQL statement used to create a 10GB disk in GCP would be: ```sql INSERT INTO google.compute.disks (project, zone, name, sizeGb) SELECT 'myProject', 'australia-southeast1-a', 'my10GbDisk', 10; ``` In the above example, _`INSERT`_, _`INTO`_ and _`SELECT`_ are keywords, _google.compute.disks_ is an identifier, _project_, _zone_, _name_, _sizeGb_ are parameters, and _'myProject'_, _'australia-southeast1-a'_, _'my10GbDisk'_, _10_ are values. ## Keywords Keywords are not case sensitive, meaning `INSERT` and `insert` are treated equivalently, however they are often capitalized by convention. A complete list of keywords can be found in the Keywords section. ## Identifiers Identifiers are symbols that represent objects in a cloud provider resource hierarchy. Identifiers are made up of multiple parts, more information on identifiers can be found in the StackQL Resource Hierarchy topic. ## Parameters and Values Parameters are specified by the resource; these can be found by using a `DESCRIBE` statement for a given cloud provider resource. Values are typed scalar or complex objects which map to parameters. For more information on parameters and values, see the `DESCRIBE` and Data Types topics. ## Variables A dollar-prefixed identifier such as `$region` dereferences a session variable assigned with [`SET`](/language-spec/set); it is replaced with the variable's typed value before the statement is planned. A single-quoted `'$region'` is a string literal. In a `FROM` clause a `$variable` resolves to a relation name, and `IDENTIFIER($variable)` resolves to a column name in expression positions. A double-quoted, dollar-prefixed path such as `"$.auth.aws.password"` is a runtime configuration target accepted by `SET` and `UNSET`. Session variables are available in StackQL `v1.0` and later, see [Session Variables](/getting-started/session-variables). ## Operators `||` is the string concatenation operator and binds more tightly than comparison operators. `OR` is boolean disjunction. StackQL releases before `v1.0` tokenised `||` as `OR`. ## Comments StackQL supports multi-line and in line comments within StackQL statements, examples of comments are shown below: ```shell /* This Is a Multiline Comment */ --This is an inline comment ``` --- # REFRESH VIEW > REFRESH VIEW in StackQL: rebuild the stored results of a materialized view from its defining query. Source: https://stackql.io/language-spec/refreshview Refreshes the data in a `materialized view` within a session. See also: [[ `CREATE` ]](/language-spec/createview) [[ `DROP` ]](/language-spec/dropview) * * * ## Syntax *refreshViewStatement::=*     ```sql REFRESH MATERIALIZED VIEW <viewName>; ``` * * * ## Examples ### Refresh a Materialized View ```sql REFRESH MATERIALIZED VIEW vw_ec2_instance_types; ``` --- # REGISTRY > REGISTRY in StackQL: list the providers and versions in the provider registry and pull the latest or a specific version into your installation. Source: https://stackql.io/language-spec/registry Lists the providers available in the configured provider registry, or pulls a provider into the local installation. See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) [[` --registry `]](/command-line-usage/global-flags#--registry) > From `v1.0`, provider documents can be required to carry a valid ML-DSA-65 signature when they are read. Verification is off by default and is enabled with the `verifyConfig` key of the [`--registry`](/command-line-usage/global-flags#--registry) flag. * * * ## Syntax *registryStatement::=*     ```sql REGISTRY { LIST [<provider>] | PULL <provider> [<version>]}; ``` * * * ## Examples ### List available providers Retrieves the list of the latest versions of each available provider. ```sql REGISTRY LIST; ``` ### List all versions for a specific provider Retrieves the list of all available versions of a specific provider. ```sql REGISTRY LIST google; ``` ### Install the latest version of a provider ``` REGISTRY PULL okta; ``` ### Install a specific version of a provider ``` REGISTRY PULL azure v23.01.00104; ``` --- # REPLACE > REPLACE in StackQL: replace every field of a resource instance, equivalent to an HTTP PUT, as opposed to the partial update performed by UPDATE. Source: https://stackql.io/language-spec/replace Updates all fields in a resource (synonymous with a `put` operation). See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) [[ `UPDATE` ]](/language-spec/update) * * * ## Syntax *replaceStatement::=*     ```sql REPLACE [ /*+ AWAIT */ ] <multipartIdentifier> SET field_name = value [, field_name = value ...] [ WHERE condition ]; ``` * * * ## Examples ### Basic `REPLACE` statement Run an `REPLACE` statement to modify a Compute Engine Disk resource's size. ```sql -- Update the size of a Compute Engine Disk resource REPLACE google.compute.disks SET sizeGb = 20 WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' AND name = 'test10gbdisk'; ``` ### `REPLACE` statement (blocking) Run an `REPLACE` statement to modify a Compute Engine Disk resource's size. This is a blocking (synchronous) invocation. ```sql -- Synchronous update of a google firewall REPLACE /*+ AWAIT */ google.compute.firewalls SET data__network = 'https://www.googleapis.com/compute/v1/projects/stackql-demo/global/networks/my-vpc', data__direction = 'INGRESS', data__sourceRanges = '["0.0.0.0/0"]', data__allowed = '[{"IPProtocol": "tcp", "ports": ["22"]}, {"IPProtocol": "tcp", "ports": ["6443"]},{"IPProtocol": "icmp"}]' WHERE firewall = 'test-fw' AND project = 'stackql-demo' ``` ### `REPLACE` statement with JSON modification Run an `REPLACE` statement to modify a resource using JSON manipulation. ```sql -- Update an Azure Network Interface's properties REPLACE azure.network.network_interfaces SET data__properties = json_replace( json_remove(data__properties, '$.auxiliarySku', '$.provisioningState', '$.resourceGuid', '$.macAddress' ), '$.ipConfigurations[0].name', 'newIpConfigurationName' ) WHERE subscription_id = '0123456789' AND resource_group_name = 'vmss-flex' AND network_interface_name = 'vmss-nic-01'; ``` --- # SELECT > SELECT in StackQL: query cloud and SaaS resources with SQL, with WHERE filters that map to API parameters, joins, grouping, ordering and JSON field access. Source: https://stackql.io/language-spec/select Returns an instance or instances of a resource. See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) [[` WITH (CTEs) `]](/language-spec/with) [[` Window Functions `]](/language-spec/windowing_functions) * * * ## Syntax *selectStatement::=*     ```sql [ WITH [ RECURSIVE ] <cteName> [ ( <columnList> ) ] AS ( <selectStatement> ) [, ...] ] SELECT { * | <fieldList> | <windowFunctionCall> [ AS <alias> ] } FROM { <multipartIdentifier> | <joinStatement(s)> } [ WHERE <expression> ] [ GROUP BY <fieldList> ] [ HAVING <expression> ] [ WINDOW <windowName> AS ( <windowSpec> ) [, ...] ] [ ORDER BY <fieldList> [ ASC | DESC ] ] [ LIMIT <integer> ] [ UNION <selectStatement> ]; ``` A `JOIN` with no `ON` clause is treated as a `CROSS JOIN`, so the join condition can be given in the `WHERE` clause instead. StackQL releases before `v0.12.732` fail to plan a condition-less `JOIN`. * * * ## Examples ### Basic `SELECT` Statement Run a basic `SELECT` statement in an authenticated session. ```sql -- Selecting all resources deployed within a service using a basic SELECT statement SELECT * FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Returning specified fields using a `SELECT` Statement Run a `SELECT` statement with a column list to return specified fields from a Compute Engine instance. ```sql -- Selecting specified fields from a resource SELECT id, name FROM google.compute.instances WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a'; ``` ### Return a result set ordered by a column in ascending order using the `ORDER BY` clause Run a `SELECT` statement to return fields from the Cloud Storage buckets resource, ordering the results in ascending order (oldest first). ```sql -- Order a list of Cloud Storage buckets by creation time (in ascending order) SELECT name, location, timeCreated FROM google.storage.buckets WHERE project = 'stackql' ORDER BY timeCreated; ``` ### Return a result set ordered by a column in descending order using the `ORDER BY` clause Run a `SELECT` statement to return fields from the Cloud Storage buckets resource, ordering the results in descending order (newest first). ```sql -- Order a list of Cloud Storage buckets by creation time (in descending order) SELECT name, location, timeCreated FROM google.storage.buckets WHERE project = 'stackql' ORDER BY timeCreated DESC; ``` ### Get the top result from a column using the `ORDER BY` and `LIMIT` clauses Run a `SELECT` statement to return the most recently created Cloud Storage bucket. ```sql -- Find the most recently created bucket SELECT name, location, timeCreated FROM google.storage.buckets WHERE project = 'stackql' ORDER BY timeCreated DESC LIMIT 1; ``` ### Use the `COUNT` function with the `GROUP BY` and `HAVING` clauses to count resources based upon a grouping and filter Run a `SELECT` statement with a `COUNT` function, using the `GROUP BY` and `HAVING` clauses to return the number of buckets in every location other than Asia. ```sql -- Return a count of the number of buckets in every location other than Asia SELECT name, location, count(*) as num_buckets FROM google.storage.buckets WHERE project = 'stackql' GROUP BY location HAVING location != 'ASIA'; ``` For more information on the `COUNT` function and other aggregate functions supported by StackQL see [Aggregate Functions](/language-spec/functions/aggregate/count). ### Get list of On Demand VMs and corresponding network interface from Azure VM Scaleset Run a `SELECT` statement using the [`SPLIT_PART`](/language-spec/functions/string/split_part) and [`JSON_EXTRACT`](/language-spec/functions/json/json_extract) functions to get list of OD VMs and their NICs. Note that without a qualifier the subscription_id and resource_group_name is applied to all the three Resources. ```sql SELECT c.name AS vm_name, SPLIT_PART(JSON_EXTRACT(c.properties,'$.networkProfile.networkInterfaces[0].id'), '/', -1) AS nic_name FROM azure.compute.virtual_machine_scale_sets a INNER JOIN azure.compute.virtual_machine_scale_set_vms b ON a.name = b.virtualMachineScaleSetName INNER JOIN azure.compute.virtual_machines c ON b.name = c.name WHERE subscription_id = '0123456789' AND resource_group_name = 'vmss-flex' AND JSON_EXTRACT(c.properties,'$.priority') is null; ``` For more information on window functions, see [Window Functions](/language-spec/windowing_functions). ### Using Common Table Expressions (CTEs) with `WITH` CTEs allow you to define temporary named result sets that can be referenced in the main query. ```sql -- Combine and rank contributors across multiple repositories WITH all_contributors AS ( SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql' UNION ALL SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-deploy' UNION ALL SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-provider-registry' ) SELECT DENSE_RANK() OVER (ORDER BY SUM(contributions) DESC) as rank, login, SUM(contributions) as total_contributions, MAX(html_url) as html_url FROM all_contributors GROUP BY login ORDER BY total_contributions DESC; ``` For more information on CTEs, see [WITH (CTEs)](/language-spec/with). --- # SET > SET in StackQL: assign typed session variables, and configure provider aliases, credential fields and secrets for the current session using dollar-prefixed targets. Source: https://stackql.io/language-spec/set Assigns a session variable, or configures runtime settings for the current session. Available in StackQL `v1.0` and later. See also: [[` UNSET `]](/language-spec/unset) [[ Session Variables ]](/getting-started/session-variables) [[ Provider Sessions ]](/getting-started/provider-sessions) [[` IDENTIFIER `]](/language-spec/functions/general/identifier) * * * ## Syntax *setStatement::=* *setExpression::=*     ```sql SET [ SESSION ] <target> = { <literal> | DEFAULT | <reference> } [, <target> = { <literal> | DEFAULT | <reference> } ...]; ``` __*target*__ A plain identifier (`region`), a double-quoted name (`"providers.saved"`) or a double-quoted, dollar-prefixed configuration path (`"$.auth.aws.password"`). __*literal*__ A string, number, boolean or `null`. Strings are single quoted. Arrays and objects are not scalar values; hold a JSON document as a string. __*DEFAULT*__ Resets the target, equivalent to [`UNSET`](/language-spec/unset). An explicit `null` is a stored value, not a reset. __*reference*__ A double-quoted `"$name"` reference to an existing variable, for example `SET "$.providers.production" = "$providers.saved";`. __*SESSION*__ Optional, and the only scope StackQL has. `SET SESSION name = ...` and `SET name = ...` are the same statement: every assignment belongs to the current session and to nothing else. The keyword exists so that scripts read the same way as they do on databases where `SET SESSION` and `SET GLOBAL` differ. `SET GLOBAL` parses but is rejected with `configuration scope "global" is not supported; use SESSION`, because there is no state shared across sessions. Assignments in one `SET` list apply in order and are not a transaction: if the second assignment in a list fails, the first stays in effect. ## Targets | Target | Effect | |--|--| | `name` or `"name"` | Stores a scalar session variable, dereferenced as `$name` in later statements. Dots alone do not select configuration: `"providers.saved"` is a variable named `providers.saved`. The older `"variables.name"` spelling is an alias for `name`. | | `"$.auth.<provider>.<field>"` | Sets one field of the provider's authentication context for this session. Fields are the keys of the [`--auth`](/command-line-usage/global-flags) object for that provider, for example `credentialsenvvar`, `password` or `token_url`. | | `"$.providers.<alias>"` | Binds a provider alias with its own credentials, tenancy label, parameter defaults and tuning. The value is a JSON document in a string, see [Provider Sessions](/getting-started/provider-sessions#provider-aliases). | | `"$.secrets.<name>"` | Stores a secret in the session's secret store. The value is a literal string, typically a JSON `auth` document, referenced from a provider alias as `auth_secret`. | | `"$.secret_store"` | Selects a persistent OS secret store, `{"backend":"os","namespace":"..."}`. Requires the operator flag `--allow-persistent-secrets`. | Every form affects the current session only. Independent connections to a [`srv`](/command-line-usage/srv) server do not see each other's assignments, and each MCP request is its own session, so configure and query in one statement batch when using the MCP server. * * * ## Examples ### Set session variables Each statement stores one scalar under the given name, and the value keeps its type: `region` is a string, `minimum_count` an integer and `enabled` a boolean. `null` is stored as a value, so `$optional_value` later resolves to SQL `NULL` instead of failing as undefined. The last statement assigns two variables in one list. ```sql SET region = 'ap-southeast-2'; SET minimum_count = 3; SET enabled = true; SET optional_value = null; SET suffix = 'East', some_id = 42; ``` ### Make the session scope explicit The first two statements are identical: `SESSION` names the only scope there is, and both assignments last until the variable is unset or the session ends. Use the keyword when a script should read the same way as it does on a database that distinguishes session from global settings. The commented-out statement is shown for contrast: it assigns nothing and fails with `configuration scope "global" is not supported; use SESSION`, because no state is shared between sessions. ```sql SET region = 'ap-southeast-2'; SET SESSION region = 'ap-southeast-2'; /* SET GLOBAL region = 'ap-southeast-2'; -- FAILS with configuration scope "global" is not supported; use SESSION */ ``` ### Use a variable in a query Dereference a variable with `$name`, without quotes, in any expression position. Values keep their type: strings are escaped as SQL literals, and numbers, booleans and `null` are passed through. Variables in a `WHERE` clause are resolved before the request is planned, so they are pushed to the provider like literals. ```sql SET project = 'stackql-demo'; SET zone = 'australia-southeast1-a'; SELECT name, status FROM google.compute.instances WHERE project = $project AND zone = $zone; ``` ### Reset a variable `DEFAULT` removes the variable, exactly as [`UNSET`](/language-spec/unset) does, so a later `$region` fails with `variable "$region" is not defined` until it is set again; the commented-out query shows that failure. This is different from assigning `null`, which leaves the variable in place with a `NULL` value. ```sql SET region = 'ap-southeast-2'; SET region = DEFAULT; /* SELECT name FROM aws.s3.buckets WHERE region = $region; -- FAILS with variable "$region" is not defined */ ``` ### Copy a value from another variable The right-hand side can be a double-quoted reference to an existing variable, which copies the value it holds at that moment. Here a provider binding is first stored as an ordinary variable named `providers.saved` (the dots do not make it configuration), then activated by copying it to the `$.providers.production` path. Removing the saved copy afterwards does not affect the active binding. ```sql SET "providers.saved" = '{"provider":"aws","tenancy":"production-account","auth":{"type":"aws_signing_v4","access_key_id_env_var":"PRODUCTION_AWS_ACCESS_KEY_ID","secret_access_key_env_var":"PRODUCTION_AWS_SECRET_ACCESS_KEY"}}'; SET "$.providers.production" = "$providers.saved"; UNSET "providers.saved"; ``` ### Override a credential field for this session A provider's authentication context is the object supplied for it through [`--auth`](/command-line-usage/global-flags) at startup. A path under `$.auth` replaces one field of that object for the rest of the session and leaves the other fields as they were. Here the GitHub provider is pointed at a different environment variable, holding a read-only token; the variable is read from the StackQL process environment, and later queries against `github.*` use it until the field is unset or the session ends. ```sql SET "$.auth.github.credentialsenvvar" = 'GITHUB_TOKEN_READONLY'; ``` ### Bind a provider alias A provider alias is a second, independently configured instance of a provider, used in place of the provider name in queries. The value is a JSON document in a string: `provider` names the underlying provider, `tenancy` labels the account, `auth` is a credential block in the same shape as `--auth`, and `params` supplies default values for request parameters such as `region`. Queries against `production.s3.buckets` then run with those credentials, while `aws.s3.buckets` keeps the startup configuration. The full list of keys is in [Provider Sessions](/getting-started/provider-sessions#provider-aliases). ```sql SET "$.providers.production" = '{ "provider": "aws", "tenancy": "production-account", "auth": { "type": "aws_signing_v4", "access_key_id_env_var": "PRODUCTION_AWS_ACCESS_KEY_ID", "secret_access_key_env_var": "PRODUCTION_AWS_SECRET_ACCESS_KEY" }, "params": {"region": "ap-southeast-2"} }'; SELECT name FROM production.s3.buckets; ``` --- # SHOW > SHOW in StackQL: list providers, services, resources and methods, generate INSERT templates, and inspect the running binary's version, contributors and dependencies. Source: https://stackql.io/language-spec/show Used to list items in a collection, for instance show all of the services available in a provider, or show all of the resources available in a given service. Also exposes the running StackQL binary's version, contributors and software dependencies. See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) * * * ## Syntax *showStatement::=*     ```sql SHOW [ EXTENDED ] { PROVIDERS | SERVICES | RESOURCES | METHODS } [ { IN | FROM } { <provider> | <service> | <resource> } ] [ { LIKE <pattern> | WHERE <expression> } ]; SHOW [ EXTENDED ] INSERT INTO <resource>; SHOW [ EXTENDED ] VERSION; SHOW [ EXTENDED ] CONTRIBUTORS; SHOW [ EXTENDED ] DEPENDENCIES [ LIKE '<pattern>' ]; ``` `VERSION`, `CONTRIBUTORS` and `DEPENDENCIES` require no provider or authentication configuration. `DEPENDENCIES` supports an optional `LIKE` clause only; `IN`, `FROM`, `WHERE` and `LIMIT` are not supported. * * * ## Examples ### List all providers List all of the available cloud providers in the installed version of StackQL. ```sql -- Returns all of the available cloud providers SHOW PROVIDERS; ``` **_Returns :_** ``` |----------------------|--------------| | name | version | |----------------------|--------------| | aws | v26.03.00379 | |----------------------|--------------| | databricks_account | v26.03.00381 | |----------------------|--------------| | databricks_workspace | v26.03.00381 | |----------------------|--------------| | google | v25.12.00357 | |----------------------|--------------| | k8s | v24.12.00276 | |----------------------|--------------| ``` ### List all services in a cloud provider List all of the services available within a given cloud provider, use the optional EXTENDED keyword to return additional information. ```sql -- Returns all services available in a cloud provider SHOW EXTENDED SERVICES IN google; ``` **_Returns :_** ``` |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| | id | name | title | description | |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| | compute:v25.12.00357 | compute | Compute Engine API | Creates and runs virtual machines on Google Cloud Platform. | |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| | storage:v25.12.00357 | storage | Cloud Storage API | Stores and retrieves unstructured object data at global sc... | |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| | bigquery:v25.12.00357 | bigquery | BigQuery API | A data platform for customers to create, manage, share and... | |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| | aiplatform:v25.12.00357 | aiplatform | Vertex AI API | Train high-quality custom machine learning models with min... | |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| | geminicloudassist:v25.12.00357 | geminicloudassist | Gemini Cloud Assist API | The AI-powered assistant for Google Cloud. | |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| | ... | ... | ... | ... | |--------------------------------|-------------------|-------------------------|---------------------------------------------------------------| ``` ### List all resources within a cloud provider service List all of the resources available within a given service of a cloud provider. The optional `EXTENDED` keyword returns the resource description in addition to the resource name. ```sql -- Returns all resources available in a cloud provider service SHOW EXTENDED RESOURCES IN google.compute; ``` **_Returns :_** ``` |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| | name | id | description | |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| | instances | google.compute.instances | Virtual machine instances running on Google Cloud Platform...| |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| | disks | google.compute.disks | Persistent block storage volumes attached to compute inst... | |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| | networks | google.compute.networks | Virtual private cloud (VPC) networking resources and conf... | |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| | backend_services | google.compute.backend_services | Backend services used for load balancing and traffic distr...| |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| | firewalls | google.compute.firewalls | Firewall rules controlling ingress and egress network traf...| |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| | ... | ... | ... | |---------------------------------------------------|--------------------------------------------------|--------------------------------------------------------------| ``` ### Show available methods for a resource within a cloud provider service List all of the methods available for a given resource. ```sql -- Returns all methods available for a cloud provider resource SHOW EXTENDED METHODS IN google.compute.instances; ``` **_Returns :_** ``` |----------------------------------------|--------------------------------|---------|---------------------------------------------| | MethodName | RequiredParams | SQLVerb | description | |----------------------------------------|--------------------------------|---------|---------------------------------------------| | list | project, zone | SELECT | Retrieves the list of instances contained...| |----------------------------------------|--------------------------------|---------|---------------------------------------------| | insert | project, zone | INSERT | Creates an instance resource in the speci...| |----------------------------------------|--------------------------------|---------|---------------------------------------------| | delete | instance, project, zone | DELETE | Deletes the specified Instance resource... | |----------------------------------------|--------------------------------|---------|---------------------------------------------| | start | instance, project, zone | EXEC | Starts an instance that was stopped using...| |----------------------------------------|--------------------------------|---------|---------------------------------------------| | stop | instance, project, zone | EXEC | Stops a running instance, shutting it dow...| |----------------------------------------|--------------------------------|---------|---------------------------------------------| | ... | ... | ... | ... | |----------------------------------------|--------------------------------|---------|---------------------------------------------| ``` ### Generating an `INSERT` template using the `SHOW INSERT` command The `SHOW` command can be used to generate templates for `INSERT` statements as shown here: ```sql SHOW INSERT INTO google.compute.addresses; ``` **_Returns :_** ```sql INSERT INTO google.compute.addresses( project, region, data__address, data__addressType, data__description, data__ipVersion, data__name, data__network, data__networkTier, data__prefixLength, data__purpose, data__subnetwork ) SELECT '{{ .values.project }}', '{{ .values.region }}', '{{ .values.data__address }}', '{{ .values.data__addressType }}', '{{ .values.data__description }}', '{{ .values.data__ipVersion }}', '{{ .values.data__name }}', '{{ .values.data__network }}', '{{ .values.data__networkTier }}', {{ .values.data__prefixLength }}, '{{ .values.data__purpose }}', '{{ .values.data__subnetwork }}' ``` > The fields returned can be limited to only those required by the provider, see [__Creating Infrastructure Templates__](/getting-started/templating) for examples of this. > This template can then be used along with a `json` or `jsonnet` data file to supply values at run time,for more information see [__Using Variables__](/getting-started/variables). ### Show the StackQL version Return the version of the running StackQL process. Useful in shell, exec, and Postgres-wire server modes when you need to confirm which build is answering queries. The same information is also surfaced through the MCP `server_info` tool. ```sql -- Returns the version of the running StackQL process SHOW VERSION; ``` **_Returns :_** ``` +---------+ | version | +---------+ | 1.2.3 | +---------+ ``` Use the optional `EXTENDED` keyword to also return the git commit, build timestamp, and build platform: ```sql -- Returns version plus build provenance SHOW EXTENDED VERSION; ``` **_Returns :_** ``` +---------+---------+----------------------+-----------------+ | version | commit | build_date | platform | +---------+---------+----------------------+-----------------+ | 1.2.3 | a1b2c3d | 2026-05-15T04:12:00Z | linux/amd64 | +---------+---------+----------------------+-----------------+ ``` > `SHOW VERSION` requires no provider, registry, or authentication configuration and is safe to issue in any session. ### List StackQL contributors Return the contributor leaderboard embedded in the running StackQL binary. The snapshot credits human GitHub contributors who have starred the StackQL repository, ordered by contribution count, highest first. It is fixed for each build and does not query GitHub at runtime. ```sql SHOW CONTRIBUTORS; SHOW EXTENDED CONTRIBUTORS; ``` | Column | Description | | --- | --- | | `contributor` | GitHub username | | `contributions` | Contribution count recorded in the snapshot; included with `EXTENDED` | ### List the binary's software dependencies Return an offline inventory of the Go modules included in the running StackQL executable. This provides a lightweight software bill of materials (SBOM) for the binary, queryable by users and agents at runtime. It includes direct and transitive Go dependencies; installed provider definitions, separate wrappers, CI tools, test-only modules, container images and operating-system packages are outside its scope. ```sql SHOW DEPENDENCIES; SHOW EXTENDED DEPENDENCIES; ``` The default columns are `name`, `version`, `license` and `description`. `EXTENDED` appends the remaining columns below without changing which rows are returned. | Column | Description | | --- | --- | | `name` | Effective Go module path, using the replacement path when a Go module replacement applies | | `version` | Exact module version, including prerelease and pseudo-versions | | `license` | Detected licence identifier; `UNKNOWN` when unidentified or ambiguous | | `description` | Component description, when available | | `source_url` | Source repository URL; included with `EXTENDED` | | `license_url` | Licence file URL pinned to the module tag or source revision; included with `EXTENDED` | | `purl` | Package URL identifying the module and version; included with `EXTENDED` | | `checksum` | Go module checksum with its `h1:` prefix, not an executable or archive SHA-256 digest; included with `EXTENDED` | | `original_name` | Originally requested module path when a replacement applies; included with `EXTENDED` | | `original_version` | Originally requested version when a replacement applies; included with `EXTENDED` | Rows are sorted by effective module name, then version. Replacements use the replacement's version, checksum and attribution. `original_name` and `original_version` are `NULL` for modules without replacements. Other unavailable metadata is also `NULL`, except that unidentified licences are `UNKNOWN`. Local filesystem replacements have no fabricated version, URLs or checksum. Use `LIKE` to search the effective module name, original module name or description: ```sql SHOW DEPENDENCIES LIKE '%stackql%'; SHOW EXTENDED DEPENDENCIES LIKE '%vitess%'; SHOW EXTENDED DEPENDENCIES LIKE 'github.com/chzyer/readline'; ``` Matching is case-insensitive. `%` matches zero or more characters and `_` matches exactly one character. Licence and version columns are not searched. Double a single quote inside a SQL string literal; after SQL string decoding, backslashes are literal and do not escape `LIKE` wildcards. When no modules match, the result has zero rows. CSV retains the column headers, PostgreSQL wire clients retain column metadata, and JSON output is `null`. The inventory combines metadata embedded at build time with the executable's Go build information. Queries need no network access, Go installation, source checkout or module cache. Builds without generated metadata still report their linked modules, with missing attribution shown as `UNKNOWN` or `NULL`. The output covers the binary's Go dependencies only. It does not include dependency relationships or export an SPDX or CycloneDX document, and is not a complete deployment SBOM or a licence-compliance determination. * * * --- # UNSET > UNSET in StackQL: remove session variables, or clear provider aliases, credential fields and secrets configured with SET for the current session. Source: https://stackql.io/language-spec/unset Removes a session variable, or clears runtime configuration set with [`SET`](/language-spec/set) for the current session. Available in StackQL `v1.0` and later. See also: [[` SET `]](/language-spec/set) [[ Session Variables ]](/getting-started/session-variables) [[ Provider Sessions ]](/getting-started/provider-sessions) * * * ## Syntax *unsetStatement::=*     ```sql UNSET [ SESSION ] <target> [, <target> ...]; ``` __*target*__ Any target accepted by `SET`: a plain or double-quoted variable name, or a double-quoted, dollar-prefixed configuration path. __*SESSION*__ Optional, and the only scope there is: `UNSET SESSION name` and `UNSET name` are the same statement, because every variable and configuration setting belongs to the current session. `UNSET GLOBAL` is rejected with `configuration scope "global" is not supported; use SESSION`. `UNSET name` is equivalent to `SET name = DEFAULT`. Targets in one list are removed in order, and removing a name that is not set is not an error. Dereferencing a variable after it has been unset fails before any provider request is made. | Target | Effect | |--|--| | `name` | Removes the session variable. | | `"$.auth.<provider>.<field>"` | Deletes that field from the provider's session authentication context. The value in force before the override is not restored. | | `"$.providers.<alias>"` | Removes the provider alias binding. | | `"$.secrets.<name>"` | Deletes the secret from the session's store. For a persistent OS store this deletes the stored value. | | `"$.secret_store"` | Discards the current store binding and starts with empty session memory. Values already persisted in an OS store are not deleted. | * * * ## Examples ### Remove a variable The variable is removed from the session, so the commented-out query fails with `variable "$region" is not defined` rather than running with a stale or empty value. Set the name again to reuse it. ```sql SET region = 'ap-southeast-2'; UNSET region; /* SELECT name FROM aws.s3.buckets WHERE region = $region; -- FAILS with variable "$region" is not defined */ ``` ### Remove several targets One statement can remove variables and configuration paths together, and the targets are processed in order. Here a plain variable, a variable with a dotted name and a credential override are removed in one list. ```sql UNSET region, "providers.saved", "$.auth.github.credentialsenvvar"; ``` ### Make the session scope explicit These two statements do the same thing: `SESSION` names the only scope there is. The explicit form suits scripts that also run on databases which distinguish session from global state. The commented-out statement fails because no shared state exists. ```sql UNSET region; UNSET SESSION region; /* UNSET GLOBAL region; -- FAILS with configuration scope "global" is not supported; use SESSION */ ``` ### Clear a credential override The field set earlier with `SET "$.auth.github.credentialsenvvar"` is deleted from the GitHub provider's session authentication context, and the other fields of that context are untouched. The value in force before the override is not restored, so set the field again if the provider still needs it. ```sql UNSET "$.auth.github.credentialsenvvar"; ``` ### Remove a provider alias and its secret The alias `production` was bound with `SET "$.providers.production"` and refers, through `auth_secret`, to a secret stored at `$.secrets.production`. Removing both in one statement drops the binding, so `production.s3.buckets` is no longer a valid relation, and deletes the secret from the session store. `SESSION` is optional here, as everywhere. ```sql UNSET SESSION "$.providers.production", "$.secrets.production"; ``` --- # UPDATE > UPDATE in StackQL: change specified fields of a resource instance, equivalent to an HTTP PATCH, with the target identified by the WHERE clause. Source: https://stackql.io/language-spec/update Updates specified fields in a resource (synonymous with a `patch` operation). See also: [[ StackQL Resource Hierarchy ]](/getting-started/resource-hierarchy) [[ `REPLACE` ]](/language-spec/replace) * * * ## Syntax *updateStatement::=*     ```sql UPDATE [ /*+ AWAIT */ ] <multipartIdentifier> SET field_name = value [, field_name = value ...] [ WHERE condition ]; ``` * * * ## Examples ### Basic `UPDATE` statement Run an `UPDATE` statement to modify a Compute Engine Disk resource's size. ```sql -- Update the size of a Compute Engine Disk resource UPDATE google.compute.disks SET sizeGb = 20 WHERE project = 'stackql-demo' AND zone = 'australia-southeast1-a' AND name = 'test10gbdisk'; ``` ### `UPDATE` statement (blocking) Run an `UPDATE` statement to modify a Compute Engine Disk resource's size. This is a blocking (synchronous) invocation. ```sql -- Synchronous update of a google firewall UPDATE /*+ AWAIT */ google.compute.firewalls SET data__network = 'https://www.googleapis.com/compute/v1/projects/stackql-demo/global/networks/my-vpc', data__direction = 'INGRESS', data__sourceRanges = '["0.0.0.0/0"]', data__allowed = '[{"IPProtocol": "tcp", "ports": ["22"]}, {"IPProtocol": "tcp", "ports": ["6443"]},{"IPProtocol": "icmp"}]' WHERE firewall = 'test-fw' AND project = 'stackql-demo' ``` ### `UPDATE` statement with JSON modification Run an `UPDATE` statement to modify a resource using JSON manipulation. ```sql -- Update an Azure Network Interface's properties UPDATE azure.network.network_interfaces SET data__properties = json_replace( json_remove(data__properties, '$.auxiliarySku', '$.provisioningState', '$.resourceGuid', '$.macAddress' ), '$.ipConfigurations[0].name', 'newIpConfigurationName' ) WHERE subscription_id = '0123456789' AND resource_group_name = 'vmss-flex' AND network_interface_name = 'vmss-nic-01'; ``` --- # Utility Commands > StackQL shell utility commands such as clear and sleep, with their syntax and when to use them in interactive sessions and scripts. Source: https://stackql.io/language-spec/utility-commands StackQL utility commands are listed in the table below: | Utility Command | Description | Example | |--|--|--| | `clear` | Clears the shell of results and commands, does not need to be terminated with a semicolon | `clear` or `CLEAR` | | `sleep n` | Sleeps for `n` milliseconds | `sleep 5000` or `SLEEP 5000` | --- # Window Functions > Window functions in StackQL: ranks, running totals, offsets and distributions across related rows, with PARTITION BY, ORDER BY and frame clauses. Source: https://stackql.io/language-spec/windowing_functions Window functions perform calculations across a set of rows that are related to the current row. Unlike aggregate functions that return a single result for a group of rows, window functions return a value for each row while considering a "window" of related rows. See also: [[` SELECT `]](/language-spec/select) [[` WITH (CTEs) `]](/language-spec/with) [[ Window Function Reference ]](/language-spec/functions/window/row_number) * * * ## Syntax Window functions use the `OVER` clause to define the window specification: ```sql SELECT <windowFunction> OVER ( <windowSpec> ) FROM <multipartIdentifier>; ``` *windowFunctionCall::=* ### Window Function Window functions are specialized functions that perform calculations across a set of rows defined by the window specification. They can be either dedicated window functions (like `ROW_NUMBER` or `LAG`) or aggregate functions (like `SUM` or `COUNT`) used with an `OVER` clause. ```sql { <aggregateFunction> | ROW_NUMBER() | RANK() | DENSE_RANK() | PERCENT_RANK() | CUME_DIST() | NTILE(<int>) | LAG(<expr> [,<offset> [,<default>]]) | LEAD(<expr> [,<offset> [,<default>]]) | FIRST_VALUE(<expr>) | LAST_VALUE(<expr>) | NTH_VALUE(<expr>, <int>) } ``` *windowFunction::=* ### Window Specification The window specification defines how rows are partitioned, ordered, and framed for the window function calculation. `PARTITION BY` divides rows into groups, `ORDER BY` determines the sequence within each partition, and the optional frame clause specifies which rows relative to the current row are included in the calculation. ```sql [ <windowName> ] [ PARTITION BY <fieldList> ] [ ORDER BY <fieldList> [ ASC | DESC ] ] [ { ROWS | RANGE | GROUPS } { UNBOUNDED PRECEDING | <int> PRECEDING | CURRENT ROW } | { ROWS | RANGE | GROUPS } BETWEEN { UNBOUNDED PRECEDING | <int> PRECEDING | CURRENT ROW | <int> FOLLOWING } AND { <int> PRECEDING | CURRENT ROW | <int> FOLLOWING | UNBOUNDED FOLLOWING } ] ``` *windowSpec::=* ## Available Window Functions | Category | Functions | |----------|-----------| | **Ranking** | [__`ROW_NUMBER()`__](/language-spec/functions/window/row_number), [__`RANK()`__](/language-spec/functions/window/rank), [__`DENSE_RANK()`__](/language-spec/functions/window/dense_rank), [__`NTILE()`__](/language-spec/functions/window/ntile) | | **Offset** | [__`LAG()`__](/language-spec/functions/window/lag), [__`LEAD()`__](/language-spec/functions/window/lead), [__`FIRST_VALUE()`__](/language-spec/functions/window/first_value), [__`LAST_VALUE()`__](/language-spec/functions/window/last_value), [__`NTH_VALUE()`__](/language-spec/functions/window/nth_value) | | **Distribution** | [__`PERCENT_RANK()`__](/language-spec/functions/window/percent_rank), [__`CUME_DIST()`__](/language-spec/functions/window/cume_dist) | | **Aggregate** | [__`SUM()`__](/language-spec/functions/aggregate/sum), [__`COUNT()`__](/language-spec/functions/aggregate/count), [__`AVG()`__](/language-spec/functions/aggregate/avg), [__`MIN()`__](/language-spec/functions/aggregate/min), [__`MAX()`__](/language-spec/functions/aggregate/max) with the __`OVER`__ clause | * * * ## Examples ### Ranking with `ROW_NUMBER`, `RANK`, and `DENSE_RANK` Use ranking functions to assign rankings to rows based on column values. ```sql -- Rank contributors by contribution count SELECT login, contributions, ROW_NUMBER() OVER (ORDER BY contributions DESC) as row_num, RANK() OVER (ORDER BY contributions DESC) as rank, DENSE_RANK() OVER (ORDER BY contributions DESC) as dense_rank FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` ### Running totals and percentages Aggregate functions like `SUM` and `COUNT` can be used as window functions to calculate running totals and percentages. ```sql -- Running total and percentage of contributions SELECT login, contributions, SUM(contributions) OVER (ORDER BY contributions DESC) as running_total, SUM(contributions) OVER () as total_contributions, ROUND(100.0 * contributions / SUM(contributions) OVER (), 2) as pct_of_total FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` ### Comparing rows with `LAG` and `LEAD` Use `LAG` and `LEAD` to access values from previous or subsequent rows. ```sql -- Compare each release to previous release SELECT tag_name, name, published_at, LAG(tag_name, 1) OVER (ORDER BY published_at) as previous_release, LEAD(tag_name, 1) OVER (ORDER BY published_at) as next_release, julianday(published_at) - julianday(LAG(published_at, 1) OVER (ORDER BY published_at)) as days_since_last_release FROM github.repos.releases WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY published_at; ``` ### Creating groups with `NTILE` Use `NTILE` to divide rows into a specified number of groups. ```sql -- Group contributors into quartiles SELECT login, contributions, NTILE(4) OVER (ORDER BY contributions DESC) as quartile, CASE NTILE(4) OVER (ORDER BY contributions DESC) WHEN 1 THEN 'Top Contributors' WHEN 2 THEN 'Active Contributors' WHEN 3 THEN 'Moderate Contributors' WHEN 4 THEN 'Occasional Contributors' END as tier FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql'; ``` ### Using `PARTITION BY` for grouped analysis Use `PARTITION BY` to perform window calculations within groups. ```sql -- Track cumulative issues by state SELECT number, title, state, created_at, ROW_NUMBER() OVER (ORDER BY created_at) as issue_sequence, COUNT(*) OVER (ORDER BY created_at) as cumulative_issues, COUNT(*) OVER (PARTITION BY state ORDER BY created_at) as cumulative_by_state FROM github.issues.issues WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY created_at; ``` ### Using window frames Specify a frame clause to control which rows are included in the window calculation. ```sql -- Calculate moving average of commit activity WITH weekly_totals AS ( SELECT week, SUM(json_each.value) as commits_this_week FROM github.repos.stats_commit_activity, JSON_EACH(days) WHERE owner = 'stackql' AND repo = 'stackql' GROUP BY week ) SELECT week, commits_this_week, ROUND(AVG(commits_this_week) OVER (ORDER BY week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW), 1) as four_week_moving_avg, SUM(commits_this_week) OVER (ORDER BY week) as cumulative_commits FROM weekly_totals ORDER BY week; ``` For detailed documentation on each window function, see the [Window Function Reference](/language-spec/functions/window/row_number). For more information, see [https://sqlite.org/windowfunctions.html](https://sqlite.org/windowfunctions.html). --- # WITH (CTEs) > WITH in StackQL: define common table expressions (CTEs), temporary named result sets scoped to a single SELECT, INSERT, UPDATE or DELETE statement. Source: https://stackql.io/language-spec/with Defines a Common Table Expression (CTE) for use in a subsequent `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement. CTEs act as temporary named result sets that exist only for the duration of the query. See also: [[` SELECT `]](/language-spec/select) [[` INSERT `]](/language-spec/insert) [[` UPDATE `]](/language-spec/update) [[` DELETE `]](/language-spec/delete) * * * ## Syntax *withClause::=* *cteDefinition::=*     ```sql WITH [RECURSIVE] cte_name [(column_name, ...)] AS ( select_statement ) [, cte_name [(column_name, ...)] AS ( select_statement )] SELECT ... FROM cte_name ...; ``` ## Arguments __*RECURSIVE*__ Optional keyword that enables the CTE to reference itself, allowing for recursive queries such as traversing hierarchical data. __*cte_name*__ The name assigned to the CTE. This name can be referenced in the main query as if it were a table. __*column_name*__ Optional. Column names for the CTE result set. If not specified, column names are derived from the SELECT statement. __*select_statement*__ The query that defines the CTE's result set. ## Return Value(s) CTEs do not return values directly. They define temporary result sets that can be referenced in the main query. * * * ## Examples ### Basic CTE for organizing complex queries A CTE can simplify complex queries by breaking them into logical, named components. ```sql -- Calculate moving average of commit activity WITH weekly_totals AS ( SELECT week, SUM(json_each.value) as commits_this_week FROM github.repos.stats_commit_activity, JSON_EACH(days) WHERE owner = 'stackql' AND repo = 'stackql' GROUP BY week ) SELECT week, commits_this_week, ROUND(AVG(commits_this_week) OVER (ORDER BY week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW), 1) as four_week_moving_avg, SUM(commits_this_week) OVER (ORDER BY week) as cumulative_commits FROM weekly_totals ORDER BY week; ``` ### Combining data from multiple sources with `UNION ALL` CTEs are useful for combining data from multiple sources before performing analysis. ```sql -- Rank total contributions across multiple repos WITH all_contributors AS ( SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql' UNION ALL SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-deploy' UNION ALL SELECT login, contributions, html_url FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-provider-registry' ) SELECT DENSE_RANK() OVER (ORDER BY SUM(contributions) DESC) as rank, login, SUM(contributions) as total_contributions, MAX(html_url) as html_url FROM all_contributors GROUP BY login ORDER BY total_contributions DESC; ``` ### Using CTEs with window functions for ranking ```sql -- Rank contributors within each repo using CTE and window functions WITH repo_contributors AS ( SELECT repo, login, contributions, RANK() OVER (PARTITION BY repo ORDER BY contributions DESC) as rank_in_repo, SUM(contributions) OVER (PARTITION BY repo) as repo_total_contributions FROM ( SELECT 'stackql' as repo, login, contributions FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql' UNION ALL SELECT 'stackql-provider-registry' as repo, login, contributions FROM github.repos.contributors WHERE owner = 'stackql' AND repo = 'stackql-provider-registry' ) t ) SELECT repo, login, contributions, rank_in_repo FROM repo_contributors ORDER BY repo, rank_in_repo; ``` ### Multiple CTEs in a single query You can define multiple CTEs separated by commas. ```sql -- Analyze issues and releases together WITH open_issues AS ( SELECT number, title, created_at FROM github.issues.issues WHERE owner = 'stackql' AND repo = 'stackql' AND state = 'open' ), recent_releases AS ( SELECT tag_name, published_at FROM github.repos.releases WHERE owner = 'stackql' AND repo = 'stackql' ORDER BY published_at DESC LIMIT 5 ) SELECT 'Open Issues' as category, COUNT(*) as count FROM open_issues UNION ALL SELECT 'Recent Releases' as category, COUNT(*) as count FROM recent_releases; ``` ## Recursive CTEs Recursive CTEs allow a CTE to reference itself, enabling queries that traverse hierarchical or graph-like data structures. ```sql WITH RECURSIVE cte_name (columns) AS ( -- Base case (anchor member) SELECT ... UNION ALL -- Recursive case (references cte_name) SELECT ... FROM cte_name WHERE ... ) SELECT * FROM cte_name; ``` :::tip Recursive CTEs are powerful for hierarchical data like organizational charts, file systems, or dependency trees. Always include a termination condition in the recursive case to prevent infinite loops. ::: ## Best Practices 1. **Use CTEs for readability**: Break complex queries into logical, named components. 2. **Combine with window functions**: CTEs work well with window functions for advanced analytics. 3. **Chain multiple CTEs**: Reference earlier CTEs in later ones to build up complex logic step by step. 4. **Consider performance**: While CTEs improve readability, very large CTEs may impact performance. Test with your actual data volumes. For more information, see [https://sqlite.org/lang_with.html](https://sqlite.org/lang_with.html). --- # MCP Tools > All tools exposed by the StackQL MCP server, grouped by purpose Source: https://stackql.io/mcp [](https://claude.ai/directory/ant.dir.gh.stackql.stackql) [ LISTED ON **GitHub MCP Registry** ](https://github.com/mcp?search=stackql) --- # describe_method > MCP tool returning the full I/O contract for one StackQL access method Source: https://stackql.io/mcp/describe_method Returns the full I/O contract for a single access method -- always EXTENDED, meaning inputs, request body schema, and full output shape. This is where an agent gets column names: each row carries a `param_type` of `input_required` (a mandatory, exact-match `WHERE` predicate), `input_optional`, or `output` (a field a `SELECT` or `RETURNING` can reference). A resource has no single field list, because each method returns its own shape, so call this for the method chosen from [`list_methods`](/mcp/list_methods) before the first query against it. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_methods` ]](/mcp/list_methods) [[ `run_select_query` ]](/mcp/run_select_query) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`provider`|Yes|Provider name.| |`service`|Yes|Service under that provider.| |`resource`|Yes|Resource under `provider.service`.| |`method`|Yes|Method name as returned by [`list_methods`](/mcp/list_methods).| :::info Identifiers may not contain whitespace, semicolons or backslashes; such input is refused before any statement is built. ::: * * * ## Output | Renderer | Shape | |--|--| | KV | One row per input and output field: name, type, `param_type` (`input_required`, `input_optional` or `output`), shape and description | * * * ## Gating Allowed in every server mode. Read only. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` Show me everything I need to know to call the insert method on Google Compute networks -- required parameters, optional parameters, and the request body shape. ``` Here's an example in Claude Desktop: --- # Embedded MCP Servers > Embed the StackQL MCP server directly in compiled applications across Go, Rust, Swift, and Kotlin Source: https://stackql.io/mcp/embedded StackQL's MCP server can be embedded directly in compiled applications - no `npx`, no separate install, no runtime dependency. The signed binary is downloaded and verified on first run (sidecar mode) or vendored into your app binary for a single self-contained executable. All four libraries share one contract: `read_only` mode by default, a cwd-independent launch, a shared binary cache at `~/.stackql/mcp-server-bin/`, and the same four platform targets (`linux-x64`, `linux-arm64`, `windows-x64`, `darwin-universal`). Native Windows ARM64 [CLI and MCPB downloads](/installing-stackql) are also available. The Go, Rust and .NET platform resolvers shipped in v0.12.778 still select only `windows-x64` on Windows; the new bundle does not add automatic ARM64 selection to those libraries. ## Common contract - Default `read_only` mode, with explicit opt-in to `safe`, `delete_safe`, or `full_access`. - The binary is Apple-notarised on macOS and Authenticode-signed on Windows. - sha256 pins are published per release. - mcp-name `io.github.stackql/stackql-mcp` on the Official MCP Registry. See the [MCP tools reference](/mcp) and the [install vectors](/installing-stackql). --- # .NET / C# > Embed the StackQL MCP server in a .NET application as a sidecar or vendored bundle Source: https://stackql.io/mcp/embedded/dotnet Embed the StackQL MCP server in a .NET application, either as a downloaded sidecar or vendored into your build as a self-contained executable. The client is the official C# MCP SDK. :::info The embedded binary is downloaded and sha256-verified on first run, or vendored into your app. See the [common contract](/mcp/embedded#common-contract). ::: * * * ## Install ``` dotnet add package StackQL.Mcp ``` An optional `StackQL.Mcp.AgentFramework` package adds Agent Framework integration. Requires .NET 8 or later. * * * ## Quick start ```csharp using StackQL.Mcp; await using var server = await StackqlMcp.CreateBuilder() .WithMode(StackqlMode.ReadOnly) .WithAuth("github", "null_auth") .StartAsync(); var tools = await server.ListToolsAsync(); var result = await server.CallToolAsync("list_services", new() { ["provider"] = "github", ["row_limit"] = 5 }); ``` The API is `StackqlMcp.CreateBuilder()` with `.WithMode()`, `.WithAuth()`, `.WithBinary()`, `.WithBundlePath()`, `.WithApproot()`, and `.WithCommand()`, then `.StartAsync()`, `.ListToolsAsync()`, and `.CallToolAsync()`. * * * ## Modes The builder defaults to `StackqlMode.ReadOnly`. Call `.WithMode()` with `StackqlMode.Safe`, `StackqlMode.DeleteSafe`, or `StackqlMode.FullAccess` to escalate. Escalation is explicit - the server will not enable mutation or lifecycle tools unless you opt in. * * * ## Vendoring / embedding Two ways to source the binary: - **Sidecar (default)** - the platform bundle is downloaded on first run, sha256-verified, cached at `~/.stackql/mcp-server-bin/<version>/<platform-key>/`, and spawned over stdio. - **Vendored** - embed the bundle as a build resource to produce a self-contained executable: ``` dotnet build -p:StackqlVendorBundle=/path/to/stackql-mcp-windows-x64.mcpb ``` You can also override the binary or bundle at runtime with the `STACKQL_MCP_BIN` or `STACKQL_MCP_BUNDLE` environment variables. * * * ## Demo app **driftwatch** is a .NET Worker Service that embeds the read-only StackQL server and, on a schedule, runs a suite of SQL drift checks (public exposure, missing tags or licenses, baseline drift) and posts the findings to a Teams Adaptive Card. * * * ## Repo link [github.com/stackql/stackql-mcp-dotnet](https://github.com/stackql/stackql-mcp-dotnet) --- # Gleam > Embed the StackQL MCP server in a Gleam application on the Erlang/BEAM target Source: https://stackql.io/mcp/embedded/gleam Embed the StackQL MCP server in a Gleam application on the Erlang/BEAM target. The library integrates with OTP supervision, downloads and verifies the signed binary, and spawns it over stdio. :::info The embedded binary is downloaded and sha256-verified on first run, or vendored into your app. See the [common contract](/mcp/embedded#common-contract). ::: * * * ## Install ``` gleam add stackql_mcp ``` Targets Erlang/BEAM only (not the JavaScript target). The server is exposed as an OTP child via `child_spec()` so it can sit inside your own supervision tree. * * * ## Quick start ```gleam import gleam/io import gleam/int import gleam/list import envoy import stackql_mcp pub fn main() { let config = stackql_mcp.Config( ..stackql_mcp.default_config(), auth: [stackql_mcp.auth_for("github", "null_auth")], ) let assert Ok(server) = stackql_mcp.start( config: config, home: "/home/u", os: "linux", arch: "x86_64", getenv: envoy.get, ) let assert Ok(tools) = stackql_mcp.list_tools(server) io.println(int.to_string(list.length(tools)) <> " tools available") stackql_mcp.stop(server) } ``` The API is `stackql_mcp.start()`, `stop()`, and `child_spec()` for lifecycle; `list_tools()` and `call_tool()` for operations (with `supervised_list_tools()` and `supervised_call_tool()` variants for use under a supervisor); and `Config`, `default_config()`, and `auth_for()` for configuration. * * * ## Modes The mode is set on `Config.mode` and defaults to `read_only`. Set it to `safe`, `delete_safe`, or `full_access` to escalate: ```gleam stackql_mcp.Config(..stackql_mcp.default_config(), mode: stackql_mcp.safe) ``` Escalation is explicit - the server will not enable mutation or lifecycle tools unless you opt in. * * * ## Vendoring / embedding On start the library downloads the platform's StackQL bundle, verifies it against baked-in sha256 pins, and caches it in the shared family cache. Resolution precedence: 1. Explicit `Config.binary`. 2. `STACKQL_MCP_BIN` environment variable. 3. Shared cache at `~/.stackql/mcp-server-bin/<version>/<platform-key>/`. For offline or air-gapped deployments, set `STACKQL_MCP_BUNDLE` to point at a local bundle. * * * ## Demo app **pipewatch** is the planned demo for this library. It is on the roadmap and not yet implemented. * * * ## Repo link [github.com/stackql/stackql-mcp-gleam](https://github.com/stackql/stackql-mcp-gleam) --- # Go > Embed the StackQL MCP server in a Go application via go:embed or sidecar Source: https://stackql.io/mcp/embedded/go Embed the StackQL MCP server in a compiled Go application, either as a downloaded sidecar or vendored into your binary with `go:embed`. The client is the official Go MCP SDK. :::info The embedded binary is downloaded and sha256-verified on first run, or vendored into your app. See the [common contract](/mcp/embedded#common-contract). ::: * * * ## Install ``` go get github.com/stackql/stackql-mcp-go ``` * * * ## Quick start ```go import ( "context" "github.com/modelcontextprotocol/go-sdk/mcp" stackqlmcp "github.com/stackql/stackql-mcp-go/embed" ) func main() { ctx := context.Background() client, err := stackqlmcp.StartServer(ctx, stackqlmcp.Options{ Binary: StackqlMCPBinary(), }) if err != nil { // handle error } defer client.Close() res, err := client.Session.CallTool(ctx, &mcp.CallToolParams{ Name: "run_select_query", Arguments: map[string]any{"sql": "SELECT name FROM google.compute.regions WHERE project = 'my-project'"}, }) _ = res } ``` The API is `StartServer(ctx, Options{Binary, Mode})`; the returned client comes from the official Go MCP SDK. * * * ## Modes The server starts in `read_only` mode by default. Set `Options.Mode` to escalate to `safe`, `delete_safe`, or `full_access`. Escalation is explicit - the server will not enable mutation or lifecycle tools unless you opt in. * * * ## Vendoring / embedding Vendor the binary with `go:embed` via a `go:generate` fetch step, producing a single self-contained executable: ``` //go:generate go run github.com/stackql/stackql-mcp-go/cmd/stackql-mcp-fetch -platform auto -package main ``` The fetch step downloads and sha256-verifies the signed binary for the target platform, then writes it where `go:embed` can pull it into your build. At runtime `StackqlMCPBinary()` returns the embedded binary so there is no first-run download. * * * ## Demo app **sandboxctl** is an infrastructure concierge: an embedded server plus a Claude agent loop in one binary that plans, cost-checks, and provisions ephemeral cloud sandboxes behind an approval gate. * * * ## Repo link [github.com/stackql/stackql-mcp-go](https://github.com/stackql/stackql-mcp-go) --- # Kotlin / JVM > Embed the StackQL MCP server in a Kotlin/JVM application as a library or Gradle plugin Source: https://stackql.io/mcp/embedded/kotlin Embed the StackQL MCP server in a Kotlin or JVM application, as a library or a Gradle plugin. The client is the official Kotlin MCP SDK. :::info The embedded binary is downloaded and sha256-verified on first run, or vendored into your app. See the [common contract](/mcp/embedded#common-contract). ::: * * * ## Install Add the `io.stackql:stackql-mcp` library: ```kotlin dependencies { implementation("io.stackql:stackql-mcp:0.1.0") } ``` Requires JDK 17 and Kotlin 2.x. The client comes from the official Kotlin MCP SDK. * * * ## Quick start ```kotlin import io.stackql.mcp.LaunchArgs import io.stackql.mcp.Mode import io.stackql.mcp.StackqlMcp suspend fun main() { val server = StackqlMcp.builder() .mode(Mode.ReadOnly) .auth(LaunchArgs.authFor("github", "null_auth")) .start() server.use { val tools = server.client.listTools().tools println("${tools.size} tools available") } } ``` The API is `StackqlMcp.builder()` with `.mode()`, `.auth()`, and `.start()`, the `Mode` enum, and `LaunchArgs.authFor()`. * * * ## Modes The builder defaults to `Mode.ReadOnly`. Call `.mode()` with `Mode.Safe`, `Mode.DeleteSafe`, or `Mode.FullAccess` to escalate. Escalation is explicit - the server will not enable mutation or lifecycle tools unless you opt in. * * * ## Vendoring / embedding The library downloads, verifies, and caches the signed binary in the shared cache at `~/.stackql/mcp-server-bin/`, independent of the working directory. The Gradle plugin wires the same launch into your build, so CI tasks can run StackQL queries without a separate install step. * * * ## Demo app **costgate** gates infrastructure deploys on cost budgets. It ships both as a CLI and as a Gradle plugin. As a CLI: ```bash costgate check --intent examples/costgate.yaml --explain ``` As a Gradle plugin: ```kotlin plugins { id("io.stackql.costgate") version "0.1.0" } costgate { intent.set(layout.projectDirectory.file("costgate.yaml")) explain.set(true) } ``` * * * ## Repo link [github.com/stackql/stackql-mcp-kotlin](https://github.com/stackql/stackql-mcp-kotlin) --- # Rust > Embed the StackQL MCP server in a Rust application via sidecar or include_bytes! vendoring Source: https://stackql.io/mcp/embedded/rust Embed the StackQL MCP server in a Rust application, either as a downloaded sidecar or vendored into your binary with `include_bytes!`. The client is `rmcp`. :::info The embedded binary is downloaded and sha256-verified on first run, or vendored into your app. See the [common contract](/mcp/embedded#common-contract). ::: * * * ## Install Add the `stackql-mcp` crate: ```toml stackql-mcp = "0.1" ``` * * * ## Quick start ```rust use stackql_mcp::{Mode, StackqlMcp}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let server = StackqlMcp::builder() .mode(Mode::ReadOnly) .auth(serde_json::json!({"github": {"type": "null_auth"}})) .start() .await?; let tools = server.list_all_tools().await?; println!("{} tools available", tools.len()); server.shutdown().await?; Ok(()) } ``` The API is `StackqlMcp::builder()` with `.mode()`, `.auth()`, `.binary()`, `.bundle_path()`, `.approot()`, `.command()`, `.start()`, and `.shutdown()`, plus `.list_all_tools()`. MSRV is Rust 1.88. * * * ## Modes The builder defaults to `Mode::ReadOnly`. Call `.mode()` with `Mode::Safe`, `Mode::DeleteSafe`, or `Mode::FullAccess` to escalate. Escalation is explicit - the server will not enable mutation or lifecycle tools unless you opt in. * * * ## Vendoring / embedding Two feature flags control how the binary is sourced: - `sidecar` (default) - download, verify, and cache the signed binary on first run. - `vendored` - embed the binary with `include_bytes!` for a single self-contained executable. The vendored binary adds roughly 80 MB to the build. * * * ## Demo app **auditron** is a terminal compliance copilot: a TUI that streams pass/fail results with the SQL shown and Claude explanations, shipped as an ~80 MB vendored single binary. * * * ## Repo link [github.com/stackql/stackql-mcp-rs](https://github.com/stackql/stackql-mcp-rs) --- # Swift > Bundle the notarised StackQL MCP server binary inside a signed macOS app Source: https://stackql.io/mcp/embedded/swift Embed the StackQL MCP server in a macOS application. The signed, notarised binary can be bundled inside your `.app`, and the client is the official Swift MCP SDK. :::info The embedded binary is downloaded and sha256-verified on first run, or vendored into your app. See the [common contract](/mcp/embedded#common-contract). ::: * * * ## Install Add the package to your `Package.swift`: ```swift .package(url: "https://github.com/stackql/stackql-mcp-swift.git", from: "0.1.0") ``` Requires macOS 13+ and Swift 6.1 (Xcode 16.3+). The single dependency is the official Swift MCP SDK. * * * ## Quick start ```swift import StackQLMCP var options = Options() options.mode = .readOnly options.auth = ["github": ["type": "null_auth"]] let server = try await StackQLServer.start(options) let tools = try await server.listToolNames() print("\(tools.count) tools available") let services = try await server.call( "list_services", ["provider": "github", "row_limit": 5]) print(services.text) await server.stop() ``` The API is `StackQLServer.start(Options)`, `.listToolNames()`, `.call(_:_:)`, and `.stop()`. `Options` carries `mode`, `auth`, `binaryOverride`, and `allowDownload`. For external harnesses, `StackQLServer.resolveCommand(_:)` returns the resolved launch command. * * * ## Modes `Options.mode` defaults to `.readOnly`. Set it to `.safe`, `.deleteSafe`, or `.fullAccess` to escalate. Escalation is explicit - the server will not enable mutation or lifecycle tools unless you opt in. * * * ## Vendoring / embedding The `darwin-universal` binary is Developer ID signed and Apple-notarised, so it can be bundled inside a signed macOS `.app` while keeping the app's own notarisation valid. This is unique to the Swift library - you ship one self-contained, notarised application with no first-run download. Binary resolution order: 1. Explicit `binaryOverride`. 2. Bundled `.app` resources. 3. Shared cache at `~/.stackql/mcp-server-bin/`. 4. Download with sha256 verification (when `allowDownload` is set). * * * ## Demo app **CloudLens** is a menu-bar cloud sentinel that embeds the notarised binary and runs a `read_only` check suite. * * * ## Repo link [github.com/stackql/stackql-mcp-swift](https://github.com/stackql/stackql-mcp-swift) --- # list_methods > MCP tool listing access methods for a StackQL resource Source: https://stackql.io/mcp/list_methods Returns the access methods (HTTP operations) bound to a resource -- the read methods, mutations, and lifecycle operations available. This is the tool an agent should call **before writing any query**, because the required `WHERE` parameters are inferred from the chosen read method. Pick the method whose SQL verb matches the intent and whose required parameters can be supplied, then call [`describe_method`](/mcp/describe_method) on it for the full contract, including the output fields. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_resources` ]](/mcp/list_resources) [[ `describe_method` ]](/mcp/describe_method) [[ `validate_select_query` ]](/mcp/validate_select_query) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`provider`|Yes|Provider name.| |`service`|Yes|Service under that provider.| |`resource`|Yes|Resource under `provider.service`.| :::info Identifiers may not contain whitespace, semicolons or backslashes; such input is refused before any statement is built. ::: * * * ## Output | Renderer | Shape | |--|--| | Table | One row per access method, including the SQL verb it maps to and the required parameters | * * * ## Gating Allowed in every server mode. Read only. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` For Google Compute instances, what methods are available and what parameters are required? ``` Here's an example in Claude Desktop: --- # list_providers > MCP tool listing cloud and SaaS providers available to the StackQL MCP server Source: https://stackql.io/mcp/list_providers Returns the providers already pulled into the local StackQL cache -- the top of the StackQL [resource hierarchy](/getting-started/resource-hierarchy). Use this as the entry point when an agent needs to discover what it can query. For providers available in the *registry* (including ones not yet pulled), see [`list_registry`](/mcp/list_registry). See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_services` ]](/mcp/list_services) [[ `list_registry` ]](/mcp/list_registry) [[ `pull_provider` ]](/mcp/pull_provider) * * * ## Inputs None. * * * ## Output | Renderer | Shape | |--|--| | Table (markdown table for the LLM) | One row per provider | Each row carries the provider name and version metadata as published by the registry. * * * ## Gating Allowed in every server mode (`read_only`, `safe`, `delete_safe`, `full_access`). Read only. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` Which cloud providers are available for you to query right now? ``` Here's an example in Claude Desktop: --- # list_registry > MCP tool listing providers and versions available in the StackQL provider registry Source: https://stackql.io/mcp/list_registry Returns the providers (and their versions) available in the configured StackQL provider registry. Distinct from [`list_providers`](/mcp/list_providers), which only reports providers already pulled into the local cache. Pass the optional `provider` argument to list the published versions for a single provider. Pair with [`pull_provider`](/mcp/pull_provider) when the agent needs to install something that is not yet local. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_providers` ]](/mcp/list_providers) [[ `pull_provider` ]](/mcp/pull_provider) [[ Registry command ]](/command-line-usage/registry) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`provider`|No|Provider name. When supplied, the result is narrowed to that provider's published versions; when omitted, every registry entry is returned.| * * * ## Output | Renderer | Shape | |--|--| | Table | One row per registry entry (provider plus version metadata) | * * * ## Gating Allowed in every server mode. No cloud control or data plane effect -- only the registry is read. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` What providers does the StackQL registry offer, and which versions of the aws provider are published? ``` Here's an example in Claude Desktop: --- # list_resources > MCP tool listing resources under a StackQL provider.service Source: https://stackql.io/mcp/list_resources Returns the resources under a `provider.service` -- the third level of the StackQL [resource hierarchy](/getting-started/resource-hierarchy). Resources are the targets that appear in the `FROM` clause of a StackQL query. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_services` ]](/mcp/list_services) [[ `list_methods` ]](/mcp/list_methods) [[ `describe_method` ]](/mcp/describe_method) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`provider`|Yes|Provider name.| |`service`|Yes|Service under that provider.| :::info Identifiers may not contain whitespace, semicolons or backslashes; such input is refused before any statement is built. ::: * * * ## Output | Renderer | Shape | |--|--| | Table | One row per resource under `provider.service` | * * * ## Gating Allowed in every server mode. Read only. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` List the resources in the google.storage service ``` Here's an example in Claude Desktop: --- # list_services > MCP tool listing services under a StackQL provider Source: https://stackql.io/mcp/list_services Returns the services exposed by a single provider -- the second level of the StackQL [resource hierarchy](/getting-started/resource-hierarchy). Call this after [`list_providers`](/mcp/list_providers) to narrow the surface area before drilling into resources. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_providers` ]](/mcp/list_providers) [[ `list_resources` ]](/mcp/list_resources) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`provider`|Yes|Provider name (e.g., `google`, `aws`, `azure`, `github`).| :::info Identifiers may not contain whitespace, semicolons or backslashes; such input is refused before any statement is built. ::: * * * ## Output | Renderer | Shape | |--|--| | Table | One row per service under the given provider | * * * ## Gating Allowed in every server mode. Read only. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` List the services available in Google Cloud ``` Here's an example in Claude Desktop: --- # pull_provider > MCP tool installing a StackQL provider from the registry into the local cache Source: https://stackql.io/mcp/pull_provider Installs a single provider from the StackQL registry into the local approot cache. When `version` is omitted, the latest published version is pulled. Writes only local cache state -- there is no cloud control or data plane effect, so this tool is allowed in every server mode (including `read_only`). Use [`list_registry`](/mcp/list_registry) to discover the provider name and the versions available before pulling. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_registry` ]](/mcp/list_registry) [[ `list_providers` ]](/mcp/list_providers) [[ Registry command ]](/command-line-usage/registry) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`provider`|Yes|Provider name as published in the registry (e.g., `aws`, `google`, `cloudflare`).| |`version`|No|Published version to pull. When omitted, the latest published version is installed.| * * * ## Output | Renderer | Shape | |--|--| | KV | Confirmation that the provider (and version) has been installed into the local cache | * * * ## Gating Allowed in every server mode. No cloud-side effects; only local cache state changes. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` I want to start querying Google resources with StackQL. Can you install the Google provider for me? ``` Here's an example in Claude Desktop: --- # query_library_get > MCP tool retrieving a StackQL query template and validating supplied parameters to return rendered SQL without execution Source: https://stackql.io/mcp/query_library_get Retrieves a [query library](pathname:///docs/query-library/) entry by an `id` returned from [`query_library_search`](/mcp/query_library_search). With `params` omitted or empty, it returns the raw template, parameter declarations and notes. With a non-empty `params` object, the server validates the values and substitutes them into the template. It returns SQL only when rendering succeeds. The model does not need to substitute values itself. This tool does not execute SQL or check cloud credentials. Its parameter validation is distinct from [`validate_select_query`](/mcp/validate_select_query), which parses and plans a `SELECT` against the installed provider. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `query_library_search` ]](/mcp/query_library_search) [[ `run_select_query` ]](/mcp/run_select_query) [[ `run_mutation_query` ]](/mcp/run_mutation_query) [[ `run_lifecycle_operation` ]](/mcp/run_lifecycle_operation) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`id`|Yes|Query ID from search results, for example `aws/s3/buckets-list`.| |`params`|No|Object mapping declared parameter names to values. Omit it or pass `{}` to inspect the template without rendering.| |`format`|No|Text rendering: `markdown` or `json`. When omitted, uses the server's render setting (`markdown` by default).| Unknown parameters are rejected. Required parameters without supplied values or defaults are reported in `missing_params`. Supplied values are checked against declared types and constraints; unresolved placeholders are errors. * * * ## Output The default text view is a KV block with identity, mutation status, the next tool, validity, source links and any template, rendered SQL or errors. Use the structured payload or `format: "json"` for the full metadata: | Field | Description | |--|--| |`id`, `title`, `description`|Entry identity and summary.| |`mutation`, `verb`|Whether the entry changes resources and, when declared, its operation type (`select`, `mutation` or `lifecycle`).| |`next_tool`|Execution tool for the entry: `run_select_query`, `run_mutation_query` or `run_lifecycle_operation`. Retrieval does not call it.| |`params`|Parameter declarations with names, types, required flags and any defaults, descriptions, examples, enums or patterns.| |`template`, `notes`|Raw template and author notes, returned when `params` is omitted or empty.| |`rendered`, `valid`|Whether rendering was attempted and succeeded. Both are `false` when inspecting the raw template.| |`sql`|Rendered SQL, present only after successful rendering.| |`missing_params`, `unknown_params`, `errors`|Validation details when rendering fails. Do not execute SQL until these are resolved.| |`auth`, `permissions`|When declared, credential environment variables and provider-native permissions needed for execution. Retrieval itself requires neither.| |`cost`, `outputs`, `related`|When declared, fan-out and expense hints, result column descriptions and related entry IDs.| |`doc_url`|Human-readable library page.| |`source_tier`, `source_url`, `stale`|Content provenance: `primary`, `fallback` or `snapshot`, its URL or embedded path, and whether content was served from cache or snapshot after a fetch failure.| An unknown or malformed ID returns an error. Use `query_library_search` to find valid IDs. * * * ## Gating Allowed in every server mode, subject to the configured tool allowlist. Retrieving or rendering a mutation or lifecycle template has no cloud-side effect and needs no approval. Executing the returned SQL is a separate call governed by the server [mode](/command-line-usage/mcp#server-modes). * * * ## Example First inspect an entry: ```json { "id": "aws/s3/buckets-list" } ``` Then supply its required routing region: ```json { "id": "aws/s3/buckets-list", "params": { "region": "us-east-1" } } ``` After checking `rendered` and `valid`, validate the returned `SELECT` with [`validate_select_query`](/mcp/validate_select_query). Execute it with the tool named in `next_tool`, passing the returned `sql` and setting `source` to the library entry's `id` for attribution. Provider credentials and permissions are required at execution time. --- # query_library_search > MCP tool searching curated StackQL query templates by natural-language intent, provider, service and tags Source: https://stackql.io/mcp/query_library_search Searches the [StackQL query library](pathname:///docs/query-library/) for templates matching a natural-language intent. Consult it before composing SQL from scratch, then pass a result's `id` to [`query_library_get`](/mcp/query_library_get) to inspect the template and validate its parameters. The tool retrieves library content only. It does not execute SQL, call cloud APIs or require provider credentials. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `query_library_get` ]](/mcp/query_library_get) [[ `validate_select_query` ]](/mcp/validate_select_query) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`intent`|Yes|Natural-language description of the task.| |`provider`|No|Filter by provider, for example `aws`.| |`service`|No|Filter by service, for example `s3`.| |`tags`|No|Array of tags. An entry must match every supplied tag.| |`include_mutations`|No|Include mutation templates. Defaults to `false`; ignored in `read_only` mode, where mutation entries are always excluded.| |`limit`|No|Maximum number of hits. Defaults to `5` when omitted or non-positive; capped at `20`.| |`format`|No|Text rendering: `markdown` or `json`. When omitted, uses the server's render setting (`markdown` by default).| * * * ## Output The default text view is a ranked table of `id`, `title`, `mutation`, `required_params` and `score`, followed by the source citation and any miss guidance. The structured payload contains: | Field | Description | |--|--| |`hits`|Ranked entries with `id`, `title`, optional `description`, `providers`, `services` and `required_params`, plus `mutation` and `score`. Follow up with `query_library_get` for the complete parameter declarations.| |`miss`|`true` when there are no hits or the top score is below the match threshold. Low-scoring nearest matches can still be returned.| |`guidance`|On a miss, directs the agent to the server instructions, discovery tools and `validate_select_query` to author a query.| |`source_tier`|Content source: `primary`, `fallback` or `snapshot`.| |`source_url`|URL or embedded path of the catalogue used, for citation.| |`stale`|When `true`, content was served from cache or the embedded snapshot after a fetch failure.| Deprecated entries are excluded. The server caches the catalogue and can fall back from the hosted library to its GitHub source and an embedded snapshot. * * * ## Gating Allowed in every server mode, subject to the configured tool allowlist. No approval or provider credentials are needed. Searching for mutation templates does not authorize their execution. * * * ## Example Tool arguments: ```json { "intent": "List S3 bucket names and regions", "provider": "aws", "service": "s3", "limit": 5 } ``` Use an `id` from `hits`, such as `aws/s3/buckets-list`, with [`query_library_get`](/mcp/query_library_get). If `miss` is `true`, inspect the nearest templates for guidance or use [`list_methods`](/mcp/list_methods) and [`describe_method`](/mcp/describe_method) before authoring SQL. --- # reload_credentials > MCP tool re-sourcing credentials from the --env.file dotenv file and reporting per-provider resolution status Source: https://stackql.io/mcp/reload_credentials Re-sources the dotenv-style file nominated by the [`--env.file`](/command-line-usage/global-flags) flag into the server's process environment, then reports credential resolution status for each provider. This solves the fixed-at-spawn environment problem: credentials written or rotated on disk mid-session reach the running server without a restart. The env file overlays the process environment rather than replacing it: credential resolution always reads the live process environment at request time, so variables already present at spawn (from the shell or the client's `env` block) keep working with or without `--env.file`. On reload, only keys present in the file with non-empty values are written and nothing is ever unset, so a failed or partial reload preserves previously working credentials. Secret values are never returned, logged, or audited - the tool reports variable names and statuses only. Without `--env.file` configured the tool degrades to a pure status probe. When a query fails on credential resolution, the MCP error carries a hint directing the agent to call `reload_credentials` and retry, so agentic clients self-heal. :::note Available in StackQL releases after `v0.10.542`. ::: See also: [[ MCP overview ]](/command-line-usage/mcp) [[ Credential (re)sourcing ]](/command-line-usage/mcp#credential-resourcing---envfile--reload_credentials) [[ `server_info` ]](/mcp/server_info) [[ Claude Desktop ]](/getting-started/claude-desktop) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`provider`|No|Scopes the status report to one provider. When omitted, every provider is reported.| * * * ## Output | Renderer | Shape | |--|--| | Table | Env-file sourcing result plus one row per provider with credential resolution status | The structured payload contains: | Field | Description | |--|--| |`env_file`|The configured `--env.file` path (empty when none is configured).| |`env_file_sourced`|`true` when the file was found and sourced on this call.| |`sourced_vars`|Names of the environment variables set from the file - names only, never values.| |`providers`|One row per provider (see below).| Each `providers` row has: | Column | Description | |--|--| |`provider`|Provider name.| |`auth_type`|Authentication type configured for the provider.| |`sourced_from`|Where the credential resolved from, e.g. `env:OKTA_SECRET_KEY`, `file:/path/key.json`, `inline`, or `none`.| |`status`|`ok`, `unresolved`, or `not_checked`.| |`detail`|Error text when `unresolved`.| Auth types that authenticate outside the credential-bytes path (interactive gcloud, azure CLI, oauth2 client credentials, assume-role chains, OCI signing, null) report `not_checked`. * * * ## Gating Allowed in every server mode, including `read_only` - the tool mutates nothing beyond the server's own process environment. Not supported in `reverse_proxy` backend mode: queries execute in the remote stackql server process, so the tool returns an error directing the user to reload credentials on the backing server. * * * ## Example Try this prompt with any MCP client with the StackQL MCP server registered (started with `--env.file`): ``` My okta query failed with a credential error - I've just written the key to the credentials file. Reload credentials and retry the query. ``` --- # run_lifecycle_operation > MCP tool executing a StackQL EXEC lifecycle operation Source: https://stackql.io/mcp/run_lifecycle_operation Executes a StackQL `EXEC` lifecycle operation -- the non-CRUD provider actions (start/stop a VM, rotate a key, trigger a workflow, etc.). **Real side effects.** Gated by the server [mode](/command-line-usage/mcp#server-modes): | Mode | Lifecycle `EXEC` | |--|--| |`read_only`|refused| |`safe` (default)|needs approval (elicitation)| |`delete_safe`|needs approval| |`full_access`|allowed| :::info A payload holding several statements is gated by its most privileged statement ::: When approval is needed and the client did not advertise elicitation, the call is refused. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `run_mutation_query` ]](/mcp/run_mutation_query) [[ `describe_method` ]](/mcp/describe_method) [[ EXEC language spec ]](/language-spec/exec) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`sql`|Yes|A StackQL `EXEC` statement targeting a lifecycle method.| |`source`|No|Query library entry ID when the SQL came from [`query_library_get`](/mcp/query_library_get). Attribution only; does not change execution or approvals.| |`format`|No|Text rendering: `markdown` or `json`. When omitted, uses the server's render setting.| * * * ## Output | Renderer | Shape | |--|--| | KV | `{messages: [...], timestamp}` | * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` The Compute instance web-01 in us-central1-a (project my-project) is stuck. Please stop it. ``` The MCP client will surface an approval prompt before the operation is dispatched, unless the server is running in `full_access` mode. Here's an example in Claude Desktop: --- # run_mutation_query > MCP tool executing INSERT, UPDATE, REPLACE, or DELETE against a provider via StackQL Source: https://stackql.io/mcp/run_mutation_query Executes `INSERT`, `UPDATE`, `REPLACE`, or `DELETE` against the provider. **Real side effects** -- a successful call changes cloud state. Gated by the server [mode](/command-line-usage/mcp#server-modes): | Mode | `INSERT` / `UPDATE` / `REPLACE` | `DELETE` | |--|--|--| |`read_only`|refused|refused| |`safe` (default)|needs approval (elicitation)|needs approval| |`delete_safe`|allowed|needs approval| |`full_access`|allowed|allowed| :::info A payload holding several statements is gated by its most privileged statement ::: When a mutation needs approval and the client did not advertise the MCP elicitation capability, the call is refused. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `run_lifecycle_operation` ]](/mcp/run_lifecycle_operation) [[ `describe_method` ]](/mcp/describe_method) [[ INSERT language spec ]](/language-spec/insert) [[ DELETE language spec ]](/language-spec/delete) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`sql`|Yes|An `INSERT`, `UPDATE`, `REPLACE`, or `DELETE` statement.| |`source`|No|Query library entry ID when the SQL came from [`query_library_get`](/mcp/query_library_get). Attribution only; does not change execution or approvals.| |`format`|No|Text rendering: `markdown` or `json`. When omitted, uses the server's render setting.| * * * ## Output | Renderer | Shape | |--|--| | KV | `{messages: [...], timestamp}` -- dispatch confirmation, not the API response body | * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` The firewall rule allow-test-old in project my-project is no longer needed. Please remove it. ``` The MCP client will surface an approval prompt before the delete is dispatched, unless the server is running in `full_access` mode. The following clip shows the elicitation flow when the StackQL MCP server is running in the default `safe` mode -- the client is prompted to approve the `DELETE` before any cloud-side change is dispatched. You can reproduce this against your own StackQL MCP server using the official [MCP Inspector](https://github.com/modelcontextprotocol/inspector) using `npx @modelcontextprotocol/inspector`: --- # run_select_query > MCP tool executing a StackQL SELECT against a provider Source: https://stackql.io/mcp/run_select_query Executes a `SELECT` statement against the configured providers and returns the result rows. Read only -- mutations and lifecycle operations are not accepted; use [`run_mutation_query`](/mcp/run_mutation_query) or [`run_lifecycle_operation`](/mcp/run_lifecycle_operation) for those. Result rows are returned to the client but are deliberately excluded from the audit log. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `validate_select_query` ]](/mcp/validate_select_query) [[ `list_methods` ]](/mcp/list_methods) [[ SELECT language spec ]](/language-spec/select) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`sql`|Yes|A `SELECT` statement. Metadata statements (`SHOW`, `DESCRIBE`, `DESC`, `EXPLAIN`) are classed as read-only by the policy gate and accepted too; `DESC` is recognised in StackQL releases from `v0.12.732`.| |`row_limit`|No|Cap on the number of rows returned to the client. `0` (default) means no client-side cap.| |`source`|No|Query library entry ID when the SQL came from [`query_library_get`](/mcp/query_library_get). Attribution only; does not change execution or approvals.| |`format`|No|Text rendering: `markdown` or `json`. When omitted, uses the server's render setting.| * * * ## Output | Renderer | Shape | |--|--| | Table | `{rows: [...]}` -- one object per row, keyed by column name | * * * ## Gating Allowed in every server mode (`read_only`, `safe`, `delete_safe`, `full_access`) when every statement in the payload is read-only. From `v1.0`, `INSERT`, `UPDATE`, `REPLACE`, `DELETE` and `EXEC` are refused by this tool in every mode, including `full_access`, with an error naming [`run_mutation_query`](/mcp/run_mutation_query) or [`run_lifecycle_operation`](/mcp/run_lifecycle_operation). A payload holding several statements is classed by its most privileged statement, so a mutation behind a leading `SELECT` is refused in the same way. The tool declares `destructiveHint: false` and `openWorldHint: true`. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` List the VPC networks in my Google Cloud project my-project and tell me which ones use auto subnet creation. ``` Here's an example in Claude Desktop: --- # server_info > MCP tool returning StackQL MCP server identity and runtime Source: https://stackql.io/mcp/server_info Returns the StackQL MCP server's identity and runtime: version, backing SQL engine, provider registry location, server mode, and the legacy read-only flag. Call this once at session start so the agent knows what it is connected to. See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_providers` ]](/mcp/list_providers) [[ `list_registry` ]](/mcp/list_registry) * * * ## Inputs None. * * * ## Output | Renderer | Shape | |--|--| | KV (markdown key/value block for the LLM) | Structured payload with the fields below | | Field | Description | |--|--| |`version`|StackQL build version.| |`commit`|Git commit short hash.| |`build_date`|RFC3339 build timestamp.| |`platform`|`os/arch` (e.g., `linux/amd64`).| |`transport`|`http` or `stdio`.| |`sql_backend`|Backing SQL engine (e.g., `sqlite3`).| |`provider_registry`|Provider registry URL.| |`mode`|Active server mode -- `read_only`, `safe`, `delete_safe`, or `full_access`.| |`is_read_only`|Legacy boolean flag (`true` iff `mode == read_only`).| * * * ## Gating Always allowed in every server mode. Not audited as a mutation. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` What StackQL server am I connected to? Show me the version, mode, and where it pulls providers from. ``` Here's an example in Claude Desktop: --- # validate_select_query > MCP tool parsing and planning a StackQL SELECT without executing it Source: https://stackql.io/mcp/validate_select_query Parses and plans a single `SELECT` statement without executing it. Returns `{valid, errors}`. Useful when an agent wants to verify its query compiles and binds against the discovered method before committing to a real API call. :::info `SELECT` only, and exactly one statement, a payload holding more than one statement is refused with `validate_select_query accepts exactly one statement`. ::: See also: [[ MCP overview ]](/command-line-usage/mcp) [[ `list_methods` ]](/mcp/list_methods) [[ `run_select_query` ]](/mcp/run_select_query) * * * ## Inputs | Argument | Required | Description | |--|--|--| |`sql`|Yes|A single `SELECT` statement.| * * * ## Output | Renderer | Shape | |--|--| | KV | `valid` (bool) and `errors` (array of strings, empty when valid) | * * * ## Gating Allowed in every server mode. No API calls are made. * * * ## Example Try this prompt with any elicitation-capable MCP client with the StackQL MCP server registered: ``` Can you validate this query before I run it: select name, network from google.compute.subnetworks where project = 'my-project' and region = 'us-central1'; ``` Here's an example in Claude Desktop: --- # Available Providers > The StackQL provider catalog: every cloud and SaaS provider you can query and manage with SQL, grouped by category, each linking to its own reference site. Source: https://stackql.io/providers --- # Using StackQL in AWS Cloud Shell > Run StackQL in AWS CloudShell as the logged-in user: download the Linux package, use the stackql shell, assume an IAM role and run batch queries with exec. Source: https://stackql.io/quick-starts/aws/aws-cloud-shell In this guide, we will demonstrate using StackQL, a powerful dev tool that enables querying and deploying cloud infrastructure and resources using SQL syntax from within AWS Cloud Shell, using the user context of the login session to the AWS Console or assuming another IAM Role. Tested with embedded sql backend linux **What is AWS Cloud Shell?** > AWS Cloud Shell is a browser-based, pre-authenticated shell service provided by Amazon Web Services (AWS). It allows developers and IT professionals to manage their cloud resources directly from their web browsers. With AWS Cloud Shell, users can quickly run commands related to AWS services without installing or configuring the AWS CLI (Command Line Interface) on their local machines. This service provides a ready-to-use environment with typical development and management tools pre-installed, such as the AWS CLI, Python, Node.js, and more, making it easier to interact with AWS services and automate tasks. AWS Cloud Shell is directly integrated with the AWS Management Console, offering a seamless experience for executing administrative tasks, exploring AWS services, and managing infrastructure. Since AWS Cloud Shell automatically authenticates users through their AWS Console login, it simplifies the process of running commands and scripts in the context of their AWS account, enhancing productivity and efficiency in cloud operations. ## How it works The StackQL linux package includes scripts to use `stackql` directly within major cloud providers built-in cloud shell environments. For AWS the script is __`stackql-aws-cloud-shell.sh`__. Usage for the __`stackql-aws-cloud-shell.sh`__ script is shown here: ``` Usage: ./stackql-aws-cloud-shell.sh [--role-arn ARN] [shell | exec] [flags] --role-arn (optional) If supplied, the program will assume the role specified; if not, then the current user context in the cloud shell will be used. Command (optional): 'shell' (default) enters the StackQL command shell to execute queries interactively. 'exec' is used to execute StackQL queries or files to provide batch outputs (such as CSV or JSON output files). If not specified, 'shell' is assumed. Flags: optional StackQL flags, documented in Command Line Usage -> Global Flags ``` The `stackql-aws-cloud-shell.sh` script automatically downloads the latest AWS provider for StackQL. Source code for the included cloud shell scripts can be found at [__github.com/stackql/cloud-shell-scripts__](https://github.com/stackql/cloud-shell-scripts). ## Download the `stackql` Linux package from AWS Cloud Shell To get started, from AWS Cloud Shell, download the latest Linux binary for StackQL, using the following commands: ```shell curl -L https://bit.ly/stackql-zip -O \ && unzip stackql-zip ``` This will download and extract the `stackql` binary along with the `stackql-aws-cloud-shell.sh` script to the home directory of your AWS Cloud Shell environment. Now you're ready to go! ## Using the `stackql shell` from AWS Cloud Shell Launching an authenticated StackQL command shell from within AWS Cloud Shell is as easy as: ```shell sh stackql-aws-cloud-shell.sh ``` You can now start running interactive SQL-based AWS queries using the StackQL provider, as shown here: ## Assuming an IAM Role using StackQL Assuming an IAM Role in AWS allows you to perform actions and access resources that you might not be able to with your default user permissions. This is particularly useful when you need temporary access to resources or perform actions with permissions different from your primary account. With StackQL, you can seamlessly assume an IAM Role to query and manage AWS resources under the permissions granted by that role. **Understanding IAM Role Assumption** > Assuming an IAM Role is a secure way to grant temporary access to AWS resources. When you assume a role, AWS STS provides you with temporary security credentials that allow you to access AWS services and resources the role has permission to use. This mechanism is ideal for cross-account access, temporary access for users, or adhering to the principle of least privilege. > Roles can be assumed using the AWS Management Console, AWS CLI, or AWS CLI, and directly within StackQL. This ensures that users and applications only have the necessary permissions for the duration required, enhancing the security posture of your AWS environment. To assume an IAM Role using StackQL in AWS Cloud Shell, you can use the `--role-arn` option with the `stackql-aws-cloud-shell.sh` script. This option requires the Amazon Resource Name (ARN) of the role you wish to assume. When provided, StackQL will use AWS Security Token Service (STS) to assume the specified role before executing any queries or commands. ```shell sh stackql-aws-cloud-shell.sh --role-arn arn:aws:iam::123456789012:role/YourRoleName ``` By assuming a role, you can leverage StackQL to interact with AWS resources that your default user might not have access to, enabling a more flexible and secure way to manage your cloud environment. When executing StackQL commands or scripts with an assumed IAM Role, ensure the role has the necessary permissions to perform the desired actions and access the specified resources. This approach facilitates granular access control and aligns with AWS best practices for security and governance. ## Running `stackql exec` (batch operations) from AWS Cloud Shell StackQL queries can be executed using the `exec` command as well; this is a valuable option for: - specifying alternate output formats such as `json` or `csv` - producing output files for the results of StackQL queries - using StackQL queries provided through input files (`.iql` files by convention) - performing complex operations, including sourcing variables or preprocessing queries (using `json` or `jsonnet`) Examples using `exec` within AWS Cloud Shell are shown here: ```shell sh stackql-aws-cloud-shell.sh exec \ --output csv --outfile instances.csv \ "SELECT region, instanceType FROM aws.ec2.instances WHERE region IN ('us-east-1')" ``` The above example runs the StackQL query specified and produces an out `CSV` file, which can be downloaded from the AWS Cloud Shell. Additionally, you can supply an IAM role using the `--role-arn` argument to assume another role for your query or mutation operation; an example is shown here (in this case, we have sourced the query from an input file): ```shell sh stackql-aws-cloud-shell.sh \ --role-arn arn:aws:iam::824532806693:role/SecurityReviewerRole exec \ --infile query.iql \ --output csv --outfile output.csv ``` More information on the `exec` command can be found [__here__](/command-line-usage/exec) --- # AWS Global Inventory > Inventory every AWS resource across all regions with StackQL: asynchronous queries, excluded resource types and filters for AWS-managed defaults. Source: https://stackql.io/quick-starts/aws/aws-global-inventory In this guide, we will demonstrate using StackQL - a powerful dev tool that enables querying and deploying cloud infrastructure and resources using SQL syntax - to generate a comprehensive inventory of __all resources__, in __all services__, in __all regions__ within a given AWS account. Tested with embedded sql backend postgres sql backend macos linux powershell ## How it works StackQL implements a SQL engine which can process multiple queries asynchronously, for instance: ```sql SELECT region, COUNT(*) as num_functions FROM aws.lambda.functions WHERE region IN ( 'us-east-1','us-east-2','us-west-1','us-west-2', 'ap-south-1','ap-northeast-3','ap-northeast-2', 'ap-southeast-1','ap-southeast-2','ap-northeast-1', 'ca-central-1','eu-central-1','eu-west-1', 'eu-west-2','eu-west-3','eu-north-1','sa-east-1') GROUP BY region; ``` The above query is actually 17 queries run in parallel (one query for each region), the results are aggregated and presented as a report. Using [__`pystackql`__](https://pystackql.readthedocs.io/en/latest/pystackql.html) - a Python wrapper for StackQL - we can iterate through __all resources__ in __all services__ for __all regions__ which are supported by the given service. The result is a report of how many instances are deployed of each resource in each region, as seen in the example below: ![aws-inventory-example](/img/blog/aws-inventory.png) ## Prerequisites - [`pystackql`](https://pystackql.readthedocs.io/en/latest/pystackql.html) which can be installed using `pip install pystackql` - An AWS user or a role (can be assumed using `sts assume-role`) with the `ReadOnlyAccess` policy or greater attached - `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables set (this can be done automatically using [AWS Cloud Shell](/blog/tutorials/using-stackql-in-native-cloud-shells-in-aws-azure-and-gcp#using-stackql-in-the-aws-cloud-shell)) ## The Code The following code performs the following actions: 1. Defines a list of all AWS regions (`regions`) and a list of regions supported for each service (`supported_regions`), more info on deriving `supported_regions` can be found at [AWS Service Support by Region at a Glance](https://dev.to/stackql/aws-service-support-by-region-at-a-glance-3p9f) 2. Pulls the [`aws`](https://aws.stackql.io/providers/aws/) and [`aws`](https://aws.stackql.io/providers/aws/) StackQL providers if they're not already installed. 3. Iterates through each service (using [`SHOW SERVICES`](/language-spec/show#list-all-services-in-a-cloud-provider)), then for each service iterates through each resource (using [`SHOW RESOURCES`](/language-spec/show#list-all-resources-within-a-cloud-provider-service)) 4. [`SELECT`](/language-spec/select)'s all instances of each resource across all regions asynchronously, groups the data by region and counts the instance of each resource for each region Here it is... **stackql-aws-inventory.py** ```python from regions import supported_regions, regions from resources import excluded_resources, resource_filters import time from pystackql import StackQL import pandas as pd stackql = StackQL(output='pandas', page_limit=-1, execution_concurrency_limit=-1) def pull_stackql_providers(): providers_df = stackql.execute("SHOW PROVIDERS") installed = providers_df['name'].values if not providers_df.empty else [] for provider in ('aws', 'awscc'): if provider not in installed: print(f"{provider} not installed. Installing {provider}") res = stackql.executeStmt(f"REGISTRY PULL {provider}") print(res['message']) def get_s3_buckets(): # special case for s3 buckets - use the awscc provider's list view, which # returns each bucket alongside its region in a single query across all regions regions_in = ", ".join([f"'{region}'" for region in regions]) buckets_df = stackql.execute(f""" SELECT region, bucket_name FROM awscc.s3.buckets_list_only WHERE region IN ({regions_in}); """) # Group by region and count the total resources (buckets) in each region grouped = buckets_df.groupby('region').size().reset_index(name='total_resources') grouped['svc'] = 's3' grouped['res'] = 'buckets' output_df = grouped[['svc', 'res', 'region', 'total_resources']] return output_df def main(): start_time = time.time() pull_stackql_providers() results_df = pd.DataFrame(columns=['svc', 'res', 'region', 'total_resources']) # get all enumerable aws services services_df = stackql.execute("SHOW SERVICES IN aws") for svcIx, svcRow in services_df.iterrows(): service = svcRow['name'] if service in supported_regions: # check all enumerable aws resources in the service against supported regions resources_df = stackql.execute(f"SHOW RESOURCES IN aws.{service}") plural_resources = [resource for resource in resources_df['name'].tolist() if resource.endswith('s')] if plural_resources: for resource in plural_resources: print(f"Checking {resource} in {service}...") if service == 's3' and resource == 'buckets': print(f"Checking location for s3 buckets...") resource_df = get_s3_buckets() else: # should we skip this service? if service in excluded_resources and resource in excluded_resources[service]: continue # check if the resource is global or regional if 'global' in supported_regions[service]: regions_in = ", ".join([f"'{region}'" for region in regions]) else: regions_in = ", ".join([f"'{region}'" for region in supported_regions[service]]) # check if there are additional where clauses for this resource where_clause = resource_filters.get(service, {}).get(resource, '') resource_df = stackql.execute(f""" SELECT '{service}' as svc, '{resource}' as res, region, COUNT(*) as total_resources FROM aws.{service}.{resource} WHERE region IN ({regions_in}){where_clause} GROUP BY svc, res, region """) if not resource_df.empty: # Append resource_df to the results_df if not 'error' in resource_df.columns: results_df = pd.concat([results_df, resource_df], ignore_index=True) end_time = time.time() elapsed_time = end_time - start_time print(f"Elapsed time: {elapsed_time:.2f} seconds") results_df.to_csv('all_aws_resources.csv', index=False) if __name__ == "__main__": main() ``` **resources.py** ```python # exclude these resources excluded_resources = { 'cloudformation': ['public_type_versions'], 'gamelift': ['locations'], 'codepipeline': ['custom_action_types'], 'ssm': ['patch_baselines'], 'iot': ['domain_configurations'], 'ce': ['anomaly_monitors', 'anomaly_subscriptions'], } # apply an additional filter to these resources, to filter defaults or AWS managed resources resource_filters = { "appconfig": { "extensions": " AND SPLIT_PART(id, '.', 1) <> 'AWS'", }, "apprunner": { "observability_configurations": " AND SPLIT_PART(observability_configuration_arn, '/', 2) <> 'DefaultConfiguration'", "auto_scaling_configurations": " AND SPLIT_PART(auto_scaling_configuration_arn, '/', 2) <> 'DefaultConfiguration'", }, "athena": { "work_groups": " AND name <> 'primary'", "data_catalogs": " AND name <> 'AwsDataCatalog'", }, "cassandra": { "keyspaces": " AND keyspace_name <> 'system_multiregion_info'", }, "codedeploy": { "deployment_configs": " AND SPLIT_PART(deployment_config_name, '.', 1) <> 'CodeDeployDefault'", }, "ec2": { "snapshots": " AND ownerAlias <> 'amazon'", }, "elasticache": { "users": " AND user_id <> 'default'", }, "events": { "event_buses": " AND name <> 'default'", }, "iam": { "managed_policies": " AND SPLIT_PART(policy_arn, '/', 1) <> 'arn:aws:iam::aws:policy'", "policies": " AND SPLIT_PART(Arn, '/', 1) <> 'arn:aws:iam::aws:policy'", }, "kms": { "aliases": " AND SPLIT_PART(alias_name, '/', 2) <> 'aws'", }, "memorydb": { "acls": " AND acl_name <> 'open-access'", "users": " AND user_name <> 'default'", "parameter_groups": " AND SPLIT_PART(parameter_group_name, '.', 1) <> 'default'", }, "ram": { "permissions": " AND SPLIT_PART(arn, '/', 1) <> 'arn:aws:ram::aws:permission'", }, "route53resolver" : { "resolver_rule_associations": " AND SPLIT_PART(resolver_rule_association_id, '-', 2) <> 'autodefined'", "resolver_rules": " AND SPLIT_PART(resolver_rule_id, '-', 2) <> 'autodefined'", }, "scheduler": { "schedule_groups": " AND name <> 'default'", }, "ssm": { "documents": " AND SUBSTRING(name, 1, 3) <> 'AWS' AND SUBSTRING(name, 1, 6) <> 'Amazon' AND SUBSTRING(name, 1, 3) <> 'Aws' AND name NOT IN ('AlertLogic-MDR', 'CrowdStrike-FalconSensorDeploy', 'DynatraceOneAgent', 'FalconSensor-Linux', 'FalconSensor-Windows', 'New-Relic-infrastructure-monitoring-agent', 'TrendMicro-CloudOne-WorkloadSecurity')", }, } ``` **regions.py** ```python # all AWS regions regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-3', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'] # regions supported by services supported_regions = { 'accessanalyzer': ['global'], 'acmpca': ['global'], 'amplify': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'apigateway': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'apigatewayv2': ['global'], 'appconfig': ['global'], 'appflow': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1'], 'applicationinsights': ['global'], 'apprunner': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3'], 'appstream': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'sa-east-1'], 'appsync': ['global'], 'aps': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'arczonalshift': ['global'], 'athena': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-west-1', 'eu-north-1'], 'autoscaling': ['global'], 'backup': ['global'], 'backupgateway': ['global'], 'batch': ['global'], 'budgets': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1'], 'cassandra': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'ce': ['global'], 'chatbot': ['global'], 'cleanrooms': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 'cloudformation': ['global'], 'cloudfront': ['us-east-1'], 'cloudtrail': ['global'], 'cloudwatch': ['global'], 'codeartifact': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1'], 'codebuild': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'sa-east-1'], 'codedeploy': ['global'], 'codeguruprofiler': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 'codegurureviewer': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 'codepipeline': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'codestarconnections': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'codestarnotifications': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'cognito': ['global'], 'comprehend': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'config': ['global'], 'connect': ['us-east-1', 'us-west-2', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-2'], 'databrew': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'datapipeline': ['us-east-1', 'us-west-2', 'ap-southeast-2', 'ap-northeast-1', 'eu-west-1'], 'datasync': ['global'], 'detective': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'devopsguru': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'directoryservice': ['us-east-1', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-west-1'], 'dms': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-north-1'], 'dynamodb': ['global'], 'ec2': ['global'], 'ecr': ['us-east-1'], 'ecs': ['global'], 'efs': ['global'], 'eks': ['global'], 'elasticache': ['global'], 'elasticbeanstalk': ['global'], 'elasticloadbalancingv2': ['global'], 'emr': ['global'], 'emrcontainers': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'emrserverless': ['global'], 'events': ['global'], 'eventschemas': ['global'], 'fis': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'forecast': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'frauddetector': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'eu-west-1'], 'fsx': ['global'], 'gamelift': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'sa-east-1'], 'globalaccelerator': ['us-east-1'], 'grafana': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'greengrassv2': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'groundstation': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'eu-central-1', 'eu-west-1', 'eu-north-1', 'sa-east-1'], 'guardduty': ['global'], 'healthlake': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1'], 'iam': ['us-east-1'], 'imagebuilder': ['global'], 'inspector': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 'inspectorv2': ['global'], 'internetmonitor': ['global'], 'iot': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1'], 'iotanalytics': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'iotevents': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'iotfleethub': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 'iotfleetwise': ['us-east-1', 'eu-central-1'], 'iotsitewise': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1'], 'iotwireless': ['us-east-1', 'us-west-2', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'sa-east-1'], 'ivs': ['us-east-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'ivschat': ['us-east-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'kafkaconnect': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'kendra': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-west-1', 'eu-west-2'], 'kinesis': ['global'], 'kinesisanalyticsv2': ['global'], 'kinesisfirehose': ['global'], 'kms': ['global'], 'lakeformation': ['global'], 'lambda': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'lex': ['us-east-1', 'us-west-2', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'lightsail': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1'], 'logs': ['global'], 'lookoutequipment': ['us-east-1', 'ap-northeast-2', 'eu-west-1'], 'lookoutmetrics': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-north-1'], 'lookoutvision': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-northeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'm2': ['global'], 'macie': ['global'], 'mediaconnect': ['global'], 'medialive': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-3', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'mediapackage': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'mediapackagev2': ['global'], 'memorydb': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1', 'sa-east-1'], 'msk': ['global'], 'mwaa': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'neptune': ['global'], 'networkfirewall': ['global'], 'networkmanager': ['global'], 'nimblestudio': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 'oam': ['global'], 'omics': ['us-east-1', 'us-west-2', 'ap-southeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'opensearchserverless': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'opsworkscm': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'organizations': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-3', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'osis': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1', 'sa-east-1'], 'pcaconnectorad': ['global'], 'personalize': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1'], 'pinpoint': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'pipes': ['global'], 'proton': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'ram': ['global'], 'rds': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1', 'sa-east-1'], 'redshift': ['global'], 'refactorspaces': ['global'], 'rekognition': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'], 'resiliencehub': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'resourceexplorer2': ['global'], 'resourcegroups': ['global'], 'robomaker': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'route53': ['us-east-1'], 'route53recoverycontrol': ['us-east-1', 'us-west-2'], 'route53recoveryreadiness': ['us-east-1', 'us-west-2'], 'route53resolver': ['global'], 'rum': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 's3': ['global'], 's3objectlambda': ['global'], 'sagemaker': ['global'], 'scheduler': ['global'], 'secretsmanager': ['global'], 'securityhub': ['ap-southeast-2'], 'servicecatalog': ['global'], 'servicecatalogappregistry': ['global'], 'ses': ['global'], 'signer': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'sns': ['global'], 'sqs': ['global'], 'ssm': ['global'], 'ssmcontacts': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'ssmincidents': ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1'], 'stepfunctions': ['global'], 'synthetics': ['global'], 'timestream': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1'], 'transfer': ['global'], 'verifiedpermissions': ['global'], 'vpclattice': ['us-east-1', 'us-east-2', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-north-1'], 'wafv2': ['us-east-1'], 'workspacesweb': ['us-east-1', 'us-west-2', 'ap-south-1', 'ap-southeast-1', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2'] } ``` --- # Asynchronous Cross Region Queries with StackQL > Query and aggregate AWS resources across multiple regions in one StackQL statement, with region lists and asynchronous execution instead of per-region loops. Source: https://stackql.io/quick-starts/aws/cross-region-queries In this guide, we will demonstrate a powerful capability within StackQL: the ability to query and aggregate resources across multiple regions in AWS. This involves numerous API requests to different endpoints, which are performed asynchronously. This is seamless and transparent to the user. > StackQL is a powerful dev tool that enables querying and deploying cloud infrastructure and resources using SQL syntax. Tested with embedded sql backend postgres sql backend macos linux powershell ## Understanding AWS Regions and Resources AWS resources are hosted in multiple locations worldwide. These locations are composed of Regions and Availability Zones, designed to allow users to place instances and store data in various locations. ## The problem with AWS Regions... When working with AWS, it's crucial to understand that the AWS Management Console provides a regionally scoped view of resources, allowing users to interact with and manage resources within a specific region at a time. Similarly, AWS Command Line Interface (CLI) commands and Software Development Kits (SDKs) use the region as an entry point for operations, necessitating the specification of a region to execute commands or run programs. > The regional framework of cloud services introduces complexities when resources span multiple regions. Additionally, security breaches, including cryptocurrency mining exploits, frequently utilize resources in various areas, extending beyond the primary region typically used by organizations. ## Specifying Regions in StackQL Queries Using StackQL, you can specify regions to target resources across different geographic locations. This is particularly useful for managing resources that are distributed across the globe. ### Example: Listing EC2 Instances Across Multiple Regions ```sql SELECT instance_id, region FROM aws.ec2.instances WHERE region IN ('us-east-1', 'eu-west-1'); ``` This query returns a list of EC2 instances from the `us-east-1` (N. Virginia) and `eu-west-1` (Ireland) regions, showcasing how StackQL can fetch data across regions in a single query. This could be used with aggregate queries as well, such as: ```sql SELECT region, COUNT(*) as num_functions FROM aws.lambda.functions WHERE region IN ( 'us-east-1','us-east-2','us-west-1','us-west-2', 'ap-south-1','ap-northeast-3','ap-northeast-2', 'ap-southeast-1','ap-southeast-2','ap-northeast-1', 'ca-central-1','eu-central-1','eu-west-1', 'eu-west-2','eu-west-3','eu-north-1','sa-east-1') GROUP BY region; ``` ## The Power of Asynchronous Queries StackQL executes these cross-region queries asynchronously, making multiple parallel API requests to AWS. This ensures efficient data retrieval without waiting for one region's request to complete before moving on to the next. ## Conclusion Asynchronous cross-region queries in StackQL provide a robust and efficient method for managing AWS resources across different geographical locations. By leveraging SQL-like syntax for these queries, StackQL simplifies complex cloud management tasks, making it an invaluable tool for developers and cloud administrators aiming to optimize their AWS infrastructure. --- # Azure Activity Observability using StackQL > Query and Deploy Azure Cloud Infrastructure and Resources using SQL Source: https://stackql.io/quick-starts/azure/azure-activity-monitor In this guide, you'll learn how to query and report Azure activity logs using StackQL, a powerful dev tool that enables querying and deploying cloud infrastructure and resources using SQL syntax. Tested with embedded sql backend macos linux powershell ## Basic query The basic query shown below uses the [__`azure.monitor.activity_logs`__](https://azure.stackql.io/providers/azure/monitor/activity_logs/) resource in the [__`azure`__](https://azure.stackql.io/providers/azure/) provider; substitute the `subscriptionId` with yours. In this query we will use `jsonnet` with external variables for StackQL query pre-processing, see [Using Variables](/getting-started/variables) for more information. In this case we have done this as an inline `jsonnet` code block, but this can also be supplied as an external file using either the `--iqldata` or `-q` arguments to `stackql exec` or `stackql shell`. The [__`JSON_EXTRACT`__](/language-spec/functions/json/json_extract) and [__`SPLIT_PART`__](/language-spec/functions/string/split_part) functions are used to manipulate response data. ```sql <<<jsonnet { stackqlQuery: { subscriptionId: '631d1c6d-2a65-43e7-93c2-688bfe4e1468', filter: "eventTimestamp ge ''" + std.extVar('startdate') + "''", } } >>> -- -- StackQL query with jsonnet preprocessing to retrieve all recent Azure activity -- SELECT eventTimestamp as event_timestamp, caller, JSON_EXTRACT(claims, '$.ipaddr') as ip_address, subscriptionId, tenantId, SPLIT_PART(JSON_EXTRACT(authorization, '$.scope'), '/', 5) as resource_group, SPLIT_PART(resourceId, '/', -1) as resource_name, level, JSON_EXTRACT(authorization, '$.action') as action, JSON_EXTRACT(category, '$.localizedValue') as category, JSON_EXTRACT(operationName, '$.localizedValue') as operation, JSON_EXTRACT(status, '$.localizedValue') as status FROM azure.monitor.activity_logs WHERE $filter = '{{ .stackqlQuery.filter }}' AND subscription_id = '{{ .stackqlQuery.subscriptionId }}'; ``` ## Running the query interactively From a machine that is authenticated to Azure (including the Azure Portal Cloud Shell): ```bash # to run on mac or linux ./stackql shell --var startdate=$(date -u -d '1 day ago' '+%Y-%m-%dT%H:%M:%SZ') ``` or using PowerShell: ```powershell # to run using windows powershell $startDate = (Get-Date).AddDays(-1).ToString("yyyy-MM-ddTHH:mm:ssZ") stackql.exe shell --var startdate=$startDate ``` You should see a tabular output with columns for: `event_timestamp`, `caller`, `ip_address`, `subscriptionId`, `tenantId`, `resource_group`, `resource_name`, `level`, `action`, `category`, `operation` and `status`. ## Generating a CSV report By saving the StackQL query to a file (`activity_report.iql`), you can produce a `csv` report from the activity query as follows (see [__`--output csv`__](/getting-started/output-modes#csv-output) for more information on `stackql` outputs): ```bash # to run on mac or linux ./stackql exec \ --output csv \ -i activity_report.iql \ -f activity_report.csv \ --var startdate=$(date -u -d '1 day ago' '+%Y-%m-%dT%H:%M:%SZ') ``` or using PowerShell: ```powershell # to run using windows powershell $startDate = (Get-Date).AddDays(-1).ToString("yyyy-MM-ddTHH:mm:ssZ") stackql.exe exec ` --output csv ` -i activity_report.iql ` -f activity_report.csv ` --var startdate=$startDate ``` ## Server-side filtering with KQL Server-side filtering in Azure is achieved through the use of KQL (Kusto Query Language). By extending the `$filter` clause in your query, you can filter data directly on the server. This method is highly efficient as it reduces the amount of data transferred over the network. Below are some examples of server-side filtering (for brevity these queries are using parameters directly instead of using the jsonnet preprocessor): ### Specifying a date range for activities ```sql -- -- List events in a time range -- SELECT eventTimestamp as event_timestamp, caller, JSON_EXTRACT(claims, '$.ipaddr') as ip_address, subscriptionId, tenantId, SPLIT_PART(JSON_EXTRACT(authorization, '$.scope'), '/', 5) as resource_group, SPLIT_PART(resourceId, '/', -1) as resource_name, level, JSON_EXTRACT(authorization, '$.action') as action, JSON_EXTRACT(category, '$.localizedValue') as category, JSON_EXTRACT(operationName, '$.localizedValue') as operation, JSON_EXTRACT(status, '$.localizedValue') as status FROM azure.monitor.activity_logs WHERE $filter = 'eventTimestamp ge ''2024-01-24T00:00:00Z'' and eventTimestamp le ''2024-01-25T00:00:00Z''' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468'; ``` ### Getting activities for a resource group ```sql -- -- List events for a resource group -- SELECT eventTimestamp as event_timestamp, caller, JSON_EXTRACT(claims, '$.ipaddr') as ip_address, subscriptionId, tenantId, SPLIT_PART(resourceId, '/', -1) as resource_name, level, JSON_EXTRACT(authorization, '$.action') as action, JSON_EXTRACT(category, '$.localizedValue') as category, JSON_EXTRACT(operationName, '$.localizedValue') as operation, JSON_EXTRACT(status, '$.localizedValue') as status FROM azure.monitor.activity_logs WHERE $filter = 'eventTimestamp ge ''2024-01-24T00:00:00Z'' and eventTimestamp le ''2024-01-25T00:00:00Z'' and resourceGroupName eq ''MC_kube-03_aks862a_australiaeast''' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468'; ``` ### Getting activities for a resource type ```sql -- -- List events for a resource provider -- SELECT eventTimestamp as event_timestamp, caller, JSON_EXTRACT(claims, '$.ipaddr') as ip_address, subscriptionId, tenantId, SPLIT_PART(JSON_EXTRACT(authorization, '$.scope'), '/', 5) as resource_group, SPLIT_PART(resourceId, '/', -1) as resource_name, level, JSON_EXTRACT(authorization, '$.action') as action, JSON_EXTRACT(category, '$.localizedValue') as category, JSON_EXTRACT(operationName, '$.localizedValue') as operation, JSON_EXTRACT(status, '$.localizedValue') as status FROM azure.monitor.activity_logs WHERE $filter = 'eventTimestamp ge ''2024-01-24T00:00:00Z'' and eventTimestamp le ''2024-01-25T00:00:00Z'' and resourceProvider eq ''Microsoft.Compute''' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468'; ``` ### Getting activities for a specific resource Note we added an additional field (`correlationId`) which we will use in the next server-side filter... ```sql -- -- List events for resource using the resourceUri -- SELECT eventTimestamp as event_timestamp, caller, JSON_EXTRACT(claims, '$.ipaddr') as ip_address, subscriptionId, tenantId, SPLIT_PART(resourceId, '/', -1) as resource_name, correlationId, level, JSON_EXTRACT(authorization, '$.action') as action, JSON_EXTRACT(category, '$.localizedValue') as category, JSON_EXTRACT(operationName, '$.localizedValue') as operation, JSON_EXTRACT(status, '$.localizedValue') as status FROM azure.monitor.activity_logs WHERE $filter = 'eventTimestamp ge ''2024-01-24T00:00:00Z'' and eventTimestamp le ''2024-01-25T00:00:00Z'' and resourceUri eq ''/subscriptions/631d1c6d-2a65-43e7-93c2-688bfe4e1468/resourceGroups/MC_kube-03_aks862a_australiaeast/providers/Microsoft.Compute/virtualMachines/aks-agentpool-35064155-1''' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468'; ``` ### Getting activities for a specific resource The correlation ID is a unique identifier used to track and group events related to a particular operation or transaction in Azure. This query helps in pinpointing specific events within a given time frame that are related to a particular operation, making it easier to troubleshoot or understand the sequence of activities. Here is an example using a `correlationId` captured in the previous query: ```sql -- -- List events for a correlation Id -- SELECT eventTimestamp as event_timestamp, caller, JSON_EXTRACT(claims, '$.ipaddr') as ip_address, subscriptionId, tenantId, SPLIT_PART(JSON_EXTRACT(authorization, '$.scope'), '/', 5) as resource_group, SPLIT_PART(resourceId, '/', -1) as resource_name, level, JSON_EXTRACT(authorization, '$.action') as action, JSON_EXTRACT(category, '$.localizedValue') as category, JSON_EXTRACT(operationName, '$.localizedValue') as operation, JSON_EXTRACT(status, '$.localizedValue') as status FROM azure.monitor.activity_logs WHERE $filter = 'eventTimestamp ge ''2024-01-24T00:00:00Z'' and eventTimestamp le ''2024-01-25T00:00:00Z'' and correlationId eq ''30b92c6d-4a82-401f-ac73-e28377669539''' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468'; ``` ## Client-side filtering with the `WHERE` Clause Client-side filtering can be done using the traditional SQL `WHERE` clause. This method filters the data after it has been retrieved from the server, offering flexibility in data manipulation and analysis within the StackQL environment. ### Getting activities for a specific user In the example query, the `WHERE` clause filters records based on the `caller` (the user), providing an additional layer of data refinement. ```sql -- -- Filter events for a particular user (caller) -- SELECT eventTimestamp as event_timestamp, caller, JSON_EXTRACT(claims, '$.ipaddr') as ip_address, subscriptionId, tenantId, SPLIT_PART(JSON_EXTRACT(authorization, '$.scope'), '/', 5) as resource_group, SPLIT_PART(resourceId, '/', -1) as resource_name, level, JSON_EXTRACT(authorization, '$.action') as action, JSON_EXTRACT(category, '$.localizedValue') as category, JSON_EXTRACT(operationName, '$.localizedValue') as operation, JSON_EXTRACT(status, '$.localizedValue') as status FROM azure.monitor.activity_logs WHERE $filter = 'eventTimestamp ge ''2024-01-01T00:00:00Z''' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468' AND caller = 'javen@stackql.io'; ``` ## Running summary/aggregate queries As StackQL is a complete SQL engine, `GROUP BY`/aggregate queries (including [__`AVG`__](/language-spec/functions/aggregate/avg), [__`COUNT`__](/language-spec/functions/aggregate/count), [__`SUM`__](/language-spec/functions/aggregate/sum), [__`MIN`__](/language-spec/functions/aggregate/min), [__`MAX`__](/language-spec/functions/aggregate/max) and more are natively available for all providers, services and resources. ### Count events by severity level In this example we will group events from a start datetime by their severity and calculate the counts for each level. ```sql -- -- Summarize events by severity level -- SELECT level, COUNT(*) as num_events FROM azure.monitor.activity_logs WHERE $filter = 'eventTimestamp ge ''2024-01-29T00:00:00Z''' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468' GROUP BY level; /* returns.. |---------------|------------| | level | num_events | |---------------|------------| | Error | 58 | |---------------|------------| | Informational | 57 | |---------------|------------| | Warning | 57 | |---------------|------------| */ ``` ## Using `JOIN` to enrich activities ```sql SELECT l.eventTimestamp as event_timestamp, l.level, JSON_EXTRACT(l.operationName, '$.localizedValue') as operation, vm.name, vm.location, JSON_EXTRACT(vm.properties, '$.timeCreated') as time_created FROM azure.monitor.activity_logs l INNER JOIN azure.compute.virtual_machines vm ON vm.name = SPLIT_PART(l.resourceId, '/', -1) WHERE vm.resource_group_name = 'MC_kube-03_aks862a_australiaeast' AND subscription_id = '631d1c6d-2a65-43e7-93c2-688bfe4e1468' AND l.$filter = 'eventTimestamp ge ''2024-01-28T00:00:00Z'' and resourceGroupName eq ''MC_kube-03_aks862a_australiaeast'''; ``` or using variables from `jsonnet`, provided as a file using either the `--iqldata` or `-q` arguments, or as a jsonnet block as shown here: ```sql <<<jsonnet { stackqlQuery: { subscriptionId: '631d1c6d-2a65-43e7-93c2-688bfe4e1468', resourceGroupName: 'MC_kube-03_aks862a_australiaeast', } } >>> SELECT l.eventTimestamp as event_timestamp, l.level, JSON_EXTRACT(l.operationName, '$.localizedValue') as operation, vm.name, vm.location, JSON_EXTRACT(vm.properties, '$.timeCreated') as time_created FROM azure.monitor.activity_logs l INNER JOIN azure.compute.virtual_machines vm ON vm.name = SPLIT_PART(l.resourceId, '/', -1) WHERE vm.resource_group_name = '{{ .stackqlQuery.resourceGroupName}}' AND subscription_id = '{{ .stackqlQuery.subscriptionId}}' AND l.$filter = 'eventTimestamp ge ''2024-01-28T00:00:00Z'' and resourceGroupName eq ''{{ .stackqlQuery.resourceGroupName}}'''; ``` :::info `WHERE` parameters in a `JOIN` query which are not disambiguated, such as `subscriptionId` in the above case are shared by both resources (`azure.monitor.activity_logs` and `azure.compute.virtual_machines` in this case). ::: --- # Open Source Project Activity Monitor powered by StackQL > Real-Time Insights for OSS Maintainers using StackQL Source: https://stackql.io/quick-starts/github/oss-activity-monitor In this guide, we will demonstrate how to self host a real-time monitoring and alerting system for GitHub open source software maintainers. > [__stackql__](https://github.com/stackql/stackql) is an open source tool allowing users to query and interact with cloud and SaaS resources using a SQL language and data visualization and analysis libraries and tools. [⭐](https://github.com/stackql/stackql) us if you like this! Get alerts like this in Slack and Discord in realtime: ![OSS Monitor](/img/tutorials/github/oss-activity-monitor.png) Tested with embedded sql backend docker linux ## Overview When I looked for tools to monitor our open source project, I found most of them didn't work as advertised or didn't work at all (in the case of thrid part apps in GitHub), so I built our own which you could launch and use on your open source GitHub project... The [__oss-activity-monitor__](https://github.com/stackql/oss-activity-monitor) project uses [__stackql__](https://github.com/stackql/stackql) to perform real-time open source project activity monitoring, this includes real time notification of: - ⭐ new GitHub repo stargazers - 👀 new GitHub repo watchers - 🍴 new GitHub repo forks - 📊 new GitHub repo issues - 🙋 new GitHub org followers - 📦 new GitHub release asset downloads - 🍺 new homebrew downloads ## How it works The project is deployed in a container (using `docker` or other container deployment platform), it is built using `python` and the [`pystackql`](https://pystackql.readthedocs.io/en/latest/intro.html) package, using the [`github`](https://github.stackql.io/providers/github/) and [`homebrew`](https://homebrew.stackql.io/providers/homebrew) providers for `stackql`. Materialized views and `SELECT` statements are used to capture and compare state between current and previous metrics for GitHub and Homebrew monitored endpoints, this is described in the diagram here: ```mermaid graph TB A[CREATE MATERIALIZED VIEW\nof GitHub or Homebrew metric] --> B[SELECT query for\nGitHub or Homebrew metric] B --> C[Compare current state\nto previous state] C --> D[Send Slack and/or Discord\nmessage with alert] D --> B ``` for example, here given this materialized view created and populated using `stackql`: ```sql CREATE OR REPLACE MATERIALIZED VIEW mvw_github_repo_stargazers AS SELECT login FROM github.activity.repo_stargazers WHERE owner = 'your-org' and repo = 'your-repo' ``` the following `stackql` query polls GitHub for new stargazers... ```sql SELECT c.login FROM github.activity.repo_stargazers c LEFT JOIN mvw_github_repo_stargazers mvw ON c.login = mvw.login WHERE mvw.login IS NULL AND c.owner = 'your-org' AND c.repo = 'your-repo' ``` then the state is refreshed using... ```sql REFRESH MATERIALIZED VIEW mvw_github_repo_stargazers ``` similar patterns are repeated for repo watchers, issues, org followers, release asset downloads and homebrew downloads. ## Running the project Follow the steps below to get the project up and running locally or on your preferred cloud platform. ### 1. Clone the repo ```bash git clone https://github.com/stackql/oss-activity-monitor.git # or git clone git@github.com:stackql/oss-activity-monitor.git ``` ### 2. Configure environment variables The following environment variables are required to configure the project (provided using environment variables, a `.env` file in the example below): | Variable | Description | Example Value | |----------------------------|-----------------------------------------------------------------------------------|--------------------------------------------------| | `LOG_LEVEL` | Log level (INFO for general logs; DEBUG for detailed logging) | INFO | | `SLEEP_INTERVAL` | Time delay in seconds between request loops | 5 | | `GITHUB_REPO` | GitHub repository name | stackql | | `GITHUB_REPO_OWNER` | GitHub organization or owner name | stackql | | `HOMEBREW_FORMULA_NAME` | Homebrew formula name, if available | stackql | | `STACKQL_GITHUB_USERNAME` | Your GitHub username | jeffreyaven | | `STACKQL_GITHUB_PASSWORD` | Your GitHub personal access token | ghp_yourpersonalaccesstoken | | `SLACK_WEBHOOK_URL` | Slack webhook URL for sending notifications | https://hooks.slack.com/services/... | | `DISCORD_WEBHOOK_URL` | Discord webhook URL for sending notifications | https://discord.com/api/webhooks/... | ### 3. Build the container ```bash docker build --no-cache -t oss-activity-monitor . ``` ### 4. Run the container ```bash docker run --env-file .env oss-activity-monitor ``` thats it! You'll now get real-time alerts when there is activity on your open source project. To stop the container, use: ```bash docker stop $(docker ps -a -q --filter ancestor=oss-activity-monitor) ``` ⭐ us on [__GitHub__](https://github.com/stackql/stackql) --- # Google GitOps IAM bindings framework using StackQL > Query and Deploy Google Cloud Infrastructure and Resources using SQL Source: https://stackql.io/quick-starts/google/iam-bindings-framework In this guide, we will demonstrate a GitOps framework for IAM Bindings (entitlements) management in GCP using StackQL, a powerful dev tool that enables querying and deploying cloud infrastructure and resources using SQL syntax. Tested with embedded sql backend macos linux powershell ## Google IAM background Google Cloud Identity and Access Management (IAM) is a framework for managing access to Google Cloud resources, allowing administrators to define who can take specific actions on resources. It operates around identities (like users and service accounts), roles, and permissions, where roles assigned to these identities govern their access rights. This guide delves into managing IAM bindings, which link these roles to identities, using StackQL, a tool that simplifies cloud resource management with SQL syntax. IAM bindings can be created at any of the following levels: - organization level - folder level - project level - resource level (Buckets, BigQuery Datasets, etc) - billing account level IAM bindings applied at organization or folder level are inherited by all child objects. ## Declarative binding definitions and GitOps The guide will show you how to master IAM bindings in your source code repository, making it the source of truth for state and history, a concept known as GitOps, and how to use StackQL to apply changes using CI/CD workflows. This example shows you how to map *many* members or principals to *many* roles from a `json` manifest stored in source control. > The GCP console, `terraform`, `gcloud` utilities only allow you to map *one* member to one or more roles in each operation ## How it works The framework that we will walk you through will deploy IAM bindings across all nodes in your GCP heirarchy, as well as creating custom roles (with curated permissions) - as opposed to predefined roles such as `roles/bigquery.dataEditor` for example. ### Project directory structure The following directory tree is used for this bindings deployment framework: ``` ├── iql │ ├── iam.iql │ ├── ... ├── data │ ├── iam.jsonnet │ ├── iam │ │ ├── bindings.json │ │ ├── custom_roles.json ``` ### `iql/iam.iql` file This is the main file which will be run by the `stackql`, using `data/iam.jsonnet` this will render and apply the transpiled policy bindings generated from the data in `data/iam/bindings.json` > this file should not need to be modified **Expand to see the `iql/iam.iql` file** ```sql /* ROOT LEVEL (ORG AND FOLDER) IAM FOR SERVICE ACCOUNTS AND GROUPS */ {{ $root := . }} /*** create custom roles ***/ {{ range .custom_roles }} INSERT INTO google.iam.`organizations.roles`( parent, data__role, data__roleId ) SELECT '{{ $root.organization_id }}', '{"title": "{{ .title }}", "description": "{{ .description }}", "stage": "{{ .stage }}", "includedPermissions": {{ .includedPermissions }}}', '{{ .id }}' ;{{ end }} /*** create org role bindings */ EXEC google.cloudresourcemanager.organizations.setIamPolicy @resource = '{{ $root.organization_id }}' @@json = '{ "policy": { "bindings": {{ $root.bindings.org }} } }'; /*** create billing role bindings */ EXEC google.cloudbilling.billingAccounts.setIamPolicy @resource = '{{ $root.billing_account_id }}' @@json = '{ "policy": { "bindings": {{ $root.bindings.billingacct }} } }'; /*** create nonprod folder role bindings */ EXEC google.cloudresourcemanager.folders.setIamPolicy @resource = '{{ $root.nonprod_folder_id }}' @@json = '{ "policy": { "bindings": {{ $root.bindings.folders.nonprod }} } }'; /*** create prod folder role bindings */ EXEC google.cloudresourcemanager.folders.setIamPolicy @resource = '{{ $root.prod_folder_id }}' @@json = '{ "policy": { "bindings": {{ $root.bindings.folders.prod }} } }'; /*** create datalabs folder role bindings */ EXEC google.cloudresourcemanager.folders.setIamPolicy @resource = '{{ $root.datalabs_folder_id }}' @@json = '{ "policy": { "bindings": {{ $root.bindings.folders.datalabs }} } }'; /*** create stackql-audit project level role bindings */ EXEC google.cloudresourcemanager.folders.setIamPolicy @resource = 'projects/stackql-audit' @@json = '{ "policy": { "bindings": {{ $root.bindings.projects.stackql_audit }} } }'; /*** create role bindings for buckets in stackql-terraform */ {{ range $root.bindings.buckets }} -- creating policy bindings for {{ .name }} EXEC google.storage.buckets.setIamPolicy @bucket = '{{ .name }}' @@json = '{ "bindings": {{ .data }} }'; {{ end }} /*** create role bindings for topics in stackql-audit */ {{ range $root.bindings.topics }} -- creating policy bindings for {{ .name }} EXEC google.pubsub.`projects.topics`.setIamPolicy @resource = '{{ .resource }}' @@json = '{ "bindings": {{ .data }} }'; {{ end }} ``` ## `data/iam.jsonnet` This file is preprocessed by `iql/iam.iql` sourcing data from `data/iam/bindings.json` > this file should not need to be modified **Expand to see the `data/iam.jsonnet` file** ```javascript // update the following files only: // data/iam/custom_roles.json // data/iam/bindings.json // variables local custom_roles_data = import './data/iam/custom_roles.json'; local bindings_data = import './data/iam/bindings.json'; local organization_id = 'organizations/123466304837'; local billing_account_id = 'billingAccounts/123456-9DFD97-EE2B33'; local nonprod_folder_id = 'folders/1234016945998'; local prod_folder_id = 'folders/123431606453'; local datalabs_folder_id = 'folders/123464988355'; local environments = [{name: 'prod'}, {name: 'nonprod'}, {name: 'datalabs'}]; // DO NOT MODIFY BEYOND THIS POINT local generate_binding(x) = local members = [x for x in x.members]; std.map(function(r) {"role": r, "members": members} , [x for x in x.roles]); local generate_conditional_binding(x) = local members = [x for x in x.members]; local condition = x.condition; std.map(function(r) {"role": r, "members": members, "condition": condition} , [x for x in x.roles]); { organization_id: organization_id, billing_account_id: billing_account_id, nonprod_folder_id: nonprod_folder_id, prod_folder_id: prod_folder_id, datalabs_folder_id: datalabs_folder_id, custom_roles: custom_roles_data, environments: environments, bindings: { org: std.flattenArrays(std.map(generate_binding, bindings_data.org)), billingacct: std.flattenArrays(std.map(generate_binding, bindings_data.billingacct)), folders: { nonprod: std.flattenArrays(std.map(generate_binding, bindings_data.folders.nonprod)), prod: std.flattenArrays(std.map(generate_binding, bindings_data.folders.prod)), datalabs: std.flattenArrays(std.map(generate_binding, bindings_data.folders.datalabs)), }, projects: { stackql_audit: std.flattenArrays(std.map(generate_conditional_binding, bindings_data.projects.stackql_audit)), }, buckets: [ { name: "stackql-tf-prod", data: std.flattenArrays(std.map(generate_binding, bindings_data.buckets.stackql_tf_prod)), }, { name: "stackql-tf-modules-prod", data: std.flattenArrays(std.map(generate_binding, bindings_data.buckets.stackql_tf_modules_prod)), }, { name: "stackql-tf-nonprod", data: std.flattenArrays(std.map(generate_binding, bindings_data.buckets.stackql_tf_nonprod)), }, { name: "stackql-tf-modules-nonprod", data: std.flattenArrays(std.map(generate_binding, bindings_data.buckets.stackql_tf_modules_nonprod)), }, { name: "stackql-tf-datalabs", data: std.flattenArrays(std.map(generate_binding, bindings_data.buckets.stackql_tf_datalabs)), }, { name: "stackql-tf-modules-datalabs", data: std.flattenArrays(std.map(generate_binding, bindings_data.buckets.stackql_tf_modules_datalabs)), }, ], topics: [ { name: "stackql-np-log-topic", resource: "projects/stackql-audit/topics/stackql-np-log-topic", data: std.flattenArrays(std.map(generate_binding, bindings_data.topics.stackql_np_log_topic)), }, { name: "stackql-prod-log-topic", resource: "projects/stackql-audit/topics/stackql-prod-log-topic", data: std.flattenArrays(std.map(generate_binding, bindings_data.topics.stackql_prod_log_topic)), }, ], }, } ``` ## `data/iam/bindings.json` > this file __will need to be modified__ to make policy binding changes This is the master source of policy and binding data, the data structure maps one or many principals (groups, serviceaccount, etc) to one or many roles (predefined or custom) at a particular level (parent) as shown below: ```json "<< level >>": [ { "members": [ "<< principal >>", ... ], "roles": [ "<< role >>", ... ] }, ``` for example: ```json "folders": { "nonprod": [ { "members": [ "serviceAccount:terraform-nonprod@stackql-terraform.iam.gserviceaccount.com" ], "roles": [ "roles/compute.networkAdmin", "roles/resourcemanager.folderViewer", "roles/resourcemanager.projectCreator", "roles/storage.admin", "roles/artifactregistry.admin", "roles/container.serviceAgent", "roles/iam.securityAdmin", "roles/bigquery.admin", "roles/serviceusage.serviceUsageAdmin", "roles/cloudsql.admin", "roles/iam.serviceAccountAdmin", "roles/pubsub.admin", "roles/cloudfunctions.developer" ] } ], ``` ## Deployment This process is intentionally not run through a CI/CD pipeline, as the changes are infrequent, and we wish not to give a service account the levels of priveleges required to deploy this. This is to be run by a priveleged adminstrator who is a member of the gcp-org-administrators Google group. The user needs to be authenticated to GCP, using either a service account or interactive authentication, for more information about authenticating StackQL to Google see [__GCP Authentication__](https://google.stackql.io/providers/google/#authentication). Run the following command to perform a dryrun: ```shell stackql exec -i ./iql/iam.iql \ --iqldata ./data/iam.jsonnet \ --outfile iam-TEMPLATED.iql \ --dryrun --output text --hideheaders ``` The resultant data in this file can be exectuted as individual statements in `stackql shell` or as a batch by running: ```shell stackql exec -i iam-TEMPLATED.iql \ ``` Alternatively, you could take the policies (JSON payloads) generated by this script and run them using the `gcloud iam` command.