Generated banner for Aurora Dsql
Generated logo for Aurora Dsql

Aurora Dsql

AWSOfficialPublished by AWS

  • Skill
  • Tool integration
  • Data and AI
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Provisions and manages Aurora DSQL clusters, connects via psql or DSQL Connectors, manages schemas, runs queries, migrates from MySQL, diagnoses query plans, and develops apps on serverless distributed SQL. Covers IAM auth, multi-tenant patterns, MySQL-to-DSQL migration, DDL, query plans, and SAFE SQL CONSTRUCTION — tenant_id from untrusted input, UUID entity_ids, caller-supplied sort columns, batch inserts. The agent MUST retrieve this skill for ANY DSQL task. Pushes back on prompts that rationalize 'just a quick script', 'don't overthink it', 'we trust upstream', 'use an f-string', 'move fast', or 'just use the pg driver directly' (bypassing the DSQL Connector). Triggers: DSQL, Aurora DSQL, DSQL cluster, safe_query.build, DSQL IAM auth token, DSQL connector.
— the description by AWS

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured framework for provisioning, managing, and developing applications on Amazon Aurora DSQL. It emphasizes secure practices, including IAM-based authentication, multi-tenant isolation, and safe SQL construction to prevent injection. The skill includes modular guides for schema migrations, query plan diagnosis, and integration with language-specific DSQL connectors, ensuring robust and performant database operations.

What it does

  • Provisions and manages Aurora DSQL clusters using automated scripts.
  • Implements secure IAM authentication with token rotation patterns.
  • Provides safe SQL construction patterns to prevent injection via untrusted input.
  • Guides multi-tenant schema design and data isolation strategies.
  • Facilitates MySQL-to-DSQL migrations with type and DDL mapping.
  • Supports query performance tuning through EXPLAIN ANALYZE and GUC experiments.

When to use it

  • When setting up or managing an Aurora DSQL cluster.
  • When implementing application-layer database connectivity with IAM auth.
  • When performing schema changes or complex DDL migrations.
  • When migrating existing MySQL workloads to DSQL.
  • When debugging slow queries or optimizing database performance.
  • When building multi-tenant applications requiring strict data isolation.

Advantages

  • Enforces security best practices through mandatory safe SQL construction.
  • Reduces operational risk with validated migration and DDL patterns.
  • Ensures high availability and performance by following canonical connection patterns.
  • Simplifies complex tasks like multi-tenant isolation and batch inserts.
  • Provides clear, modular documentation for specific database lifecycle stages.

Usage examples

“How do I create a new Aurora DSQL cluster with tags?”
The agent will use the provided scripts/create-cluster.sh to issue an atomic CreateCluster call with the specified tags and deletion protection.
“I need to insert 5000 records into my DSQL table safely.”
The agent will guide you to use safe_query.build() for each row, chunking the inserts into batches of under 3000 rows per transaction.
“How should I connect my Python application to DSQL?”
The agent will verify the installation of the aurora-dsql-python-connector and provide code examples using the canonical IAM-token-refresh pattern.
“My query is running slowly, how can I diagnose it?”
The agent will guide you through the query-plan module, using EXPLAIN ANALYZE and GUC experiments to identify bottlenecks.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/aws/aurora-dsql/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip aurora-dsql.zip -d .agents/skills

Documentation by AWS

Amazon Aurora DSQL

Overview

Aurora DSQL is a serverless, PostgreSQL-compatible distributed SQL database. This skill provides direct database interaction via psql scripts and PostgreSQL drivers, schema management, migration support, multi-tenant patterns, and query-plan explainability.

Key capabilities:

  • Direct query execution via psql with generated IAM auth tokens (see scripts/psql-connect.sh)

  • Schema management with DSQL constraints (one DDL per transaction, async indexes)

  • Safe data migration (column-level, constraint-level, MySQL→DSQL)

  • Multi-tenant isolation via tenant_id + parameterized SQL

  • IAM-based authentication with a 15-minute token expiry

  • Query-plan diagnosis for slow queries (EXPLAIN ANALYZE + GUC experiments)

The recommended runtime is psql with aws dsql generate-db-connect-auth-token for IAM-authenticated sessions. Application code SHOULD use the language-specific DSQL Connectors and SDKs. For AWS knowledge lookups (service docs, AWS API calls), the AWS MCP Server is the preferred MCP integration.


Reference Files

Load these files as needed for detailed guidance:

development-guide.md

When: ALWAYS load before implementing schema changes or database operations Contains: Best Practices, DDL rules, connection patterns, transaction limits, data type serialization patterns, application-layer referential integrity instructions, security best practices

Query Execution:
database-tools.md

When: Load when you need detailed syntax and examples for ad-hoc query execution against DSQL. PREFER psql (via scripts/psql-connect.sh) for ad-hoc queries — execute directly rather than writing one-off scripts. Contains: psql-based read-only and write patterns, transaction semantics, input validation

MCP (AWS knowledge / API):
mcp-setup.md

When: Load when configuring or recommending the AWS MCP Server for AWS knowledge lookups, AWS API access, or per-assistant install. Contains: When to use psql vs the AWS MCP Server, pointer to the canonical AWS setup docs, credential reminders.

mcp-tools.md

When: Load when invoking AWS MCP Server tools to verify DSQL service limits, fetch docs, or drive AWS API calls. Contains: Tool surface — knowledge (aws___search_documentation, aws___read_documentation, aws___recommend, aws___retrieve_skill, aws___list_regions, aws___get_regional_availability) and API (aws___call_aws, aws___run_script, aws___get_tasks, aws___get_presigned_url); pointers to documentation-tools.md.

documentation-tools.md

When: Load when looking up DSQL service limits, fetching a specific AWS docs page, or polling long-running AWS API calls launched via the AWS MCP Server. Contains: Detailed parameters and example calls for the AWS knowledge tools.

