@fabrika/db 0.9.0-dev.1 → 0.9.0-dev.11

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 (78) hide show
  1. package/package.json +44 -12
  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 +191 -0
  6. package/src/codegen.ts +170 -28
  7. package/src/database.ts +227 -61
  8. package/src/description.ts +34 -8
  9. package/src/errors.ts +6 -4
  10. package/src/file-columns.ts +36 -9
  11. package/src/framework-tables.ts +28 -8
  12. package/src/framework.ts +14 -5
  13. package/src/guard.ts +8 -0
  14. package/src/index.ts +10 -1
  15. package/src/job-leases.ts +210 -54
  16. package/src/job-wakes.ts +450 -0
  17. package/src/json.ts +124 -0
  18. package/src/links.ts +8 -1
  19. package/src/migrations-sqlite.ts +163 -0
  20. package/src/migrations.ts +25 -0
  21. package/src/nodes.ts +64 -9
  22. package/src/orm-types.ts +5 -5
  23. package/src/orm.ts +94 -37
  24. package/src/policy.ts +17 -2
  25. package/src/postgres.ts +26 -0
  26. package/src/registry.ts +11 -2
  27. package/src/sql.ts +230 -477
  28. package/src/sqlite-bun.ts +149 -0
  29. package/src/sqlite-migrate.ts +242 -0
  30. package/src/sqlite.ts +224 -0
  31. package/src/store.ts +385 -103
  32. package/src/stored-files.ts +188 -52
  33. package/src/tables.ts +16 -0
  34. package/src/temporal.ts +122 -9
  35. package/src/testing-shared.ts +999 -0
  36. package/src/testing-sqlite.ts +576 -0
  37. package/src/testing.ts +261 -482
  38. package/types/src/admissions.d.ts +21 -0
  39. package/types/src/application-rows.d.ts +58 -0
  40. package/types/src/builtins.d.ts +42 -0
  41. package/types/src/capability.d.ts +119 -0
  42. package/types/src/codegen-sqlite.d.ts +13 -0
  43. package/types/src/codegen.d.ts +113 -0
  44. package/types/src/database.d.ts +185 -0
  45. package/types/src/description.d.ts +124 -0
  46. package/types/src/errors.d.ts +98 -0
  47. package/types/src/file-columns.d.ts +39 -0
  48. package/types/src/file-references.d.ts +27 -0
  49. package/types/src/framework-tables.d.ts +59 -0
  50. package/types/src/framework.d.ts +38 -0
  51. package/types/src/guard.d.ts +23 -0
  52. package/types/src/identifier.d.ts +4 -0
  53. package/types/src/index.d.ts +11 -0
  54. package/types/src/job-leases.d.ts +112 -0
  55. package/types/src/job-wakes.d.ts +101 -0
  56. package/types/src/json.d.ts +18 -0
  57. package/types/src/links.d.ts +13 -0
  58. package/types/src/migrations-sqlite.d.ts +4 -0
  59. package/types/src/migrations.d.ts +26 -0
  60. package/types/src/nodes.d.ts +73 -0
  61. package/types/src/orm-types.d.ts +638 -0
  62. package/types/src/orm.d.ts +82 -0
  63. package/types/src/policy.d.ts +358 -0
  64. package/types/src/postgres.d.ts +12 -0
  65. package/types/src/production.d.ts +5 -0
  66. package/types/src/registry.d.ts +43 -0
  67. package/types/src/sql.d.ts +67 -0
  68. package/types/src/sqlite-bun.d.ts +21 -0
  69. package/types/src/sqlite-migrate.d.ts +28 -0
  70. package/types/src/sqlite.d.ts +24 -0
  71. package/types/src/store.d.ts +351 -0
  72. package/types/src/stored-files.d.ts +102 -0
  73. package/types/src/tables.d.ts +21 -0
  74. package/types/src/temporal.d.ts +36 -0
  75. package/types/src/testing-shared.d.ts +269 -0
  76. package/types/src/testing-sqlite.d.ts +22 -0
  77. package/types/src/testing.d.ts +35 -0
  78. package/types/src/vocabulary-tables.d.ts +225 -0
