Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/mysql-write-results.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@maple-dev/effect-orm": minor
---

`Db.runWrite` runs an insert, update or delete and returns a `WriteResult`: `affectedRows`, and for an insert `insertId`, the key of the row it wrote. It is how MySQL, which has no `RETURNING` (and MariaDB, whose `RETURNING` the builder does not write), reads an `AUTO_INCREMENT` key; it reads `@effect/sql-mysql2`, `@effect/sql-pg`, PGlite, node:sqlite and D1 results, and refuses a ClickHouse write before sending it. `layerTest` takes a `TestWriteReply` (`{ affectedRows, insertId? }`) to answer one.

MySQL and MariaDB constraint failures are now refined like the other dialects': `refineConstraints` reads the server's error number, so a foreign key (1451, 1452), NOT NULL (1048, 1364) or CHECK (3819, MariaDB 4025) failure becomes `ForeignKeyViolation`, `NotNullViolation` or `CheckViolation`, with the key, constraint, table or column the message names. Before, only a duplicate key was refined, and without names. A MySQL `DatabaseError` now also carries the server's `sqlState` and its error number as `errorCode`. Names are read from the server's whole message and anchored where the server writes them, so a duplicated value quoted in the message cannot name the key. A Node error name (`EPIPE`, `EBUSY`) is no longer read as a SQLSTATE.
2 changes: 1 addition & 1 deletion docs/coming-from-drizzle-prisma.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Two things change for every operation:
| `include` / `select` a relation | `with: { posts: true }` | `Db.findMany` with nested `with` over `Db.defineRelations`, one statement per level ([Relational reads](./relations.md)); or `innerJoin` / `leftJoin` ([Joins](./joins-and-subqueries.md)) |
| `_count: { select: { posts: true } }` | `db.$count(posts, eq(...))` | `_count: { posts: true }` in `Db.findMany` ([Count relations](./relations.md#count-relations)); or `leftJoin` + `PG.countDistinct` + `groupBy` |
| `where: { posts: { some / none / every } }` | `exists(...)` | `r.posts.some(where)`, `none`, `every` in a `findMany` `where` ([Filter by relations](./relations.md#filter-by-relations)); or `PG.exists`, `PG.inSubquery` ([Subquery conditions](./joins-and-subqueries.md#subquery-conditions)) |
| `create`, `createMany({ data })` | `db.insert(t).values([...])` | `PG.insertInto(T).values(row or rows)`, `.returning()` ([Inserting rows](./inserts.md)); MySQL has no `RETURNING` |
| `create`, `createMany({ data })` | `db.insert(t).values([...])` | `PG.insertInto(T).values(row or rows)`, `.returning()` ([Inserting rows](./inserts.md)); MySQL has no `RETURNING`: `Db.runWrite` returns the `insertId` and `affectedRows` Drizzle's `$returningId()` and result header gave ([Write results](./database.md#write-results)) |
| `upsert` | `.onConflictDoUpdate({ target, set })` | `.onConflictDoUpdate({ target, set })`; `set: PG.excluded([...])` or `PG.excludedAll()` copies the proposed row ([On conflict](./inserts.md#on-conflict), [recipe](./recipes.md#insert-or-update-a-row)). Postgres, SQLite and D1; not MySQL |
| `update`, `updateMany` | `db.update(t).set().where()` | `PG.update(T).set(...).where(...)`; a write with no `where` or `allRows()` does not compile ([Updating and deleting](./updates-and-deletes.md)) |
| `delete`, `deleteMany` | `db.delete(t).where()` | `PG.deleteFrom(T).where(...)` |
Expand Down
79 changes: 71 additions & 8 deletions docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ again. `read uncommitted` is not offered because Postgres runs it as `read commi

| Error | When |
| --- | --- |
| `DatabaseError` | A statement failed. `reason` is the driver's classification (`UniqueViolation`, `SerializationError`, `DeadlockError`, ...), `sqlState` the server's five-character code (Postgres) and `errorCode` its numeric code (ClickHouse) |
| `DatabaseError` | A statement failed. `reason` is the driver's classification (`UniqueViolation`, `SerializationError`, `DeadlockError`, ...), `sqlState` the server's five-character code (Postgres, MySQL) and `errorCode` its numeric code (ClickHouse, MySQL's error number) |
| `TransactionCommitFailed` | COMMIT failed: a deferred constraint, a serialization failure at commit, a dropped connection. Carries `reason`, `sqlState` and `errorCode` |
| `TransactionRollbackFailed` | ROLLBACK failed after the body failed. `bodyCause` is the body's failure, `cause` the rollback's |
| `TransactionOptionsRejected` | A setting the dialect does not support, or settings on a nested transaction |
Expand All @@ -397,10 +397,10 @@ reading SQLSTATEs. Every other failure passes through unchanged.

| Error | Postgres SQLSTATE | ClickHouse code | SQLite and D1 | MySQL, MariaDB |
| --- | --- | --- | --- | --- |
| `UniqueViolation` | 23505 | — | `SQLITE_CONSTRAINT_UNIQUE`, `SQLITE_CONSTRAINT_PRIMARYKEY` | 1062 (`ER_DUP_ENTRY`) |
| `ForeignKeyViolation` | 23503 | — | `SQLITE_CONSTRAINT_FOREIGNKEY` | — |
| `NotNullViolation` | 23502 | — | `SQLITE_CONSTRAINT_NOTNULL` | — |
| `CheckViolation` | 23514 | 469 (`VIOLATED_CONSTRAINT`) | `SQLITE_CONSTRAINT_CHECK` | — |
| `UniqueViolation` | 23505 | — | `SQLITE_CONSTRAINT_UNIQUE`, `SQLITE_CONSTRAINT_PRIMARYKEY` | 1062 (`ER_DUP_ENTRY`), 1586 |
| `ForeignKeyViolation` | 23503 | — | `SQLITE_CONSTRAINT_FOREIGNKEY` | 1451, 1452 (also 1216, 1217) |
| `NotNullViolation` | 23502 | — | `SQLITE_CONSTRAINT_NOTNULL` | 1048, and 1364 for a NOT NULL column with no default left out |
| `CheckViolation` | 23514 | 469 (`VIOLATED_CONSTRAINT`) | `SQLITE_CONSTRAINT_CHECK` | 3819 (MySQL), 4025 (MariaDB) |

Each carries `message`, `sql`, the server's `sqlState` or `errorCode`, and `cause` (the error it
came from). It also carries `constraint`, `table` and `column` when the server named them:
Expand All @@ -410,9 +410,12 @@ or NOT NULL constraints to violate. SQLite names no unique index: a unique or NO
carries the `table` and, when the key has one column, the `column`. A CHECK violation carries
the CHECK's name as `constraint`, or its expression when it has no name. A foreign key violation
names nothing. SQLite's extended code is read from `node:sqlite` and from D1's message; neither
sets `sqlState` or `errorCode`. On MySQL only a duplicate key is refined, from the
`UniqueViolation` reason `@effect/sql-mysql2` gives error 1062; a foreign key, NOT NULL or CHECK
failure stays a `DatabaseError` (reason `ConstraintError`).
sets `sqlState` or `errorCode`. MySQL and MariaDB give a duplicate key, a foreign key and a
NOT NULL failure the same SQLSTATE, 23000, and a CHECK failure `HY000`, the generic one, so the
kind is read from the server's error number, which is the violation's
`errorCode`. They name things only in the message: a duplicate key names the key (MySQL 8 as
`table.key`, which becomes `table` and `constraint`), a foreign key names the constraint and the
referencing table, NOT NULL the column, and a CHECK its constraint (MariaDB also the table).

```ts title="database-constraints.ts"
import { Effect } from "effect"
Expand Down Expand Up @@ -791,3 +794,63 @@ The builder compiles SELECTs, [INSERTs](./inserts.md) and
rows, decoded, or none without `returning`; a write without it goes through `command`, as
`execute` does. Write other statements with `sql`, as above, and read `RETURNING` with `query`
and a schema.

### Write results

`runWrite(write, params?)` runs an insert, update or delete that has no `returning` and gives
back what the server reported of it, a `WriteResult`:

| Field | What it is |
| --- | --- |
| `affectedRows` | The rows the statement wrote, as the server counts them |
| `insertId` | The key of the row an insert wrote, or `undefined` |

It is how MySQL, which has no `RETURNING`, reads an `AUTO_INCREMENT` key. MariaDB has
`INSERT ... RETURNING`, but the builder writes none for either; run it with `Db.query` and a
schema when you need the rows:

```ts title="database-write-result.ts"
import { Effect } from "effect"
import * as Db from "@maple-dev/effect-orm/database"
import * as MySQL from "@maple-dev/effect-orm/mysql"

const Notes = MySQL.table("notes", { id: MySQL.bigint, orgId: MySQL.varchar(36), body: MySQL.text }, { defaults: ["id"] })

export const addNote = (orgId: string, body: string) =>
Effect.gen(function* () {
const { insertId } = yield* Db.runWrite(MySQL.insertInto(Notes).values({ orgId, body }))
const { affectedRows } = yield* Db.runWrite(
MySQL.update(Notes)
.set({ body: body.trim() })
.where(($) => [$.orgId.eq(orgId), $.id.eq(insertId ?? 0)]),
)
return { id: insertId, touched: affectedRows }
})
```

The counts are the driver's, and they differ by database:

- **MySQL and MariaDB** (`@effect/sql-mysql2`): `insertId` is the first row's `AUTO_INCREMENT`
value, whether the server generated it or the insert gave it (an insert of `id: 500` reports
500), and `undefined` for a table with no `AUTO_INCREMENT` column. A multi-row insert's keys follow it only when `auto_increment_increment` is 1 and
`innodb_autoinc_lock_mode` hands out consecutive keys; read them back otherwise. mysql2 connects
with `CLIENT_FOUND_ROWS`, so an UPDATE counts every row it matched, including those it left as
they were. An `ON DUPLICATE KEY UPDATE` counts 2 for a row it updated and 1 for a row inserted or
matched and left as it was, so 1 does not mean inserted; on an update, `insertId` is the
existing row's key.
- **SQLite and D1**: `insertId` is the rowid of the last row inserted. That rowid belongs to the
connection, not the statement, so it is not read for an `onConflictDoUpdate` (an upsert that
updates leaves an earlier insert's), and it is meaningless for a `WITHOUT ROWID` table.
`affectedRows` counts the rows changed.
- **Postgres** (`@effect/sql-pg`, PGlite): `insertId` is always `undefined`; read a generated key
with `returning`. `affectedRows` is the command's row count.
- **ClickHouse** reports neither, so `runWrite` refuses a ClickHouse write, as a defect, before
sending it. Use `run`.

`insertId` is `undefined` for an update or delete, and for an insert that wrote no row. SQLite's
rowid can be 0 or negative, and is reported as it is. A
count or key past 2^53 fails with `DatabaseError` (reason `UnsafeInteger`) rather than being
rounded, and a client whose result `runWrite` cannot read fails with reason
`WriteResultUnsupported`. Both happen after the write ran, so outside a transaction it is
committed: do not retry such a failure as if nothing was written. `layerTest` answers a `runWrite` with a queued `{ affectedRows, insertId }` reply; see
[Testing](./testing.md).
4 changes: 3 additions & 1 deletion docs/inserts.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,9 @@ const created = PG.insertInto(ApiKeys)
The row schema is derived from the list, as it is from a SELECT: an untyped expression
(`untypedExpr`) leaves the insert undecoded, with `rowSchemaSource: "none"` and the alias in
`untypedColumns`. `CompiledQuery.returning` lists the aliases. ClickHouse and MySQL have no
RETURNING, so compiling an insert with `returning` for them is a `QueryBuilderDefect`.
RETURNING, so compiling an insert with `returning` for them is a `QueryBuilderDefect`. On MySQL,
`Db.runWrite` returns the insert's `AUTO_INCREMENT` key and affected rows instead
([Write results](./database.md#write-results)).

## On conflict

Expand Down
3 changes: 2 additions & 1 deletion docs/mysql.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,8 @@ another dialect is refused in the type and at compile time.
- **Unsigned arithmetic does not go below zero.** On an `UNSIGNED` column, `id - 5` fails with
`BIGINT UNSIGNED value is out of range` when the result would be negative. Use a signed type,
or `CAST`.
- **Not supported, and refused at compile time:** `RETURNING`, `ON CONFLICT` (MySQL's
- **Not supported, and refused at compile time:** `RETURNING` (read an `AUTO_INCREMENT` key and
the affected rows with `Db.runWrite`, [Write results](./database.md#write-results)), `ON CONFLICT` (MySQL's
`ON DUPLICATE KEY UPDATE` reacts to every unique key, not one target), `DISTINCT ON`, `ILIKE`,
`FOR NO KEY UPDATE` and `FOR KEY SHARE`. MariaDB has no lock `OF` at all.
- **Row locks:** `forUpdate` and `forShare` with `skipLocked`, `noWait` and, on MySQL, `of`.
Expand Down
4 changes: 2 additions & 2 deletions docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,7 @@ the default.
| Running a migration a step at a time, for an orchestrator: `pendingMigrations`, `planMigration`, `planSteps`, `applyStep`, `completeMigration`, `resolveStep`, with `MigrationPlan`, `PlannedStep`, `ResolveStepOptions` | `/migrate` |
| Options and results: `RunOptions`, `BaselineOptions`, `VerifyOptions`, `VerifyResult`, `Drift`, `AppliedMigration`, `MigrationStatus`, `MigrationState`; `LEDGER_TABLES` names the three ledger tables | `/migrate` |
| The errors, each a tagged error, and their union `MigrateError`: `MigrateSqlError`, `MigrateSourceError`, `MigrateHashMismatch`, `MigrateLeaseHeld`, `MigrateStepFailed`, `MigrateStepChanged`, `MigrateStepUncertain` | `/migrate` |
| `Database` (the service), `run` (compile, run and decode a query or write), `runOne`, `runOption`, `runNonEmpty` (the same with a row-count check), `stream` (rows as a `Stream`), `batch` (several statements, `BatchCheck`, `BatchRows`; [Batches](./database.md#batches)), `paginate` (a keyset page; [Pagination](./database.md#pagination), [recipe](./recipes.md#page-through-rows-with-a-cursor)), `sql` (a template with bound values), `query`, `execute` (run a statement, with or without rows), `transaction`, `requireTransaction`, `afterCommit`, `retryContention`, `Transaction` ([Transactions](./database.md#transactions), [recipe](./recipes.md#several-writes-in-one-transaction)). See [Running statements and transactions](./database.md) | `/database` |
| `Database` (the service), `run` (compile, run and decode a query or write), `runOne`, `runOption`, `runNonEmpty` (the same with a row-count check), `runWrite` (a write's `WriteResult`: its affected rows and generated key, for a `Write`; [Write results](./database.md#write-results)), `stream` (rows as a `Stream`), `batch` (several statements, `BatchCheck`, `BatchRows`; [Batches](./database.md#batches)), `paginate` (a keyset page; [Pagination](./database.md#pagination), [recipe](./recipes.md#page-through-rows-with-a-cursor)), `sql` (a template with bound values), `query`, `execute` (run a statement, with or without rows), `transaction`, `requireTransaction`, `afterCommit`, `retryContention`, `Transaction` ([Transactions](./database.md#transactions), [recipe](./recipes.md#several-writes-in-one-transaction)). See [Running statements and transactions](./database.md) | `/database` |
| `DatabaseError` (a failed statement, with the driver's `reason`), `ResultCardinalityError` (`runOne` and friends got the wrong number of rows), `InvalidCursor` (a `paginate` cursor that does not decode), `TransactionCommitFailed`, `TransactionRollbackFailed` and the other transaction errors ([Errors](./database.md#errors)) | `/database` |
| Building one: `fromSqlClient`, `layerSqlClient`, `FromSqlClientOptions`, `DatabaseApi` | `/database` |
| What statements are: `Runnable` and `RowOf` (for `run`), `Statement` and `StatementInput` (for `query` and `execute`), `RowSchema` (the row codec `query` takes), and the `sql` template's `SqlTemplate`, `SqlIdentifier`, `SqlRawText` | `/database` |
Expand All @@ -651,7 +651,7 @@ the default.
| `defineRelations`, `findMany`, `Relation`, `RelationBuilder`, `RelationsConfig`, `RelationTables`, `RelationalSchema`, `RelationalTable`, `RelationOptions`, `FindManyOptions`, `FindManyRow`, `WithOf`, `KeyColumn` — relational reads, one statement per level ([Relational reads](./relations.md)) | `/database` |
| `related`, `Related`, `RelationFilter`, `RelationWhere`, `CountOf` — relation filters `some` / `none` / `every`, relation counts, and `_count` in `findMany` ([Filter by relations](./relations.md#filter-by-relations)) | `/database` |
| `withQuerySummary`, `QuerySummary` — the `db.query.summary` of the statements an effect runs, for spans | `/database` |
| `layerTest`, `TestDatabase`, `TestDatabaseApi`, `TestDatabaseOptions`, `TestReply`, `TestStatement` — a `Database` with no server, for unit tests | `/database` |
| `layerTest`, `TestDatabase`, `TestDatabaseApi`, `TestDatabaseOptions`, `TestReply`, `TestWriteReply`, `TestStatement` — a `Database` with no server, for unit tests | `/database` |
| `rows`, `insert`, `arbitrary`, `pick`, `SeedError`, `SeedRow`, `SeedRowOf`, `ColumnOverride`, `RowsOptions`, `InsertOptions`, `ArbitraryOptions` — rows from the column Schemas; see [Seeding](./seeding.md) | `/seed` |
| `StatementObservation` — what `observeExit` gets for each statement: names, duration, rows, `error.type` | `/database` |
| `ClickhouseHttpClient` (the service: a `SqlClient` plus `asCommand`, `withQueryId`, `withSettings`), `layer` and `make` (build one from a `ClickhouseHttpClientConfig`: `url`, `username`, `password`, `database`, `settings`, `spanAttributes`), `ClickhouseSetting` (a setting value) — a ClickHouse `SqlClient` over `fetch`, for Workers. Needs ClickHouse 23.9+; a query that fails after its first rows fails, and values bind as typed server-side params ([On Workers and other fetch runtimes](./running-queries.md#on-workers-and-other-fetch-runtimes)) | `/clickhouse-http` |
Expand Down
3 changes: 2 additions & 1 deletion docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,8 @@ const error = yield* Effect.flip(insertAccount) // DatabaseError, reason "Uniqu
| `layerTest(options)` | A `Database` and a `TestDatabase`, with no requirements |
| `TestDatabase` | The control side: `statements`, `reply(...replies)`, `reset` |
| `TestDatabaseOptions` | `dialect` (required), `respond`, `requireTenantScope` |
| `TestReply` | Rows as the server sends them, or a `SqlError` |
| `TestReply` | Rows as the server sends them, a `TestWriteReply`, or a `SqlError` |
| `TestWriteReply` | `{ affectedRows, insertId? }`: what a write reports to `runWrite`. With no reply queued, `runWrite` sees `{ affectedRows: 0 }` |
| `TestStatement` | `{ sql, parameters }`, as received |

The fake does not run SQL. A test that needs real SQL semantics (constraints, joins over stored
Expand Down
4 changes: 4 additions & 0 deletions src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export {
runNonEmpty,
runOne,
runOption,
runWrite,
stream,
transaction,
type BatchCheck,
Expand All @@ -36,6 +37,8 @@ export {
type Statement,
type TransactionInfo,
type TransactionOptions,
type Write,
type WriteResult,
} from "./database/database"
export { constraintViolation, refineConstraints } from "./database/constraint"
export {
Expand Down Expand Up @@ -98,6 +101,7 @@ export {
type TestDatabaseApi,
type TestDatabaseOptions,
type TestReply,
type TestWriteReply,
type TestStatement,
} from "./database/test-layer"
export {
Expand Down
14 changes: 14 additions & 0 deletions src/database/constraint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Miniflare } from "miniflare"
import { postgresDialect } from "../pg/dialect"
import * as Db from "../database"
import * as SQLite from "../sqlite"
import { toDatabaseError } from "./sql-error"

const Live = Layer.effect(
Db.Database,
Expand Down Expand Up @@ -174,3 +175,16 @@ describe("constraint violations on SQLite", () => {
}
}, 30_000)
})

describe("reading driver errors", () => {
it("takes no SQLSTATE from a Node error name, and no MySQL number from another driver's errno", () => {
const node = Object.assign(new Error("write EPIPE"), { code: "EPIPE", errno: -32 })
expect(toDatabaseError("SELECT 1")(node)).not.toHaveProperty("sqlState")
expect(toDatabaseError("SELECT 1")(node)).not.toHaveProperty("errorCode")
// bun:sqlite: an extended result code as `errno`, a name as `code`, no `sqlMessage`.
const bun = Object.assign(new Error("UNIQUE constraint failed: t.a"), { code: "SQLITE_CONSTRAINT_UNIQUE", errno: 2067 })
expect(toDatabaseError("INSERT")(bun)).not.toHaveProperty("errorCode")
const mysql = Object.assign(new Error("Duplicate entry"), { code: "ER_DUP_ENTRY", errno: 1062, sqlState: "23000", sqlMessage: "Duplicate entry 'a' for key 't.k'" })
expect(toDatabaseError("INSERT")(mysql)).toMatchObject({ sqlState: "23000", errorCode: 1062 })
})
})
Loading