platforms/ — per-assistant install notes

When: Load when installing the AWS MCP Server inside a specific coding assistant. Contains: Per-assistant entry-point details — claude-code.md, codex.md, gemini.md, kiro.md.

language.md

When: MUST load before writing DSQL connection code. Mirror the linked example_preferred.<ext> for the chosen driver — memory-authored connections drift from the canonical IAM-token-refresh pattern. Canonical entry-point examples (load language.md for the full driver list + pool/TLS/token-refresh details):

  • Python: import aurora_dsql_psycopg as dsql → dsql.connect(host, region, user)

  • JS (node-postgres): import { AuroraDSQLPool } from "@aws/aurora-dsql-node-postgres-connector" → new AuroraDSQLPool({ host, user })

  • JS (postgres.js): import { auroraDSQLPostgres } from "@aws/aurora-dsql-postgresjs-connector" → auroraDSQLPostgres({ host, user })

  • Go (pgx): import "github.com/awslabs/aurora-dsql-connectors/go/pgx/dsql"

  • Java (JDBC): software.amazon.dsql:aurora-dsql-jdbc-connector:1.4.0 → jdbc:aws-dsql:postgresql://...

Contains: Canonical DSQL connector packages per language, driver selection, framework patterns, IAM auth token rotation and TLS configuration, and connection code examples for Python / JavaScript / TypeScript / Go / Java / Rust.

troubleshooting.md

When: Load when debugging errors or unexpected behavior. SHOULD always consult for OCC errors, connection failures, or unexpected query results. Contains: Common pitfalls, error messages, solutions

onboarding.md

When: User explicitly requests to "Get started with DSQL" or similar phrase Contains: Interactive step-by-step guide for new users

access-control.md

When: MUST load when creating database roles, granting permissions, setting up schemas for applications, or handling sensitive data. ALWAYS use scoped roles for applications — create database roles with dsql:DbConnect. Contains: Scoped role setup, IAM-to-database role mapping, schema separation for sensitive data, role design patterns

Authentication & Operations:
auth/authentication-guide.md

When: MUST load when handling IAM auth tokens, secrets, SSL/TLS, connection pooling, or audit logging. Contains: Token lifecycle, secret storage patterns, SSL/TLS settings, connection-pool guidance, audit-log integration.

auth/connectivity-tools.md

When: Load when picking a driver/ORM/adapter or planning bulk-data loading. Contains: Pointer to the canonical AWS DSQL connectivity tools page (drivers, ORMs, adapters) and the bulk-loading docs page.

auth/scaling-guide.md

When: Load when designing for scale — connection pooling, batch optimization, hot-key avoidance, identifier choice. Contains: Horizontal scaling strategy, pool sizing, batch-size guidance, IDENTITY/UUID trade-offs, sequence cache rules.

Implementation Examples:
workflow-patterns.md

When: Load when looking for a worked example of a common multi-step DSQL workflow (schema explore, CREATE+INDEX, safe migration, batch insert, application-layer FK check). Contains: Five canonical patterns with psql / driver code.

dsql-examples.md

