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