# Neon

> How to use Reylo with Neon. The connection string the type check reads, Neon's serverless driver over HTTP and WebSockets, pg and postgres.js, and branches for development and pull requests.

Reylo on Neon's serverless Postgres

Neon is Postgres, so everything on the [Postgres](https://reylo.dev/postgres) page holds for it.

| | |
| --- | --- |
| Dialect | Postgres |
| The type check reads | The direct connection string, through [`direct_url`](https://reylo.dev/configuration#direct_url) |
| Queries run on | `@neondatabase/serverless`, `pg` or postgres.js, through the pooled connection string |
| Transactions | On a `Pool`'s client over a WebSocket, not on `neon()` over HTTP |
| Branches | Each has connection strings of its own, to type against its schema |
| Edge runtimes | Neon's driver, on the [Next.js edge runtime](https://reylo.dev/nextjs#the-edge-runtime) and in [Cloudflare Workers](https://reylo.dev/d1#setup) |

**View the schema behind the examples**

```sql
create table users (
  id serial primary key,
  name text not null,
  email text
);
```

## Connection strings

Neon gives each branch two connection strings. The pooled one's host ends in `-pooler`:

`.env`:

```sh
# pooled, for your app
DATABASE_URL=postgresql://…@ep-name-pooler.us-east-2.aws.neon.tech/neondb
# direct, for the type check
DATABASE_URL_UNPOOLED=postgresql://…@ep-name.us-east-2.aws.neon.tech/neondb
```

Point [`direct_url`](https://reylo.dev/configuration#direct_url) at the direct one:

`.reylo.yaml`:

```yaml
direct_url: ${DATABASE_URL_UNPOOLED}
```

- Neon's pooler is PgBouncer in transaction mode. Your app's queries can go through it, but the type check can fail there, and [migrations](https://reylo.dev/migrations) refuse it: a run holds a session, which the pooler shares between clients.
- Without this line, Reylo reads `DATABASE_URL` and nothing else. `DATABASE_URL_UNPOOLED` is the name Neon's Vercel integration gives the direct string.
- The type check takes the string as Neon writes it, `sslmode=require` and `channel_binding=require` included ([TLS](https://reylo.dev/configuration#tls)).

## Serverless driver

Pass `neon()` from `@neondatabase/serverless`, which sends each query over HTTP:

`main.ts`:

```ts
import { neon } from "@neondatabase/serverless";
import getUser from "./get_user.sql";

const sql = neon(process.env.DATABASE_URL);
const user = await getUser.run(sql, { id: 1 });
//    ^? const user: {
//           id: number;
//           name: string;
//           email: string | null;
//       } | null
```

`get_user.sql`:

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

A `Pool` or `Client` from the same package works too, over a WebSocket. Passed a `Pool`, each query runs on a client the pool checks out for it.

## Transactions

Run a transaction on a client checked out of a `Pool`:

`main.ts`:

```ts
import { Pool } from "@neondatabase/serverless";
import createUser from "./create_user.sql";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

// both inserts land, or neither
const client = await pool.connect();
try {
  await client.query("begin");
  await createUser.run(client, { name: "Ada" });
  await createUser.run(client, { name: "Grace" });
  await client.query("commit");
} catch (error) {
  await client.query("rollback");
  throw error;
} finally {
  client.release();
}
```

`create_user.sql`:

```sql
insert into users (name)
values (:name)
returning id
```

- The `transaction()` of `neon()` takes queries built with Neon's own `sql` tag, so a Reylo query can't join one.
- Drizzle over Neon's driver has transactions over a `Pool`, and none over HTTP ([Drizzle](https://reylo.dev/postgres#drizzle)).

## TCP drivers

Over TCP, pass a `pg` pool or a postgres.js client made with the pooled connection string:

**pg**:

```ts
import pg from "pg";
import getUser from "./get_user.sql";

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const user = await getUser.run(db, { id: 1 });
```

`postgres.js`:

```ts
import postgres from "postgres";
import getUser from "./get_user.sql";

const db = postgres(process.env.DATABASE_URL);
const user = await getUser.run(db, { id: 1 });
```

Each runs a transaction its own way: on a client checked out of the pool with `pg`, and in `db.begin()` with postgres.js ([Drivers](https://reylo.dev/postgres#drivers)).

## Branches

Neon's CLI prints a branch's direct connection string:

**Terminal**:

```sh
# add --pooled for the pooled one
neon connection-string my-branch
```

To type against your own branch, set it in `.env.local`, which Reylo reads before `.env`:

`.env.local`:

```sh
DATABASE_URL_UNPOOLED=postgresql://…@ep-mine.us-east-2.aws.neon.tech/neondb
```

A branch starts with its parent's schema, so run your migrations on it before the type check reads it.

## Pull requests

In CI, create a branch for each pull request with Neon's GitHub Action, migrate it, and type-check against it:

`.github/workflows/ci.yml`:

```yaml
on: pull_request
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      # ...
      - id: branch
        uses: neondatabase/create-branch-action@v6
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          api_key: ${{ secrets.NEON_API_KEY }}
          branch_name: pr-${{ github.event.number }}
      - env:
          DATABASE_URL_UNPOOLED: ${{ steps.branch.outputs.db_url }}
        # your migrations, then the type check and the build
        run: |
          npm run migrate
          npm run typecheck
          npm run build
```

Delete the branch when the pull request closes:

`.github/workflows/cleanup.yml`:

```yaml
on:
  pull_request:
    types: [closed]
jobs:
  delete:
    runs-on: ubuntu-latest
    steps:
      - uses: neondatabase/delete-branch-action@v3
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          api_key: ${{ secrets.NEON_API_KEY }}
          branch: pr-${{ github.event.number }}
```

- The action's `db_url` is the branch's direct connection string, and `db_url_pooled` its pooled one.
- Neon's Vercel integration can also create a branch for each preview deployment, with its own `DATABASE_URL_UNPOOLED`. It starts with its parent's schema, so run your migrations on it before the build ([A host that builds before it migrates](https://reylo.dev/deployment#build-before-migrate)).

## Edge runtimes

Neon's driver connects over HTTP and WebSockets, so it runs where TCP doesn't, such as a Cloudflare Worker:

`worker.ts`:

```ts
import { neon } from "@neondatabase/serverless";
import getUser from "./get_user.sql";

export default {
  async fetch(request: Request, env: { DATABASE_URL: string }) {
    const sql = neon(env.DATABASE_URL);
    return Response.json(await getUser.run(sql, { id: 1 }));
  },
};
```

- In a Worker, it needs no `nodejs_compat` flag. [Cloudflare D1](https://reylo.dev/d1#setup) covers the Vite plugin that loads `.sql` files there.
- On the Next.js edge runtime, use it the same way ([The edge runtime](https://reylo.dev/nextjs#the-edge-runtime)).
- In an edge runtime, connect, use and close a `Pool` or `Client` within one request.
