1. dialects
prorm
  • prorm documentation
  • Known test gaps
  • Architecture
  • Core concepts
  • Database types & coverage
  • Getting started
  • Going further
  • compliance
    • Compliance
    • The security toolkit: `prorm audit`
    • Checklists by regulation
    • Declaring personal data
    • Evidence bundles
    • Evidence
    • Frameworks: `@Security`
    • Jurisdictions
    • Platform policies
    • Protecting data
    • The regulation dataset
    • Residency and cross-border transfers
    • Retention & integrity
    • Status
    • Subject rights
  • decorators
    • prorm with decorators
    • Models with decorators
    • Querying a decorated model
    • Relations with decorators
  • diagrams
    • Diagram generators
    • Chen diagram
    • Class diagram
    • Dependency diagram
    • ER diagram
    • Flow diagram
    • From your models to a diagram
    • Gantt diagram
    • Index diagram
    • Migration diagram
    • Model diagram
    • Package diagram
    • Crow’s-foot diagram
    • Schema documentation
    • Sequence diagram
    • State diagram
    • Tree diagram
  • dialects
    • SQL dialects
    • AlloyDB Dialect
    • AlloyDB Omni Dialect
    • Amazon Athena Dialect
    • Aurora DSQL Dialect
    • Amazon Aurora MySQL Dialect
    • Amazon Aurora PostgreSQL Dialect
    • Azure Database for MySQL Dialect
    • Azure Database for PostgreSQL Dialect
    • Azure SQL Database Dialect
    • Azure SQL Managed Instance Dialect
    • Google BigQuery Dialect
    • Citus Dialect
    • ClickHouse dialect
    • Cloud Authentication (`cloud-auth`)
    • Cloud SQL for SQL Server Dialect
    • Cloud SQL for MySQL Dialect
    • Cloud SQL for PostgreSQL Dialect
    • CockroachDB Dialect
    • Azure Cosmos DB for PostgreSQL Dialect
    • CrateDB Dialect
    • Cloudflare D1 Dialect
    • Databricks dialect
    • IBM Db2 Dialect
    • Dolt Dialect
    • Apache Doris Dialect
    • Druid Dialect
    • DuckDB Dialect
    • Exasol dialect
    • Microsoft Fabric Data Warehouse Dialect
    • Firebird Dialect
    • Greenplum Dialect
    • SAP HANA Dialect
    • MySQL HeatWave Dialect
    • Azure Data Explorer (Kusto) Dialect — T-SQL
    • MariaDB Dialect
    • Materialize Dialect
    • MonetDB Dialect
    • MotherDuck Dialect
    • Microsoft SQL Server Dialect
    • MySQL Dialect
    • Neon Dialect
    • OceanBase Dialect
    • openGauss Dialect
    • Oracle Dialect
    • Oracle Autonomous Database Dialect
    • ParadeDB Dialect
    • PolarDB Dialect
    • PostgreSQL Dialect
    • Presto Dialect
    • QuestDB Dialect
    • Aurora RDS Data API Dialect (`rdsdata`)
    • Amazon RDS for Db2 Dialect
    • Amazon RDS for MariaDB Dialect
    • Amazon RDS for SQL Server Dialect
    • Amazon RDS for MySQL Dialect
    • Amazon RDS for Oracle Dialect
    • Amazon RDS for PostgreSQL Dialect
    • Amazon Redshift
    • Amazon Redshift Data API Dialect
    • RisingWave Dialect
    • rqlite Dialect
    • SingleStore Dialect
    • Snowflake Dialect
    • Google Cloud Spanner Dialect
    • Spanner (PostgreSQL interface) Dialect
    • SQLite Dialect
    • StarRocks Dialect
    • Supabase Dialect
    • Azure Synapse Analytics (dedicated SQL pool)
    • Teradata Dialect
    • TiDB Dialect
    • TimescaleDB Dialect
    • Trino Dialect
    • Turso / libSQL Dialect
    • Vertica dialect
    • Vitess Dialect
    • Yellowbrick Dialect
    • YugabyteDB Dialect
  • guides
    • Access rules and behaviour profiles
    • ArangoDB (AQL)
    • Associations
    • Audit levels and escalation
    • Audit logging
    • In the browser
    • Bulk operations
    • Caching
    • Capabilities, tiers and team roles
    • CLI
    • Cloudflare
    • Compliance & data protection
    • Connection Pooling & Performance
    • Security in the console
    • Couchbase: structured N1QL queries
    • Data types
    • Decorators
    • Eager loading
    • Enums and constants
    • Error handling & error types
    • Extensions
    • External fields
    • Foreign data wrappers
    • Graph databases
    • Hooks & lifecycle events
    • Indexes & constraints
    • InfluxDB: structured Flux pipelines
    • klock-errors
    • klock — the `.klock` file
    • Local databases (`prorm db up`)
    • Structured log search — Splunk, Graylog, Papertrail, Sumo Logic
    • Logging
    • Grafana Loki: structured LogQL queries
    • MCP server
    • Migrate — the data transfer subsystem
    • Migrations & Schema Sync
    • Models from an existing database
    • Defining models
    • Multiple databases
    • OrientDB, Neptune and TigerGraph
    • Passwords
    • Importing a Prisma schema
    • Structured PromQL and MetricsQL
    • Query firewall
    • QueryInterface
    • Query operators reference
    • Query optimization
    • Composing find options with `pipe()` and `Q`
    • Query safety: the fail-closed WHERE guard
    • Querying
    • Raw Queries & Query Building
    • Read replicas
    • Schema diffing & migration generation
    • Views, triggers & other schema objects
    • Scopes & default scopes
    • Seeders
    • SPARQL / RDF triplestores
    • SQL constants
    • SQL features
    • SQL function builders
    • SQLite advanced features
    • StoreKey — a prod-orm database as the storage
    • Streaming results
    • Terraform
    • Transactions & Isolation Levels
    • Type mapping: legacy and modern
    • TypeScript types
    • Database users, roles & privileges
    • Validation & constraints
    • Virtual & Computed Fields
    • Writing docs
  • javascript
    • prorm in JavaScript
    • Models in JavaScript
    • Querying in JavaScript
    • Relations in JavaScript
  • runbooks
    • Operational runbooks
    • Connection failures
    • Credential rotation
    • Failover
    • Incident checklist
    • Deploying klock v2
    • Migration rollback
  • running-databases
    • Running databases in Docker
    • Running prorm under Bun in Docker
    • Running Cassandra in Docker with prorm
    • Running ClickHouse in Docker with prorm
    • Running CockroachDB in Docker with prorm
    • Running prorm under Deno in Docker
    • Running Elasticsearch in Docker with prorm
    • Running MariaDB in Docker with prorm
    • Running MongoDB in Docker with prorm
  • prorm control plane
    • Introduction
    • Authentication
    • Errors
    • Getting started
      • Service
        • Is it up
        • This description
    • Account
      • Sign-up and verification
        • Create an account
        • Exchange credentials for a token
        • Verify with the emailed code
        • Verify by clicking the emailed link
        • Name the parent or guardian
        • What a consent link is about
        • Give consent for a child's account
        • Ask the parent or guardian again
        • Send a new code and link
      • Family
        • Everyone this account is responsible for
        • One child, in detail
        • Turn a limit on or off
      • Profile
        • Who am I
        • Change the account
        • Every address on the account
        • Add an address
        • Confirm an address with the code mailed to it
        • Mail a fresh code to an unconfirmed address
        • Make an address primary
        • Remove an address
        • What this caller may do
    • Security
      • Sessions
        • Everywhere this account is signed in
        • Sign out everywhere else
        • Sign one out
        • A token for the CLI on a named machine
        • A token for the customer console, from the staff one
        • Park a sign-in for the CLI to collect
        • The CLI collecting its sign-in
        • The team's members' live sessions
        • Sign a member's session out
        • Sign an account out everywhere
        • Everywhere the account is signed in
        • Sign an account's session out
      • Single sign-on
        • Begin a single sign-on
        • The provider's return
        • Link the signed-in account to a team's provider
        • Which team an address signs in to
        • The team's single sign-on, as a member sees it
        • Set the team's OpenID Connect provider up, or change it
        • Remove the provider
        • The team's domain claims and the DNS record each needs
        • Prove a claimed domain
      • MFA and passwords
        • Start enrolling a second factor
        • Prove the app has it
        • Remove the second factor
        • Ask for a reset link
        • Set a new password with the emailed token
      • Klock
        • Open a device-bound klock session
        • Check in, for the next grant
        • Step up the session asking
        • Rotate the device key
        • Freeze a session
        • Unfreeze a session
        • A guest grant
        • The revocation feed
        • The published keyset
        • What this control plane supports
      • Devices
        • Your devices, or a team's
        • Approve a new device's pairing code
        • One device
        • Rename a device
        • Revoke a device
        • Suspend a device
        • Reinstate a suspended device
        • Wipe a device
        • Ask a device to rotate its key
        • The team's members' devices
        • Revoke a member's device
        • An account's devices
        • Revoke an account's device
        • Wipe an account's device
        • The device fleet
      • Access rules and behaviour
        • The access rules that bear on you
        • Add an access rule
        • This request, as the rules see it
        • One access rule
        • Remove an access rule
        • The behaviour profiles that bear on you
        • Add or change a behaviour profile
        • The profile presets
        • Your behaviour findings
        • Acknowledge a finding
        • One behaviour profile
        • Remove a behaviour profile
        • The team's access rules
        • Add a team access rule
        • Remove a team access rule
        • The team's behaviour profiles
        • Add or change a team behaviour profile
        • Remove a team behaviour profile
        • What the team's profiles caught
        • Acknowledge a team finding
      • Recovery and lockdown
        • Ask for a recovery link
        • Recover access with the emailed code
        • Is the account locked down
        • Lock the account down
        • Release a lockdown
        • Lock a member down
        • Release a member's lockdown
      • MCP tokens
        • Make a delegated token for one MCP client
        • The account's delegated tokens
        • Revoke a delegated token
        • What a delegated token may do now
        • Run one MCP tool with a delegated token
        • Run a device-signed MCP tool call relayed by the MCP Worker
      • Kerberos
        • Give the team its own Kerberos realm
        • The team's realm
        • Remove the team's realm
    • Logging and monitoring
      • Audit log
        • What has been done to the account
        • What has happened to this account
        • The account's audit trail
      • Operations
        • Everything that has been asked of this database
        • One, with its steps
        • Stop it
        • Put a failed one back in the queue
        • Every operation, across all accounts
      • Metrics and events
        • Every measurement, for a graph
        • Who did what to it
    • Billing
      • Plans and pricing
        • What the plans allow
        • The rate card
        • What one database would cost
        • What this account is paying for, itemised
      • Subscriptions and invoices
        • What this month's invoice will say
        • What this account is on
        • What it has been charged
        • Start a Stripe Checkout session
        • Open the customer portal
        • Stripe's events
        • Buy more connection pools
      • Team billing
        • The team's billing account
        • What the team has been charged
        • What this month's invoice will say
        • The team's cards
        • Add a card, through a Stripe-hosted setup session
        • Make a card the team's default
        • Remove a card
        • Start the team paying
        • Open the Stripe portal on the team's customer
        • Change the team's plan
        • Who receives the team's bills
        • How the team pays for transfers
    • Support
      • Support chat
        • My conversations
        • Start a conversation
        • Every support conversation, open first
        • A ticket for the socket
        • One conversation, with who is in it and who is connected
        • Rename a group; open or close a support conversation
        • The lines, oldest first
        • Say something
        • Add somebody
        • Mark read
    • Administration
      • Users
        • Every account
        • One account, with everything hanging off it
        • Grant or revoke admin
        • Verify an account by hand
        • Lock or unlock sign-in
        • Allow or hold provisioning
        • Send the verification mail again
        • Set the plan by hand
      • Platform
        • Every database and store, across all accounts
        • The counts worth putting on a dashboard
      • Staff and permissions
        • What kind of admin the caller is, and which scopes they hold
        • The admin presets
        • Every admin, and the scopes each resolves to
        • Make an account an admin of a kind
        • Change an admin's kind, or a custom admin's scopes
        • Revoke admin
      • Team administration
        • Every team, with its owner and size
        • One team in full — members with their accounts, and projects
        • Hand the team to another member
        • Put an account in the team, active at once
        • Change a member's role
        • Remove a member
      • Assumed identities
        • Assume an identity — act as a customer account
        • The identities the caller holds open
        • End an assumed identity
      • Support inbox
        • The platform's addresses
        • Add a platform address
        • One address, with its counts
        • Change an address's label, routing, or whether it accepts mail
        • Remove an address that holds no mail
        • Make, adopt or repair the address's routing rule
        • Every admin's personal address, made where missing
        • File a raw message, as if it had arrived
        • The inbox
        • One message, whole
        • Mark a message
        • Hand a message to an admin, or take it back
        • Leave an internal note
        • Reply, from the address the message came to
        • What is waiting
    • Databases
      • Databases
        • Data stores
          • Every data store on the account
          • Provision a data store
          • Change a data store that is already running
          • One data store
          • Deprovision it
          • Report what it is using
          • How to reach a data store
        • Connections and credentials
          • The api keys on a database
          • Issue a key
          • Revoke a key
          • The engine users we created
          • Create a user inside the database
          • Give a user a new password
          • Drop a user
          • How the database is reached
          • Set how it is reached
          • Revoke every api key on it
          • How to connect to it
          • The ssh keys that open its bastion
          • Add a key, or have one made
          • The private half of a generated key, once
          • Revoke an ssh key
        • Schema and objects
          • The SQL objects we put in it
          • Create one, and apply it
          • What is in the database, as the engine reports it
          • One table
          • What it would run, without running it
          • Redefine an object in place
          • Drop it
          • The extensions installed in it
        • Migrations
          • A plan compiled to statements, recording nothing
          • The migrations recorded for it
          • Record one
          • Apply everything recorded and not yet run
          • Apply everything pending, oldest version first
        • Lifecycle
          • Grow or shrink it
          • Stop it accepting connections
          • Start it again
          • Move it to another region
        • Backups and replicas
          • Take a backup
          • The backups it has
          • Restore one into it
          • What has been restored into it, and from where
          • Its read copies
          • Add one
        • Policies
          • The catalog
          • One policy
          • What this database is held to
          • Switch a policy on, or change its knobs
          • Switch it off
          • Mark the policies reviewed
          • Evaluate the periodic policies now
          • Who is behind a credential
        • Passwordless
          • The database's passwordless sessions
          • Issue a passwordless session (v1)
          • Revoke a passwordless session
          • Bind a session to a device key
          • Issue a v2 session for a host to bind
          • Redeem an enrolment ticket on the host
          • Check a passwordless credential
          • Run one described query under a passwordless credential
        • Database roles
          • The database's roles
          • Define a role
          • One role
          • Change what a role permits
          • Delete a role, and revoke every key granted it
          • Grant a role, which mints a key
          • Who holds a role
          • The api keys bound to a role
        • Pools
          • A database's connection pools, and how busy each is
          • Open another pool
          • Rename a pool or change its size
          • Close a pool
        • Data plane
          • Run a query against a database
          • Several statements, in order, over one connection
          • Is this database answering
          • What the proxy itself is holding
        • Transfers
          • The strategies this account's tier may use
          • Price a transfer without creating it
          • The account's transfer jobs, newest first
          • Create a transfer job
          • One job, and whether its certificate holds
          • Cancel an unfinished job
          • Start a created job, confirming its price
          • Report a job's status (the runner, or the owner's side of a local run)
        • Every database on the account
        • Provision a database
        • Change a database that is already running
        • One database
        • Deprovision it
        • Read or write it
        • Report what it is using
        • The engines this API will provision
        • Where a managed database can be put
    • Teams
      • Teams
        • Members
          • Who is on it
          • Invite somebody
          • Accept an invitation
          • Change somebody's role
          • Remove somebody
        • Projects
          • The projects a team runs
          • Start one
          • Rename a project, or move its environment
          • Delete a project
          • One project, and what is in it
          • Put a database or store in it
          • What is in a project
          • Take one out
        • The teams this account is on
        • Start one
        • The twelve roles, and what each may do
        • Rename a team
        • Close a team
        • One team
        • Hand the team to somebody else
        • Leave a team
    • Schemas
      • Error
      • ValidationErrors
      • Token
      • PolicyCategory
      • PolicySeverity
      • PolicyAction
      • PolicyTrigger
      • PolicyParam
      • Policy
      • PolicyCatalog
      • PolicyAssignment
      • PolicyOutcome
      • PolicyFiring
      • CredentialTrace
      • Relation
      • Restrictions
      • ChildSummary
      • SignupRequest
      • SigninRequest
      • UpdateMeRequest
      • User
      • Address
      • GeoPoint
      • D1Region
      • Usage
      • UsageReport
      • Resource
      • Database
      • DataStore
      • NewDatabase
      • NewDataStore
      • QueryRequest
      • DatabasePrivilege
      • ApiKey
      • DbUser
      • Access
      • AccessRequest
      • DatabaseObject
      • NewDatabaseObject
      • NewMigration
      • SchemaOperation
      • Migration
      • Operation
      • Session
      • AdminPowers
      • Admin
      • AuditEntry
      • TeamRole
      • Conversation
      • ChatMessage
      • TeamSso
      • Team
      • TeamMember
      • SshKey
      • ConnectionInfo
      • InboxAddress
      • InboxMailbox
      • InboxMessageSummary
      • InboxMessage
      • InboxNote
      • Page
      • Quote
      • Plan
      • ApiError
      • CapabilityRefusal
      • KlockErrorCode
      • PageWindow
      • SessionView
      • KlockStepUpRequest
      • KlockOpenRequest
      • KlockOpenedSession
      • UpdateMeResult
      • CapabilitiesView
      • SessionLimits
      • Device
      • DeviceListed
      • DeviceTeamRef
      • DeviceCommand
      • DeviceAuditLine
      • DeviceActionRequest
      • StaffActionRequest
      • ManagedSession
      • SessionRevoked
      • AccessRule
      • AccessRuleRequest
      • BehaviourProfile
      • BehaviourProfileRequest
      • BehaviourProfileSaved
      • BehaviourFinding
      • BehaviourFindingAck
      • StepUpProof
      • Removed
      • MemberLockdownRequest
      • McpClient
      • McpDelegatedView
      • McpToolCall
      • McpForwardRequest
      • PasswordlessScope
      • RoleScope
      • PasswordlessSession
      • PasswordlessTlsMaterial
      • PasswordlessKerberosMaterial
      • ServiceDeviceKeys
      • ServiceSession
      • DatabaseRole
      • TransferEndpoint
      • TransferJobRequest
      • TransferQuote
      • TransferStrategy
      • TransferJob
      • TransferJobAccess
      • Pool
      • PoolAllowance
      • BillingSubscription
      • Invoice
      • BillingContact
      • PaymentMethod
      • UpcomingCharges
      • TeamBilling
      • TeamKerberosRealm
      • TeamSsoDomain
      • TeamSsoResponse
      • StoreConnection
      • BatchFailure
      • ProxyStatus
  1. dialects