When: Load when looking for specific implementation examples. Contains: Index of examples/*.md (connection, schema, data-operations, migrations, patterns).

DDL Migrations (modular):
ddl-migrations/overview.md

When: MUST load when performing DROP COLUMN, RENAME COLUMN, ALTER COLUMN TYPE, or DROP CONSTRAINT Contains: Table recreation pattern overview, transaction rules, common verify & swap pattern

ddl-migrations/column-operations.md

When: Load for DROP COLUMN, ALTER COLUMN TYPE, SET/DROP NOT NULL, SET/DROP DEFAULT migrations Contains: Step-by-step migration patterns for column-level changes

ddl-migrations/constraint-operations.md

When: Load for ADD/DROP CONSTRAINT, MODIFY PRIMARY KEY, column split/merge migrations Contains: Step-by-step migration patterns for constraint and structural changes

ddl-migrations/batched-migration.md

When: Load when migrating tables exceeding 3,000 rows Contains: OFFSET-based and cursor-based batching patterns, progress tracking, error handling

MySQL Migrations (modular):
mysql-migrations/type-mapping.md

When: MUST load when migrating MySQL schemas to DSQL Contains: MySQL data type mappings, feature alternatives, DDL operation mapping

mysql-migrations/ddl-operations.md

When: Load when translating MySQL DDL operations to DSQL equivalents Contains: ALTER COLUMN, DROP COLUMN, AUTO_INCREMENT, ENUM, SET, FOREIGN KEY migration patterns

mysql-migrations/full-example.md

When: Load when migrating a complete MySQL table to DSQL Contains: End-to-end MySQL CREATE TABLE migration example with decision summary

Query Plan Explainability (modular):

When: MUST load all four at Workflow 8 Phase 0 — query-plan/plan-interpretation.md, query-plan/catalog-queries.md, query-plan/guc-experiments.md, query-plan/report-format.md Contains: DSQL node types + Node Duration math + estimation-error bands, pg_class/pg_stats/pg_indexes SQL + correlated-predicate verification, GUC experiment procedures + 30-second skip protocol, required report structure + element checklist + support request template


Query Execution

Run ad-hoc DSQL queries with psql and a freshly-generated IAM auth token. The bundled scripts/psql-connect.sh wraps token generation, TLS configuration, and single-statement guards — PREFER it over hand-rolled psql invocations.

Read-only:

./scripts/psql-connect.sh --cluster <cluster-id> --command "SELECT * FROM entities LIMIT 10"

Write/DDL (IAM admin auth token required):

./scripts/psql-connect.sh --cluster <cluster-id> --admin --command "CREATE INDEX ASYNC ..."

Schema discovery: there is no special list_tables helper — use information_schema:

SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';

See database-tools.md for detailed usage and examples.

AWS Knowledge via the AWS MCP Server (optional)

When connected to the AWS MCP Server, its aws___search_documentation and aws___read_documentation tools can verify DSQL service limits before advising users. The numeric limits below are defaults that may change — when a user's decision depends on an exact limit, verify it first:

LimitDefaultVerify query
Max rows mutated per transaction3,000aurora dsql transaction limits
Max data modified per write transaction10 MiBaurora dsql transaction limits
Max transaction duration5 minutesaurora dsql transaction limits
Max connections per cluster10,000aurora dsql connection limits
IAM auth token expiry15 minutesaurora dsql authentication token
Max connection duration60 minutesaurora dsql connection limits
Max indexes per table24aurora dsql index limits
Max columns per index8aurora dsql index limits
IDENTITY/SEQUENCE CACHE values1 or >= 65536aurora dsql sequence cache

When to verify: Before recommending batch sizes, connection pool settings, or schema designs where hitting a limit would cause failures. No need to verify for general guidance or when the exact number doesn't affect the user's decision.

Fallback: If the AWS MCP Server is unavailable, use the defaults above and note to the user that limits should be verified against DSQL documentation.

CLI Scripts Available

Bash scripts in scripts/ for cluster management (create, delete, list, cluster info) and psql connection. See references/scripts-guide.md for usage. For bulk data loading, see Loading data into Aurora DSQL.

ALWAYS prefer scripts/create-cluster.sh. The script issues a single atomic CreateCluster call with tags embedded — matching the AWS DSQL API shape with interpretable output.

TaskScriptExample
Create cluster with tagsscripts/create-cluster.sh./scripts/create-cluster.sh --created-by <model-id> --tags Environment=eval,Project=dsql-skill-eval
List clustersscripts/list-clusters.sh./scripts/list-clusters.sh --region us-east-1
Inspect clusterscripts/cluster-info.sh./scripts/cluster-info.sh <cluster-id>
Connect via psqlscripts/psql-connect.sh./scripts/psql-connect.sh --cluster <id> --command "SELECT 1"

Quick Start

1. List tables and explore schema
./scripts/psql-connect.sh --cluster <id> --command "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"
./scripts/psql-connect.sh --cluster <id> --command "SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '<table>' ORDER BY ordinal_position"
2. Query data
Use psql-connect.sh (or the language connector in app code) for SELECT queries
Always include tenant_id in WHERE clause for multi-tenant apps
MUST build SQL with safe_query.build() — see references/input-validation.md
3. Execute schema changes
Use ./scripts/psql-connect.sh --admin (or the language connector with the IAM admin auth token) for DDL
Follow one-DDL-per-transaction rule
Always use CREATE INDEX ASYNC in a separate statement
ALTER COLUMN TYPE, DROP COLUMN, DROP CONSTRAINT → Table Recreation Pattern (Workflow 6)

Common Tasks

Workflow 0: Verify Dependencies

Check for required tools and warn the user if any are missing.

Constraints:

  • You MUST verify the following tools are available before proceeding: psql (>=14 for SNI support) and the AWS CLI v2 with aws dsql generate-db-connect-auth-token (and generate-db-connect-admin-auth-token for DDL/role setup)

  • You SHOULD also confirm the AWS MCP Server is available when the user's decision depends on a precise service limit; if absent, use the defaults in the table above and note that limits should be verified against DSQL documentation

  • You MUST inform the user about any missing tools with a clear message

  • You MUST ask if the user wants to proceed despite missing tools

  • You MUST use the scoped (non-admin) IAM auth token for read-only diagnostics whenever the user has a scoped role configured; reserve the IAM admin auth token for cluster setup, role grants, and DDL

  • For cluster lifecycle (create / inspect / delete), see Workflow 0a

  • Before writing application code, ALSO verify the language-specific DSQL Connector per Workflow 0b

Workflow 0a: Cluster Lifecycle

SHOULD use the bundled scripts for cluster create and delete — they issue atomic aws dsql CLI calls and process outputs.

Create a cluster with tags and deletion protection:

./scripts/create-cluster.sh --created-by <model-id> --tags Environment=eval,Project=dsql-skill-eval

Inspect a cluster (status, tags, endpoint, deletion protection):

./scripts/cluster-info.sh <cluster-id>

Delete a cluster:

./scripts/delete-cluster.sh <cluster-id> [--force]   # --force skips the confirmation prompt in non-TTY

In MCP-only environments (no shell access), the equivalent calls go through the AWS MCP Server's aws___call_aws tool. The tool takes a JSON payload — invoke it with arguments matching the AWS API operation:

{"service": "dsql", "operation": "CreateCluster",
 "parameters": {"tags": {"created_by": "<model-id>", "Environment": "eval", "Project": "dsql-skill-eval"}, "deletionProtectionEnabled": true}}
{"service": "dsql", "operation": "GetCluster", "parameters": {"identifier": "<cluster-id>"}}
{"service": "dsql", "operation": "DeleteCluster", "parameters": {"identifier": "<cluster-id>"}}

CreateCluster and DeleteCluster are asynchronous on the DSQL side — the API returns immediately with the cluster's current status (CREATING / DELETING). Poll readiness by re-invoking aws___call_aws with dsql:GetCluster until .status == "ACTIVE" (create) or the call returns a 404 (delete). aws___get_tasks is for polling MCP-side long-running tool invocations — not the DSQL API.

See AWS CLI aws dsql reference for full parameter details and call context.

Workflow 0b: Verify Language Connector

Before writing application code, MUST verify the language-specific DSQL Connector is installed per language.md. The Connectors are the canonical IAM-token-refresh path; bare drivers (pg, psycopg, pgx, tokio-postgres) work until the first 15-minute token expiry and then start returning auth errors on every new connection — DSQL users who try the bare form report this as a DSQL bug. MUST install:

  • Python: aurora-dsql-python-connector + the chosen driver wheel

  • Node.js: @aws/aurora-dsql-node-postgres-connector or @aws/aurora-dsql-postgresjs-connector

  • Go: github.com/awslabs/aurora-dsql-connectors/go/pgx

  • Java: software.amazon.dsql:aurora-dsql-jdbc-connector

  • Rust: aurora-dsql-sqlx-connector

If a Connector is unavailable for the chosen runtime, document the manual token-refresh strategy and schedule with the user before writing code.


Workflow 1: Create Multi-Tenant Schema

MUST load workflow-patterns.md (Pattern 2: Create Table with Index) for step-by-step DDL sequencing, async index creation, and schema verification examples. Key rules: tenant_id in all tables, CREATE INDEX ASYNC only, one DDL per transaction, arrays/JSON stored as TEXT.

Workflow 2: Safe Data Migration

MUST load workflow-patterns.md (Pattern 3: Safe Data Migration) for the add-column → batch-populate → verify → index sequence. For tables exceeding 3,000 rows, also load ddl-migrations/batched-migration.md. Key rules: add column first, apply DEFAULT via separate UPDATE, batch under 3,000 rows per transaction.

Workflow 3: Application-Layer Referential Integrity

MUST load workflow-patterns.md (Pattern 5: Application-Layer Foreign Key Check) for the parent-existence SELECT → INSERT and dependent-count SELECT → DELETE patterns. Build all SQL with safe_query.build() — see Workflow 4a.

Workflow 4: Query with Tenant Isolation
  1. MUST authorize the caller against the tenant — format validation does not establish authorization

  2. MUST build SQL with safe_query.build() — use allow()/regex() for values (emits 'v'), ident() for table/column names (emits "v"). See input-validation.md

  3. MUST include tenant_id in the WHERE clause; reject cross-tenant access at the application layer

Workflow 4a: Rubric-Critical — Building SQL with User Input

Whenever constructing SQL for psql -c "..." (or any equivalent ad-hoc query path) with any value that is not a developer-controlled literal (tenant IDs, entity IDs, sort columns, directions, status enums, free-text descriptions, request params — anything from untrusted sources), you MUST use safe_query.build(). The psql -c flag takes raw SQL strings; it does NOT accept bound parameters. When using a Postgres driver (psycopg, pgx, etc.) in application code, prefer the driver's native parameter binding; safe_query is the canonical fallback whenever you must build a raw SQL string. Validation via safe_query is the primary defense for raw-SQL paths.

Validator selection table (canonical — mirrors input-validation.md):

Value kindValidatorEmits
Known set (tenant ID, status enum)allow(v, SET)'value'
Known set used as SQL keyword (ASC/DESC)keyword(v, SET)value (unquoted)
Strict format (UUID, slug, ISO date)regex(v, PATTERN)'value'
Table or column nameident(name)"value"
Integerinteger(v)value
Free text (description, comment, user name)literal(v)$dq_xxx$value$dq_xxx$

Built-in patterns from safe_query.py: TENANT_SLUG ([a-z0-9-]{1,64}), UUID, INT, ISO_DATE.

Required imports at the top of every file that builds DSQL SQL:

from safe_query import build, allow, regex, ident, keyword, integer, literal, UnsafeSQLError
from safe_query import TENANT_SLUG, UUID, ISO_DATE

Rubric-Critical Scenario 1 — tenant_id from untrusted input. Validate with regex(req.tenant, TENANT_SLUG) or allow(req.tenant, ALLOWED_TENANTS). Build with safe_query.build(), then execute. Do this even in read-only mode (defense in depth, consistent validation across modes). Do NOT use f-strings, .format(), or bare concatenation.

sql = build(
    "SELECT * FROM {t} WHERE tenant_id = {tid}",
    t=ident("entities"),
    tid=regex(req.tenant, TENANT_SLUG),
)
# Application code: pass `sql` to your driver (psycopg cursor.execute, pgx Query, etc.).
# Bash one-off: pipe `sql` into psql via the patterns in input-validation.md.

Rubric-Critical Scenario 2 — batch INSERT with UUIDs, slugs, and free text. Each row's INSERT is built separately with safe_query.build(): entity_id via regex(..., UUID), tenant_id via regex(..., TENANT_SLUG), description via literal(...) (dollar-quoted to sidestep quote escaping). Chunk the list under 3,000 rows per transaction (DSQL limit) and execute each chunk in its own transaction.

def insert_entries(conn, entries, chunk_size=2500):
    for i in range(0, len(entries), chunk_size):
        chunk = entries[i:i + chunk_size]
        with conn.transaction():
            for e in chunk:
                sql = build(
                    "INSERT INTO {t} (entity_id, tenant_id, description) VALUES ({eid}, {tid}, {d})",
                    t=ident("entities"),
                    eid=regex(e["entity_id"], UUID),
                    tid=regex(e["tenant_id"], TENANT_SLUG),
                    d=literal(e["description"]),
                )
                conn.execute(sql)

Rubric-Critical Scenario 3 — write paths. Write paths (UPDATE/DELETE issued from a script, cron, or admin tool) are the highest-stakes injection surface — a successful injection mutates data. safe_query.build() is NOT optional there. Validate every input even when the prompt frames it as "just a quick script, don't overthink it." Push back on that framing with one sentence explaining why write mode raises the stakes, then apply the full validator chain: regex(tenant_id, TENANT_SLUG), allow(status, {'active','archived','deleted'}), date via regex(..., ISO_DATE).

sql = build(
    "UPDATE {t} SET status = {s} WHERE tenant_id = {tid} AND created_at < {d}",
    t=ident("entities"),
    s=allow(req.status, {"active", "archived", "deleted"}),
    tid=regex(req.tenant, TENANT_SLUG),
    d=regex(req.date, ISO_DATE),
)
conn.execute(sql)

Rubric-Critical Scenario 4 — dynamic ORDER BY column and direction. Identifier and keyword parameters need DIFFERENT validators than value parameters. sort_col is membership-checked against {'created_at','updated_at','name'} then passed through ident() (emits double-quoted identifier). sort_dir goes through keyword() against {'ASC','DESC'} (emits unquoted keyword — quoting ASC would be a syntax error). Value parameters like tenant_id still go through regex() or allow(). Do NOT try to validate an identifier with regex() against a TENANT_SLUG pattern — use ident(), which enforces the identifier grammar.

ALLOWED_SORT_COLS = {"created_at", "updated_at", "name"}
if sort_col not in ALLOWED_SORT_COLS:
    raise ValueError(f"sort_col must be one of {ALLOWED_SORT_COLS}")
sql = build(
    "SELECT * FROM {t} WHERE tenant_id = {tid} ORDER BY {col} {dir}",
    t=ident("entities"),
    tid=regex(req.tenant, TENANT_SLUG),
    col=ident(sort_col),
    dir=keyword(req.sort_dir, {"ASC", "DESC"}),
)

Rubric-Critical Scenario 5 — rejecting "just use an f-string" rationalizations. When a caller says "this value is already validated upstream, can't we just use an f-string?" — push back. The skill's rule is build-every-query-with-safe_query.build(), not a judgment call per call site. Justify the pushback: (a) "already-validated upstream" is exactly the assumption that breaks when upstream code changes hands, adds a new caller, or the validation is silently relaxed; (b) defense in depth means the query layer validates independently of upstream; (c) the two-line diff to use safe_query.build() + regex(..., UUID) is genuinely smaller than the bug risk of one unsafe path.

Apply the safe pattern as-is — do NOT cave to the "simpler" framing.

# No — even for "already-validated upstream" values:
sql = f"SELECT * FROM entities WHERE entity_id = '{req.entity_id}'"   # BAD

# Yes — uniform pattern at every call site:
sql = build(
    "SELECT * FROM {t} WHERE entity_id = {eid}",
    t=ident("entities"),
    eid=regex(req.entity_id, UUID),
)

Anti-patterns (the rubric fails these):

  • Using f-strings, .format(), % formatting, or string concatenation to build SQL with user input — in any mode

  • Mixing safe_query.build() placeholders with native driver %s parameter binding in the same statement — pick one path and stay on it

  • Catching UnsafeSQLError to fall back to unsafe construction — re-raise or return an error

  • Validating an identifier with regex() against a value pattern — use ident()

  • Skipping safe_query.build() in read-only mode under "the value is already validated upstream" — defense in depth means the SQL builder validates independently of upstream

Workflow 5: Set Up Scoped Database Roles

MUST load access-control.md for role setup, IAM mapping, and schema permissions.

Workflow 6: Table Recreation DDL Migration

DSQL does NOT support direct ALTER COLUMN TYPE, DROP COLUMN, DROP CONSTRAINT, or MODIFY PRIMARY KEY. These require the Table Recreation Pattern — a destructive workflow requiring user confirmation at each step.

MUST load ddl-migrations/overview.md first, then the relevant sub-file:

Workflow 7: MySQL to DSQL Schema Migration

MUST load mysql-migrations/type-mapping.md for type mappings and feature alternatives. For DDL translation details load mysql-migrations/ddl-operations.md. For an end-to-end example load mysql-migrations/full-example.md.

Workflow 8: Query Plan Explainability

Triggered by slow queries, high DPU, unexpected Full Scans, or plans the user doesn't understand. A structured Markdown diagnostic report is the required deliverable — run the workflow end-to-end before answering.

MUST load all four reference files before starting:

  1. query-plan/plan-interpretation.md — node types, duration math, anomalous values

  2. query-plan/catalog-queries.md — pg_class / pg_stats / pg_indexes SQL

  3. query-plan/guc-experiments.md — GUC procedures and >30s skip protocol

  4. query-plan/report-format.md — required report structure and elements checklist

Phase 1 — Capture the plan. ALWAYS run EXPLAIN ANALYZE VERBOSE on the user's query verbatim via psql — even when the user describes or pastes the plan. SELECT runs as-is. UPDATE/DELETE: rewrite to the equivalent SELECT before running. INSERT, pl/pgsql, DO blocks, and functions MUST be rejected. MUST NOT run mutating DML during plan capture. When EXPLAIN errors, report verbatim — do not invent DSQL-specific semantics. Extract Query ID, Planning Time, Execution Time, and DPU Estimate.

Phase 2 — Gather evidence. Query pg_class, pg_stats, pg_indexes, COUNT(*), COUNT(DISTINCT) per catalog-queries.md. Classify estimation errors per plan-interpretation.md.

Phase 3 — Experiment (conditional). ≤30s: run GUC experiments per guc-experiments.md plus redundant-predicate test. >30s: skip, include manual GUC SQL verbatim in the report. Anomalous row counts: confirm results are correct, flag as potential DSQL bug, produce Support Request Template.

Phase 4 — Report and invite reassessment. Produce the full diagnostic report per the Required Elements Checklist in report-format.md. End with the "Next Steps" block. When user says "reassess", re-run Phases 1–2 and append an "Addendum: After-Change Performance" to the original report.

psql invocation:

./scripts/psql-connect.sh --cluster <id> --command "EXPLAIN ANALYZE VERBOSE <sql>"
./scripts/psql-connect.sh --cluster <id> --script ./experiment-2.sql   # GUC multi-statement

Security Considerations

This section consolidates key security controls. For detailed guidance, see the linked reference files.

  1. IAM auth token expiry: IAM auth tokens expire after 15 minutes. Always generate fresh tokens per connection or implement periodic refresh. Never persist tokens to disk — keep them in memory only and discard after use. See authentication-guide.md.

  2. Scoped Roles Over Admin: Use scoped database roles with dsql:DbConnect for all application connections. Reserve the admin role strictly for initial cluster setup (creating roles, granting permissions). Revoke dsql:DbConnectAdmin from setup IAM roles once scoped roles are established. See access-control.md.

  3. Encryption in Transit: SSL/TLS is enforced server-side. Use sslmode=verify-full (default in DSQL connectors and psql-connect.sh) to validate the server certificate against DSQL's CA, preventing MITM attacks. Only downgrade to require when the client lacks access to a trusted CA bundle.

  4. Encryption at Rest: Aurora DSQL encrypts all data at rest using AWS-managed keys by default. No additional configuration is required; verify encryption status in cluster properties when compliance frameworks require attestation.

  5. Audit Logging via CloudTrail: Enable CloudTrail logging for DSQL API calls to monitor token generation patterns, cluster configuration changes, and failed authentication attempts. Configure CloudWatch alarms for suspicious activity. Enable encryption on CloudWatch Log Groups used for DSQL monitoring using a KMS key to protect potentially sensitive query metadata. See authentication-guide.md.

  6. Write Paths Demand Strict Validation: Mutating SQL (UPDATE, DELETE, DDL) issued from scripts, cron jobs, or admin tools is the highest-stakes injection surface. Every write path MUST route through safe_query.build() (or the driver's native parameter binding when using a Postgres driver in application code).

  7. Input Validation Is the Primary Defense: safe_query.build() is the primary defense against SQL injection on raw-SQL paths. Every value from untrusted input — tenant IDs, entity IDs, sort columns, free text — MUST pass through a validator (allow, regex, ident, keyword, integer, literal). Do not use f-strings, .format(), or concatenation. See input-validation.md.

  8. Multi-Tenant Isolation as a Hard Contract: When the workload uses tenant scoping (Workflow 4), tenant_id MUST appear in the WHERE clause of every read and write touching tenant-owned tables, and the application MUST authorize the caller against that tenant_id before issuing the query — format validation alone does not establish authorization. Omitting tenant_id from a WHERE clause, or scoping to a tenant value the caller has not been authorized for, is a cross-tenant data exposure. This boundary is enforced by the skill, not by DSQL — verify every data-access path scopes to the authenticated tenant before deployment. See access-control.md and Workflow 4.


Troubleshooting

  • AWS MCP Server returns no results: Use the default limits in the table above and note that limits should be verified against DSQL documentation.

  • OCC serialization error: Retry the transaction. If persistent, check for hot-key contention — see troubleshooting.md.

  • Transaction exceeds limits: Split into batches under 3,000 rows — see batched-migration.md.

  • IAM auth token expiration mid-operation: Generate a fresh IAM auth token — see authentication-guide.md. See troubleshooting.md for other issues.


Additional Resources

Handoff from aws-database-selection

This skill can be invoked directly, or it can be entered from the aws-database-selection parent skill after that skill has run a requirements interview and produced a requirements.json artifact. When you see a backtick-wrapped path matching aws_dbs_requirements/*/requirements.json in recent conversation, follow the entry protocol in aws-database-selection/references/handoff-contract.md:

  1. Read the artifact using file_read.

  2. Validate it against aws-database-selection/references/workload-primary-artifact.schema.json. If malformed or unreadable, tell the user and proceed without it.

  3. Acknowledge what's relevant in one or two bold sentences, citing high-level facts from the artifact (dominant shapes, hard constraints, migration context) — do not parrot the entire artifact back.

  4. Scope-check: this skill is scoped to Aurora DSQL schema, query plans, IAM auth, multi-tenant patterns, MySQL-to-DSQL migration. If the artifact's workload_primaries.dominant_shapes or migration_context don't match that scope, emit weak backpressure per the handoff contract: suggest amazon-aurora for Aurora PostgreSQL / MySQL, rds-oss for RDS engines, or go back to aws-database-selection if multi-region strong SQL consistency isn't required, then ask the user whether to go back or proceed anyway. Do not silently misuse the artifact.

  5. Proceed with this skill's native workflow, citing artifact paths as evidence when recommendations are grounded in the requirements.

