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
5 changes: 5 additions & 0 deletions .changeset/mysql-write-limit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@maple-dev/effect-orm": minor
---

MySQL and MariaDB `ORDER BY` and `LIMIT` on a single-table UPDATE or DELETE: `deleteFrom(table).where(...).orderBy(["id", "asc"]).limit(20000)` writes `DELETE FROM t WHERE ... ORDER BY ... LIMIT 20000`, and `update(table)` takes the same two clauses, for chunked deletes that keep each transaction small (loop until `Db.runWrite` reports fewer `affectedRows` than the limit). `orderBy` takes `[column, direction]` tuples of the table's columns or a callback of `[expression, direction]` pairs; `limit(n)` writes `n` as a literal, as a query's limit, and a negative or fractional literal is a type error, such a value at run time an `InvalidArguments` failure. Both add the new `WriteLimitClause` to the write's params, so compiling it for Postgres, SQLite, D1 or ClickHouse is a type error, and the compile refuses it as a `QueryBuilderDefect`; beside `update(...).from(...)`, a multi-table write MySQL refuses them on, they are a defect too. Tenant scope is unchanged: the WHERE decides it, and a subquery in the ORDER BY counts as a read. New: `Dialect.clauses.writeOrderLimit`, and the `WriteLimitClause` and `WriteOrderBySpec` types.
14 changes: 12 additions & 2 deletions design/writes.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,5 +292,15 @@ compiled beside INSERT and sharing its value encoding (`valueCells`), SET record
Checked on 26.2.19.43 and 26.8.2.7.
- **Tenant scope** is derived from the WHERE as for a query over the table; an UPDATE that sets
the tenant column to anything but the pinned value is cross-tenant.
- Not built: UPDATE ... FROM / joins, DELETE USING, ORDER BY / LIMIT, a VALUES source for bulk
updates. See `design/gap-review.md`.
- **ORDER BY / LIMIT** (`orderBy`, `limit`) on a single-table UPDATE or DELETE, MySQL and
MariaDB only (`DialectClauses.writeOrderLimit`). They add `WriteLimitClause` to the write's
params, so `compile` for another dialect is a type error, and the compile refuses them as a
defect too (Postgres, ClickHouse; SQLite unless built with `SQLITE_ENABLE_UPDATE_DELETE_LIMIT`,
which is not modelled). The limit is checked and written as a query's is, a literal (`LIMIT 20000`), so no generated
param name can stand in for one the statement names: a negative or
fractional value is an `InvalidArguments` failure. MySQL refuses both on a multi-table write,
so beside `from` they are a defect. They do not change the tenant scope; a subquery in the
ORDER BY counts as a read. The use: chunked deletes that keep each transaction small
(`DELETE ... WHERE runId = ? LIMIT 20000`, looped until `Db.runWrite` reports fewer rows).
- Not built: UPDATE ... FROM / joins on MySQL, DELETE USING, a VALUES source for bulk updates.
See `design/gap-review.md`.
3 changes: 3 additions & 0 deletions docs/mysql.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,9 @@ another dialect is refused in the type and at compile time.
written as a `CONCAT` of parts. A name (select key, alias, CTE name) that spells it has no
such escape and fails the compile with `InvalidLiteral`.
- **OFFSET without LIMIT** is written with MySQL's largest row count.
- **UPDATE and DELETE take `orderBy` and `limit`**, MySQL's single-table `ORDER BY ... LIMIT n`,
for chunked deletes; no other dialect does. See
[ORDER BY and LIMIT](./updates-and-deletes.md#order-by-and-limit-mysql).
- **MariaDB 11.4 pages `DISTINCT` over a join wrongly.** It counts `OFFSET` over the join's rows
before `DISTINCT` removes their duplicates, so a page can repeat a row from the page before.
Page a de-duplicated join from a subquery (`fromQuery(query.distinct(), "d")`) or with `groupBy`.
Expand Down
4 changes: 2 additions & 2 deletions docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ Everything in this section is exported, identically, from `/clickhouse`, `/postg
| `fromQuery` | `(query, alias) => CHQuery` |
| `fromUnion` | `(union, alias) => CHQuery` |
| `unionAll` | `(...queries) => CHUnionQuery` |
| `update` | `(table) => CHUpdateStart`, then `CHUpdate`: `.from(source, alias)` (before `set`, once, giving a `CHUpdateFromStart`; Postgres and SQLite, `UpdateFromClause` elsewhere), `.set(record \| fn)`, `.where(fn)` or `.allRows()`, `.returning(...)`, `.settings(record)`. See [Updating and deleting](./updates-and-deletes.md) |
| `deleteFrom` | `(table) => CHDelete`: `.where(fn)` or `.allRows()`, `.returning(...)`, `.settings(record)` |
| `update` | `(table) => CHUpdateStart`, then `CHUpdate`: `.from(source, alias)` (before `set`, once, giving a `CHUpdateFromStart`; Postgres and SQLite, `UpdateFromClause` elsewhere), `.set(record \| fn)`, `.where(fn)` or `.allRows()`, `.orderBy(...)` (`WriteOrderBySpec` tuples or a callback) and `.limit(n)` (MySQL and MariaDB, `WriteLimitClause` elsewhere), `.returning(...)`, `.settings(record)`. See [Updating and deleting](./updates-and-deletes.md) |
| `deleteFrom` | `(table) => CHDelete`: `.where(fn)` or `.allRows()`, `.orderBy(...)` and `.limit(n)` (MySQL and MariaDB, `WriteLimitClause` elsewhere; see [ORDER BY and LIMIT](./updates-and-deletes.md#order-by-and-limit-mysql)), `.returning(...)`, `.settings(record)` |
| `tableSchemas` | `(table) => TableSchemas`: the `select`, `insert`, `update`, `json`, `jsonCreate` and `jsonUpdate` row Schemas. See [Row Schemas](./tables-and-types.md#row-schemas) |
| `insertInto` | `(table) => CHInsertStart`, then `CHInsert`; `.values(row \| rows)` or `.select(query)` sets its rows, `.settings(record)` ClickHouse `SETTINGS`, `.returning(...)` the RETURNING list, `.onConflictDoNothing(options?)` / `.onConflictDoUpdate(options)` the ON CONFLICT clause (Postgres and SQLite), `.onDuplicateKeyUpdate({ set })` the ON DUPLICATE KEY UPDATE clause and `.onDuplicateKeyDoNothing()` a no-op one (MySQL and MariaDB). See [Inserting rows](./inserts.md) |
| `fillDefaults` | `(write) => Effect<write, never, RequirementsOf<write>>`: runs the `defaultFn` / `onUpdate` Effects of an insert's or update's table into its rows or SET. `Database.run` calls it; call it before `compile` when you compile a write yourself. See [client-side defaults](./inserts.md#client-side-defaults) |
Expand Down
33 changes: 33 additions & 0 deletions docs/updates-and-deletes.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,39 @@ it to the target's tenant, or pin it, as a join would.

_(Backed by `docs/updates-and-deletes.md > UPDATE ... FROM reads the source in SET and WHERE`.)_

## ORDER BY and LIMIT (MySQL)

On MySQL and MariaDB, `orderBy` and `limit` bound a single-table UPDATE or DELETE:
`DELETE FROM t WHERE ... ORDER BY ... LIMIT n`. `orderBy` takes `[column, "asc" | "desc"]`
tuples of the table's columns, or a callback giving `[expression, direction]` pairs; calling it
again replaces the order. `limit(n)` takes a non-negative integer, written as a literal as a query's limit is; a negative or
fractional literal is a type error, and such a value at run time is a `QueryBuilderError`
(`InvalidArguments`). Without `orderBy`, which rows a `limit` takes is up to the server.

Deleting a large set of rows in chunks keeps each transaction small: loop until a chunk deletes
fewer rows than the limit, reading the count from `Db.runWrite`
([write results](./database.md#write-results)).

```ts
const Steps = MySQL.table("steps", { id: MySQL.bigint, runId: MySQL.varchar(36) })

const chunk = MySQL.deleteFrom(Steps)
.where(($) => [$.runId.eq(MySQL.param.string("runId"))])
.orderBy(["id", "asc"])
.limit(20000)
// DELETE FROM `steps` WHERE `runId` = ? ORDER BY `id` ASC LIMIT 20000

// let deleted = 20000
// while (deleted === 20000) deleted = (yield* Db.runWrite(chunk, { runId })).affectedRows
```

Postgres, SQLite, D1 and ClickHouse take neither: the write carries `WriteLimitClause`, so
compiling it for them is a type error, and the compile refuses it as well. MySQL refuses them on
a multi-table write, so they cannot be combined with [`from`](#update--from). The WHERE decides
the [tenant scope](#tenant-scope), as without them; a subquery in the ORDER BY counts as a read.

_(Backed by `docs/updates-and-deletes.md > A chunked DELETE with ORDER BY and LIMIT`.)_

## WHERE, and writing every row

`where` works as in a query: a list of conditions, AND-joined, with an `undefined` one skipped,
Expand Down
73 changes: 64 additions & 9 deletions src/ch/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { CHFloatResult, CHNumber, columnSqlName, custom, dateTime, dateTime64, t
import type { CHQuery, CHQueryState, ColumnAccessor, NeedsSelect } from "./query"
import type { CHUnionQuery } from "./union"
import { isExcludedSet, isInsert, type AnyInsert, type CHInsert, type ConflictClause, type ConflictTarget, type ExcludedSet } from "./insert"
import { isDelete, isUpdate, type CHDelete, type CHUpdate } from "./update"
import { isDelete, isUpdate, type CHDelete, type CHDeleteState, type CHUpdate, type CHUpdateState } from "./update"
import type { Table } from "./table"
import { createColumnAccessor, createQualifiedColumnAccessor, createJoinedColumnAccessor, sourceAlias } from "./query"
import {
Expand Down Expand Up @@ -120,10 +120,10 @@ const orderByClause = (specs: ReadonlyArray<[string, "asc" | "desc"]>): Array<st
})

/** The callback form of `orderBy`: each expression as it renders, then its direction. */
const orderByExprs = (specs: ReadonlyArray<readonly [Expr<any, any>, "asc" | "desc"]>): Array<string> =>
const orderByExprs = (specs: ReadonlyArray<readonly [Expr<any, any>, "asc" | "desc"]>, where = "CHQuery"): Array<string> =>
specs.map(([expr, direction]) => {
if (!isExprLike(expr) || (direction !== "asc" && direction !== "desc")) {
return fail(new QueryBuilderDefect({ message: "CHQuery: orderBy(($) => ...) returns [expression, \"asc\" | \"desc\"] pairs" }), "")
return fail(new QueryBuilderDefect({ message: `${where}: orderBy(($) => ...) returns [expression, "asc" | "desc"] pairs` }), "")
}
return `${compileSqlFragment(expr.toFragment())} ${direction.toUpperCase()}`
})
Expand Down Expand Up @@ -2556,6 +2556,47 @@ const valuesColumns = (

// UPDATE and DELETE

/** Whether `limit` was called: `limit(undefined)` (a missing value at run time) is refused, not dropped. */
const hasLimit = (state: CHUpdateState | CHDeleteState): boolean => Object.hasOwn(state, "limitValue")

/**
* A write's `ORDER BY ... LIMIT ?`, or "" without either. Order specs name the
* table's columns, which render as `$` does (so a renamed column is written by
* its database name); the limit is checked and written as a query's is, a
* literal, so no generated param name can stand in for one the statement names.
*/
const writeOrderLimit = (
state: CHUpdateState | CHDeleteState,
$: Record<string, unknown>,
where: string,
): string => {
let sql = ""
const order =
state.orderByFn !== undefined
? orderByExprs(state.orderByFn($), where)
: (state.orderBySpecs ?? []).map((spec) => {
const [column, direction] = Array.isArray(spec) ? spec : []
if (typeof column !== "string" || !Object.hasOwn(state.table.columns, column) || (direction !== "asc" && direction !== "desc")) {
return fail(new QueryBuilderDefect({
message: `${where}: orderBy() takes [column, "asc" | "desc"] tuples naming the table's columns, got ${JSON.stringify(spec)}`,
}), "")
}
return `${compileSqlFragment(($[column] as Expr<any>).toFragment())} ${direction.toUpperCase()}`
})
if ((state.orderBySpecs !== undefined || state.orderByFn !== undefined) && order.length === 0) {
return fail(new QueryBuilderDefect({ message: `${where}: orderBy() needs at least one column` }), "")
}
if (order.length > 0) sql += `\nORDER BY ${order.join(", ")}`
if (hasLimit(state)) {
const value: unknown = state.limitValue
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
return fail(new QueryBuilderError({ code: "InvalidArguments", message: `${where}: limit(${String(value)}): expected a non-negative integer` }), "")
}
sql += `\nLIMIT ${compileSqlFragment(rowCount("limit", value)!)}`
}
return sql
}