Amazon Athena Dialect

Overview#

PropertyValue
Dialect nameathena
ExtendsTrinoDialect (trino)
Driver@aws-sdk/client-athena
Cloud SDK@aws-sdk/client-athena
Default port8080
Local runtimenone — hosted service only
Source: athena
Tests: athena, athena-driver
Amazon Athena is a serverless, query-only SQL engine over data in S3. Athena engine version 3 is built on Trino, so its query surface — ANSI SQL, double-quoted identifiers, OFFSET before LIMIT, ARRAY(...) types, no key constraints, no identity columns — is Trino's.
AthenaDialect therefore extends TrinoDialect, the same way TimescaleDBDialect extends PostgresDialect and TiDBDialect extends MySQLDialect:
export class AthenaDialect extends TrinoDialect {
  readonly library = '@aws-sdk/client-athena';
  // ...
}
What is not Trino, and is overridden here:
No connection. Athena is an HTTP API. connect() builds an AthenaClient; queries go out through StartQueryExecution → GetQueryExecution → GetQueryResults.
Two identifier-quoting rules. DDL is Hive DDL (backticks); queries are Trino (double quotes).
Two type vocabularies. Hive names (string, int, binary, array<t>) in DDL; Trino names (VARCHAR, INTEGER, VARBINARY, ARRAY(t)) in queries.
No ordinary CREATE TABLE (cols). A table is a CREATE EXTERNAL TABLE ... LOCATION 's3://...', an Iceberg CREATE TABLE ... TBLPROPERTIES ('table_type'='ICEBERG'), or a CTAS.
Writes only where Athena has them. INSERT INTO works everywhere; UPDATE/DELETE/MERGE work on Iceberg tables only; there is no TRUNCATE.
No transactions, indexes, constraints, sequences, triggers, stored procedures, materialized views or renames. Each throws, naming Athena and the replacement.