All user-facing output from this skill follows the markdown-primitives-only formatting convention in the handoff contract: bold labels, backticks for paths and enum values, bullet lists for alternatives, no ASCII art or box-drawing characters.

Files

references/onboarding.md

Aurora DSQL Get Started Guide

Overview

This guide provides steps to help users get started with Aurora DSQL in their project. It sets up their DSQL cluster with IAM authentication and connects their database to their code by understanding the context within the codebase.

Use Case

These guidelines apply when users say "Get started with DSQL" or similar phrases. The user's codebase may be mature (with existing database connections) or have little to no code - the guidelines should apply to both cases.

Contents

  • Overview

  • Use Case

  • Agent Communication Style

  • Get Started with DSQL (Interactive Guide) — 10-step linear walkthrough

  • DSQL Best Practices

  • Additional Resources

Agent Communication Style

Keep all responses succinct:

  • ALWAYS tell the user what you did.

    • Responses MUST be concise and concrete.

    • ALWAYS contain descriptions to necessary steps.

    • ALWAYS remove unnecessary verbiage.

    • Example:

      • "Created an inventory table with 4 columns"

      • "Updated the product column to be NOT NULL"

  • Ask direct questions when needed:

    • ALWAYS ask clarifying questions to avoid inaccurate assumptions

    • User ambiguity SHOULD result in questions.

    • MUST clarify incompatible user decisions

    • Example:

      • "What column names would you like in this table?"

      • "What is the column name of the primary key?"

      • "JSON must be serialized. Would you like to stringify the JSON to serialize it as TEXT?"

