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

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