Quick start#

Install#

$ npm install ts-prorm-orm @aws-sdk/client-athena
$ pnpm add ts-prorm-orm @aws-sdk/client-athena
$ yarn add ts-prorm-orm @aws-sdk/client-athena
$ bun add ts-prorm-orm @aws-sdk/client-athena

Connect#

import { Prorm } from 'ts-prorm-orm';

export const db = new Prorm({
  dialect: 'athena',
  database: 'analytics', // the Glue database
  dialectOptions: {
    region: 'us-east-1',
    workGroup: 'primary',
    outputLocation: 's3://my-bucket/athena-results/',
  },
});

Define a model#

import { DataTypes } from 'ts-prorm-orm';

const User = db.define('User', {
  id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  email: { type: DataTypes.STRING(255), allowNull: false, unique: true },
  name: { type: DataTypes.STRING(100) },
});

await db.sync(); // CREATE TABLE — see Generated SQL below
[!WARNING] db.sync() cannot create this table
Athena cannot create the table 'users' without an S3 location. Athena stores nothing itself — every table points at a prefix in S3, e.g. { location: 's3://my-bucket/warehouse/events/' }.

Query#

import { Op } from 'ts-prorm-orm';

await User.create({ email: 'ada@example.com', name: 'Ada' });

const page = await User.findAll({
  where: { name: { [Op.like]: 'A%' } },
  order: [['id', 'ASC']],
  limit: 20,
  offset: 40,
});