Examples:

  • Good: "Generated auth token. Ready to connect with psql?"

  • Bad: "I'm going to generate an authentication token using the AWS CLI which will allow you to connect to your database. This token will be valid for..."


Get Started with DSQL (Interactive Guide)

TRIGGER PHRASE: When the user says "Get started with DSQL", "Get started with Aurora DSQL", or similar phrases, provide an interactive onboarding experience by following these steps:

Before starting: Let the user know they can pause and resume anytime by saying "Continue with DSQL setup" if they need to come back later.

RESUME TRIGGER: If the user says "Continue with DSQL setup" or similar, check what's already configured (AWS credentials, clusters, AWS MCP Server installation if applicable, connection tested) and resume from where they left off. Ask them which step they'd like to continue from or analyze their setup to determine automatically.

Step 1: Verify Prerequisites

Check AWS credentials:

aws sts get-caller-identity

If not configured:

  • Guide them through aws configure

  • MUST verify IAM permissions include dsql:CreateCluster, dsql:GetCluster, dsql:DbConnectAdmin

  • For initial setup, use a scoped inline policy with only the minimum permissions needed. dsql:CreateCluster and dsql:ListClusters cannot target a specific cluster ARN (the cluster does not yet exist, and ListClusters is a list operation), so they go in a separate statement with Resource: "*". Cluster-scoped actions stay on the specific ARN:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "dsql:CreateCluster",
            "dsql:ListClusters"
          ],
          "Resource": "*"
        },
        {
          "Effect": "Allow",
          "Action": [
            "dsql:GetCluster",
            "dsql:DeleteCluster",
            "dsql:DbConnectAdmin"
          ],
          "Resource": "arn:aws:dsql:<region>:<account-id>:cluster/<cluster-id>"
        }
      ]
    }

    Replace <cluster-id> with the actual cluster ID returned from cluster creation. After Step 4, narrow the first statement further by adding an aws:RequestTag/<key> condition to dsql:CreateCluster (or remove dsql:CreateCluster entirely once the cluster exists). aws:RequestTag is required here because dsql:CreateCluster runs before any cluster (and any resource tag) exists. Revoke dsql:DbConnectAdmin after scoped database roles are established (Step 9).

