@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/package.json +34 -3
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/capability.ts +5 -0
  5. package/src/codegen-sqlite.ts +146 -0
  6. package/src/codegen.ts +59 -9
  7. package/src/database.ts +227 -61
  8. package/src/errors.ts +2 -2
  9. package/src/file-columns.ts +4 -1
  10. package/src/framework-tables.ts +28 -8
  11. package/src/framework.ts +14 -5
  12. package/src/guard.ts +8 -0
  13. package/src/index.ts +9 -1
  14. package/src/job-leases.ts +210 -54
  15. package/src/job-wakes.ts +450 -0
  16. package/src/links.ts +8 -1
  17. package/src/migrations-sqlite.ts +163 -0
  18. package/src/migrations.ts +25 -0
  19. package/src/nodes.ts +64 -9
  20. package/src/orm-types.ts +2 -2
  21. package/src/orm.ts +68 -35
  22. package/src/policy.ts +8 -2
  23. package/src/postgres.ts +26 -0
  24. package/src/registry.ts +11 -2
  25. package/src/sql.ts +216 -473
  26. package/src/sqlite-bun.ts +149 -0
  27. package/src/sqlite-migrate.ts +242 -0
  28. package/src/sqlite.ts +224 -0
  29. package/src/store.ts +362 -93
  30. package/src/stored-files.ts +188 -52
  31. package/src/tables.ts +16 -0
  32. package/src/temporal.ts +115 -9
  33. package/src/testing-shared.ts +733 -0
  34. package/src/testing-sqlite.ts +513 -0
  35. package/src/testing.ts +169 -482
  36. package/types/src/application-rows.d.ts +58 -0
  37. package/types/src/capability.d.ts +5 -0
  38. package/types/src/codegen-sqlite.d.ts +6 -0
  39. package/types/src/codegen.d.ts +30 -0
  40. package/types/src/database.d.ts +81 -20
  41. package/types/src/errors.d.ts +2 -2
  42. package/types/src/framework.d.ts +11 -5
  43. package/types/src/index.d.ts +1 -1
  44. package/types/src/job-leases.d.ts +32 -4
  45. package/types/src/job-wakes.d.ts +101 -0
  46. package/types/src/migrations-sqlite.d.ts +4 -0
  47. package/types/src/migrations.d.ts +1 -0
  48. package/types/src/nodes.d.ts +13 -2
  49. package/types/src/orm-types.d.ts +2 -2
  50. package/types/src/policy.d.ts +4 -0
  51. package/types/src/postgres.d.ts +12 -0
  52. package/types/src/registry.d.ts +10 -2
  53. package/types/src/sql.d.ts +29 -21
  54. package/types/src/sqlite-bun.d.ts +21 -0
  55. package/types/src/sqlite-migrate.d.ts +28 -0
  56. package/types/src/sqlite.d.ts +24 -0
  57. package/types/src/store.d.ts +26 -9
  58. package/types/src/stored-files.d.ts +6 -2
  59. package/types/src/tables.d.ts +10 -0
  60. package/types/src/temporal.d.ts +21 -0
  61. package/types/src/testing-shared.d.ts +201 -0
  62. package/types/src/testing-sqlite.d.ts +22 -0
  63. package/types/src/testing.d.ts +2 -93
package/src/sql.ts CHANGED
@@ -1,26 +1,27 @@
1
1
  // `ctx.sql(Row)`…``: one statement of the application's own SQL, for a site that declares `sql: 'read' | 'write'`. The
2
- // template's static text is classified before anything is sent: an interpolation is always a bound parameter (`$n`),
3
- // never SQL. The statement runs in the site's session — the invocation's transaction, or a job's fenced one — so it
4
- // commits and rolls back with every `ctx.db` handle. The name rules are defense in depth; the runtime role
5
- // (`run_<id>`, DML only) is what bounds a statement they admit.
2
+ // template's static text is classified before anything is sent: an interpolation is always a bound parameter (`$n` on
3
+ // Postgres, `?n` on SQLite), never SQL. The statement runs in the site's session — the invocation's transaction, or a
4
+ // job's fenced one — so it commits and rolls back with every `ctx.db` handle. The hard rules keep it inside the
5
+ // platform (the framework's tables, the catalog, the transaction); what it does with the application's own data is the
6
+ // approver's to review, since the `sql:` declaration marks the site for a closer look (ADR-0012, ADR-0050).
6
7
 
7
8
  import {
8
9
  dmlForeignSchema,
9
10
  frameworkReference,
10
11
  lexSql,
12
+ lexSqlite,
11
13
  nameReferences,
12
- nameText,
13
14
  nestedStatement,
14
15
  parenthesizedTarget,
15
16
  refusedFunctionCall,
16
17
  type SqlToken,
17
18
  statementKind,
18
- topLevelStatements,
19
+ statementsOf,
19
20
  unicodeIdentifier,
20
21
  upperWord,
21
22
  } from '@fabrika/platform-node/sql'
22
23
  import { z } from 'zod/v4'
23
- import { freeze, hasOwn, isArray, ownDescriptor, ownKeys, parseList } from './builtins'
24
+ import { freeze, hasOwn, isArray, isSafeInteger, OBJECT_PROTOTYPE, ownDescriptor, ownKeys, parseList, prototypeOf } from './builtins'
24
25
  import { runApplicationStatement, type Session, type SqlParameter } from './database'
25
26
  import { type QueryRefusal, QueryRefusedError, SqlRowError } from './errors'
26
27
  import { isPlainIdentifier } from './identifier'
@@ -29,9 +30,12 @@ import { dayText } from './temporal'
29
30
  /** What a site declares: `'read'` runs queries only, `'write'` also `INSERT`, `UPDATE` and `DELETE`. */
30
31
  export type SqlMode = 'read' | 'write'
31
32
 
32
- /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers (an array). */
33
+ /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers. */
33
34
  export type SqlValue = string | number | boolean | bigint | Date | null | readonly (string | number)[]
34
35
 
36
+ /** The database a statement is classified for: Postgres in the application's schema, or a Durable Object's SQLite. */
37
+ export type SqlDatabase = { readonly dialect: 'postgres'; readonly schema: string } | { readonly dialect: 'sqlite' }
38
+
35
39
  /** One test of a capability's scope on a table: the column holds the value, or one of the list. */