Generated SQL#

Each block is the statement the model call above it hands the dialect's query(), captured with the driver stubbed out. The model layer inlines the values.

Insert, update and delete#

await User.create({ email: 'ada@example.com', name: 'Ada' });
[!WARNING] No row-level update
UPDATE is not supported on athena. Athena runs UPDATE only against Apache Iceberg tables. Configure the dialect with tableType: 'iceberg' when your tables are Iceberg, or rewrite the change as an INSERT INTO plus a CTAS rebuild for Hive tables.
[!WARNING] No row-level delete
DELETE is not supported on athena. Athena runs DELETE only against Apache Iceberg tables. Configure the dialect with tableType: 'iceberg' when your tables are Iceberg, or rewrite the change as an INSERT INTO plus a CTAS rebuild for Hive tables.

Upsert#

[!WARNING] No upsert
MERGE (upsert) is not supported on athena. Athena runs MERGE (upsert) only against Apache Iceberg tables. Configure the dialect with tableType: 'iceberg' when your tables are Iceberg, or rewrite the change as an INSERT INTO plus a CTAS rebuild for Hive tables.

Pagination#

await User.findAll({
  where: { name: { [Op.like]: 'A%' } },
  order: [['id', 'ASC']],
  limit: 20,
  offset: 40,
});

Transaction#

[!CAUTION] No transactions
Transactions (startTransaction) is not supported on athena. Athena executes each statement independently with no session and no BEGIN/COMMIT. An individual Iceberg write is atomic on its own; nothing spans two statements.

Table sampling#

sample on the select builder reads a random fraction of the table, for estimates over large tables:
const sample = db.getDialectInstance()!.buildSelectQuery({
  tableName: 'users',
  sample: { method: 'BERNOULLI', percent: 10 },
});
await db.query(sample.sql);
Type mapping for the portable descriptors: STRING → VARCHAR, auto-increment INTEGER → INTEGER, BOOLEAN → BOOLEAN, DATE → TIMESTAMP, UUID → VARCHAR, JSON → VARCHAR. The type comparison lines the major engines up side by side.

Connection#