Check PostgreSQL client:

psql --version

**If missing OR version <=14:** DSQL requires SNI support from psql >=14.

  • macOS: brew install postgresql@17

  • Linux (Debian/Ubuntu): sudo apt-get install postgresql-client

  • Linux (RHEL/CentOS/Amazon Linux):

    sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
    sudo yum install -y postgresql17
Step 2: Check for Existing Clusters

Set region (uses AWS_REGION or REGION if set, defaults to us-east-1):

REGION=${AWS_REGION:-${REGION:-us-east-1}}
echo $REGION

List clusters in the region:

aws dsql list-clusters --region $REGION

If they have NO clusters:

  • Ask: "Would you like to create a new DSQL cluster in $REGION or a different region?"

    • If yes, proceed to create single-region cluster

    • If they want different region, ask which one and update REGION variable

If they have ANY clusters:

  • List ALL cluster identifiers with creation dates and status

  • Ask: "Would you like to use one of these clusters or create a new one?"

    • If using existing, proceed to Step 3.

    • If creating new:

      • "Which region would you like to create a enw cluster in?"

      • Immediately update REGION variable

  • Confirm all selections before proceeding.

Create cluster command (if needed):

aws dsql create-cluster --region $REGION --tags '{"Name":"my-dsql-cluster","created_by":"<model-id>"}'