package/src/sql.ts CHANGED
@@ -1,26 +1,29 @@
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
- dmlForeignSchema,
9
+ CTE_FORM,
9
10
  frameworkReference,
10
11
  lexSql,
12
+ lexSqlite,
11
13
  nameReferences,
12
- nameText,
13
14
  nestedStatement,
14
15
  parenthesizedTarget,
15
- refusedFunctionCall,
16
+ ReadSql,
17
+ referencedForeignSchema,
18
+ refusedCall,
16
19
  type SqlToken,
17
20
  statementKind,
18
- topLevelStatements,
21
+ statementsOf,
19
22
  unicodeIdentifier,
20
23
  upperWord,
21
24
  } from '@fabrika/platform-node/sql'
22
25
  import { z } from 'zod/v4'
23
- import { freeze, hasOwn, isArray, ownDescriptor, ownKeys, parseList } from './builtins'
26
+ import { freeze, hasOwn, isArray, isSafeInteger, OBJECT_PROTOTYPE, ownDescriptor, ownKeys, parseList, prototypeOf } from './builtins'
24
27
  import { runApplicationStatement, type Session, type SqlParameter } from './database'
25
28
  import { type QueryRefusal, QueryRefusedError, SqlRowError } from './errors'
26
29
  import { isPlainIdentifier } from './identifier'
@@ -29,9 +32,12 @@ import { dayText } from './temporal'
29
32
  /** What a site declares: `'read'` runs queries only, `'write'` also `INSERT`, `UPDATE` and `DELETE`. */
30
33
  export type SqlMode = 'read' | 'write'
31
34
 
32
- /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers (an array). */
35
+ /** A value an interpolation binds: a scalar, a `Date` (bound as ISO text), or a list of strings or numbers. */
33
36
  export type SqlValue = string | number | boolean | bigint | Date | null | readonly (string | number)[]
34
37
 
38
+ /** The database a statement is classified for: Postgres in the application's schema, or a Durable Object's SQLite. */
39
+ export type SqlDatabase = { readonly dialect: 'postgres'; readonly schema: string } | { readonly dialect: 'sqlite' }
40
+
35
41
  /** One test of a capability's scope on a table: the column holds the value, or one of the list. */