There is no host, port, username or password. An Athena "connection" is an AWS SDK client plus a query context:
export interface AthenaDialectOptions extends TrinoDialectOptions {
  region?: string;                  // e.g. 'us-east-1'
  workGroup?: string;               // default 'primary'
  outputLocation?: string;          // 's3://my-bucket/athena-results/'
  encryptionOption?: 'SSE_S3' | 'SSE_KMS' | 'CSE_KMS';
  kmsKey?: string;
  resultReuseMaxAgeMinutes?: number;
  credentials?: { accessKeyId: string; secretAccessKey: string; sessionToken?: string };
  endpoint?: string;
  pollIntervalMs?: number;          // default 200
  maxPollIntervalMs?: number;       // default 5000
  queryTimeoutMs?: number;          // default 300000
  pageSize?: number;                // default 1000 (Athena's maximum)
  tableType?: 'hive' | 'iceberg';   // default 'hive'
}
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'athena',
  database: 'analytics',            // the Glue database
  dialectOptions: {
    region: 'us-east-1',
    workGroup: 'analytics-wg',
    outputLocation: 's3://my-bucket/athena-results/',
    catalog: 'AwsDataCatalog',      // enables "catalog"."db"."table" in queries
    tableType: 'iceberg',           // unlocks UPDATE / DELETE / MERGE
  },
});
The driver is loaded lazily, inside connect():
connect() makes no AWS call. The only cheap probe (GetWorkGroup) needs an IAM permission that query-only roles routinely lack, and the alternative — running a statement — is a billed query on every connect. Credentials are validated by the first real query. What connect() does check is that results have somewhere to go:
new AthenaDialect({ region: 'us-east-1' }).connect();
// throws: "Athena needs somewhere to write query results: set `outputLocation` ..."

catalog, database and workGroup#

catalog is the Athena data catalog ('AwsDataCatalog' for Glue, or a federated Lambda catalog). It occupies the same slot as Trino's connector catalog and, when set, turns on three-part "catalog"."database"."table" naming in queries.
database (or schema) is the Glue database. It is what information_schema introspection is scoped to, and what DDL statements qualify with.
workGroup selects the engine version, the enforced result location and the data-scanned limits.

3. Athena-specific behavior#

Two quoting rules#

Athena's DDL parser is Hive's, where a double-quoted token is a string literal, not an identifier. Its query parser is Trino's, where a backtick is invalid. Both are needed, so the dialect has both:
d.escapeId('events');        // "events"          — queries (inherited from Trino)
d.escapeHiveId('events');    // `events`          — DDL
d.quoteTable('events');      // "analytics"."events" (with a catalog: three parts)
d.quoteHiveTable('events');  // `analytics`.`events`
Hive DDL takes no data-catalog prefix, so quoteHiveTable never emits a three-part name even when catalog is configured.

CREATE EXTERNAL TABLE#

Athena stores nothing itself, so location is mandatory:
d.buildCreateTableSQL(
  'events',
  { id: { type: DataTypes.BIGINT }, name: { type: DataTypes.STRING } },
  { location: 's3://bucket/events/' },
);
Omitting it throws rather than producing DDL Athena rejects:
d.buildCreateTableSQL('events', { id: { type: DataTypes.BIGINT } });
// throws: "Athena cannot create the table 'events' without an S3 `location`. ..."
The full Hive shape:
export interface AthenaTableOptions extends TrinoTableOptions {
  location?: string;                                  // LOCATION 's3://...'   (required)
  partitionedBy?: Record<string, DataType>;           // PARTITIONED BY (`day` string)
  partitionTransforms?: string[];                     // Iceberg: PARTITIONED BY (day(ts), bucket(16, id))
  storedAs?: string;                                  // STORED AS PARQUET
  serde?: string;                                     // ROW FORMAT SERDE '...'
  serdeProperties?: Record<string, string>;           // WITH SERDEPROPERTIES (...)
  rowFormatDelimited?: string;                        // ROW FORMAT DELIMITED ...
  bucketedBy?: string[];                              // CLUSTERED BY (...) INTO n BUCKETS
  bucketCount?: number;
  tblProperties?: Record<string, string | number | boolean>;
  partitionProjection?: AthenaPartitionProjection;
  tableType?: 'hive' | 'iceberg';                     // per-table override
  external?: boolean;                                 // default true for Hive
}
Two mistakes are caught before the statement is built, because Athena's own errors for them are hard to read:
// Hive partition columns live in the S3 key, never in the data file.
d.buildCreateTableSQL('events', { day: { type: DataTypes.STRING } },
  { location: 's3://b/e/', partitionedBy: { day: DataTypes.STRING } });
// throws: "'day' is declared both as a column and in `partitionedBy` ..."

d.buildCreateTableSQL('events', { id: { type: DataTypes.BIGINT } },
  { location: 's3://b/e/', bucketedBy: ['id'] });
// throws: "`bucketedBy` on 'events' needs a `bucketCount` ..."

Iceberg tables#

An Iceberg table is not EXTERNAL, carries TBLPROPERTIES ('table_type' = 'ICEBERG'), and partitions by transforms over ordinary columns (which stay in the column list):
new AthenaDialect({ database: 'analytics', tableType: 'iceberg' }).buildCreateTableSQL(
  'events',
  { id: { type: DataTypes.BIGINT }, ts: { type: DataTypes.DATE } },
  { location: 's3://bucket/events/', format: 'PARQUET',
    partitionTransforms: ['day(ts)', 'bucket(16, id)'] },
);
Without that table_type property Athena silently creates a plain Hive table, and the first UPDATE fails with "not an Iceberg table".

CREATE TABLE AS SELECT#

Athena's CTAS property names differ from Trino's — Trino's spellings come back as "Table property … does not exist":
AthenaTrino
external_location (Hive) / location (Iceberg)—
partitioned_by = ARRAY[...]partitioning = ARRAY[...]
bucketed_by / bucket_count—
write_compression, field_delimiter—
table_type = 'ICEBERG'—
d.buildCreateTableAsSelectSQL('summary', 'SELECT day, count(*) AS n FROM events GROUP BY day', {
  location: 's3://bucket/summary/',
  format: 'PARQUET',
  partitionedBy: ['day'],
  writeCompression: 'ZSTD',
});
Trino's partitioning spelling is accepted as an alias and rendered as partitioned_by, so a query written against the Trino dialect keeps working. The CTAS target is double-quoted: CTAS is a query statement, not Hive DDL.

Partitions#