Wait for ACTIVE status (takes ~60 seconds):

aws dsql get-cluster --identifier CLUSTER_ID --region $REGION
Step 3: Get Cluster Connection Details

Construct cluster endpoint:

CLUSTER_ID="<selected-cluster-id>"
CLUSTER_ENDPOINT="${CLUSTER_ID}.dsql.${REGION}.on.aws"
echo $CLUSTER_ENDPOINT

Store endpoint for their project environment:

  • Check for .env file or environment config

  • Add or update: DSQL_ENDPOINT=<endpoint>

  • Add region: AWS_REGION=$REGION

  • ALWAYS try reading .env first before modifying

  • If file is unreadable, use: echo "DSQL_ENDPOINT=$CLUSTER_ENDPOINT" >> .env

Step 4: Set Up the AWS MCP Server (Optional)

Would the user like AWS knowledge tools (documentation search/read, AWS API access) wired into their coding assistant?

If so, install the AWS MCP Server per the AWS docs. It provides:

  • aws___search_documentation / aws___read_documentation / aws___recommend — DSQL docs lookup

  • aws___call_aws — authenticated AWS API calls (for dsql: actions like cluster management)

  • aws___run_script — sandboxed Python with AWS API access

A custom DSQL-specific MCP is optional. If the user has one configured already, it can stay alongside the AWS MCP Server. For ad-hoc DSQL queries, this skill PREFERS direct psql via scripts/psql-connect.sh over MCP-mediated execution.

Step 5: Test Connection

⚠️ Security Note: The admin connection (generate-db-connect-admin-auth-token + admin user) should only be used for the initial setup steps below (creating roles, granting permissions). Once scoped roles are established in Step 9, all subsequent operations should use the scoped role with generate-db-connect-auth-token. Consider revoking dsql:DbConnectAdmin from the setup IAM role after scoped roles are in place.

Generate authentication token and connect:

export PGPASSWORD=$(aws dsql generate-db-connect-admin-auth-token \
  --region $REGION \
  --hostname $CLUSTER_ENDPOINT \
  --expires-in 3600)