36
40
  export interface ScopeTest {
37
41
  readonly column: string
@@ -41,25 +45,23 @@ export interface ScopeTest {
41
45
  /** A capability's predicate on one table: every row (`'all'`), or an OR of AND groups; no group matches nothing. */
42
46
  export type ScopeTerms = 'all' | readonly (readonly ScopeTest[])[]
43
47
 
44
- /** What a fragment's table is to its statement: read, or the target of its UPDATE or DELETE. */
48
+ /** What a fragment's table is to its statement, as its author states it: read, or the target of an UPDATE or DELETE. */
45
49
  export type ScopeUse = 'read' | 'update' | 'delete'
46
50
 
47
- /**
48
- * The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not
49
- * reach it for that use. `assigned` is the columns an UPDATE's SET names (none when the SET cannot be read with
50
- * certainty), and `undefined` before a statement is known.
51
- */
52
- export type ScopeOf = (capability: unknown, table: string, use: ScopeUse, assigned?: readonly string[]) => ScopeTerms
53
-
54
- /** The operation a write statement performs on one of its targets. */
55
- export type WriteOperation = 'insert' | 'update' | 'delete'
51
+ /** The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not reach it. */
52
+ export type ScopeOf = (capability: unknown, table: string, use: ScopeUse) => ScopeTerms
56
53
 
57
- /** Throws for a table no statement may write with `operation`: a reference table. */
58
- export type WriteTarget = (table: string, operation: WriteOperation) => void
54
+ /** The third argument of `ctx.sql.scope`: the table's alias in the statement, and what the statement does with it. */
55
+ export interface SqlScopeOptions {
56
+ /** The table's name in the statement; the table's own name by default. */
57
+ readonly alias?: string
58
+ /** `'update'` or `'delete'` where the statement writes the table, which needs that operation's action; `'read'` by default. */
59
+ readonly use?: ScopeUse
60
+ }
59
61
 
60
62
  /**
61
- * `ctx.sql.scope(capability, table, alias?)`: the capability's whole predicate on one table, as SQL with bound values.
62
- * A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
63
+ * `ctx.sql.scope(capability, table, { alias, use })`: the capability's whole predicate on one table, as SQL with bound
64
+ * values. A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
63
65
  * methods captured at load, so no object an application builds or changes is ever taken for one.
64
66
  */
65
67
  export interface SqlScope {
@@ -68,9 +70,8 @@ export interface SqlScope {
68
70
 
69
71
  interface ScopeData {
70
72
  readonly site: SqlSite
71
- readonly capability: unknown
72
- readonly table: string
73
73
  readonly alias: string
74
+ readonly terms: ScopeTerms
74
75
  }
75
76
 
76
77
  const scopes = new WeakMap<object, ScopeData>()
@@ -83,7 +84,7 @@ function newScope(data: ScopeData): SqlScope {
83
84
  const scope: SqlScope = { kind: 'sql-scope' }
84
85
  withoutPrototype(scope, null)
85
86
  freeze(scope)
86
- register(scope, freeze({ site: data.site, capability: data.capability, table: data.table, alias: data.alias }))
87
+ register(scope, freeze({ site: data.site, alias: data.alias, terms: data.terms }))
87
88
  return scope
88
89
  }
89
90
 
@@ -95,7 +96,7 @@ function scopeOf(value: unknown): ScopeData | undefined {
95
96
  /** `ctx.sql(Row)`: the tag for rows of `Row`, and `scope` for the capability's predicate inside its text. */
96
97
  export interface SqlTag {
97
98
  <S extends z.core.$ZodType>(row: S): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<z.output<S>[]>
98
- scope(capability: unknown, table: string, alias?: string): SqlScope
99
+ scope(capability: unknown, table: string, options?: SqlScopeOptions): SqlScope
99
100
  }
100
101
 
101
102
  /** The site a tag is made for: its mode, its binding to the invocation, and the session its statements run in. */
@@ -108,15 +109,16 @@ export interface SqlSite {
108
109
  fail(): void
109
110
  }
110
111
 
111
- const READ_STATEMENTS: ReadonlySet<string> = new Set(['SELECT', 'WITH', 'VALUES', 'TABLE'])
112
+ const POSTGRES_READS: ReadonlySet<string> = new Set(['SELECT', 'WITH', 'VALUES', 'TABLE'])
113
+ const SQLITE_READS: ReadonlySet<string> = new Set(['SELECT', 'WITH', 'VALUES'])
112
114
  const WRITE_STATEMENTS: ReadonlySet<string> = new Set(['INSERT', 'UPDATE', 'DELETE'])
113
115
  const WRITE_WORDS: ReadonlySet<string> = new Set(['INSERT', 'UPDATE', 'DELETE', 'MERGE'])
114
116
  /** `FOR UPDATE`, `FOR NO KEY UPDATE`, `FOR SHARE`, `FOR KEY SHARE`: what follows `FOR` in a locking clause. */
115
117
  const LOCK_WORDS: ReadonlySet<string> = new Set(['UPDATE', 'NO', 'SHARE', 'KEY'])
116
118
  /** ctx.sql calls reviewed built-ins only: the functions the migrations declare are not known at runtime. */
117
119
  const NO_DECLARED_FUNCTIONS: ReadonlySet<string> = new Set()
118
-
119
- const ALLOWED_STATEMENTS = "SELECT, WITH, VALUES or TABLE, and INSERT, UPDATE or DELETE on a site that declares sql: 'write'"
120
+ /** What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`): only the tag writes one. */
121
+ const SQLITE_PARAMETER_STARTS: ReadonlySet<string> = new Set(['?', ':', '@', '$', '#'])
120
122
 
121
123
  function refuse(reason: QueryRefusal, message: string): never {
122
124
  throw new QueryRefusedError(reason, `ctx.sql: ${message}`)
@@ -125,6 +127,9 @@ function refuse(reason: QueryRefusal, message: string): never {
125
127
  const isPunct = (token: SqlToken | undefined, char: string): boolean => token?.kind === 'punct' && token.char === char
126
128
  const isDigit = (token: SqlToken | undefined): boolean => token?.kind === 'punct' && token.char >= '0' && token.char <= '9'
127
129
 
130
+ /** The character that opens a placeholder the tag writes: `$1` on Postgres, `?1` on SQLite. */
131
+ const markerOf = (database: SqlDatabase): string => (database.dialect === 'postgres' ? '$' : '?')
132
+
128
133
  /** The template's static parts. A call with a plain array, or a text with an invalid escape, is refused. */
129
134
  function templateParts(text: unknown): readonly string[] {
130
135
  const raw: unknown = isArray(text) && hasOwn(text, 'raw') ? ownDescriptor(text, 'raw')?.value : undefined
@@ -142,26 +147,57 @@ function templateParts(text: unknown): readonly string[] {
142
147
  return parts
143
148
  }
144
149
 
145
- /** The statement's text, each interpolation a `$n` placeholder between the static parts. */
146
- function statementText(parts: readonly string[]): string {
150
+ /** The statement's text, each interpolation a placeholder (`$n` or `?n`) between the static parts. */
151
+ function statementText(parts: readonly string[], marker: string): string {
147
152
  let text = parts[0] ?? ''
148
153
  for (let index = 1; index < parts.length; index++) {
149
154
  const part = parts[index] ?? ''
150
155
  if (/^[0-9]/.test(part)) {
151
156
  refuse('sql_template', `a digit right after the value \${…} number ${index} would join its placeholder; put a space between them`)
152
157
  }
153
- text += `$${index}${part}`
158
+ text += `${marker}${index}${part}`
154
159
  }
155
160
  return text
156
161
  }
157
162
 
158
- /** How many `$n` placeholders the lexer sees outside literals, quoted names, dollar-quoted bodies and comments. */
159
- function placeholderCount(tokens: readonly SqlToken[]): number {
160
- let count = 0
161
- for (let index = 0; index + 1 < tokens.length; index++) {
162
- if (isPunct(tokens[index], '$') && isDigit(tokens[index + 1])) count++
163
+ /**
164
+ * The tokens of the statement `parts` make, refused unless each placeholder the tag writes is one the lexer sees at
165
+ * code level (not in a literal, a quoted name, a dollar body or a comment) and the text writes none of its own.
166
+ */
167
+ function placedTokens(parts: readonly string[], database: SqlDatabase): readonly SqlToken[] {
168
+ const marker = markerOf(database)
169
+ const written = database.dialect === 'postgres' ? /\$[0-9]/ : /\?[0-9]/
170
+ for (const part of parts) {
171
+ if (written.test(part)) {
172
+ refuse(
173
+ 'sql_template',
174
+ `the text holds ${marker} and a digit, which reads as a positional parameter; interpolate the value with \${…}, a literal one too`,
175
+ )
176
+ }
177
+ }
178
+ const { tokens, unterminated } = database.dialect === 'postgres' ? lexSql(statementText(parts, marker)) : lexSqlite(statementText(parts, marker))
179
+ if (unterminated !== undefined) {
180
+ refuse('sql_template', `a string, quoted name, dollar-quoted body or comment at line ${unterminated} never closes`)
181
+ }
182
+ let placed = 0
183
+ for (let index = 0; index < tokens.length; index++) {
184
+ const token = tokens[index]
185
+ if (isPunct(token, marker) && isDigit(tokens[index + 1])) {
186
+ placed++
187
+ } else if (database.dialect === 'sqlite' && token?.kind === 'punct' && SQLITE_PARAMETER_STARTS.has(token.char)) {
188
+ refuse(
189
+ 'sql_template',
190
+ `${token.char} at line ${token.line} starts a parameter the text writes, which nothing binds; interpolate the value with \${…}`,
191
+ )
192
+ }
193
+ }
194
+ if (placed !== parts.length - 1) {
195
+ refuse(
196
+ 'sql_template',
197
+ 'a value ${…} inside a string literal, a quoted name, a dollar-quoted body or a comment is not bound; interpolate a whole value',
198
+ )
163
199
  }
164
- return count
200
+ return tokens
165
201
  }
166
202
 
167
203
  /** The first `SELECT … INTO`: it creates a table. `INSERT INTO` is the one `INTO` a statement may hold. */
@@ -185,29 +221,32 @@ function readRefusal(tokens: readonly SqlToken[]): string | undefined {
185
221
  }
186
222
 
187
223
  /**
188
- * The SQL `parts` make, with `$1…$n` for the values, or a `QueryRefusedError` that names what is refused: more than
189
- * one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for `'write'`), a nested statement of
190
- * another kind, a qualified name outside `schema`, a `fabrika_*` or `pg_*` name, a function call outside the reviewed
191
- * built-ins, and a value placed where it would not be bound.
224
+ * The first name, quoted name or string literal SQLite could read as a framework (`fabrika_*`) or catalog (`sqlite_*`)
225
+ * object. SQLite folds names case-insensitively, quoted ones too, and takes a string where only a name may stand
226
+ * (`FROM 'fabrika_x'`), so every form counts.
192
227
  */
193
- export function classifySql(parts: readonly string[], mode: SqlMode, schema: string): string {
194
- for (const part of parts) {
195
- if (/\$[0-9]/.test(part)) {
196
- refuse('sql_template', 'the text holds $ and a digit, which reads as a positional parameter; interpolate the value with ${…}, a literal one too')
197
- }
198
- }
199
- const text = statementText(parts)
200
- const { tokens: all, unterminated } = lexSql(text)
201
- if (unterminated !== undefined) {
202
- refuse('sql_template', `a string, quoted name, dollar-quoted body or comment at line ${unterminated} never closes`)
228
+ function sqliteNameRefusal(tokens: readonly SqlToken[]): { readonly name: string; readonly line: number; readonly catalog: boolean } | undefined {
229
+ for (const token of tokens) {
230
+ const text = token.kind === 'word' || token.kind === 'quoted' || token.kind === 'string' ? token.text : undefined
231
+ const name = text?.toLowerCase()
232
+ if (name === undefined) continue
233
+ if (name.startsWith('fabrika_')) return { name: text ?? name, line: token.line, catalog: false }
234
+ if (name.startsWith('sqlite_')) return { name: text ?? name, line: token.line, catalog: true }
203
235
  }
204
- if (placeholderCount(all) !== parts.length - 1) {
205
- refuse(
206
- 'sql_template',
207
- 'a value ${…} inside a string literal, a quoted name, a dollar-quoted body or a comment is not bound; interpolate a whole value',
208
- )
209
- }
210
- const statements = topLevelStatements(text)
236
+ return undefined
237
+ }
238
+
239
+ /**
240
+ * The SQL `parts` make, with a bound placeholder for each value, or a `QueryRefusedError` that names what is refused.
241
+ * On both dialects: more than one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for
242
+ * `'write'`), a `'read'` statement that writes or locks, a value placed where it would not be bound, and a `fabrika_*`
243
+ * name. On Postgres also a nested statement of another kind, `SELECT … INTO`, a `U&` name, a `pg_*` name, a qualified
244
+ * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
245
+ * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
246
+ */
247
+ export function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase): string {
248
+ const all = placedTokens(parts, database)
249
+ const statements = statementsOf(all)
211
250
  const [statement] = statements
212
251
  if (statement === undefined) {
213
252
  refuse('sql_statement', 'the template holds no statement')
@@ -217,13 +256,35 @@ export function classifySql(parts: readonly string[], mode: SqlMode, schema: str
217
256
  }
218
257
  const tokens = statement.tokens
219
258
  const first = upperWord(tokens[0]) ?? ''
220
- if (!READ_STATEMENTS.has(first) && !WRITE_STATEMENTS.has(first)) {
221
- refuse('sql_statement', `${statementKind(tokens)} is refused; it runs ${ALLOWED_STATEMENTS}`)
259
+ const reads = database.dialect === 'postgres' ? POSTGRES_READS : SQLITE_READS
260
+ if (!reads.has(first) && !WRITE_STATEMENTS.has(first)) {
261
+ refuse(
262
+ 'sql_statement',
263
+ `${statementKind(tokens)} is refused; it runs ${
264
+ database.dialect === 'postgres' ? 'SELECT, WITH, VALUES or TABLE' : 'SELECT, WITH or VALUES'
265
+ }, and INSERT, UPDATE or DELETE on a site that declares sql: 'write'`,
266
+ )
222
267
  }
223
268
  const writes = mode === 'read' ? (WRITE_STATEMENTS.has(first) ? `${first} at line ${statement.line}` : readRefusal(tokens)) : undefined
224
269
  if (writes !== undefined) {
225
270
  refuse('sql_read_only', `sql: 'read' runs queries only, and the statement holds ${writes}; declare sql: 'write' on a mutation, a job or a webhook`)
226
271
  }
272
+ const framework = frameworkReference(tokens)
273
+ if (framework !== undefined) {
274
+ refuse('sql_name', `'${framework.name}' at line ${framework.line} is the framework's; ctx.sql reaches only the application's own tables`)
275
+ }
276
+ if (database.dialect === 'sqlite') {
277
+ const name = sqliteNameRefusal(tokens)
278
+ if (name !== undefined) {
279
+ refuse(
280
+ 'sql_name',
281
+ `'${name.name}' at line ${name.line} ${
282
+ name.catalog ? "is SQLite's catalog" : "is the framework's"
283
+ }; ctx.sql reaches only the application's own tables`,
284
+ )
285
+ }
286
+ return statementText(parts, markerOf(database))
287
+ }
227
288
  const nested = nestedStatement(tokens) ?? parenthesizedTarget(tokens)
228
289
  if (nested !== undefined) {
229
290
  refuse('sql_statement', `${nested.statement} at line ${nested.line} is refused inside another statement`)
@@ -235,44 +296,57 @@ export function classifySql(parts: readonly string[], mode: SqlMode, schema: str
235
296
  if (unicodeIdentifier(tokens) !== undefined) {
236
297
  refuse('sql_name', 'a U&"…" name is refused: write the name plainly')
237
298
  }
238
- const framework = frameworkReference(tokens)
239
- if (framework !== undefined) {
240
- refuse('sql_name', `'${framework.name}' at line ${framework.line} is the framework's; ctx.sql reaches only the application's own tables`)
241
- }
242
299
  for (const reference of nameReferences(tokens)) {
243
300
  if (reference.role !== 'call' && reference.name.startsWith('pg_')) {
244
301
  refuse('sql_name', `'${reference.name}' at line ${reference.line} is a catalog name; ctx.sql reaches only the application's own tables`)
245
302
  }
246
303
  }
247
- const foreign = dmlForeignSchema(tokens, schema)
304
+ const foreign = dmlForeignSchema(tokens, database.schema)
248
305
  if (foreign !== undefined) {
249
306
  refuse('sql_name', `the schema '${foreign}' is outside the application's; write its tables' names unqualified`)
250
307
  }
251
- const call = refusedFunctionCall(tokens, schema, NO_DECLARED_FUNCTIONS)
308
+ const call = refusedFunctionCall(tokens, database.schema, NO_DECLARED_FUNCTIONS)
252
309
  if (call !== undefined) {
253
310
  refuse(
254
311
  'sql_function',
255
312
  `${call.qualifier === undefined ? '' : `${call.qualifier}.`}${call.name}(…) at line ${call.line} is not a reviewed built-in function`,
256
313
  )
257
314
  }
258
- return text
315
+ return statementText(parts, markerOf(database))
259
316
  }
260
317
 
261
- function arrayElement(item: unknown): string {
318
+ function arrayElement(item: unknown): string | number {
262
319
  if (typeof item === 'string') {
263
- return `"${item.replace(/["\\]/g, (char) => `\\${char}`)}"`
320
+ return item
264
321
  }
265
322
  if (typeof item === 'number' && Number.isFinite(item)) {
266
- return String(item)
323
+ return item
267
324
  }
268
325
  return refuse('invalid_value', 'a list value holds only strings and finite numbers')
269
326
  }
270
327
 
271
- /** A value as the driver binds it. Unprepared, `Bun.SQL` mis-binds a JS array and sends a `Date` as `Date#toString()`. */
272
- function parameterOf(value: unknown, position: number): SqlParameter {
273
- if (value === null || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'bigint') {
328
+ /** A Postgres array literal's element: a string quoted, its `"` and `\` escaped. */
329
+ function postgresElement(item: string | number): string {
330
+ return typeof item === 'string' ? `"${item.replace(/["\\]/g, (char) => `\\${char}`)}"` : String(item)
331
+ }
332
+
333
+ /**
334
+ * A value as the driver binds it. Unprepared, `Bun.SQL` mis-binds a JS array and sends a `Date` as `Date#toString()`,
335
+ * so a list is a Postgres array literal; SQLite binds no boolean and no bigint, and reads a list as JSON
336
+ * (`json_each`).
337
+ */
338
+ function parameterOf(value: unknown, position: number, database: SqlDatabase): SqlParameter {
339
+ if (value === null || typeof value === 'string') {
274
340
  return value
275
341
  }
342
+ if (typeof value === 'boolean') {
343
+ return database.dialect === 'sqlite' ? (value ? 1 : 0) : value
344
+ }
345
+ if (typeof value === 'bigint') {
346
+ if (database.dialect === 'postgres') return value
347
+ const integer = Number(value)
348
+ return isSafeInteger(integer) ? integer : refuse('invalid_value', `the value \${…} number ${position} is a bigint outside the safe integer range`)
349
+ }
276
350
  if (typeof value === 'number') {
277
351
  return Number.isFinite(value) ? value : refuse('invalid_value', `the value \${…} number ${position} is not a finite number`)
278
352
  }
@@ -281,13 +355,13 @@ function parameterOf(value: unknown, position: number): SqlParameter {
281
355
  }
282
356
  const items = parseList(value, arrayElement)
283
357
  if (items !== undefined) {
284
- return `{${items.join(',')}}`
358
+ return database.dialect === 'sqlite' ? JSON.stringify(items) : `{${items.map(postgresElement).join(',')}}`
285
359
  }
286
360
  return refuse(
287
361
  'invalid_value',
288
362
  `the value \${…} number ${position} is ${
289
363
  value === undefined ? 'undefined' : 'an object'
290
- }; bind a string, number, boolean, bigint, Date, null or a plain list (JSON as JSON.stringify(v) with ::jsonb)`,
364
+ }; bind a string, number, boolean, bigint, Date, null or a plain list (JSON as JSON.stringify(v))`,
291
365
  )
292
366
  }
293
367
 
@@ -366,387 +440,52 @@ function rowIssue(
366
440
  return `ctx.sql: row ${index + 1} does not match the row schema${where}: ${kind}`
367
441
  }
368
442
 
369
- /** The predicate `terms` make over `alias`'s columns: static parts around one bound value per test. */
370
- function scopeFragment(terms: ScopeTerms, alias: string): { readonly parts: readonly string[]; readonly values: readonly SqlValue[] } {
443
+ /**
444
+ * The predicate `terms` make over `alias`'s columns: static parts around one bound value per test. A list is
445
+ * `= any($n)` on Postgres and `in (select value from json_each(?n))` on SQLite, one parameter either way.
446
+ */
447
+ function scopeFragment(
448
+ terms: ScopeTerms,
449
+ alias: string,
450
+ database: SqlDatabase,
451
+ ): { readonly parts: readonly string[]; readonly values: readonly SqlValue[] } {
371
452
  if (terms === 'all') return { parts: ['(true)'], values: [] }
372
453
  if (terms.length === 0) return { parts: ['(false)'], values: [] }
454
+ const [listOpen, listClose] = database.dialect === 'postgres' ? [' = any(', ')'] : [' in (select value from json_each(', '))']
373
455
  const parts: string[] = []
374
456
  const values: SqlValue[] = []
375
457
  let text = '('
376
- terms.forEach((group, groupIndex) => {
458
+ // Index loops, never a method of the terms or of Array.prototype: this is the scope of the statement.
459
+ for (let groupIndex = 0; groupIndex < terms.length; groupIndex++) {
460
+ const group = terms[groupIndex] ?? []
377
461
  text += `${groupIndex === 0 ? '' : ' or '}(`
378
- group.forEach((test, testIndex) => {
379
- text += `${testIndex === 0 ? '' : ' and '}${alias}.${test.column} = ${typeof test.value === 'string' ? '' : 'any('}`
380
- parts.push(text)
381
- values.push(test.value)
382
- text = typeof test.value === 'string' ? '' : ')'
383
- })
384
- text += ')'
385
- })
386
- parts.push(`${text})`)
387
- return { parts, values }
388
- }
389
-
390
- /** One table a write statement writes, at any depth (a data-modifying CTE too), and how. */
391
- interface Target {
392
- readonly table: string
393
- readonly operation: WriteOperation
394
- }
395
-
396
- /** The relation an UPDATE or DELETE writes: its table, under its alias (the table's name without one), and what it sets. */
397
- interface Written {
398
- readonly table: string
399
- readonly alias: string
400
- readonly operation: 'update' | 'delete'
401
- /** The columns an UPDATE's SET assigns; none for a DELETE. */
402
- readonly assigned: readonly string[]
403
- }
404
-
405
- /** What a statement writes, and for each interpolation, in order, the UPDATE or DELETE of the query block it stands in. */
406
- interface StatementWrites {
407
- readonly targets: readonly Target[]
408
- readonly blocks: readonly (Written | undefined)[]
409
- }
410
-
411
- /** Words that cannot be an alias: what follows a target that has none. */
412
- const NOT_ALIASES: ReadonlySet<string> = new Set(['SET', 'WHERE', 'USING', 'RETURNING', 'DEFAULT', 'VALUES', 'SELECT', 'ON', 'OVERRIDING'])
413
-
414
- /** The target name at `index` (`ONLY` and a schema skipped) and its alias, or `undefined` when no name is there. */
415
- function targetAt(tokens: readonly SqlToken[], index: number): { readonly table: string; readonly alias: string } | undefined {
416
- const at = upperWord(tokens[index]) === 'ONLY' ? index + 1 : index
417
- const qualified = isPunct(tokens[at + 1], '.')
418
- const table = qualified ? nameText(tokens[at + 2]) : nameText(tokens[at])
419
- if (table === undefined) return undefined
420
- let next = qualified ? at + 3 : at + 1
421
- if (upperWord(tokens[next]) === 'AS') next++
422
- const word = upperWord(tokens[next])
423
- const alias = tokens[next]?.kind === 'quoted' || (word !== undefined && !NOT_ALIASES.has(word)) ? nameText(tokens[next]) : undefined
424
- return { table, alias: alias ?? table }
425
- }
426
-
427
- /**
428
- * Every `INSERT INTO`, `UPDATE` and `DELETE FROM` target of the statement, and the query block of each interpolation.
429
- * A block opens at a `SELECT`, `INSERT`, `UPDATE` or `DELETE` and closes with the parenthesis it stands in, or at the
430
- * next block of its depth: a subquery, a data-modifying CTE and an `INSERT`'s `SELECT` are blocks of their own.
431
- * `ON CONFLICT … DO UPDATE` is an UPDATE of the INSERT's target; a locking clause (`FOR UPDATE`) writes nothing.
432
- */
433
- function statementWrites(tokens: readonly SqlToken[]): StatementWrites {
434
- const targets: Target[] = []
435
- const blocks: (Written | undefined)[] = []
436
- const open: { readonly depth: number; readonly write: Written | undefined }[] = []
437
- const inserts = new Map<number, { readonly table: string; readonly alias: string }>()
438
- let depth = 0
439
- const enter = (write: Written | undefined) => {
440
- while ((open[open.length - 1]?.depth ?? -1) >= depth) open.pop()
441
- open.push({ depth, write })
442
- }
443
- for (let index = 0; index < tokens.length; index++) {
444
- const token = tokens[index]
445
- if (isPunct(token, '(')) {
446
- depth++
447
- continue
448
- }
449
- if (isPunct(token, ')')) {
450
- depth--
451
- while ((open[open.length - 1]?.depth ?? -1) > depth) open.pop()
452
- for (const level of inserts.keys()) if (level > depth) inserts.delete(level)
453
- continue
454
- }
455
- if (isPunct(token, '$') && isDigit(tokens[index + 1])) {
456
- blocks.push(open[open.length - 1]?.write)
457
- continue
458
- }
459
- const word = upperWord(token)
460
- const next = upperWord(tokens[index + 1])
461
- if (word === 'SELECT') {
462
- enter(undefined)
463
- } else if (word === 'INSERT' && next === 'INTO') {
464
- const target = targetAt(tokens, index + 2)
465
- enter(undefined)
466
- if (target !== undefined) {
467
- inserts.set(depth, target)
468
- targets.push({ table: target.table, operation: 'insert' })
469
- }
470
- } else if (word === 'DELETE' && next === 'FROM') {
471
- const target = targetAt(tokens, index + 2)
472
- enter(target === undefined ? undefined : { ...target, operation: 'delete', assigned: [] })
473
- if (target !== undefined) targets.push({ table: target.table, operation: 'delete' })
474
- } else if (word === 'UPDATE') {
475
- const before = upperWord(tokens[index - 1])
476
- if (before === 'FOR' || before === 'KEY') continue
477
- const target = before === 'DO' ? inserts.get(depth) : targetAt(tokens, index + 1)
478
- enter(target === undefined ? undefined : { ...target, operation: 'update', assigned: assignedColumns(tokens, index + 1) })
479
- if (target !== undefined) targets.push({ table: target.table, operation: 'update' })
480
- }
481
- }
482
- return { targets, blocks }
483
- }
484
-
485
- /** Words that end an UPDATE's SET list at its own depth, outside a CASE; `IS [NOT] DISTINCT FROM` does not. */
486
- const SET_ENDS: ReadonlySet<string> = new Set(['FROM', 'WHERE', 'RETURNING'])
487
-
488
- /**
489
- * The columns the SET of the UPDATE whose target starts at `from` assigns: `a = …` and `(a, b) = …` items, a column's
490
- * subfield or subscript by the column. A SET it cannot read to its end with certainty assigns no column it can name,
491
- * which refuses a column's own write action: an item that is not a name, an unmatched bracket, a CASE without END.
492
- */
493
- function assignedColumns(tokens: readonly SqlToken[], from: number): readonly string[] {
494
- const set = setKeyword(tokens, from)
495
- if (set === undefined) return []
496
- const columns: string[] = []
497
- let index = set + 1
498
- for (;;) {
499
- const item = assignmentTarget(tokens, index)
500
- const end = item === undefined ? undefined : expressionEnd(tokens, item.equals + 1)
501
- if (item === undefined || end === undefined) return []
502
- columns.push(...item.columns)
503
- if (!isPunct(tokens[end], ',')) return columns
504
- index = end + 1
505
- }
506
- }
507
-
508
- /**
509
- * The index of what ends the assigned expression that starts at `index`: the `,` before the next item, or the end of the
510
- * SET list (`FROM`, `WHERE`, `RETURNING`, the `)` around the statement, `;`, the end of the text). A clause word inside
511
- * brackets or a CASE, and the `FROM` of `IS [NOT] DISTINCT FROM`, belong to the expression. `undefined` when a bracket
512
- * or a CASE does not close before the end.
513
- */
514
- function expressionEnd(tokens: readonly SqlToken[], index: number): number | undefined {
515
- let depth = 0
516
- let cases = 0
517
- for (let position = index; position < tokens.length; position++) {
518
- const token = tokens[position]
519
- const word = upperWord(token)
520
- if (isPunct(token, '(') || isPunct(token, '[')) {
521
- depth++
522
- } else if (isPunct(token, ')') || isPunct(token, ']')) {
523
- if (--depth < 0) return cases === 0 && isPunct(token, ')') ? position : undefined
524
- } else if (depth > 0) {
525
- continue
526
- } else if (word === 'CASE') {
527
- cases++
528
- } else if (word === 'END') {
529
- if (--cases < 0) return undefined
530
- } else if (isPunct(token, ',') || isPunct(token, ';')) {
531
- return cases === 0 ? position : undefined
532
- } else if (cases === 0 && word !== undefined && SET_ENDS.has(word) && !distinctFrom(tokens, position)) {
533
- return position
534
- }
535
- }
536
- return depth === 0 && cases === 0 ? tokens.length : undefined
537
- }
538
-
539
- /** The index of the SET of the UPDATE whose target starts at `from`, at the UPDATE's depth. */
540
- function setKeyword(tokens: readonly SqlToken[], from: number): number | undefined {
541
- let depth = 0
542
- for (let index = from; index < tokens.length; index++) {
543
- const token = tokens[index]
544
- const word = upperWord(token)
545
- if (depth === 0 && word === 'SET') return index
546
- if (isPunct(token, '(')) depth++
547
- if (isPunct(token, ')') && --depth < 0) return undefined
548
- if (depth === 0 && word !== undefined && SET_ENDS.has(word)) return undefined
549
- }
550
- return undefined
551
- }
552
-
553
- /** Whether the `FROM` at `index` ends `IS [NOT] DISTINCT FROM`, a comparison, not a clause. */
554
- function distinctFrom(tokens: readonly SqlToken[], index: number): boolean {
555
- if (upperWord(tokens[index]) !== 'FROM' || upperWord(tokens[index - 1]) !== 'DISTINCT') return false
556
- const before = upperWord(tokens[index - 2])
557
- return before === 'IS' || (before === 'NOT' && upperWord(tokens[index - 3]) === 'IS')
558
- }
559
-
560
- /**
561
- * The columns one SET item at `index` assigns and the index of its `=`: a name with any `.field` and `[…]` after it,
562
- * or a parenthesized list of them. `undefined` when the item has no such form.
563
- */
564
- function assignmentTarget(tokens: readonly SqlToken[], index: number): { readonly columns: readonly string[]; readonly equals: number } | undefined {
565
- if (!isPunct(tokens[index], '(')) {
566
- const name = nameText(tokens[index])
567
- if (name === undefined) return undefined
568
- const equals = afterIndirection(tokens, index + 1)
569
- return equals !== undefined && isPunct(tokens[equals], '=') ? { columns: [name], equals } : undefined
570
- }
571
- const columns: string[] = []
572
- let position = index
573
- do {
574
- const name = nameText(tokens[position + 1])
575
- const next = name === undefined ? undefined : afterIndirection(tokens, position + 2)
576
- if (name === undefined || next === undefined) return undefined
577
- columns.push(name)
578
- position = next
579
- } while (isPunct(tokens[position], ','))
580
- return isPunct(tokens[position], ')') && isPunct(tokens[position + 1], '=') ? { columns, equals: position + 1 } : undefined
581
- }
582
-
583
- /** The index past a column's `.field` and `[…]` subscripts from `index`, or `undefined` when a bracket never closes. */
584
- function afterIndirection(tokens: readonly SqlToken[], index: number): number | undefined {
585
- let position = index
586
- for (;;) {
587
- if (isPunct(tokens[position], '.') && nameText(tokens[position + 1]) !== undefined) {
588
- position += 2
589
- } else if (isPunct(tokens[position], '[')) {
590
- let depth = 0
591
- for (; position < tokens.length; position++) {
592
- if (isPunct(tokens[position], '[')) depth++
593
- if (isPunct(tokens[position], ']') && --depth === 0) break
594
- }
595
- if (position >= tokens.length) return undefined
596
- position++
597
- } else {
598
- return position
599
- }
600
- }
601
- }
602
-
603
- /** What a fragment on `table` under `alias` is to its block: the relation its UPDATE or DELETE writes, or else read. */
604
- function fragmentUse(written: Written | undefined, table: string, alias: string): Written | undefined {
605
- return written !== undefined && written.table === table && written.alias === alias ? written : undefined
606
- }
607
-
608
- /** Words that open the clause a scope may stand in. */
609
- const SCOPE_CLAUSES: ReadonlySet<string> = new Set(['WHERE', 'ON'])
610
- /** Words that end a WHERE or ON clause at its own depth. */
611
- const CLAUSE_ENDS: ReadonlySet<string> = new Set([
612
- 'GROUP',
613
- 'ORDER',
614
- 'LIMIT',
615
- 'OFFSET',
616
- 'FETCH',
617
- 'HAVING',
618
- 'WINDOW',
619
- 'UNION',
620
- 'INTERSECT',
621
- 'EXCEPT',
622
- 'RETURNING',
623
- 'FOR',
624
- 'JOIN',
625
- 'LEFT',
626
- 'RIGHT',
627
- 'INNER',
628
- 'FULL',
629
- 'CROSS',
630
- 'NATURAL',
631
- 'WHERE',
632
- 'ON',
633
- 'USING',
634
- 'SET',
635
- 'FROM',
636
- 'SELECT',
637
- 'VALUES',
638
- ])
639
- const CONJUNCT_FORM = 'write it as a conjunct of its WHERE or JOIN … ON clause: where (<filter>) and ${ctx.sql.scope(…)}'
640
-
641
- /** Whether the token at `position` ends a WHERE or ON clause at its depth; `IS DISTINCT FROM` does not. */
642
- function endsClause(tokens: readonly SqlToken[], position: number): boolean {
643
- const token = tokens[position]
644
- const word = upperWord(token)
645
- if (isPunct(token, ';')) return true
646
- if (word === undefined || !CLAUSE_ENDS.has(word)) return false
647
- return word !== 'FROM' || upperWord(tokens[position - 1]) !== 'DISTINCT'
648
- }
649
-
650
- /** The index of the token after the `$n` placeholder at `index`. */
651
- function afterPlaceholder(tokens: readonly SqlToken[], index: number): number {
652
- let next = index + 1
653
- while (isDigit(tokens[next])) next++
654
- return next
655
- }
656
-
657
- /**
658
- * A scope must restrict every row its clause admits: it stands alone, joined by AND, at the top level of a WHERE or
659
- * JOIN … ON clause whose top level holds no OR (`where (<filter>) and ${scope}`). Anything else could reach past it.
660
- */
661
- function checkConjunct(tokens: readonly SqlToken[], index: number): void {
662
- const line = tokens[index]?.line
663
- let depth = 0
664
- let start = -1
665
- for (let position = index - 1; position >= 0 && start === -1; position--) {
666
- const token = tokens[position]
667
- const word = upperWord(token)
668
- if (isPunct(token, ')')) depth++
669
- else if (isPunct(token, '(')) {
670
- if (depth === 0) refuse('sql_scope', `ctx.sql.scope(…) at line ${line} stands inside parentheses; ${CONJUNCT_FORM}`)
671
- depth--
672
- } else if (depth === 0 && word !== undefined && SCOPE_CLAUSES.has(word)) start = position
673
- else if (depth === 0 && endsClause(tokens, position)) break
674
- }
675
- if (start === -1) refuse('sql_scope', `ctx.sql.scope(…) at line ${line} stands outside a WHERE or JOIN … ON clause; ${CONJUNCT_FORM}`)
676
- const next = afterPlaceholder(tokens, index)
677
- let end = tokens.length
678
- depth = 0
679
- for (let position = next; position < tokens.length && end === tokens.length; position++) {
680
- const token = tokens[position]
681
- if (isPunct(token, '(')) depth++
682
- else if (isPunct(token, ')')) {
683
- if (depth === 0) end = position
684
- else depth--
685
- } else if (depth === 0 && endsClause(tokens, position)) end = position
686
- }
687
- depth = 0
688
- for (let position = start + 1; position < end; position++) {
689
- const token = tokens[position]
690
- if (isPunct(token, '(')) depth++
691
- else if (isPunct(token, ')')) depth--
692
- else if (depth === 0 && upperWord(token) === 'OR') {
693
- refuse(
694
- 'sql_scope',
695
- `the clause that holds ctx.sql.scope(…) at line ${line} has an OR at its top level, which reaches past the scope; ${CONJUNCT_FORM}`,
696
- )
697
- } else if (depth === 0 && upperWord(token) === 'BETWEEN') {
698
- refuse('sql_scope', `put BETWEEN … AND … in parentheses in the clause that holds ctx.sql.scope(…) at line ${line}`)
462
+ for (let testIndex = 0; testIndex < group.length; testIndex++) {
463
+ const test = group[testIndex]
464
+ if (test === undefined) continue
465
+ const single = typeof test.value === 'string'
466
+ text += `${testIndex === 0 ? '' : ' and '}${alias}.${test.column}${single ? ' = ' : listOpen}`
467
+ parts[parts.length] = text
468
+ values[values.length] = test.value
469
+ text = single ? '' : listClose
699
470
  }
471
+ text += ')'
700
472
  }
701
- const before = upperWord(tokens[index - 1])
702
- const after = next === end ? 'END' : upperWord(tokens[next])
703
- if ((index - 1 !== start && before !== 'AND') || (after !== 'END' && after !== 'AND')) {
704
- refuse('sql_scope', `ctx.sql.scope(…) at line ${line} must stand alone, joined by AND; ${CONJUNCT_FORM}`)
705
- }
706
- }
707
-
708
- /**
709
- * Before any scope is spliced in, each interpolation must stand where a value binds (not in a literal, a quoted name,
710
- * a dollar-quoted body or a comment), and each scope where it restricts every row of its clause.
711
- */
712
- function checkInterpolations(parts: readonly string[], values: readonly unknown[]): void {
713
- for (const part of parts) {
714
- if (/\$[0-9]/.test(part)) {
715
- refuse('sql_template', 'the text holds $ and a digit, which reads as a positional parameter; interpolate the value with ${…}, a literal one too')
716
- }
717
- }
718
- const { tokens, unterminated } = lexSql(statementText(parts))
719
- if (unterminated !== undefined) {
720
- refuse('sql_template', `a string, quoted name, dollar-quoted body or comment at line ${unterminated} never closes`)
721
- }
722
- if (placeholderCount(tokens) !== parts.length - 1) {
723
- refuse(
724
- 'sql_template',
725
- 'a value ${…} inside a string literal, a quoted name, a dollar-quoted body or a comment is not bound; interpolate a whole value',
726
- )
727
- }
728
- let interpolation = 0
729
- for (let index = 0; index + 1 < tokens.length; index++) {
730
- if (!isPunct(tokens[index], '$') || !isDigit(tokens[index + 1])) continue
731
- if (scopeOf(values[interpolation]) !== undefined) checkConjunct(tokens, index)
732
- interpolation++
733
- }
473
+ parts[parts.length] = `${text})`
474
+ return { parts, values }
734
475
  }
735
476
 
736
477
  /**
737
- * The template with every scope spliced in as text around its own values, and the values a parameter each. Each
738
- * fragment is rendered for what its relation is to its query block: the one its UPDATE or DELETE writes, or read.
478
+ * The template with every scope spliced in as text around its own values, and the values a parameter each. Before
479
+ * anything is spliced, each interpolation must stand where a value binds (not in a literal, a quoted name, a dollar
480
+ * body or a comment), fragments with no value included, and each fragment must be this site's.
739
481
  */
740
482
  function expandScopes(
741
483
  site: SqlSite,
742
484
  parts: readonly string[],
743
485
  values: readonly unknown[],
744
- termsOf: ScopeOf,
745
- writeTarget: WriteTarget,
486
+ database: SqlDatabase,
746
487
  ): { parts: string[]; values: unknown[] } {
747
- checkInterpolations(parts, values)
748
- const writes: StatementWrites = site.mode === 'write' ? statementWrites(lexSql(statementText(parts)).tokens) : { targets: [], blocks: [] }
749
- for (const target of writes.targets) writeTarget(target.table, target.operation)
488
+ placedTokens(parts, database)
750
489
  const expanded: string[] = [parts[0] ?? '']
751
490
  const bound: unknown[] = []
752
491
  for (let index = 0; index < values.length; index++) {
@@ -761,11 +500,7 @@ function expandScopes(
761
500
  if (fragment.site !== site) {
762
501
  refuse('sql_scope', 'a ctx.sql.scope(…) of another invocation or site is refused; build it with this ctx.sql')
763
502
  }
764
- const written = fragmentUse(writes.blocks[index], fragment.table, fragment.alias)
765
- const terms = written === undefined
766
- ? termsOf(fragment.capability, fragment.table, 'read')
767
- : termsOf(fragment.capability, fragment.table, written.operation, written.assigned)
768
- const rendered = scopeFragment(terms, fragment.alias)
503
+ const rendered = scopeFragment(fragment.terms, fragment.alias, database)
769
504
  expanded[expanded.length - 1] += rendered.parts[0] ?? ''
770
505
  for (let position = 0; position < rendered.values.length; position++) {
771
506
  bound.push(rendered.values[position])
@@ -789,34 +524,39 @@ async function failing<T>(site: SqlSite, work: () => Promise<T>): Promise<T> {
789
524
  }
790
525
  }
791
526
 
792
- const WRITE_USES: readonly ScopeUse[] = ['update', 'delete']
527
+ const SCOPE_FORM =
528
+ "ctx.sql.scope(capability, table, { alias?, use? }) takes an alias of lowercase letters, digits and _ and use 'read', 'update' or 'delete'"
793
529
 
794
- /**
795
- * Throws unless `capability` reaches `table` for some use the site may make of it: reading, or on a `'write'` site
796
- * the target of an UPDATE or a DELETE. The statement's own use is checked when the tag renders the fragment.
797
- */
798
- function reaches(site: SqlSite, termsOf: ScopeOf, capability: unknown, table: string): void {
799
- try {
800
- termsOf(capability, table, 'read')
801
- } catch (error) {
802
- if (site.mode !== 'write') throw error
803
- for (const use of WRITE_USES) {
804
- try {
805
- termsOf(capability, table, use)
806
- return
807
- } catch {
808
- // The read refusal names what a read needs, which is what most fragments are.
809
- }
810
- }
811
- throw error
530
+ /** The options of `ctx.sql.scope`, read from a plain object's own data properties; anything else is refused. */
531
+ function scopeOptions(options: unknown): { readonly alias: string | undefined; readonly use: ScopeUse } {
532
+ if (options === undefined) {
533
+ return { alias: undefined, use: 'read' }
534
+ }
535
+ if (typeof options === 'string') {
536
+ refuse('invalid_argument', `ctx.sql.scope takes its alias as an option: write ctx.sql.scope(capability, table, { alias: '${options}' })`)
812
537
  }
538
+ if (
539
+ typeof options !== 'object' || options === null || isArray(options) || (prototypeOf(options) !== OBJECT_PROTOTYPE && prototypeOf(options) !== null)
540
+ ) {
541
+ refuse('invalid_argument', SCOPE_FORM)
542
+ }
543
+ let alias: string | undefined
544
+ let use: ScopeUse = 'read'
545
+ for (const key of ownKeys(options)) {
546
+ const descriptor = ownDescriptor(options, key)
547
+ const value: unknown = descriptor !== undefined && hasOwn(descriptor, 'value') ? descriptor.value : refuse('invalid_argument', SCOPE_FORM)
548
+ if (key === 'alias' && typeof value === 'string') alias = value
549
+ else if (key === 'use' && (value === 'read' || value === 'update' || value === 'delete')) use = value
550
+ else if (value !== undefined) refuse('invalid_argument', SCOPE_FORM)
551
+ }
552
+ return { alias, use }
813
553
  }
814
554
 
815
555
  /**
816
556
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
817
557
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
818
558
  */
819
- export function sqlTag(site: SqlSite, schema: string | undefined, termsOf: ScopeOf, writeTarget: WriteTarget): SqlTag {
559
+ export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf): SqlTag {
820
560
  const tag = <S extends z.core.$ZodType>(row: S) => {
821
561
  site.check()
822
562
  if (!(row instanceof z.core.$ZodType)) {
@@ -826,27 +566,30 @@ export function sqlTag(site: SqlSite, schema: string | undefined, termsOf: Scope
826
566
  return async (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]): Promise<z.output<S>[]> => {
827
567
  site.check()
828
568
  return failing(site, async () => {
829
- const expanded = expandScopes(site, templateParts(text), values, termsOf, writeTarget)
830
- const statement = classifySql(expanded.parts, site.mode, schema ?? '')
831
- const parameters = expanded.values.map((value, index) => parameterOf(value, index + 1))
569
+ const expanded = expandScopes(site, templateParts(text), values, database)
570
+ const statement = classifySql(expanded.parts, site.mode, database)
571
+ const parameters = expanded.values.map((value, index) => parameterOf(value, index + 1, database))
832
572
  const session = await site.session()
833
573
  if (session.readOnly && site.mode === 'write') {
834
574
  refuse('read_only', 'this invocation is read-only')
835
575
  }
836
- const rows = await runApplicationStatement(session, statement, parameters)
576
+ const rows = await runApplicationStatement(session, statement, parameters, site.mode)
837
577
  return rows.map((value, index) => parseRow(row, value, index))
838
578
  })
839
579
  }
840
580
  }
841
- const scope = (capability: unknown, table: string, alias?: string): SqlScope => {
581
+ const scope = (capability: unknown, table: string, options?: SqlScopeOptions): SqlScope => {
842
582
  site.check()
843
583
  try {
584
+ const { alias, use } = scopeOptions(options)
844
585
  const name = alias ?? table
845
586
  if (!isPlainIdentifier(table) || !isPlainIdentifier(name)) {
846
- refuse('invalid_argument', 'ctx.sql.scope(capability, table, alias?) takes a table name and an alias of lowercase letters, digits and _')
587
+ refuse('invalid_argument', SCOPE_FORM)
588
+ }
589
+ if (use !== 'read' && site.mode !== 'write') {
590
+ refuse('sql_read_only', `sql: 'read' runs queries only, and ctx.sql.scope(…, { use: '${use}' }) is the target of a write; declare sql: 'write'`)
847
591
  }
848
- reaches(site, termsOf, capability, table)
849
- return newScope({ site, capability, table, alias: name })
592
+ return newScope({ site, alias: name, terms: termsOf(capability, table, use) })
850
593
  } catch (error) {
851
594
  site.fail()
852
595
  throw error