An Athena partition is a prefix in S3. There are three ways to make Athena aware of one, and the dialect covers all three:
await d.repairTable('events');
// MSCK REPAIR TABLE `analytics`.`events`      — scan S3 for key=value directories

await d.addPartitionSpec('events', { day: '2024-01-01' }, {
  location: 's3://bucket/events/2024-01-01/', ifNotExists: true,
});
// ALTER TABLE `analytics`.`events` ADD IF NOT EXISTS PARTITION (`day` = '2024-01-01')
//   LOCATION 's3://bucket/events/2024-01-01/'

await d.dropPartitionSpec('events', { day: '2024-01-01' }, { ifExists: true });
await d.showPartitions('events');               // SHOW PARTITIONS `analytics`.`events`
buildAddPartitionSQL / buildDropPartitionSQL are the synchronous builders behind the last two.

Partition projection — the replacement for indexes#

Athena has no indexes. Beyond partitioning, bucketing and a columnar format, the thing that removes work from a query is partition projection: instead of listing partitions out of Glue, Athena computes them from rules stored in TBLPROPERTIES.
d.buildCreateTableSQL('events', { id: { type: DataTypes.BIGINT } }, {
  location: 's3://bucket/events/',
  partitionedBy: { region: DataTypes.STRING, day: DataTypes.STRING },
  partitionProjection: {
    storageLocationTemplate: 's3://bucket/events/${region}/${day}/',
    columns: {
      region: { type: 'enum', values: ['us-east-1', 'eu-west-1'] },
      day: { type: 'date', range: ['2020/01/01', 'NOW'], format: 'yyyy/MM/dd',
             interval: 1, intervalUnit: 'DAYS' },
    },
  },
});
An incomplete rule is rejected at build time — Athena accepts the table and only reports the problem much later, when a query tries to prune partitions:
{ region: { type: 'enum' } }                       // throws: is type 'enum' but lists no `values`
{ day: { type: 'date', format: 'yyyy' } }          // throws: is type 'date' but has no `range`
{ day: { type: 'date', range: ['2020', 'NOW'] } }  // throws: is type 'date' but has no `format`

Result pagination and cost#

query() submits, polls to a terminal state, then pages GetQueryResults to exhaustion:
Polling starts at pollIntervalMs and backs off ×1.5 to maxPollIntervalMs, because GetQueryExecution is itself rate limited.
A query that outruns queryTimeoutMs is cancelled with StopQueryExecution before the error is thrown — an abandoned Athena query keeps scanning, and keeps billing.
MaxResults is 1000, Athena's maximum.
Athena prefixes a SELECT result with a row that repeats the column names. It is dropped only when it actually is the header (every cell equals its column name); dropping row 0 unconditionally would eat a real row from an INSERT/CTAS/UNLOAD result.
DDL statements skip GetQueryResults entirely.
INSERT/UPDATE/DELETE/MERGE report their effect as UpdateCount, which becomes rowCount.
Every cell arrives as text and is coerced by the column's Athena type. A bigint too large for an IEEE double is left as its exact digits rather than silently rounded:
(await d.query('SELECT id FROM t')).rows[0].id;  // '9007199254740993', not 9007199254740992
Cost and history come off the last execution:
d.getLastQueryExecutionId();   // 'a1b2c3d4-...' — the key for Athena history and CloudTrail
d.getLastQueryStatistics();    // { dataScannedInBytes, engineExecutionTimeInMillis, ... }
dataScannedInBytes is what Athena bills.

Streaming#

queryStream() uses the shared paginated pager (SELECT * FROM (<sql>) AS ... OFFSET n LIMIT m). Athena has no server-side cursor: GetQueryResults pages a finished result set, so a page of a new query is a new — and separately billed — query.

Placeholders#