export PGSSLMODE=verify-full
export PGAPPNAME="<app-name>/<model-id>"

psql --quiet -h $CLUSTER_ENDPOINT -U admin -d postgres

Verify with test query:

SELECT current_database(), version();

If connection fails:

  • Check token expiration (regenerate if needed)

  • Verify SSL mode is set

  • Confirm cluster is ACTIVE

  • Check IAM permissions

Step 6: Understand the Project

First, check if this is an empty/new project:

  • Look for existing source code, routes, or application logic

  • Check if it's just minimal boilerplate

If empty or near-empty project:

  • Ask briefly (1-2 questions): What are they building? Any specific tech preferences?

  • Remember context for subsequent steps

If established project:

  • Skip questions - infer from codebase

  • Check for existing database code or ORMs

  • Update relevant code to use DSQL

ALWAYS reference ./development-guide.md before making schema changes

Step 7: Install Database Driver

Based on their language, install appropriate driver (some examples):

JavaScript/TypeScript:

npm install @aws/aurora-dsql-node-postgres-connector tsx

Python:

pip install aurora-dsql-python-connector 'psycopg[binary]' psycopg-pool

Go:

go get github.com/awslabs/aurora-dsql-connectors/go/pgx

Rust:

cargo add aurora-dsql-sqlx-connector --features pool,occ
cargo add sqlx tokio --features postgres,runtime-tokio-native-tls,full

For implementation patterns, reference ./dsql-examples.md and ./language.md

Step 8: Schema Setup

Check for existing schema:

  • Search for .sql files, migration folders, ORM schemas (Prisma, Drizzle, TypeORM)

If existing schema found:

  • Show what you found

  • Ask: "Found existing schema definitions. Want to migrate these to DSQL?"

  • If yes, MUST verify DSQL compatibility:

    • No SERIAL types (use GENERATED AS IDENTITY with sequences, or UUID)

    • No foreign keys (implement in application)

    • No array/JSON column types (serialize as TEXT)

    • Reference ./development-guide.md for full constraints

If no schema found:

  • Ask if they want to:

    1. Create simple example table

    2. Design custom schema together

    3. Skip for now

If creating example table:

Use scripts/psql-connect.sh --admin to execute:

CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX ASYNC idx_users_email ON users(email);

For custom schema:

  • Ask about their app's needs

  • Design tables following DSQL constraints

  • Reference ./dsql-examples.md for patterns

  • ALWAYS use CREATE INDEX ASYNC for all indexes

Step 9: Set Up Scoped Database Roles

Recommend creating scoped roles before application development begins.

  • Ask: "Would you like to set up scoped database roles for your application? This is recommended over using admin directly."

  • If yes, follow access-control.md for detailed guidance

  • At minimum, guide creating one application role:

-- As admin
CREATE ROLE app_user WITH LOGIN;
AWS IAM GRANT app_user TO 'arn:aws:iam::<account-id>:role/<AppIAMRole>';
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
  • If the application handles sensitive user data, recommend a separate schema:

CREATE SCHEMA users_schema;
GRANT USAGE ON SCHEMA users_schema TO app_user;
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA users_schema TO app_user;
GRANT CREATE ON SCHEMA users_schema TO app_user;
  • After setup, application connections should use generate-db-connect-auth-token (not the admin variant)

Step 10: What's Next

Let them know you're ready to help with more:

"You're all set! Here are some things I can help with - feel free to ask about any of these (or anything else):

  • Schema design and migrations following DSQL best practices

  • Writing queries with proper tenant isolation

  • Connection pooling and token refresh strategies

  • Multi-region cluster setup for high availability

  • Performance optimization with indexes and query patterns

  • Setting up additional scoped roles for different services"

Important Notes:
  • ALWAYS be succinct - guide step-by-step without verbose explanations

  • ALWAYS check ./development-guide.md before schema operations

  • ALWAYS prefer scripts/psql-connect.sh for DSQL queries; reach for the AWS MCP Server when AWS knowledge or dsql: API calls are needed

  • ALWAYS validate DSQL compatibility for existing schemas

  • ALWAYS provide working, tested commands

  • MUST handle token expiration gracefully (15-minute default, 1-hour recommended)


DSQL Best Practices

Critical Constraints

ALWAYS follow these rules:

  1. Indexes: Use CREATE INDEX ASYNC - synchronous index creation not supported

  2. Serialization: Store arrays/JSON as TEXT (comma-separated or JSON.stringify)

  3. Referential Integrity: Implement foreign key validation in application code

  4. DDL Operations: Execute one DDL per transaction, no mixing with DML

  5. Transaction Limits: Maximum 3,000 row modifications, 10 MiB data size per transaction

  6. Token Refresh: Regenerate auth tokens before 15-minute expiration

  7. SSL Required: Always set PGSSLMODE=verify-full or sslmode=verify-full (use require as a fallback only when the CA bundle is unavailable)

DSQL-Specific Features

Leverage Aurora DSQL capabilities:

  1. Serverless: True scale-to-zero with consumption-based pricing

  2. Distributed: Active-active writes across multiple regions

  3. Strong Consistency: Immediate read-your-writes across all regions

  4. IAM Authentication: No password management, automatic token rotation

  5. PostgreSQL Compatible: Supports many database drivers, ORMs, and adapters — see the AWS DSQL connectivity tools page for the current list.

For detailed patterns, see ./development-guide.md

Additional Resources

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
AWS
Publisher
AWS (Official)
Source
aws/agent-toolkit-for-aws · skills/specialized-skills/database-skills/aurora-dsql · commit 0a218f8
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • NOTICE (added by AutoGineer from NOTICE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by AWS.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aurora-dsql.zip