# ctx.db()

> Reference for ctx.db(), the typed Drizzle query builder over a project's managed Postgres database, with its errors and limits.

`ctx.db()` returns a typed [Drizzle ORM](https://orm.drizzle.team/) query builder over the project's own managed Postgres database. Call it with no argument. The tables come from `db/schema.ts`, and every function in the project reads and writes the same database.

## Signature

```typescript
db(): DrizzleInstance
```

`DrizzleInstance` is the Drizzle query builder typed from your `db/schema.ts`. Setup, schema changes, and local development are in [the database guide](/documentation/guides/database/).

## Query builder

Use the builder and operators exactly as in Drizzle:

```typescript
import { defineFunction } from '@trayai/helix-sdk';
import { eq } from 'drizzle-orm';
import { notes } from '../../db/schema';

export default defineFunction(async (ctx) => {
  const db = ctx.db();
  const open = await db.select().from(notes).where(eq(notes.done, false));
  return open;
});
```

Row types come from the schema, with no generation step:

```typescript
type Note = typeof notes.$inferSelect;     // rows returned by queries
type NewNote = typeof notes.$inferInsert;  // values accepted by inserts
```

## Transactions and raw SQL

`transaction()` runs a callback against a transactional handle. Everything inside commits together or rolls back together, and a thrown error rolls it back:

```typescript
await ctx.db().transaction(async (tx) => {
  await tx.insert(notes).values({ title: 'First' });
  await tx.insert(notes).values({ title: 'Second' });
});
```

`execute` runs raw SQL written with the `sql` tag. Interpolated values are bound as parameters:

```typescript
import { sql } from 'drizzle-orm';

const result = await ctx.db().execute(sql`SELECT count(*)::int AS total FROM notes`);
```

## Columns that need a cast

The deployed database receives string parameters untyped, so an enum column, a `numeric` column in `number` mode, an array column, a `vector` value, and a bare `Date` or bare string inside a `sql` template fail there with errors like `column "status" is of type status but expression is of type text`. `helix dev` binds parameters the same way, so they fail locally too. `@trayai/helix-sdk/db` exports replacements that cast for you and need no migration:

| Export | Replaces | Reads and writes |
|---|---|---|
| `enumColumn(name, enumType)` | `enumType(name)` | the enum's string values |
| `numericNumber(name, { precision, scale })` | `numeric(name, { mode: 'number' })` | a `number` |
| `textArray(name)` | `text(name).array()` | a `string[]` (no NULL elements) |
| `asTimestamptz(date)` | a bare `${date}` in `sql` | a `Date`, or an ISO 8601 string with a timezone |

These are columns, so they do not work with `sql.placeholder()` or prepared statements. Cast a `vector` value, or anything else without a helper, in the SQL (``sql`cast(${value} as vector)` ``). See [Columns that need a cast](/documentation/guides/database/#columns-that-need-a-cast) in the guide.

## Behavior and limits

| Behavior | Detail |
|---|---|
| Schema changes | `ctx.db()` never creates or alters tables. `CREATE`, `ALTER`, and `DROP` from a function are rejected. |
| Retries | A failed statement is not retried. A call made while an idle database wakes up is retried automatically, up to three attempts and about 30 seconds in all. |
| Size | A single result of about 1 MiB and a single request of about 4 MB are rejected. |
| Local development | `helix dev` runs `ctx.db()` on an in-memory PGlite database that is reset on every file save and every restart. It never touches a deployed database. It binds parameters as the deployed database does, so a missing cast fails locally too. |

## Errors

| Kind | Meaning |
|---|---|
| `db_call_failed` | The statement failed. The message is `CODE: message` and the original error is `cause`. |
| `db_managed_requires_provisioning` | The project is not deployed yet. Run `helix deploy` first. |
| `db_managed_not_available` | In `helix dev`, the project has no `db/schema.ts`. |
| `db_dev_setup_failed` | `helix dev` could not create the local database: `drizzle-kit` is missing, or `db/schema.ts` does not compile. |

## Deprecated: ctx.db(alias)

Calling `ctx.db()` with an alias returns the older Redshift client, used as `.sql(query)` or `.parameters({...}).sql(query)`. It is deprecated. It still works unchanged, logs one warning per alias, and will be removed in a future major version. No replacement is documented yet.

---

Canonical: https://helix.tray.ai/documentation/reference/context/db/
Any link on this page is available as markdown by appending .md to its URL.
Full corpus: https://helix.tray.ai/documentation/llms-full.txt