/**
* An UPDATE or DELETE. Postgres writes `UPDATE t SET ... WHERE ...` and
* `DELETE FROM t WHERE ...`; ClickHouse an `ALTER TABLE t UPDATE ... WHERE ...`
Expand Down Expand Up @@ -2599,11 +2640,25 @@ function compileUpdateOrDelete(
}
const conditions = (state.whereFn?.($) ?? []).filter((c): c is NonNullable<typeof c> => c != null)

// ORDER BY and LIMIT: MySQL's single-table UPDATE and DELETE. A multi-table
// write (a FROM source) refuses them there, so it is refused here too.
const ordered = state.orderBySpecs !== undefined || state.orderByFn !== undefined
const limited = hasLimit(state)
if ((ordered || limited) && dialect.clauses.writeOrderLimit !== true) {
const named = ordered && limited ? "orderBy() and limit() have" : ordered ? "orderBy() has" : "limit() has"
return fail(new QueryBuilderDefect({
message: `${where}: ${named} no meaning for the ${dialect.name} dialect, whose ${kind === "update" ? "UPDATE" : "DELETE"} takes no ORDER BY or LIMIT`,
}), failedQuery<any, undefined>())
}
if ((ordered || limited) && from !== undefined) {
return fail(new QueryBuilderDefect({ message: `${where}: orderBy() and limit() write a single-table UPDATE; an UPDATE ... FROM takes neither` }), failedQuery<any, undefined>())
}

const tenant = table.tenantColumn
const setWrites: Array<{ readonly value: unknown; readonly sql: string }> = []

const reads: Array<TenantSource> = []
const [assignments, whereSql, fromSql] = withSubqueryCompiler(
const [assignments, whereSql, fromSql, orderLimitSql] = withSubqueryCompiler(
recordingSubqueries(values, reads),
() => {
let fromSql = ""
Expand All @@ -2621,11 +2676,11 @@ function compileUpdateOrDelete(
let assignments: ReadonlyArray<string> = []
if (write._tag === "CHUpdate") {
const set = (write as CHUpdate<any, any, any>)._state.set
if (set === undefined) return fail(new QueryBuilderDefect({ message: `${where}: set() is required` }), [assignments, "", ""] as const)
if (set === undefined) return fail(new QueryBuilderDefect({ message: `${where}: set() is required` }), [assignments, "", "", ""] as const)
const record = typeof set === "function" ? set($) : set
const unfilled = missingClientDefaults(table.clientDefaults?.update, record as Record<string, unknown>)
if (unfilled.length > 0) {
return fail(new QueryBuilderDefect({ message: clientDefaultsMessage(where, "update", unfilled) }), [assignments, "", ""] as const)
return fail(new QueryBuilderDefect({ message: clientDefaultsMessage(where, "update", unfilled) }), [assignments, "", "", ""] as const)
}
assignments = setAssignments(table, record as Record<string, unknown>, cell, (column, value, sql) => {
if (column === tenant) setWrites.push({ value, sql })
Expand All @@ -2637,15 +2692,15 @@ function compileUpdateOrDelete(
return fail(new QueryBuilderError({
code: "InvalidArguments",
message: `${where}: where() gave no conditions (each was undefined or empty), which would write every row; call allRows() if that is meant`,
}), [assignments, "", ""] as const)
}), [assignments, "", "", ""] as const)
}
const whereSql =
rendered.length > 0
? `\nWHERE ${rendered.join("\n AND ")}`
: dialect.clauses.alterTableUpdate === true
? "\nWHERE 1"
: ""
return [assignments, whereSql, fromSql] as const
return [assignments, whereSql, fromSql, writeOrderLimit(state, $, where)] as const
},
)

Expand Down Expand Up @@ -2688,7 +2743,7 @@ function compileUpdateOrDelete(
: dialect.clauses.alterTableUpdate === true
? `ALTER TABLE ${target} UPDATE ${assignments.join(", ")}`
: `UPDATE ${target} SET ${assignments.join(", ")}`
const rendered = renderParams(`${head}${fromSql}${whereSql}${returning?.sql ?? ""}${settings}`, values, dialect)
const rendered = renderParams(`${head}${fromSql}${whereSql}${orderLimitSql}${returning?.sql ?? ""}${settings}`, values, dialect)
const scope = withReads({ scope: tenantScope, bound: tenantScope === "single-tenant" ? tenantBound : undefined }, reads)
return writeCompiledQuery(rendered, kind, scope.scope, scope.bound, returning, state.crossTenant, table.name)
}
4 changes: 4 additions & 0 deletions src/ch/dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ export interface DialectClauses {
readonly alterTableUpdate?: boolean
/** `UPDATE t SET … FROM source WHERE …`: Postgres, and SQLite 3.33+. */
readonly updateFrom?: boolean
/** `ORDER BY` and `LIMIT` on a single-table UPDATE or DELETE (MySQL,
* MariaDB). Absent means no: a write with `.orderBy()` or `.limit()`
* fails to compile for the dialect. */
readonly writeOrderLimit?: boolean
/** The FROM a SELECT with no source writes, where one is needed (MySQL's `DUAL`, for a WHERE). */
readonly fromlessSelect?: string
}
Expand Down
Loading