@fabrika/platform-node 0.9.0-dev.3 → 0.9.0-dev.31
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 +3 -3
- package/src/application-postgres-grants.ts +23 -6
- package/src/index.ts +0 -1
- package/src/migration-classify.ts +670 -91
- package/src/migration-sql.ts +6 -1
- package/src/pg-catalog-names.ts +2 -2
- package/src/postgres-migrations.ts +27 -0
- package/src/sql-names.ts +444 -25
- package/src/sql-postgres.ts +14 -8
- package/src/sql.ts +15 -4
- package/src/sqlite-sql.ts +86 -0
- package/types/src/application-postgres-grants.d.ts +4 -3
- package/types/src/index.d.ts +0 -1
- package/types/src/migration-classify.d.ts +69 -4
- package/types/src/migration-sql.d.ts +2 -0
- package/types/src/sql-names.d.ts +63 -11
- package/types/src/sql-postgres.d.ts +4 -4
- package/types/src/sql.d.ts +4 -3
- package/types/src/sqlite-sql.d.ts +17 -0
- package/src/postgres-test-provisioner.ts +0 -178
- package/types/src/postgres-test-provisioner.d.ts +0 -37
package/src/sql-postgres.ts
CHANGED
|
@@ -26,8 +26,11 @@
|
|
|
26
26
|
// already coerce `undefined` → null, so this matches what the services are tested against.
|
|
27
27
|
// * SQLite-only SQL still fails, obviously: `unixepoch()` does not exist in Postgres. Several
|
|
28
28
|
// statements in `@fabrika/control` and `@fabrika/iam` use it today.
|
|
29
|
-
// *
|
|
30
|
-
//
|
|
29
|
+
// * NO NAMED PREPARED STATEMENTS. A Zerops PostgreSQL service hands one server session to the IAM, Control and
|
|
30
|
+
// Operations processes in turn, so a statement prepared before a migration's ADD COLUMN outlives the
|
|
31
|
+
// process that prepared it, and `SELECT *` then fails with `cached plan must not change result type`
|
|
32
|
+
// (0A000). The same happens to one client that runs a migration between two reads. `connect` therefore
|
|
33
|
+
// defaults to `{ prepare: false }`: every statement is parsed where it runs.
|
|
31
34
|
|
|
32
35
|
import type { SqlDatabase, SqlQueryResult, SqlRunResult, SqlStatement } from '@fabrika/platform'
|
|
33
36
|
import { rewritePlaceholders, type RewrittenSql } from './placeholders'
|
|
@@ -36,7 +39,7 @@ import { rewritePlaceholders, type RewrittenSql } from './placeholders'
|
|
|
36
39
|
const MUTATING_COMMANDS = new Set(['INSERT', 'UPDATE', 'DELETE', 'MERGE'])
|
|
37
40
|
|
|
38
41
|
/** What a bound value may be. Anything else is a programming error and throws at bind time, as D1 does. */
|
|
39
|
-
export type SqlBindValue = string | number | bigint | boolean |
|
|
42
|
+
export type SqlBindValue = string | number | bigint | boolean | Uint8Array | null
|
|
40
43
|
|
|
41
44
|
/**
|
|
42
45
|
* One prepared statement. IMMUTABLE: `bind()` returns a NEW statement carrying the values and leaves
|
|
@@ -99,11 +102,11 @@ export class PostgresDatabase implements SqlDatabase {
|
|
|
99
102
|
constructor(private readonly sql: Bun.SQL) {}
|
|
100
103
|
|
|
101
104
|
/**
|
|
102
|
-
* Open a pooled client. The URL is a CREDENTIAL — it is
|
|
103
|
-
* error message raised here.
|
|
105
|
+
* Open a pooled client that prepares no named statement (see the header). The URL is a CREDENTIAL — it is
|
|
106
|
+
* never logged, and never included in an error message raised here.
|
|
104
107
|
*/
|
|
105
|
-
static connect(url: string, options: Omit<Bun.SQL.PostgresOrMySQLOptions, 'url' | 'adapter'> = {}): PostgresDatabase {
|
|
106
|
-
return new PostgresDatabase(new Bun.SQL({ ...options, url, adapter: 'postgres' }))
|
|
108
|
+
static connect(url: string, options: Omit<Bun.SQL.PostgresOrMySQLOptions, 'url' | 'adapter' | 'prepare'> = {}): PostgresDatabase {
|
|
109
|
+
return new PostgresDatabase(new Bun.SQL({ ...options, prepare: false, url, adapter: 'postgres' }))
|
|
107
110
|
}
|
|
108
111
|
|
|
109
112
|
prepare(sql: string): SqlStatement {
|
|
@@ -198,11 +201,14 @@ function toBindValue(value: unknown): SqlBindValue {
|
|
|
198
201
|
|| typeof value === 'number'
|
|
199
202
|
|| typeof value === 'bigint'
|
|
200
203
|
|| typeof value === 'boolean'
|
|
201
|
-
|| value instanceof Date
|
|
202
204
|
|| value instanceof Uint8Array
|
|
203
205
|
) {
|
|
204
206
|
return value
|
|
205
207
|
}
|
|
208
|
+
// Without a prepared statement Bun sends a parameter as text, and a Date as `Date#toString()`, which Postgres refuses.
|
|
209
|
+
if (value instanceof Date) {
|
|
210
|
+
return value.toISOString()
|
|
211
|
+
}
|
|
206
212
|
if (value instanceof ArrayBuffer) {
|
|
207
213
|
return new Uint8Array(value)
|
|
208
214
|
}
|
package/src/sql.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @fabrika/platform-node/sql — the SQL
|
|
1
|
+
// @fabrika/platform-node/sql — the SQL lexers (Postgres, SQLite) and the migration classifier, RUNTIME-NEUTRAL: no Bun, no Node, no
|
|
2
2
|
// driver, so a Cloudflare Worker (Control reading a commit) loads it as the runner does. `sql-subpath.test.ts` holds
|
|
3
3
|
// the import graph to that.
|
|
4
4
|
|
|
@@ -18,25 +18,32 @@ export {
|
|
|
18
18
|
classifyMigration,
|
|
19
19
|
type ClassifyMigrationOptions,
|
|
20
20
|
classifyMigrations,
|
|
21
|
+
type ClassifyMigrationsOptions,
|
|
21
22
|
type DatabaseObject,
|
|
22
23
|
type DatabaseObjectKind,
|
|
24
|
+
type DataLossStatement,
|
|
23
25
|
declaredFunctions,
|
|
24
26
|
type DeviationKind,
|
|
27
|
+
type FileAdoption,
|
|
25
28
|
type ManifestChange,
|
|
26
29
|
type MigrationClassification,
|
|
30
|
+
type MigrationDataLoss,
|
|
27
31
|
type MigrationDeviation,
|
|
32
|
+
type MigrationDialect,
|
|
28
33
|
type MigrationFile,
|
|
29
34
|
migrationManifest,
|
|
30
35
|
type MigrationRefusal,
|
|
31
36
|
type MigrationSetClassification,
|
|
32
37
|
} from './migration-classify'
|
|
33
|
-
export { lexSql, type SqlToken, sqlTokens, type Statement, topLevelStatements, upperWord } from './migration-sql'
|
|
38
|
+
export { lexSql, type SqlToken, sqlTokens, type Statement, statementsOf, topLevelStatements, upperWord } from './migration-sql'
|
|
34
39
|
export { PG_CATALOG_FUNCTIONS, SQL_KEYWORDS } from './pg-catalog-names'
|
|
35
40
|
export {
|
|
36
41
|
afterName,
|
|
42
|
+
type BodyStatement,
|
|
37
43
|
closingParenthesis,
|
|
44
|
+
CTE_FORM,
|
|
45
|
+
type CteLists,
|
|
38
46
|
ddlForeignSchema,
|
|
39
|
-
dmlForeignSchema,
|
|
40
47
|
dmlRelations,
|
|
41
48
|
frameworkReference,
|
|
42
49
|
type FunctionUse,
|
|
@@ -50,9 +57,13 @@ export {
|
|
|
50
57
|
nestedStatement,
|
|
51
58
|
objectNameAt,
|
|
52
59
|
parenthesizedTarget,
|
|
53
|
-
|
|
60
|
+
ReadBody,
|
|
61
|
+
ReadSql,
|
|
62
|
+
referencedForeignSchema,
|
|
63
|
+
refusedCall,
|
|
54
64
|
skipWords,
|
|
55
65
|
splitAtCommas,
|
|
56
66
|
statementKind,
|
|
57
67
|
unicodeIdentifier,
|
|
58
68
|
} from './sql-names'
|
|
69
|
+
export { lexSqlite, SQLITE_PARAMETER_STARTS } from './sqlite-sql'
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// SQLite's lexical rules (tokenize.c), emitting the Postgres lexer's `SqlToken` shape so the same name and statement
|
|
2
|
+
// checks read both. Runtime-neutral: a Worker (an application's Durable Object) loads it.
|
|
3
|
+
|
|
4
|
+
import type { SqlToken } from './migration-sql'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`), each a `punct` token here.
|
|
8
|
+
* SQLite reads `$x(…)` up to a space or `)` as one parameter, a quote included, so the tokens after one may not be what
|
|
9
|
+
* SQLite reads: a reader of SQLite text refuses it at the first.
|
|
10
|
+
*/
|
|
11
|
+
export const SQLITE_PARAMETER_STARTS: ReadonlySet<string> = new Set(['?', ':', '@', '$', '#'])
|
|
12
|
+
|
|
13
|
+
/** SQLite's space (`sqlite3Isspace`), and the UTF-8 byte-order mark, which its tokenizer skips as space anywhere. */
|
|
14
|
+
const isSpace = (char: string): boolean => /[ \t\n\r\f\v]/.test(char)
|
|
15
|
+
/** Every character from U+0080 up but the byte-order mark is part of a name, as SQLite reads any byte from 0x80. */
|
|
16
|
+
const isWordStart = (char: string): boolean => /[A-Za-z_\u0080--]/.test(char)
|
|
17
|
+
const isWordPart = (char: string): boolean => /[A-Za-z0-9_$\u0080--]/.test(char)
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The tokens of `sql` as SQLite reads it, and the line of the first string, quoted name or block comment that never
|
|
21
|
+
* closes. `'…'` (with `''`) is a string; `"…"`, `` `…` `` (each with its doubled quote) and `[…]` (no escape) are quoted
|
|
22
|
+
* names; `--` runs to a line feed and `/* *\/` does not nest. There is no `E''` string and no dollar quoting, so a `\`
|
|
23
|
+
* or a `$` is no quote: `E'\'; DROP …` is a string, then a `;`.
|
|
24
|
+
*/
|
|
25
|
+
export function lexSqlite(sql: string): { readonly tokens: SqlToken[]; readonly unterminated: number | undefined } {
|
|
26
|
+
const tokens: SqlToken[] = []
|
|
27
|
+
let unterminated: number | undefined
|
|
28
|
+
let line = 1
|
|
29
|
+
let index = 0
|
|
30
|
+
const skipTo = (end: number): void => {
|
|
31
|
+
for (let at = index; at < end && at < sql.length; at++) if (sql[at] === '\n') line++
|
|
32
|
+
index = Math.min(end, sql.length)
|
|
33
|
+
}
|
|
34
|
+
/** The body of a quote that `close` ends, `close` doubled standing for itself; `doubles` false for `[…]`. */
|
|
35
|
+
const quoted = (close: string, doubles: boolean): { readonly text: string; readonly line: number } => {
|
|
36
|
+
const startLine = line
|
|
37
|
+
let at = index + 1
|
|
38
|
+
let text = ''
|
|
39
|
+
while (at < sql.length) {
|
|
40
|
+
if (doubles && sql[at] === close && sql[at + 1] === close) {
|
|
41
|
+
text += close
|
|
42
|
+
at += 2
|
|
43
|
+
} else if (sql[at] === close) break
|
|
44
|
+
else text += sql[at++] ?? ''
|
|
45
|
+
}
|
|
46
|
+
if (at >= sql.length) unterminated ??= startLine
|
|
47
|
+
skipTo(at + 1)
|
|
48
|
+
return { text, line: startLine }
|
|
49
|
+
}
|
|
50
|
+
while (index < sql.length) {
|
|
51
|
+
const char = sql[index] ?? ''
|
|
52
|
+
const next = sql[index + 1] ?? ''
|
|
53
|
+
if (char === '\n') {
|
|
54
|
+
line++
|
|
55
|
+
index++
|
|
56
|
+
} else if (isSpace(char)) {
|
|
57
|
+
index++
|
|
58
|
+
} else if (char === '-' && next === '-') {
|
|
59
|
+
// SQLite ends a comment at a line feed only: a carriage return does not end it.
|
|
60
|
+
const end = sql.indexOf('\n', index + 2)
|
|
61
|
+
skipTo(end === -1 ? sql.length : end)
|
|
62
|
+
} else if (char === '/' && next === '*') {
|
|
63
|
+
const end = sql.indexOf('*/', index + 2)
|
|
64
|
+
if (end === -1) unterminated ??= line
|
|
65
|
+
skipTo(end === -1 ? sql.length : end + 2)
|
|
66
|
+
} else if (char === "'") {
|
|
67
|
+
const body = quoted("'", true)
|
|
68
|
+
tokens.push({ kind: 'string', text: body.text, line: body.line })
|
|
69
|
+
} else if (char === '"' || char === '`') {
|
|
70
|
+
const body = quoted(char, true)
|
|
71
|
+
tokens.push({ kind: 'quoted', text: body.text, line: body.line })
|
|
72
|
+
} else if (char === '[') {
|
|
73
|
+
const body = quoted(']', false)
|
|
74
|
+
tokens.push({ kind: 'quoted', text: body.text, line: body.line })
|
|
75
|
+
} else if (isWordStart(char)) {
|
|
76
|
+
let at = index + 1
|
|
77
|
+
while (at < sql.length && isWordPart(sql[at] ?? '')) at++
|
|
78
|
+
tokens.push({ kind: 'word', text: sql.slice(index, at), line })
|
|
79
|
+
index = at
|
|
80
|
+
} else {
|
|
81
|
+
tokens.push({ kind: 'punct', char, line })
|
|
82
|
+
index++
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { tokens, unterminated }
|
|
86
|
+
}
|
|
@@ -12,8 +12,9 @@ export declare function acquireMigrationLock(db: SqlDatabase, lockKey: number, t
|
|
|
12
12
|
export declare function normalizeDefaultPrivileges(db: SqlDatabase, schema: string): Promise<void>;
|
|
13
13
|
/**
|
|
14
14
|
* Resets the schema's privileges to what the runtime role needs: PUBLIC and the runtime role lose everything on the
|
|
15
|
-
* schema and its objects, then the runtime role gets USAGE,
|
|
16
|
-
* routines and USAGE on its types. One transaction, so a live
|
|
17
|
-
* are verified, PUBLIC included, and anything beyond that
|
|
15
|
+
* schema and its objects, then the runtime role gets USAGE, SELECT on every relation, DML on every table but the
|
|
16
|
+
* ledger (never on a view), EXECUTE on the schema's routines and USAGE on its types. One transaction, so a live
|
|
17
|
+
* runtime never sees a gap. Then the effective privileges are verified, PUBLIC included, and anything beyond that
|
|
18
|
+
* stops the deploy.
|
|
18
19
|
*/
|
|
19
20
|
export declare function grantRuntimeRole(db: SqlDatabase, schema: string, ledgerTable: string, role: string): Promise<void>;
|
package/types/src/index.d.ts
CHANGED
|
@@ -9,7 +9,6 @@ export { decodeJob, type Job, PostgresJobConsumer, type PostgresJobConsumerOptio
|
|
|
9
9
|
export type { DatabaseObject, DatabaseObjectKind } from './migration-classify';
|
|
10
10
|
export { rewritePlaceholders, type RewrittenSql } from './placeholders';
|
|
11
11
|
export { applyPostgresMigrations, definePostgresMigrationPlan, migrationChecksum, platformNodePostgresMigrationBundle, type PostgresApplicationMigrationSettings, type PostgresMigration, type PostgresMigrationBundle, PostgresMigrationError, postgresMigrationFilenames, postgresMigrationIdentity, type PostgresMigrationPlan, readPostgresMigrationBundle, type ReadPostgresMigrationBundleOptions, } from './postgres-migrations';
|
|
12
|
-
export { createTestProvisioner, type TestProvisioner } from './postgres-test-provisioner';
|
|
13
12
|
export { definePostgresServiceMigrations, postgresMigrationResultMessage, type PostgresServiceMigrations, type PostgresServiceMigrationsConfig, } from './service-postgres-migrations';
|
|
14
13
|
export { PostgresDatabase, PostgresStatement, type SqlBindValue } from './sql-postgres';
|
|
15
14
|
export { type BackgroundTasks, type BackgroundTasksOptions, createBackgroundTasks } from './wait-until';
|
|
@@ -18,6 +18,48 @@ export interface MigrationDeviation {
|
|
|
18
18
|
readonly file: string;
|
|
19
19
|
readonly line: number;
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* A step of a file collection's adoption into a file column (ADR-0061): the `INSERT … SELECT` that copies the
|
|
23
|
+
* collection's files into a table, and the call that releases the collection. Paved, and shown to the approver: an
|
|
24
|
+
* adopted file is read under its table's policy from then on, and a release deletes every file no column adopted.
|
|
25
|
+
*/
|
|
26
|
+
export type FileAdoption = {
|
|
27
|
+
readonly step: 'adopt';
|
|
28
|
+
readonly collection: string;
|
|
29
|
+
readonly table: string;
|
|
30
|
+
readonly file: string;
|
|
31
|
+
readonly line: number;
|
|
32
|
+
} | {
|
|
33
|
+
readonly step: 'release';
|
|
34
|
+
readonly collection: string;
|
|
35
|
+
readonly file: string;
|
|
36
|
+
readonly line: number;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* A statement that deletes or overwrites stored data in the application's own schema, or that the classifier cannot show
|
|
40
|
+
* keeps every stored value: allowed, and shown to the approver on its own, because no later deploy brings the data back.
|
|
41
|
+
*/
|
|
42
|
+
export interface MigrationDataLoss {
|
|
43
|
+
readonly statement: DataLossStatement;
|
|
44
|
+
/**
|
|
45
|
+
* `<table>`; `<table>.<column>` for a dropped or converted column; `<kind> <name>` for a `DROP … CASCADE`; the
|
|
46
|
+
* function's name for a call of database code; the statement's first keywords for `UNPROVEN`.
|
|
47
|
+
*/
|
|
48
|
+
readonly object: string;
|
|
49
|
+
/** The columns an `UPDATE` sets, when the classifier could read every one. */
|
|
50
|
+
readonly columns?: readonly string[];
|
|
51
|
+
readonly file: string;
|
|
52
|
+
readonly line: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* What a statement does to stored data. It deletes: `DROP TABLE`, `DROP COLUMN`, any `DROP … CASCADE` (it also drops
|
|
56
|
+
* the columns of a dropped type or domain), `TRUNCATE` (`TRUNCATE CASCADE` empties every table that references one too)
|
|
57
|
+
* and `DELETE`. It overwrites: `UPDATE` (`UPDATE OR REPLACE` also deletes the rows it conflicts with),
|
|
58
|
+
* `INSERT … ON CONFLICT … DO UPDATE` (`UPSERT`) and `ALTER COLUMN … TYPE`, whose cast may change a value. It may change
|
|
59
|
+
* data: `CALL`, a migration statement that calls a function the migration set declares, whose body may write anything;
|
|
60
|
+
* `UNPROVEN`, any other statement that is not known to keep every stored value (`classifyStatement`).
|
|
61
|
+
*/
|
|
62
|
+
export type DataLossStatement = 'DROP TABLE' | 'DROP COLUMN' | 'DROP CASCADE' | 'TRUNCATE' | 'TRUNCATE CASCADE' | 'DELETE' | 'UPDATE' | 'UPDATE OR REPLACE' | 'UPSERT' | 'ALTER COLUMN TYPE' | 'CALL' | 'UNPROVEN';
|
|
21
63
|
export interface MigrationRefusal {
|
|
22
64
|
/** What is refused, phrased to precede "is not allowed". */
|
|
23
65
|
readonly reason: string;
|
|
@@ -55,16 +97,37 @@ export interface MigrationClassification {
|
|
|
55
97
|
/** One per refused statement, in order. A file with a refusal does not run. */
|
|
56
98
|
readonly refused: readonly MigrationRefusal[];
|
|
57
99
|
readonly deviations: readonly MigrationDeviation[];
|
|
100
|
+
/** The file's adoption steps, in order. */
|
|
101
|
+
readonly adoptions: readonly FileAdoption[];
|
|
102
|
+
/** The file's statements that delete or overwrite stored data, or call database code that may, in order. */
|
|
103
|
+
readonly dataLoss: readonly MigrationDataLoss[];
|
|
58
104
|
/** The objects the file creates. */
|
|
59
105
|
readonly objects: readonly DatabaseObject[];
|
|
60
106
|
readonly changes: readonly ManifestChange[];
|
|
61
107
|
}
|
|
108
|
+
/** The database an application's migrations run on: Postgres, or SQLite in its Durable Object on Cloudflare (ADR-0065). */
|
|
109
|
+
export type MigrationDialect = 'postgres' | 'sqlite';
|
|
62
110
|
export interface ClassifyMigrationOptions {
|
|
63
111
|
readonly file: string;
|
|
112
|
+
/** Postgres when absent. SQLite only adds the table options SQLite has (`STRICT`, `WITHOUT ROWID`). */
|
|
113
|
+
readonly dialect?: MigrationDialect;
|
|
64
114
|
/** The functions and procedures the whole migration set declares in the schema: a body or an expression may call them. */
|
|
65
115
|
readonly functions?: ReadonlySet<string>;
|
|
116
|
+
/** The views and materialized views the whole migration set declares in the schema: reading one may run database code. */
|
|
117
|
+
readonly views?: ReadonlySet<string>;
|
|
66
118
|
/** The framework's own bundle, which alone may name the framework's `fabrika_*` tables. */
|
|
67
119
|
readonly framework?: boolean;
|
|
120
|
+
/** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
|
|
121
|
+
readonly accessTables?: ReadonlySet<string>;
|
|
122
|
+
/** The views the migration set declares over an access table, lowercased (`accessViews`): written like one. */
|
|
123
|
+
readonly accessViews?: ReadonlySet<string>;
|
|
124
|
+
}
|
|
125
|
+
/** What the whole migration set is classified against besides its schema. */
|
|
126
|
+
export interface ClassifyMigrationsOptions {
|
|
127
|
+
/** Postgres when absent. */
|
|
128
|
+
readonly dialect?: MigrationDialect;
|
|
129
|
+
/** The application's access tables, lowercased (`accessTables` of `@fabrika/db/tables`): no stored code writes one. */
|
|
130
|
+
readonly accessTables?: ReadonlySet<string>;
|
|
68
131
|
}
|
|
69
132
|
export interface MigrationFile {
|
|
70
133
|
readonly name: string;
|
|
@@ -84,14 +147,16 @@ export interface MigrationSetClassification {
|
|
|
84
147
|
* `ALTER … RENAME TO`, `DO`, and a stored expression that calls anything but a paved built-in. Refused: a schema
|
|
85
148
|
* other than `schema` (`pg_catalog` relations included), a framework `fabrika_*` name, `SECURITY DEFINER`, a function
|
|
86
149
|
* `SET` clause, a language other than `sql` and `plpgsql`, a body that is not literal or that holds dynamic `EXECUTE`
|
|
87
|
-
* or a statement outside its allowlist, a call outside the function allowlist,
|
|
150
|
+
* or a statement outside its allowlist, a call outside the function allowlist, a conflict clause on a constraint
|
|
151
|
+
* (SQLite's `ON CONFLICT REPLACE`, which turns a plain `INSERT` into a delete), and every form not named here:
|
|
88
152
|
* `COPY`, `GRANT`, `REVOKE`, roles, extensions, event triggers, domains (codegen cannot bind one), `SELECT`, `WITH`
|
|
89
153
|
* and `MERGE` among them. Transaction control and
|
|
90
|
-
* `SET`/`RESET` are refused for every plan before this runs (`refusedStatement`).
|
|
154
|
+
* `SET`/`RESET` are refused for every plan before this runs (`refusedStatement`). Apart from all three, a statement not
|
|
155
|
+
* known to keep every stored value records a data line (`dataLoss`, `classifyStatement`).
|
|
91
156
|
*/
|
|
92
157
|
export declare function classifyMigration(sql: string, schema: string, options: ClassifyMigrationOptions): MigrationClassification;
|
|
93
158
|
/** The names of the functions and procedures a migration creates or renames to in `schema`, read without classifying them. */
|
|
94
|
-
export declare function declaredFunctions(sql: string, schema: string): string[];
|
|
159
|
+
export declare function declaredFunctions(sql: string, schema: string, dialect?: MigrationDialect): string[];
|
|
95
160
|
/**
|
|
96
161
|
* The manifest of a migration set, folded in file order: a create adds an object (a replace keeps it), a drop removes
|
|
97
162
|
* it, dropping a table removes its triggers, rules and policies, and renaming a table renames them. A `CASCADE` may
|
|
@@ -102,4 +167,4 @@ export declare function migrationManifest(classifications: readonly MigrationCla
|
|
|
102
167
|
* Classifies a whole migration set in order. A body or an expression may call a function any file of the set
|
|
103
168
|
* declares; the manifest is what the catalog check admits.
|
|
104
169
|
*/
|
|
105
|
-
export declare function classifyMigrations(files: readonly MigrationFile[], schema: string): MigrationSetClassification;
|
|
170
|
+
export declare function classifyMigrations(files: readonly MigrationFile[], schema: string, options?: ClassifyMigrationsOptions): MigrationSetClassification;
|
|
@@ -53,6 +53,8 @@ export interface Statement {
|
|
|
53
53
|
* makes a check stricter.
|
|
54
54
|
*/
|
|
55
55
|
export declare function topLevelStatements(sql: string): Statement[];
|
|
56
|
+
/** Splits lexed text into its statements at every `;` token: `topLevelStatements` over any lexer's tokens. */
|
|
57
|
+
export declare function statementsOf(all: readonly SqlToken[]): Statement[];
|
|
56
58
|
export declare const upperWord: (token: SqlToken | undefined) => string | undefined;
|
|
57
59
|
/** Reports how each top-level statement begins. A keyword inside a comment, a literal or a quoted body is no statement. */
|
|
58
60
|
export declare function statementStarts(sql: string): StatementStart[];
|
package/types/src/sql-names.d.ts
CHANGED
|
@@ -44,21 +44,64 @@ export interface NameReference {
|
|
|
44
44
|
/**
|
|
45
45
|
* Every name of a DML statement, a query or an expression, with its role. A name in a relation position (after
|
|
46
46
|
* `FROM`, `JOIN`, `USING`, `INTO`, `UPDATE`, `TABLE`, `REFERENCES`, or a `,` of a `FROM` list) is a relation; a name
|
|
47
|
-
* that `(` follows is a call, unless it is syntax
|
|
48
|
-
*
|
|
47
|
+
* that `(` follows is a call, unless it is syntax, a type with a modifier or a CTE's name before its column list
|
|
48
|
+
* (`WITH RECURSIVE tree (id, depth) AS`); a name after `::` or `AS` is a type. A two-part name anywhere else is a
|
|
49
|
+
* column of a table or an alias (`d.note`, `NEW.stage`).
|
|
49
50
|
*/
|
|
50
|
-
export declare function nameReferences(
|
|
51
|
+
export declare function nameReferences(read: ReadSql): NameReference[];
|
|
51
52
|
/**
|
|
52
|
-
* The first schema a DML statement, a query or a function body
|
|
53
|
-
* qualified relation, call or type, or a three-part name. An unqualified
|
|
54
|
-
* resolves to the catalog and counts as `pg_catalog`.
|
|
53
|
+
* The first schema the `references` of a DML statement, a query or a function body (`nameReferences`) reach other
|
|
54
|
+
* than `schema`, `pg_catalog` included: a qualified relation, call or type, or a three-part name. An unqualified
|
|
55
|
+
* relation whose name starts with `pg_` resolves to the catalog and counts as `pg_catalog`.
|
|
55
56
|
*/
|
|
56
|
-
export declare function
|
|
57
|
+
export declare function referencedForeignSchema(references: readonly NameReference[], schema: string): string | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* The form of a CTE that a list must take to be read, for a refusal to name: a `CYCLE` mark is a constant, as Postgres
|
|
60
|
+
* requires, never a bound value.
|
|
61
|
+
*/
|
|
62
|
+
export declare const CTE_FORM = "name [(columns)] AS [[NOT] MATERIALIZED] (query) [SEARCH {BREADTH | DEPTH} FIRST BY columns SET column] [CYCLE columns SET column [TO constant DEFAULT constant] USING column]";
|
|
63
|
+
/** The CTE lists of a statement, a query or a body. */
|
|
64
|
+
export interface CteLists {
|
|
65
|
+
/** The statement each list ends in, by the index of its `WITH`, wherever that stands: a nested statement is refused there too. */
|
|
66
|
+
readonly terminals: ReadonlyMap<number, SqlToken | undefined>;
|
|
67
|
+
/** The index of each CTE's name in a list whose `WITH` begins a query: a `(` after one opens its column list. */
|
|
68
|
+
readonly names: ReadonlySet<number>;
|
|
69
|
+
/** The line of the first `WITH` that begins a query and whose list does not read as one; the entry refuses it. */
|
|
70
|
+
readonly unread: number | undefined;
|
|
71
|
+
}
|
|
72
|
+
/** A statement of a PL/pgSQL body: the index of its first token, and whether it stands in a declaration section. */
|
|
73
|
+
export interface BodyStatement {
|
|
74
|
+
readonly index: number;
|
|
75
|
+
readonly declaring: boolean;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The tokens of a query, a statement, a clause or an expression, read once with their CTE lists. The name checks take
|
|
79
|
+
* the tokens and their lists as this one value, which only its factories build: its private member makes it nominal,
|
|
80
|
+
* so an object that merely has its fields is none, and a list is never read against tokens it was not read from.
|
|
81
|
+
*/
|
|
82
|
+
export declare class ReadSql {
|
|
83
|
+
#private;
|
|
84
|
+
readonly tokens: readonly SqlToken[];
|
|
85
|
+
readonly ctes: CteLists;
|
|
86
|
+
protected constructor(tokens: readonly SqlToken[], ctes: CteLists);
|
|
87
|
+
/** A query or a data-changing statement: a query begins at its first token. */
|
|
88
|
+
static query(tokens: readonly SqlToken[]): ReadSql;
|
|
89
|
+
/** A clause or a condition (a policy's expressions, a rule, a trigger's `WHEN`): a query begins only in parentheses. */
|
|
90
|
+
static clause(tokens: readonly SqlToken[]): ReadSql;
|
|
91
|
+
/** A stored expression, which Postgres lets hold no subquery: no CTE list is read, so every `name (` is a call. */
|
|
92
|
+
static expression(tokens: readonly SqlToken[]): ReadSql;
|
|
93
|
+
}
|
|
94
|
+
/** A function or `DO` body read once: its statements (`bodyOf`), and its CTE lists with a query wherever one begins. */
|
|
95
|
+
export declare class ReadBody extends ReadSql {
|
|
96
|
+
readonly statements: readonly BodyStatement[];
|
|
97
|
+
private constructor();
|
|
98
|
+
static of(tokens: readonly SqlToken[]): ReadBody;
|
|
99
|
+
}
|
|
57
100
|
/**
|
|
58
101
|
* The first nested statement a nested position may not hold: in parentheses (a CTE body, a subquery) and after a
|
|
59
102
|
* CTE list, anything but a query or `INSERT`/`UPDATE`/`DELETE`, whose names the same checks read. `MERGE` among them.
|
|
60
103
|
*/
|
|
61
|
-
export declare function nestedStatement(
|
|
104
|
+
export declare function nestedStatement(read: ReadSql): {
|
|
62
105
|
readonly statement: string;
|
|
63
106
|
readonly line: number;
|
|
64
107
|
} | undefined;
|
|
@@ -70,8 +113,17 @@ export declare function parenthesizedTarget(tokens: readonly SqlToken[]): {
|
|
|
70
113
|
readonly statement: string;
|
|
71
114
|
readonly line: number;
|
|
72
115
|
} | undefined;
|
|
116
|
+
/**
|
|
117
|
+
* The relations the data-changing statements among `tokens` write, in order: the name after `INSERT INTO`,
|
|
118
|
+
* `MERGE INTO`, `UPDATE [ONLY]` and `DELETE FROM [ONLY]`. A parenthesized target is `parenthesizedTarget`'s to refuse;
|
|
119
|
+
* `MERGE` is refused before a body or a rule action is read, and is listed so no write form depends on that.
|
|
120
|
+
*/
|
|
121
|
+
export declare function writeTargets(tokens: readonly SqlToken[]): {
|
|
122
|
+
readonly name: string;
|
|
123
|
+
readonly line: number;
|
|
124
|
+
}[];
|
|
73
125
|
/** The relations a DML statement or a query names, in order: what its static text reads or writes. */
|
|
74
|
-
export declare function dmlRelations(
|
|
126
|
+
export declare function dmlRelations(read: ReadSql): NameReference[];
|
|
75
127
|
/**
|
|
76
128
|
* Whether a name is the framework's (`fabrika_…`): its tables share the application's schema and hold its secrets,
|
|
77
129
|
* leases and deliveries. Case-insensitive, so a quoted `"FABRIKA_x"` counts too.
|
|
@@ -94,8 +146,8 @@ export type FunctionUse = 'paved' | 'reviewed' | 'declared';
|
|
|
94
146
|
*/
|
|
95
147
|
export declare function functionUse(call: NameReference, schema: string, functions: ReadonlySet<string>): FunctionUse | undefined;
|
|
96
148
|
/**
|
|
97
|
-
* The first call among `
|
|
149
|
+
* The first call among the `references` of a body, a query or a backfill (`nameReferences`) that it may not make: anything but a paved or reviewed
|
|
98
150
|
* built-in, or a function the migrations declare in `schema`. An allowlist, because a built-in such as
|
|
99
151
|
* `query_to_xml`, `dblink` or `lo_import` runs SQL from a string or reaches past the schema, which no name rule sees.
|
|
100
152
|
*/
|
|
101
|
-
export declare function
|
|
153
|
+
export declare function refusedCall(references: readonly NameReference[], schema: string, functions: ReadonlySet<string>): NameReference | undefined;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { SqlDatabase, SqlQueryResult, SqlRunResult, SqlStatement } from '@fabrika/platform';
|
|
2
2
|
/** What a bound value may be. Anything else is a programming error and throws at bind time, as D1 does. */
|
|
3
|
-
export type SqlBindValue = string | number | bigint | boolean |
|
|
3
|
+
export type SqlBindValue = string | number | bigint | boolean | Uint8Array | null;
|
|
4
4
|
/**
|
|
5
5
|
* One prepared statement. IMMUTABLE: `bind()` returns a NEW statement carrying the values and leaves
|
|
6
6
|
* the receiver untouched, which is D1's contract and what call sites rely on when they prepare once
|
|
@@ -33,10 +33,10 @@ export declare class PostgresDatabase implements SqlDatabase {
|
|
|
33
33
|
private readonly rewrites;
|
|
34
34
|
constructor(sql: Bun.SQL);
|
|
35
35
|
/**
|
|
36
|
-
* Open a pooled client. The URL is a CREDENTIAL — it is
|
|
37
|
-
* error message raised here.
|
|
36
|
+
* Open a pooled client that prepares no named statement (see the header). The URL is a CREDENTIAL — it is
|
|
37
|
+
* never logged, and never included in an error message raised here.
|
|
38
38
|
*/
|
|
39
|
-
static connect(url: string, options?: Omit<Bun.SQL.PostgresOrMySQLOptions, 'url' | 'adapter'>): PostgresDatabase;
|
|
39
|
+
static connect(url: string, options?: Omit<Bun.SQL.PostgresOrMySQLOptions, 'url' | 'adapter' | 'prepare'>): PostgresDatabase;
|
|
40
40
|
prepare(sql: string): SqlStatement;
|
|
41
41
|
/**
|
|
42
42
|
* Run every statement in ONE transaction, in order. A throw rolls the whole batch back. The transaction is sent by
|
package/types/src/sql.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { applicationDatabaseSchema } from './application-schema';
|
|
2
2
|
export { FILE_SCAN_COLUMNS, FILE_STATUSES, FILE_TABLE_PREFIX, fileScanAlter, fileScanAlterTable, fileScanIndex, fileStatusCheck, fileTableScanReady, legacyStatusCheckName, } from './file-table-ddl';
|
|
3
|
-
export { classifyMigration, type ClassifyMigrationOptions, classifyMigrations, type DatabaseObject, type DatabaseObjectKind, declaredFunctions, type DeviationKind, type ManifestChange, type MigrationClassification, type MigrationDeviation, type MigrationFile, migrationManifest, type MigrationRefusal, type MigrationSetClassification, } from './migration-classify';
|
|
4
|
-
export { lexSql, type SqlToken, sqlTokens, type Statement, topLevelStatements, upperWord } from './migration-sql';
|
|
3
|
+
export { classifyMigration, type ClassifyMigrationOptions, classifyMigrations, type ClassifyMigrationsOptions, type DatabaseObject, type DatabaseObjectKind, type DataLossStatement, declaredFunctions, type DeviationKind, type FileAdoption, type ManifestChange, type MigrationClassification, type MigrationDataLoss, type MigrationDeviation, type MigrationDialect, type MigrationFile, migrationManifest, type MigrationRefusal, type MigrationSetClassification, } from './migration-classify';
|
|
4
|
+
export { lexSql, type SqlToken, sqlTokens, type Statement, statementsOf, topLevelStatements, upperWord } from './migration-sql';
|
|
5
5
|
export { PG_CATALOG_FUNCTIONS, SQL_KEYWORDS } from './pg-catalog-names';
|
|
6
|
-
export { afterName, closingParenthesis,
|
|
6
|
+
export { afterName, type BodyStatement, closingParenthesis, CTE_FORM, type CteLists, ddlForeignSchema, dmlRelations, frameworkReference, type FunctionUse, functionUse, isFrameworkName, isPunct, type NameReference, nameReferences, type NameRole, nameText, nestedStatement, objectNameAt, parenthesizedTarget, ReadBody, ReadSql, referencedForeignSchema, refusedCall, skipWords, splitAtCommas, statementKind, unicodeIdentifier, } from './sql-names';
|
|
7
|
+
export { lexSqlite, SQLITE_PARAMETER_STARTS } from './sqlite-sql';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { SqlToken } from './migration-sql';
|
|
2
|
+
/**
|
|
3
|
+
* What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`), each a `punct` token here.
|
|
4
|
+
* SQLite reads `$x(…)` up to a space or `)` as one parameter, a quote included, so the tokens after one may not be what
|
|
5
|
+
* SQLite reads: a reader of SQLite text refuses it at the first.
|
|
6
|
+
*/
|
|
7
|
+
export declare const SQLITE_PARAMETER_STARTS: ReadonlySet<string>;
|
|
8
|
+
/**
|
|
9
|
+
* The tokens of `sql` as SQLite reads it, and the line of the first string, quoted name or block comment that never
|
|
10
|
+
* closes. `'…'` (with `''`) is a string; `"…"`, `` `…` `` (each with its doubled quote) and `[…]` (no escape) are quoted
|
|
11
|
+
* names; `--` runs to a line feed and `/* *\/` does not nest. There is no `E''` string and no dollar quoting, so a `\`
|
|
12
|
+
* or a `$` is no quote: `E'\'; DROP …` is a string, then a `;`.
|
|
13
|
+
*/
|
|
14
|
+
export declare function lexSqlite(sql: string): {
|
|
15
|
+
readonly tokens: SqlToken[];
|
|
16
|
+
readonly unterminated: number | undefined;
|
|
17
|
+
};
|