36
42
  export interface ScopeTest {
37
43
  readonly column: string
@@ -41,25 +47,23 @@ export interface ScopeTest {
41
47
  /** A capability's predicate on one table: every row (`'all'`), or an OR of AND groups; no group matches nothing. */
42
48
  export type ScopeTerms = 'all' | readonly (readonly ScopeTest[])[]
43
49
 
44
- /** What a fragment's table is to its statement: read, or the target of its UPDATE or DELETE. */
50
+ /** What a fragment's table is to its statement, as its author states it: read, or the target of an UPDATE or DELETE. */
45
51
  export type ScopeUse = 'read' | 'update' | 'delete'
46
52
 
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'
53
+ /** The scope of `capability` on `table` for `use`, as the data layer predicates its handles; throws when it does not reach it. */
54
+ export type ScopeOf = (capability: unknown, table: string, use: ScopeUse) => ScopeTerms
56
55
 
57
- /** Throws for a table no statement may write with `operation`: a reference table. */
58
- export type WriteTarget = (table: string, operation: WriteOperation) => void
56
+ /** The third argument of `ctx.sql.scope`: the table's alias in the statement, and what the statement does with it. */
57
+ export interface SqlScopeOptions {
58
+ /** The table's name in the statement; the table's own name by default. */
59
+ readonly alias?: string
60
+ /** `'update'` or `'delete'` where the statement writes the table, which needs that operation's action; `'read'` by default. */
61
+ readonly use?: ScopeUse
62
+ }
59
63
 
60
64
  /**
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
65
+ * `ctx.sql.scope(capability, table, { alias, use })`: the capability's whole predicate on one table, as SQL with bound
66
+ * values. A fragment is a frozen object with no prototype; what it holds lives in this module's registry, read through
63
67
  * methods captured at load, so no object an application builds or changes is ever taken for one.
64
68
  */
65
69
  export interface SqlScope {
@@ -68,9 +72,8 @@ export interface SqlScope {
68
72
 
69
73
  interface ScopeData {
70
74
  readonly site: SqlSite
71
- readonly capability: unknown
72
- readonly table: string
73
75
  readonly alias: string
76
+ readonly terms: ScopeTerms
74
77
  }
75
78
 
76
79
  const scopes = new WeakMap<object, ScopeData>()
@@ -83,7 +86,7 @@ function newScope(data: ScopeData): SqlScope {
83
86
  const scope: SqlScope = { kind: 'sql-scope' }
84
87
  withoutPrototype(scope, null)
85
88
  freeze(scope)
86
- register(scope, freeze({ site: data.site, capability: data.capability, table: data.table, alias: data.alias }))
89
+ register(scope, freeze({ site: data.site, alias: data.alias, terms: data.terms }))
87
90
  return scope
88
91
  }
89
92
 
@@ -95,7 +98,7 @@ function scopeOf(value: unknown): ScopeData | undefined {
95
98
  /** `ctx.sql(Row)`: the tag for rows of `Row`, and `scope` for the capability's predicate inside its text. */
96
99
  export interface SqlTag {
97
100
  <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
101
+ scope(capability: unknown, table: string, options?: SqlScopeOptions): SqlScope
99
102
  }
100
103
 
101
104
  /** The site a tag is made for: its mode, its binding to the invocation, and the session its statements run in. */
@@ -108,15 +111,16 @@ export interface SqlSite {
108
111
  fail(): void
109
112
  }
110
113
 
111
- const READ_STATEMENTS: ReadonlySet<string> = new Set(['SELECT', 'WITH', 'VALUES', 'TABLE'])
114
+ const POSTGRES_READS: ReadonlySet<string> = new Set(['SELECT', 'WITH', 'VALUES', 'TABLE'])
115
+ const SQLITE_READS: ReadonlySet<string> = new Set(['SELECT', 'WITH', 'VALUES'])
112
116
  const WRITE_STATEMENTS: ReadonlySet<string> = new Set(['INSERT', 'UPDATE', 'DELETE'])
113
117
  const WRITE_WORDS: ReadonlySet<string> = new Set(['INSERT', 'UPDATE', 'DELETE', 'MERGE'])
114
118
  /** `FOR UPDATE`, `FOR NO KEY UPDATE`, `FOR SHARE`, `FOR KEY SHARE`: what follows `FOR` in a locking clause. */
115
119
  const LOCK_WORDS: ReadonlySet<string> = new Set(['UPDATE', 'NO', 'SHARE', 'KEY'])
116
120
  /** ctx.sql calls reviewed built-ins only: the functions the migrations declare are not known at runtime. */
117
121
  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'"
122
+ /** What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`): only the tag writes one. */
123
+ const SQLITE_PARAMETER_STARTS: ReadonlySet<string> = new Set(['?', ':', '@', '$', '#'])
120
124
 
121
125
  function refuse(reason: QueryRefusal, message: string): never {
122
126
  throw new QueryRefusedError(reason, `ctx.sql: ${message}`)
@@ -125,6 +129,9 @@ function refuse(reason: QueryRefusal, message: string): never {
125
129
  const isPunct = (token: SqlToken | undefined, char: string): boolean => token?.kind === 'punct' && token.char === char
126
130
  const isDigit = (token: SqlToken | undefined): boolean => token?.kind === 'punct' && token.char >= '0' && token.char <= '9'
127
131
 
132
+ /** The character that opens a placeholder the tag writes: `$1` on Postgres, `?1` on SQLite. */
133
+ const markerOf = (database: SqlDatabase): string => (database.dialect === 'postgres' ? '$' : '?')
134
+
128
135
  /** The template's static parts. A call with a plain array, or a text with an invalid escape, is refused. */
129
136
  function templateParts(text: unknown): readonly string[] {
130
137
  const raw: unknown = isArray(text) && hasOwn(text, 'raw') ? ownDescriptor(text, 'raw')?.value : undefined
@@ -142,26 +149,57 @@ function templateParts(text: unknown): readonly string[] {
142
149
  return parts
143
150
  }
144
151
 
145
- /** The statement's text, each interpolation a `$n` placeholder between the static parts. */
146
- function statementText(parts: readonly string[]): string {
152
+ /** The statement's text, each interpolation a placeholder (`$n` or `?n`) between the static parts. */
153
+ function statementText(parts: readonly string[], marker: string): string {
147
154
  let text = parts[0] ?? ''
148
155
  for (let index = 1; index < parts.length; index++) {
149
156
  const part = parts[index] ?? ''
150
157
  if (/^[0-9]/.test(part)) {
151
158
  refuse('sql_template', `a digit right after the value \${…} number ${index} would join its placeholder; put a space between them`)
152
159
  }
153
- text += `$${index}${part}`
160
+ text += `${marker}${index}${part}`
154
161
  }
155
162
  return text
156
163
  }
157
164
 
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++
165
+ /**
166
+ * The tokens of the statement `parts` make, refused unless each placeholder the tag writes is one the lexer sees at
167
+ * code level (not in a literal, a quoted name, a dollar body or a comment) and the text writes none of its own.
168
+ */
169
+ function placedTokens(parts: readonly string[], database: SqlDatabase): readonly SqlToken[] {
170
+ const marker = markerOf(database)
171
+ const written = database.dialect === 'postgres' ? /\$[0-9]/ : /\?[0-9]/
172
+ for (const part of parts) {
173
+ if (written.test(part)) {
174
+ refuse(
175
+ 'sql_template',
176
+ `the text holds ${marker} and a digit, which reads as a positional parameter; interpolate the value with \${…}, a literal one too`,
177
+ )
178
+ }
179
+ }
180
+ const { tokens, unterminated } = database.dialect === 'postgres' ? lexSql(statementText(parts, marker)) : lexSqlite(statementText(parts, marker))
181
+ if (unterminated !== undefined) {
182
+ refuse('sql_template', `a string, quoted name, dollar-quoted body or comment at line ${unterminated} never closes`)
183
+ }
184
+ let placed = 0
185
+ for (let index = 0; index < tokens.length; index++) {
186
+ const token = tokens[index]
187
+ if (isPunct(token, marker) && isDigit(tokens[index + 1])) {
188
+ placed++
189
+ } else if (database.dialect === 'sqlite' && token?.kind === 'punct' && SQLITE_PARAMETER_STARTS.has(token.char)) {
190
+ refuse(
191
+ 'sql_template',
192
+ `${token.char} at line ${token.line} starts a parameter the text writes, which nothing binds; interpolate the value with \${…}`,
193
+ )
194
+ }
195
+ }
196
+ if (placed !== parts.length - 1) {
197
+ refuse(
198
+ 'sql_template',
199
+ 'a value ${…} inside a string literal, a quoted name, a dollar-quoted body or a comment is not bound; interpolate a whole value',
200
+ )
163
201
  }
164
- return count
202
+ return tokens
165
203
  }
166
204
 
167
205
  /** The first `SELECT … INTO`: it creates a table. `INSERT INTO` is the one `INTO` a statement may hold. */
@@ -185,29 +223,32 @@ function readRefusal(tokens: readonly SqlToken[]): string | undefined {
185
223
  }
186
224
 
187
225
  /**
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.
226
+ * The first name, quoted name or string literal SQLite could read as a framework (`fabrika_*`) or catalog (`sqlite_*`)
227
+ * object. SQLite folds names case-insensitively, quoted ones too, and takes a string where only a name may stand
228
+ * (`FROM 'fabrika_x'`), so every form counts.
192
229
  */
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`)
230
+ function sqliteNameRefusal(tokens: readonly SqlToken[]): { readonly name: string; readonly line: number; readonly catalog: boolean } | undefined {
231
+ for (const token of tokens) {
232
+ const text = token.kind === 'word' || token.kind === 'quoted' || token.kind === 'string' ? token.text : undefined
233
+ const name = text?.toLowerCase()
234
+ if (name === undefined) continue
235
+ if (name.startsWith('fabrika_')) return { name: text ?? name, line: token.line, catalog: false }
236
+ if (name.startsWith('sqlite_')) return { name: text ?? name, line: token.line, catalog: true }
203
237
  }
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)
238
+ return undefined
239
+ }
240
+
241
+ /**
242
+ * The SQL `parts` make, with a bound placeholder for each value, or a `QueryRefusedError` that names what is refused.
243
+ * On both dialects: more than one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for
244
+ * `'write'`), a `'read'` statement that writes or locks, a value placed where it would not be bound, and a `fabrika_*`
245
+ * name. On Postgres also a nested statement of another kind, `SELECT … INTO`, a `U&` name, a `pg_*` name, a qualified
246
+ * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
247
+ * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
248
+ */
249
+ export function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase): string {
250
+ const all = placedTokens(parts, database)
251
+ const statements = statementsOf(all)
211
252
  const [statement] = statements
212
253
  if (statement === undefined) {
213
254
  refuse('sql_statement', 'the template holds no statement')
@@ -217,14 +258,43 @@ export function classifySql(parts: readonly string[], mode: SqlMode, schema: str
217
258
  }
218
259
  const tokens = statement.tokens
219
260
  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}`)
261
+ const reads = database.dialect === 'postgres' ? POSTGRES_READS : SQLITE_READS
262
+ if (!reads.has(first) && !WRITE_STATEMENTS.has(first)) {
263
+ refuse(
264
+ 'sql_statement',
265
+ `${statementKind(tokens)} is refused; it runs ${
266
+ database.dialect === 'postgres' ? 'SELECT, WITH, VALUES or TABLE' : 'SELECT, WITH or VALUES'
267
+ }, and INSERT, UPDATE or DELETE on a site that declares sql: 'write'`,
268
+ )
222
269
  }
223
270
  const writes = mode === 'read' ? (WRITE_STATEMENTS.has(first) ? `${first} at line ${statement.line}` : readRefusal(tokens)) : undefined
224
271
  if (writes !== undefined) {
225
272
  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
273
  }
227
- const nested = nestedStatement(tokens) ?? parenthesizedTarget(tokens)
274
+ const framework = frameworkReference(tokens)
275
+ if (framework !== undefined) {
276
+ refuse('sql_name', `'${framework.name}' at line ${framework.line} is the framework's; ctx.sql reaches only the application's own tables`)
277
+ }
278
+ if (database.dialect === 'sqlite') {
279
+ const name = sqliteNameRefusal(tokens)
280
+ if (name !== undefined) {
281
+ refuse(
282
+ 'sql_name',
283
+ `'${name.name}' at line ${name.line} ${
284
+ name.catalog ? "is SQLite's catalog" : "is the framework's"
285
+ }; ctx.sql reaches only the application's own tables`,
286
+ )
287
+ }
288
+ return statementText(parts, markerOf(database))
289
+ }
290
+ const read = ReadSql.query(tokens)
291
+ if (read.ctes.unread !== undefined) {
292
+ refuse(
293
+ 'sql_statement',
294
+ `the WITH at line ${read.ctes.unread} begins a CTE list that cannot be read; write each CTE as ${CTE_FORM}, a CYCLE mark a constant and never an interpolated value`,
295
+ )
296
+ }
297
+ const nested = nestedStatement(read) ?? parenthesizedTarget(tokens)
228
298
  if (nested !== undefined) {
229
299
  refuse('sql_statement', `${nested.statement} at line ${nested.line} is refused inside another statement`)
230
300
  }
@@ -235,44 +305,58 @@ export function classifySql(parts: readonly string[], mode: SqlMode, schema: str
235
305
  if (unicodeIdentifier(tokens) !== undefined) {
236
306
  refuse('sql_name', 'a U&"…" name is refused: write the name plainly')
237
307
  }
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
- for (const reference of nameReferences(tokens)) {
308
+ const references = nameReferences(read)
309
+ for (const reference of references) {
243
310
  if (reference.role !== 'call' && reference.name.startsWith('pg_')) {
244
311
  refuse('sql_name', `'${reference.name}' at line ${reference.line} is a catalog name; ctx.sql reaches only the application's own tables`)
245
312
  }
246
313
  }
247
- const foreign = dmlForeignSchema(tokens, schema)
314
+ const foreign = referencedForeignSchema(references, database.schema)
248
315
  if (foreign !== undefined) {
249
316
  refuse('sql_name', `the schema '${foreign}' is outside the application's; write its tables' names unqualified`)
250
317
  }
251
- const call = refusedFunctionCall(tokens, schema, NO_DECLARED_FUNCTIONS)
318
+ const call = refusedCall(references, database.schema, NO_DECLARED_FUNCTIONS)
252
319
  if (call !== undefined) {
253
320
  refuse(
254
321
  'sql_function',
255
322
  `${call.qualifier === undefined ? '' : `${call.qualifier}.`}${call.name}(…) at line ${call.line} is not a reviewed built-in function`,
256
323
  )
257
324
  }
258
- return text
325
+ return statementText(parts, markerOf(database))
259
326
  }
260
327
 
261
- function arrayElement(item: unknown): string {
328
+ function arrayElement(item: unknown): string | number {
262
329
  if (typeof item === 'string') {
263
- return `"${item.replace(/["\\]/g, (char) => `\\${char}`)}"`
330
+ return item
264
331
  }
265
332
  if (typeof item === 'number' && Number.isFinite(item)) {
266
- return String(item)
333
+ return item
267
334
  }
268
335
  return refuse('invalid_value', 'a list value holds only strings and finite numbers')
269
336
  }
270
337
 
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') {
338
+ /** A Postgres array literal's element: a string quoted, its `"` and `\` escaped. */
339
+ function postgresElement(item: string | number): string {
340
+ return typeof item === 'string' ? `"${item.replace(/["\\]/g, (char) => `\\${char}`)}"` : String(item)
341
+ }
342
+
343
+ /**
344
+ * A value as the driver binds it. Unprepared, `Bun.SQL` mis-binds a JS array and sends a `Date` as `Date#toString()`,
345
+ * so a list is a Postgres array literal; SQLite binds no boolean and no bigint, and reads a list as JSON
346
+ * (`json_each`).
347
+ */
348
+ function parameterOf(value: unknown, position: number, database: SqlDatabase): SqlParameter {
349
+ if (value === null || typeof value === 'string') {
274
350
  return value
275
351
  }
352
+ if (typeof value === 'boolean') {
353
+ return database.dialect === 'sqlite' ? (value ? 1 : 0) : value
354
+ }
355
+ if (typeof value === 'bigint') {
356
+ if (database.dialect === 'postgres') return value
357
+ const integer = Number(value)
358
+ return isSafeInteger(integer) ? integer : refuse('invalid_value', `the value \${…} number ${position} is a bigint outside the safe integer range`)
359
+ }
276
360
  if (typeof value === 'number') {
277
361
  return Number.isFinite(value) ? value : refuse('invalid_value', `the value \${…} number ${position} is not a finite number`)
278
362
  }
@@ -281,13 +365,13 @@ function parameterOf(value: unknown, position: number): SqlParameter {
281
365
  }
282
366
  const items = parseList(value, arrayElement)
283
367
  if (items !== undefined) {
284
- return `{${items.join(',')}}`
368
+ return database.dialect === 'sqlite' ? JSON.stringify(items) : `{${items.map(postgresElement).join(',')}}`
285
369
  }
286
370
  return refuse(
287
371
  'invalid_value',
288
372
  `the value \${…} number ${position} is ${
289
373
  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)`,
374
+ }; bind a string, number, boolean, bigint, Date, null or a plain list (JSON as JSON.stringify(v))`,
291
375
  )
292
376
  }
293
377
 
@@ -366,387 +450,52 @@ function rowIssue(
366
450
  return `ctx.sql: row ${index + 1} does not match the row schema${where}: ${kind}`
367
451
  }
368
452
 
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[] } {
453
+ /**
454
+ * The predicate `terms` make over `alias`'s columns: static parts around one bound value per test. A list is
455
+ * `= any($n)` on Postgres and `in (select value from json_each(?n))` on SQLite, one parameter either way.
456
+ */
457
+ function scopeFragment(
458
+ terms: ScopeTerms,
459
+ alias: string,
460
+ database: SqlDatabase,
461
+ ): { readonly parts: readonly string[]; readonly values: readonly SqlValue[] } {
371
462
  if (terms === 'all') return { parts: ['(true)'], values: [] }
372
463
  if (terms.length === 0) return { parts: ['(false)'], values: [] }
464
+ const [listOpen, listClose] = database.dialect === 'postgres' ? [' = any(', ')'] : [' in (select value from json_each(', '))']
373
465
  const parts: string[] = []
374
466
  const values: SqlValue[] = []
375
467
  let text = '('
376
- terms.forEach((group, groupIndex) => {
468
+ // Index loops, never a method of the terms or of Array.prototype: this is the scope of the statement.
469
+ for (let groupIndex = 0; groupIndex < terms.length; groupIndex++) {
470
+ const group = terms[groupIndex] ?? []
377
471
  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}`)
472
+ for (let testIndex = 0; testIndex < group.length; testIndex++) {
473
+ const test = group[testIndex]
474
+ if (test === undefined) continue
475
+ const single = typeof test.value === 'string'
476
+ text += `${testIndex === 0 ? '' : ' and '}${alias}.${test.column}${single ? ' = ' : listOpen}`
477
+ parts[parts.length] = text
478
+ values[values.length] = test.value
479
+ text = single ? '' : listClose
699
480
  }
481
+ text += ')'
700
482
  }
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
- }
483
+ parts[parts.length] = `${text})`
484
+ return { parts, values }
734
485
  }
735
486
 
736
487
  /**
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.
488
+ * The template with every scope spliced in as text around its own values, and the values a parameter each. Before
489
+ * anything is spliced, each interpolation must stand where a value binds (not in a literal, a quoted name, a dollar
490
+ * body or a comment), fragments with no value included, and each fragment must be this site's.
739
491
  */
740
492
  function expandScopes(
741
493
  site: SqlSite,
742
494
  parts: readonly string[],
743
495
  values: readonly unknown[],
744
- termsOf: ScopeOf,
745
- writeTarget: WriteTarget,
496
+ database: SqlDatabase,
746
497
  ): { 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)
498
+ placedTokens(parts, database)
750
499
  const expanded: string[] = [parts[0] ?? '']
751
500
  const bound: unknown[] = []
752
501
  for (let index = 0; index < values.length; index++) {
@@ -761,11 +510,7 @@ function expandScopes(
761
510
  if (fragment.site !== site) {
762
511
  refuse('sql_scope', 'a ctx.sql.scope(…) of another invocation or site is refused; build it with this ctx.sql')
763
512
  }
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)
513
+ const rendered = scopeFragment(fragment.terms, fragment.alias, database)
769
514
  expanded[expanded.length - 1] += rendered.parts[0] ?? ''
770
515
  for (let position = 0; position < rendered.values.length; position++) {
771
516
  bound.push(rendered.values[position])
@@ -789,34 +534,39 @@ async function failing<T>(site: SqlSite, work: () => Promise<T>): Promise<T> {
789
534
  }
790
535
  }
791
536
 
792
- const WRITE_USES: readonly ScopeUse[] = ['update', 'delete']
537
+ const SCOPE_FORM =
538
+ "ctx.sql.scope(capability, table, { alias?, use? }) takes an alias of lowercase letters, digits and _ and use 'read', 'update' or 'delete'"
793
539
 
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
540
+ /** The options of `ctx.sql.scope`, read from a plain object's own data properties; anything else is refused. */
541
+ function scopeOptions(options: unknown): { readonly alias: string | undefined; readonly use: ScopeUse } {
542
+ if (options === undefined) {
543
+ return { alias: undefined, use: 'read' }
544
+ }
545
+ if (typeof options === 'string') {
546
+ refuse('invalid_argument', `ctx.sql.scope takes its alias as an option: write ctx.sql.scope(capability, table, { alias: '${options}' })`)
812
547
  }
548
+ if (
549
+ typeof options !== 'object' || options === null || isArray(options) || (prototypeOf(options) !== OBJECT_PROTOTYPE && prototypeOf(options) !== null)
550
+ ) {
551
+ refuse('invalid_argument', SCOPE_FORM)
552
+ }
553
+ let alias: string | undefined
554
+ let use: ScopeUse = 'read'
555
+ for (const key of ownKeys(options)) {
556
+ const descriptor = ownDescriptor(options, key)
557
+ const value: unknown = descriptor !== undefined && hasOwn(descriptor, 'value') ? descriptor.value : refuse('invalid_argument', SCOPE_FORM)
558
+ if (key === 'alias' && typeof value === 'string') alias = value
559
+ else if (key === 'use' && (value === 'read' || value === 'update' || value === 'delete')) use = value
560
+ else if (value !== undefined) refuse('invalid_argument', SCOPE_FORM)
561
+ }
562
+ return { alias, use }
813
563
  }
814
564
 
815
565
  /**
816
566
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
817
567
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
818
568
  */
819
- export function sqlTag(site: SqlSite, schema: string | undefined, termsOf: ScopeOf, writeTarget: WriteTarget): SqlTag {
569
+ export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf): SqlTag {
820
570
  const tag = <S extends z.core.$ZodType>(row: S) => {
821
571
  site.check()
822
572
  if (!(row instanceof z.core.$ZodType)) {
@@ -826,27 +576,30 @@ export function sqlTag(site: SqlSite, schema: string | undefined, termsOf: Scope
826
576
  return async (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]): Promise<z.output<S>[]> => {
827
577
  site.check()
828
578
  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))
579
+ const expanded = expandScopes(site, templateParts(text), values, database)
580
+ const statement = classifySql(expanded.parts, site.mode, database)
581
+ const parameters = expanded.values.map((value, index) => parameterOf(value, index + 1, database))
832
582
  const session = await site.session()
833
583
  if (session.readOnly && site.mode === 'write') {
834
584
  refuse('read_only', 'this invocation is read-only')
835
585
  }
836
- const rows = await runApplicationStatement(session, statement, parameters)
586
+ const rows = await runApplicationStatement(session, statement, parameters, site.mode)
837
587
  return rows.map((value, index) => parseRow(row, value, index))
838
588
  })
839
589
  }
840
590
  }
841
- const scope = (capability: unknown, table: string, alias?: string): SqlScope => {
591
+ const scope = (capability: unknown, table: string, options?: SqlScopeOptions): SqlScope => {
842
592
  site.check()
843
593
  try {
594
+ const { alias, use } = scopeOptions(options)
844
595
  const name = alias ?? table
845
596
  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 _')
597
+ refuse('invalid_argument', SCOPE_FORM)
598
+ }
599
+ if (use !== 'read' && site.mode !== 'write') {
600
+ 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
601
  }
848
- reaches(site, termsOf, capability, table)
849
- return newScope({ site, capability, table, alias: name })
602
+ return newScope({ site, alias: name, terms: termsOf(capability, table, use) })
850
603
  } catch (error) {
851
604
  site.fail()
852
605
  throw error