# Aurora DSQL

> Use Reylo with Amazon Aurora DSQL. Covers IAM login tokens, typing queries against a cluster, pg with a token for each connection, and migrations under DSQL's limits.

Reylo on Amazon Aurora DSQL

Aurora DSQL is a Postgres 16, so the [Postgres](https://reylo.dev/docs/postgres) page holds for its queries.

| | |
| --- | --- |
| Dialect | Postgres |
| The type check reads | The cluster's endpoint, signed in as `admin` with your AWS credentials |
| Queries run on | `pg`, or any [Postgres driver](https://reylo.dev/docs/postgres#drivers), with an IAM token for each connection |
| Migrations | One DDL statement in each file, an index built `async`, a shadow cluster for each check |
| Not supported | Triggers, enums, extensions, arrays in columns, `serial`, row-level security, partitions, `truncate` |

```sql
create table users (
  id uuid primary key default gen_random_uuid(),
  email text not null,
  profile jsonb
);
```

## Connection strings

Put the cluster's endpoint in `DATABASE_URL`, with no password:

`.env`:

```sh
DATABASE_URL=postgres://abc123.dsql.us-east-1.on.aws/postgres
```

What Reylo does with it:

- It signs a login token for each connection, with the AWS credentials of your environment, profile or SSO session.
- It signs in as `admin` unless the URL names another role. Another role signs with `DbConnect`, so its IAM policy needs that action.
- It checks the cluster's certificate, since DSQL takes TLS only.
- A password in the URL is a token you generated, and Reylo sends it as it is.

To use a profile, set `AWS_PROFILE`:

**Terminal**:

```sh
AWS_PROFILE=dev reylo analyze queries
```

Reylo reads SSO and assumed-role profiles through the AWS CLI, so install it for those.

## Running queries

Pass a `pg` pool whose password is a function. Each new connection then signs a fresh token:

`main.ts`:

```ts
import { DsqlSigner } from "@aws-sdk/dsql-signer";
import pg from "pg";
import getUser from "./get_user.sql";

const hostname = "abc123.dsql.us-east-1.on.aws";
const signer = new DsqlSigner({ hostname, region: "us-east-1" });

const db = new pg.Pool({
  host: hostname,
  user: "admin",
  database: "postgres",
  ssl: true,
  password: () => signer.getDbConnectAdminAuthToken(),
});

const user = await getUser.run(db, { id });
```

`get_user.sql`:

```sql
select id, email, profile
from users
where id = :id
```

DSQL closes a connection after an hour, and a pool opens another with a new token.

## Transactions

DSQL's transactions are optimistic. A transaction that conflicts with another fails at its `commit`, with SQLSTATE `40001`. Retry it:

`main.ts`:

```ts
for (let attempt = 1; ; attempt++) {
  const client = await db.connect();
  try {
    await client.query("begin");
    await moveCredits.run(client, { from, to, amount });
    await client.query("commit");
    break;
  } catch (error) {
    await client.query("rollback");
    if (error.code !== "40001" || attempt === 5) throw error;
  } finally {
    client.release();
  }
}
```

A transaction changes 3,000 rows at most. Split a larger write into batches.

## Migrations

On a DSQL endpoint, Reylo Migrate works within its rules:

- Each file holds one DDL statement, since DSQL runs one in a transaction, with no row changed beside it. `reylo migrate new` writes a file for each.
- An index is built with `create index async`. Each deploy waits for the build before it goes on, and a failed build fails the migration.
- A new table's foreign keys go in its `create table`. One added to a table that exists is `not valid`: DSQL validates none, but each holds for every row written after it.
- A column added with a default is added bare, and its default set after. The rows already in the table keep null, and the migration says so.
- A migration one deploy has started holds every other deploy back, since DSQL has no advisory locks.

Write an index this way in `schema.sql` too:

```sql
create table posts (
  id uuid primary key default gen_random_uuid(),
  author_id uuid not null references users (id),
  title text not null
);

create index async posts_author_idx on posts (author_id);
```

A `schema.sql` or a migration that holds what DSQL doesn't run is refused before anything changes:

```terminal
$ reylo migrate new add_events
✗ reylo/schema.sql holds a statement Aurora DSQL doesn't run
    create table events (id serial primary key, tags text[])
  DSQL has no serial: its sequences are made with an explicit cache.
  Write instead:
    bigint generated by default as identity (cache 1) primary key
  DSQL stores no array in a column (text[]): a jsonb column, or a table of one row per element, holds the elements.

Nothing was changed.
```

## Shadow clusters

A DSQL cluster holds one database, so each [shadow database](https://reylo.dev/docs/migrate/cli#configuration) is a cluster of its own. Reylo makes it in your cluster's region, tags it `reylo=shadow`, and deletes it when the command ends.

What that needs:

- Your AWS role may create, read, tag and delete clusters: `dsql:CreateCluster`, `dsql:GetCluster`, `dsql:TagResource` and `dsql:DeleteCluster`.
- Each command makes two or three, and builds each `async` index in each. So `reylo migrate new` and `dev` take about two minutes, where Postgres takes seconds.
- Clusters count against your region's quota, 20 by default.

Deploys and status checks make no shadow, so a deploy role needs `dsql:DbConnectAdmin` alone.

Introspection writes the schema only as Reylo's own SQL, checked on a shadow cluster. It can't fall back on `pg_dump`, which DSQL refuses.

## Limits

DSQL refuses these, and so does Reylo Migrate, before any change:

| Refused | Write instead |
| --- | --- |
| `serial`, `bigserial` | `bigint generated by default as identity (cache 1)` |
| A sequence without `cache` | `cache 1`, or `cache 65536` and more |
| `create index`, `concurrently` | `create index async` |
| `add column` with a default, `not null`, a key or a check | `add column` bare, then `set default` in a file of its own |
| `add constraint … foreign key` | The same, `not valid` |
| `alter column … type` | A new column, the values copied over, the old one dropped |
| Arrays, ranges, geometric types, `money`, `xml`, `tsvector` | `jsonb`, or a table of its own |
| `create type`: enums, composites, ranges | A domain, or a check |
| Triggers, rules, policies, extensions, partitions, materialized views, `truncate`, temporary tables | |

These work as on Postgres:

- Views, domains and sequences
- SQL and PL/pgSQL functions and procedures
- Identity columns and stored generated columns
- Unique, partial and expression indexes, built `async`