Athena, like Trino, has no PostgreSQL $1. That is harmless: this library never sends bind parameters on the wire. query() inlines them through the inherited replaceReplacements()/escape() before submitting, which is what every dialect here already does.
await d.query('SELECT * FROM t WHERE name = $1', { replacements: ["o'brien"] });
// submitted: SELECT * FROM t WHERE name = 'o''brien'
The built statements returned by buildInsertQuery and friends still carry $1 placeholders (they are Trino's, inherited unchanged) together with the values array — pair them back up if you execute them somewhere other than through this dialect.

Engine version#

Athena has no version(). getDatabaseVersion() reads the effective engine version off the workgroup:
await d.getDatabaseVersion();   // 'Athena engine version 3'   (via GetWorkGroup)

4. Type mapping#

Two vocabularies. getDataTypeSql() is the query/CTAS one (Trino's, inherited with two corrections); getHiveDataTypeSql() is the DDL one.
ORM type / keyQuery (getDataTypeSql)DDL (getHiveDataTypeSql)
STRING / TEXTVARCHARstring
CHARCHAR(n)char(n)
INTEGERINTEGERint
BIGINTBIGINTbigint
FLOATREALfloat
DOUBLEDOUBLEdouble
DECIMALDECIMAL(p, s)decimal(p, s)
BOOLEANBOOLEANboolean
DATETIMESTAMPtimestamp
DATEONLYDATEdate
TIMETIMEthrows
BLOBVARBINARYbinary
JSON / JSONBVARCHARstring
UUIDVARCHARstring
ARRAYARRAY(elementType)array<elementType>
'DATETIME' / 'DATETIME(n)'TIMESTAMP / TIMESTAMP(n)timestamp (no precision)
Three of those rows are corrections to what Trino would have produced:
JSON and UUID do not exist in Athena, in either vocabulary or either engine version. JSON lives in a string column and is read with json_extract; a UUID is a string. Emitting JSON or UUID produces a type error from Athena. The correction applies inside an ARRAY element type too.
Hive DDL has no time-of-day type at all, so a TIME column throws rather than being mapped to something Athena will reject:
d.getHiveDataTypeSql(DataTypes.TIME);
// throws: "A TIME column is not supported on athena. Athena table definitions have no
//          time-of-day type. Store the value as a `string`, or as a `timestamp` ..."

5. Writes#

StatementHive tableIceberg table
SELECTyesyes
INSERT INTOyesyes
UPDATEthrowsyes
DELETEthrowsyes
MERGE (upsert)throwsyes
TRUNCATEthrows — Athena has no TRUNCATEunqualified DELETE FROM
OPTIMIZE / VACUUMthrowsyes
Which side of that table you are on is set by tableType:
const hive = new AthenaDialect({ database: 'analytics' });
hive.buildUpdateQuery('events', { n: 1 }, { id: 1 });
// throws: "UPDATE is not supported on athena. Athena runs UPDATE only against Apache
//          Iceberg tables. Configure the dialect with `tableType: 'iceberg'` ..."

const iceberg = new AthenaDialect({ database: 'analytics', tableType: 'iceberg' });
iceberg.buildUpsertQuery('events', { id: 1, n: 2 }, { conflictFields: ['id'] });
// MERGE INTO "events" AS t USING (VALUES ($1, $2)) AS s ("id", "n") ON t."id" = s."id"
//   WHEN MATCHED THEN UPDATE SET "n" = s."n"
//   WHEN NOT MATCHED THEN INSERT ("id", "n") VALUES (s."id", s."n")
INSERT INTO writes new S3 objects rather than appending to existing ones, so many small inserts produce many small files. On Iceberg, optimizeTable() (OPTIMIZE ... REWRITE DATA USING BIN_PACK) compacts them and vacuumTable() expires old snapshots.
INSERT never emits RETURNING (Athena has none), and neither UPDATE nor DELETE emits LIMIT.

6. DDL that differs from Trino#

await d.addColumn('events', 'age', { type: DataTypes.INTEGER });
// ALTER TABLE `analytics`.`events` ADD COLUMNS (`age` int)
Hive DDL spells it ADD COLUMNS — plural, and parenthesised. Trino's ADD COLUMN name type is a syntax error in Athena.
await d.dropTable('events', { ifExists: true, cascade: true });
// DROP TABLE IF EXISTS `analytics`.`events`        (never CASCADE)

await d.createSchema('staging');
// CREATE DATABASE IF NOT EXISTS `staging`          (a Glue database; SCHEMA is a synonym)

await d.dropSchema('staging', { ifExists: true, cascade: true });
// DROP DATABASE IF EXISTS `staging` CASCADE
removeColumn is Iceberg-only, because a Hive table has no DROP COLUMN:
await hive.removeColumn('events', 'age');
// throws: "... For a Hive table, restate the surviving columns with
//          `ALTER TABLE ... REPLACE COLUMNS (...)` ..."
Column definitions carry only name, type and COMMENT. NOT NULL, DEFAULT, PRIMARY KEY, UNIQUE and REFERENCES are all omitted: Athena's DDL parser rejects them, and nothing enforces a constraint over S3 objects anyway.

7. Introspection#

Athena exposes a Trino-style information_schema, so these are real queries — scoped to the configured Glue database, not PostgreSQL's 'public':
await d.showTables();        // information_schema.tables  WHERE table_schema = 'analytics'
await d.showViews();         // information_schema.views
await d.describeTable('events');
describeTable reports primaryKey: false, autoIncrement: false and defaultValue: null for every column — Athena has none of the three, so these are facts rather than gaps. Calling any of them without a configured database throws and says which option is missing.

8. Unsupported operations#

Each of these throws UnsupportedSchemaObjectError naming athena and the replacement, rather than emitting SQL Athena will reject.
AreaMethodsReplacement named in the error
IndexesaddIndex, createIndex, removeIndex, dropIndex, createPartialIndex, createExpressionIndex, createFulltextIndex, createSpatialIndex, showIndexesPARTITIONED BY, CLUSTERED BY ... INTO n BUCKETS, a columnar format, partition projection
ConstraintsaddConstraint, removeConstraint, createConstraint, dropConstraint, addForeignKey, showConstraintsvalidate before writing, or query for violations
TransactionsstartTransaction, commitTransaction, rollbackTransactionone statement at a time; an Iceberg write is atomic on its own
Renames / type changesrenameTable, renameColumn, changeColumnrecreate over the same S3 location; ALTER TABLE ... REPLACE COLUMNS
ExtensionscreateExtension, dropExtension, getExtensions, hasExtensionfederated catalogs backed by Lambda connectors
SequencescreateSequence, dropSequence, nextSequenceValue, currSequenceValue, hasSequence, listSequencessupply keys from the application, or row_number() in a CTAS
TriggerscreateTrigger, dropTrigger, hasTriggerEventBridge / S3 event notifications
Stored procedurescreateStoredProcedure, createProcedure, dropStoredProcedure, dropProcedure, executeStoredProcedure, hasStoredProcedureorchestrate from the application, Step Functions or Glue
Row-level securitycreatePolicy, dropPolicy, hasPolicy, createSecurityPolicy, dropSecurityPolicyLake Formation permissions, IAM policies over the S3 prefixes
Materialized viewscreateMaterializedView, refreshMaterializedView, dropMaterializedViewCTAS on a schedule
Declarative partitioningcreatePartitionedTable, createPartition, attachPartition, detachPartition, dropPartitionthe partitionedBy table option, addPartitionSpec()/repairTable(), projection
LISTEN/NOTIFYlisten, unlisten, notifyEventBridge or SNS
Ordinary (non-materialized) CREATE VIEW / DROP VIEW are supported and inherited unchanged — Athena has Trino views.

9. Verification status#

The two test suites run without AWS. athena.test.ts asserts on generated SQL strings and thrown errors; athena-driver.test.ts runs the execution layer against a jest.mock(..., { virtual: true }) stand-in for @aws-sdk/client-athena (which also proves the driver require() is lazy — nothing loads until connect()).
Verified here (SQL generation and execution logic, no live Athena):
Dialect identity (name === 'athena', library === '@aws-sdk/client-athena') and construction with no options.
Backtick DDL quoting including embedded-backtick doubling; double-quote query quoting; quoteHiveTable omitting the data catalog; inherited three-part query naming.
Both type maps in full, the JSON/UUID corrections (including inside ARRAY), and the TIME refusal.
CREATE EXTERNAL TABLE with IF NOT EXISTS, COMMENT, PARTITIONED BY, CLUSTERED BY, SerDe + SERDEPROPERTIES, STORED AS, LOCATION, TBLPROPERTIES; the missing-location, duplicated-partition-column and missing-bucketCount refusals; omission of every key constraint.
The Iceberg CREATE TABLE form, table_type='ICEBERG', transform partitioning, and per-table tableType override.
Partition-projection rendering for enum/integer/date and the three incomplete-rule refusals.
CTAS property names (external_location/location, partitioned_by, bucketed_by, bucket_count, write_compression), the partitioning alias, and double-quoted CTAS targets.
ADD COLUMNS, DROP TABLE, CREATE/DROP DATABASE, MSCK REPAIR TABLE, ADD/DROP PARTITION, OPTIMIZE, VACUUM, Iceberg-only DROP COLUMN.
information_schema introspection scoped to the Glue database, and the missing-database error.
The Hive/Iceberg write matrix, Trino pagination ordering, and every entry in the unsupported table above.
Execution: client configuration, no AWS call during connect(), disconnect() releasing sockets, the StartQueryExecution input (context / result configuration / workgroup / result reuse), replacement inlining, polling through QUEUED/RUNNING, DDL skipping GetQueryResults, FAILED/CANCELLED error text, timeout + StopQueryExecution, NextToken paging, MaxResults 1000, header-row detection (both directions), type coercion including the unsafe-integer case, UpdateCount as rowCount, field metadata, execution id and statistics, GetWorkGroup version lookup, and the paginated stream.
Not verified — needs a live AWS account:
That AWS accepts each generated statement. Every DDL shape here is written from Athena's documented grammar, not from a round trip.
Real credentials, IAM permissions, workgroup enforcement of outputLocation, and KMS result encryption.
WITH NO DATA on CTAS. It is inherited from Trino and appears in Athena's documented CTAS synopsis, but has not been run.
Whether a given SerDe, STORED AS format or TBLPROPERTIES key is accepted for a particular table.
Behaviour of OFFSET on engine version 2 (it is an engine v3 feature; the dialect always emits Trino ordering).
Partition projection actually pruning partitions at query time, as opposed to the properties being written correctly.
Iceberg UPDATE/DELETE/MERGE/OPTIMIZE/VACUUM against a real Iceberg table.
Result-set edge cases only a real engine produces: very wide rows, struct/map column values (returned as their string rendering), and results larger than the 1000-row page across many pages.

What differs from Trino#

AthenaDialect extends TrinoDialect (trino) and
overrides 124 of its methods (Object.getOwnPropertyNames(AthenaDialect.prototype),
computed by the scratch test); everything else is inherited unchanged.
AreaOverridden
Connection and executioncommitTransaction, connect, disconnect, getConnection, isConnected, listen, notify, query, queryStream, rollbackTransaction, startTransaction, unlisten
DML buildersbuildDeleteQuery, buildInsertQuery, buildUpdateQuery, buildUpsertMergeQuery, buildUpsertQuery, coerceValue, quoteLiteral
TypescanonicalTypeSql, dataTypeKey, documentTypeSql, effectiveTableType, getDataTypeSql, getHiveColumnDefinitionSql, getHiveDataTypeSql, networkTypeSql, temporalTypeSql
DDL and schemaaddColumn, addConstraint, addForeignKey, addIndex, addPartitionSpec, attachPartition, buildAddPartitionSQL, buildCreateTableAsSelectSQL, buildCreateTableSQL, buildDropPartitionSQL, buildPartitionProjectionProperties, buildTblPropertiesClause, changeColumn, createConstraint, createExpressionIndex, createExtension, createFulltextIndex, createIndex, createMaterializedView, createPartialIndex, createPartition, createPartitionedTable, createPolicy, createProcedure, createSchema, createSecurityPolicy, createSequence, createSpatialIndex, createStoredProcedure, createTable, createTrigger, detachPartition, dropConstraint, dropExtension, dropIndex, dropMaterializedView, dropPartition, dropPartitionSpec, dropPolicy, dropProcedure, dropSchema, dropSecurityPolicy, dropSequence, dropStoredProcedure, dropTable, dropTrigger, optimizeTable, refreshMaterializedView, removeColumn, removeConstraint, removeIndex, renameColumn, renameTable, vacuumTable
IntrospectiondescribeTable, getDatabaseVersion, getExtensions, getLastQueryExecutionId, getLastQueryStatistics, hasExtension, hasPolicy, hasSequence, hasStoredProcedure, hasTrigger, isHeaderRow, listSequences, showConstraints, showIndexes, showPartitions, showTables, showViews
OtherbuildAthenaCtasPropertiesClause, collectResults, currSequenceValue, escapeHiveId, executeStoredProcedure, mapRow, mapStatistics, nextSequenceValue, noConstraints, noDeclarativePartitions, noIndexSupport, noMaterializedViews, noNotifications, noPolicies, noProcedures, noSequences, noTransactions, noTriggers, quoteHiveTable, repairTable, requireDatabase, requireIceberg, runStatement, sleep, unsupported

Capabilities#

Computed from the code — capabilitiesOf() (src/transaction-support.ts),
whereSupportOf() (src/query-builders/expression-render.ts),
sqlObjectCapabilitiesOf() (src/sql-objects/capabilities.ts) and the
builders — by the scratch test described in the
capability matrix.
Capabilityathena
Transactions atomicyes
Savepointsno — a nested transaction() throws
Isolationup to SERIALIZABLE
Transaction modesread-only yes; deferrable yes; constraint deferral yes
RETURNINGnot emitted; returning is accepted and ignored
Upsertrefused — MERGE (upsert) is not supported on athena. Athena runs MERGE (upsert) only against Apache Iceberg tables. Configure the dialect with tableType: 'iceberg' when
JSON columnVARCHAR (JSONB → VARCHAR)
Vector columnARRAY(REAL)
Array columnARRAY(INTEGER)
WHERE builder46 operator keys; $and/$or/$not; $exists: yes; $in subquery: yes; expression operands: yes
SQL objectsfamily unknown: triggers no; procedures no; functions no; materialized views no; sequences no; enums check; RLS no
StreamingqueryStream() present; LISTEN present; createExtension() present

Testing#

tests/dialects/athena.test.ts exercises the dialect with a mocked driver, so nothing touches a server.

Related reading#

All dialects — what each engine supports
Trino — the base class, and everything inherited unchanged
Data types — how each type maps to this engine
Querying — how a FindOptions becomes SQL
Modified at 2026-10-04 00:40:16
Previous
AlloyDB Omni Dialect
Next
Aurora DSQL Dialect
Built with