@fabrika/platform-node 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/platform-node",
3
- "version": "0.9.0-cloudflare.2",
3
+ "version": "0.9.0-cloudflare.3",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,6 +38,6 @@
38
38
  "test": "bun test"
39
39
  },
40
40
  "dependencies": {
41
- "@fabrika/platform": "0.9.0-cloudflare.2"
41
+ "@fabrika/platform": "0.9.0-cloudflare.3"
42
42
  }
43
43
  }
@@ -62,6 +62,19 @@ export interface MigrationDeviation {
62
62
  readonly line: number
63
63
  }
64
64
 
65
+ /**
66
+ * A step of a file collection's adoption into a file column (ADR-0061): the `INSERT … SELECT` that copies the
67
+ * collection's files into a table, and the call that releases the collection. Paved, and shown to the approver: an
68
+ * adopted file is read under its table's policy from then on, and a release deletes every file no column adopted.
69
+ */
70
+ export type FileAdoption =
71
+ | { readonly step: 'adopt'; readonly collection: string; readonly table: string; readonly file: string; readonly line: number }
72
+ | { readonly step: 'release'; readonly collection: string; readonly file: string; readonly line: number }
73
+
74
+ /** A file adoption step before the file it lies in is known. */
75
+ type AdoptionStep = WithoutFile<FileAdoption>
76
+ type WithoutFile<T> = T extends unknown ? Omit<T, 'file'> : never
77
+
65
78
  export interface MigrationRefusal {
66
79
  /** What is refused, phrased to precede "is not allowed". */
67
80
  readonly reason: string
@@ -84,6 +97,8 @@ export interface MigrationClassification {
84
97
  /** One per refused statement, in order. A file with a refusal does not run. */
85
98
  readonly refused: readonly MigrationRefusal[]
86
99
  readonly deviations: readonly MigrationDeviation[]
100
+ /** The file's adoption steps, in order. */
101
+ readonly adoptions: readonly FileAdoption[]
87
102
  /** The objects the file creates. */
88
103
  readonly objects: readonly DatabaseObject[]
89
104
  readonly changes: readonly ManifestChange[]
@@ -206,6 +221,7 @@ class Refused extends Error {
206
221
  /** What one statement adds when it is not refused. */
207
222
  interface Collected {
208
223
  readonly deviations: { readonly kind: DeviationKind; readonly object: string; readonly line: number }[]
224
+ readonly adoptions: AdoptionStep[]
209
225
  readonly changes: ManifestChange[]
210
226
  }
211
227
 
@@ -916,26 +932,46 @@ function adoptedTableNames(tokens: readonly SqlToken[]): ReadonlySet<string> {
916
932
 
917
933
  /**
918
934
  * `SELECT fabrika_files_copy_legacy('<collection>');` and `SELECT fabrika_files_release('<collection>');`: the only
919
- * calls of a framework function an application migration makes, each a statement of its own.
935
+ * calls of a framework function an application migration makes, each a statement of its own. Answers the function and
936
+ * the collection, or `undefined` for any other statement.
920
937
  */
921
- function isFileAdoptionCall(tokens: readonly SqlToken[]): boolean {
938
+ function fileAdoptionCall(tokens: readonly SqlToken[]): { readonly called: string; readonly collection: string } | undefined {
922
939
  const [select, name, open, collection, close] = tokens
923
940
  const called = nameText(name)
924
- return tokens.length === 5 && upperWord(select) === 'SELECT' && (called === FILES_COPY_FUNCTION || called === FILES_RELEASE_FUNCTION)
925
- && isPunct(open, '(')
926
- && collection?.kind === 'string' && /^[a-z_][a-z0-9_]*$/.test(collection.text ?? '') && isPunct(close, ')')
941
+ const value = collection?.kind === 'string' ? collection.text : undefined
942
+ const matches = tokens.length === 5 && upperWord(select) === 'SELECT' && (called === FILES_COPY_FUNCTION || called === FILES_RELEASE_FUNCTION)
943
+ && isPunct(open, '(') && value !== undefined && /^[a-z_][a-z0-9_]*$/.test(value) && isPunct(close, ')')
944
+ return matches ? { called, collection: value } : undefined
945
+ }
946
+
947
+ /** The adoption an `INSERT … SELECT` from collection tables makes: each collection's files into the target table. */
948
+ function adoptionSteps(tokens: readonly SqlToken[], adopted: ReadonlySet<string>): AdoptionStep[] {
949
+ // `checkQuery` refused a schema other than the application's, so a qualified target is its own table.
950
+ const table = objectNameAt(tokens, skipWords(tokens, 1, 'INTO'))?.name
951
+ const line = tokens[0]?.line ?? 1
952
+ if (table === undefined) return []
953
+ return [...adopted].sort().map((name) => ({ step: 'adopt', collection: name.slice(FILE_TABLE_PREFIX.length), table, line }))
927
954
  }
928
955
 
929
956
  function classifyStatement(tokens: readonly SqlToken[], context: Context, out: Collected): void {
930
957
  const line = tokens[0]?.line ?? 1
931
958
  const unicode = unicodeIdentifier(tokens)
932
959
  if (unicode !== undefined) throw new Refused('a Unicode-escaped identifier (U&"…")', unicode.line)
933
- if (!context.framework && isFileAdoptionCall(tokens)) return
934
- const allowed = new Set([...fileTableNames(tokens), ...adoptedTableNames(tokens)])
960
+ const call = context.framework ? undefined : fileAdoptionCall(tokens)
961
+ if (call !== undefined) {
962
+ if (call.called === FILES_RELEASE_FUNCTION) out.adoptions.push({ step: 'release', collection: call.collection, line: tokens[0]?.line ?? 1 })
963
+ return
964
+ }
965
+ const adopted = adoptedTableNames(tokens)
966
+ const allowed = new Set([...fileTableNames(tokens), ...adopted])
935
967
  const framework = context.framework ? undefined : frameworkReference(withoutFileReferences(tokens), allowed)
936
968
  if (framework !== undefined) throw new Refused(`a reference to the framework's ${framework.name}`, framework.line)
937
969
  const first = upperWord(tokens[0])
938
- if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') return checkQuery(tokens, context, first)
970
+ if (first === 'INSERT' || first === 'UPDATE' || first === 'DELETE') {
971
+ checkQuery(tokens, context, first)
972
+ if (!context.framework) out.adoptions.push(...adoptionSteps(tokens, adopted))
973
+ return
974
+ }
939
975
  if (first === 'COMMENT' && upperWord(tokens[1]) === 'ON') return classifyComment(tokens, context)
940
976
  if (first === 'DO') return classifyDo(tokens, context, out)
941
977
  if (first === 'CREATE') return classifyCreate(tokens, context, out)
@@ -967,6 +1003,7 @@ export function classifyMigration(sql: string, schema: string, options: Classify
967
1003
  const context: Context = { schema, functions: options.functions ?? new Set(), framework: options.framework === true, doBlocks: 0 }
968
1004
  const refused: MigrationRefusal[] = []
969
1005
  const deviations: MigrationDeviation[] = []
1006
+ const adoptions: FileAdoption[] = []
970
1007
  const changes: ManifestChange[] = []
971
1008
  const keys = new Set<string>()
972
1009
  const { unterminated } = lexSql(sql)
@@ -974,7 +1011,7 @@ export function classifyMigration(sql: string, schema: string, options: Classify
974
1011
  refused.push({ reason: 'a literal, a quoted name or a comment that never closes', file: options.file, line: unterminated })
975
1012
  }
976
1013
  for (const { tokens, line } of topLevelStatements(sql)) {
977
- const out: Collected = { deviations: [], changes: [] }
1014
+ const out: Collected = { deviations: [], adoptions: [], changes: [] }
978
1015
  try {
979
1016
  classifyStatement(tokens, context, out)
980
1017
  } catch (error) {
@@ -988,10 +1025,11 @@ export function classifyMigration(sql: string, schema: string, options: Classify
988
1025
  keys.add(key)
989
1026
  deviations.push({ ...deviation, file: options.file })
990
1027
  }
1028
+ adoptions.push(...out.adoptions.map((step) => ({ ...step, file: options.file })))
991
1029
  changes.push(...out.changes)
992
1030
  }
993
1031
  const objects = changes.flatMap((change) => (change.change === 'create' || change.change === 'create routine' ? [change.object] : []))
994
- return { file: options.file, refused, deviations, objects, changes }
1032
+ return { file: options.file, refused, deviations, adoptions, objects, changes }
995
1033
  }
996
1034
 
997
1035
  /** The names of the functions and procedures a migration creates or renames to in `schema`, read without classifying them. */
@@ -165,9 +165,14 @@ export interface Statement {
165
165
  * makes a check stricter.
166
166
  */
167
167
  export function topLevelStatements(sql: string): Statement[] {
168
+ return statementsOf(sqlTokens(sql))
169
+ }
170
+
171
+ /** Splits lexed text into its statements at every `;` token: `topLevelStatements` over any lexer's tokens. */
172
+ export function statementsOf(all: readonly SqlToken[]): Statement[] {
168
173
  const statements: Statement[] = []
169
174
  let tokens: SqlToken[] = []
170
- for (const token of sqlTokens(sql)) {
175
+ for (const token of all) {
171
176
  if (token.kind === 'punct' && token.char === ';') {
172
177
  if (tokens[0] !== undefined) statements.push({ tokens, line: tokens[0].line })
173
178
  tokens = []
package/src/sql-names.ts CHANGED
@@ -539,6 +539,9 @@ export function unicodeIdentifier(tokens: readonly SqlToken[]): { readonly line:
539
539
  */
540
540
  const PAVED_FUNCTIONS: ReadonlySet<string> = new Set([
541
541
  'now',
542
+ // SQLite's clock in a Cloudflare application's DEFAULT, the form the checker's `cloudflare-current-timestamp` rule
543
+ // prescribes (`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`); no side effect, no other row.
544
+ 'strftime',
542
545
  'gen_random_uuid',
543
546
  'lower',
544
547
  'upper',
package/src/sql.ts CHANGED
@@ -1,4 +1,4 @@
1
- // @fabrika/platform-node/sql — the SQL lexer and the migration classifier, RUNTIME-NEUTRAL: no Bun, no Node, no
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
 
@@ -22,6 +22,7 @@ export {
22
22
  type DatabaseObjectKind,
23
23
  declaredFunctions,
24
24
  type DeviationKind,
25
+ type FileAdoption,
25
26
  type ManifestChange,
26
27
  type MigrationClassification,
27
28
  type MigrationDeviation,
@@ -30,7 +31,7 @@ export {
30
31
  type MigrationRefusal,
31
32
  type MigrationSetClassification,
32
33
  } from './migration-classify'
33
- export { lexSql, type SqlToken, sqlTokens, type Statement, topLevelStatements, upperWord } from './migration-sql'
34
+ export { lexSql, type SqlToken, sqlTokens, type Statement, statementsOf, topLevelStatements, upperWord } from './migration-sql'
34
35
  export { PG_CATALOG_FUNCTIONS, SQL_KEYWORDS } from './pg-catalog-names'
35
36
  export {
36
37
  afterName,
@@ -56,3 +57,4 @@ export {
56
57
  statementKind,
57
58
  unicodeIdentifier,
58
59
  } from './sql-names'
60
+ export { lexSqlite } from './sqlite-sql'
@@ -0,0 +1,79 @@
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
+ /** SQLite's space (`sqlite3Isspace`), and the UTF-8 byte-order mark, which its tokenizer skips as space anywhere. */
7
+ const isSpace = (char: string): boolean => /[ \t\n\r\f\v]/.test(char)
8
+ /** Every character from U+0080 up but the byte-order mark is part of a name, as SQLite reads any byte from 0x80. */
9
+ const isWordStart = (char: string): boolean => /[A-Za-z_\u0080-﻾＀-￿]/.test(char)
10
+ const isWordPart = (char: string): boolean => /[A-Za-z0-9_$\u0080-﻾＀-￿]/.test(char)
11
+
12
+ /**
13
+ * The tokens of `sql` as SQLite reads it, and the line of the first string, quoted name or block comment that never
14
+ * closes. `'…'` (with `''`) is a string; `"…"`, `` `…` `` (each with its doubled quote) and `[…]` (no escape) are quoted
15
+ * names; `--` runs to a line feed and `/* *\/` does not nest. There is no `E''` string and no dollar quoting, so a `\`
16
+ * or a `$` is no quote: `E'\'; DROP …` is a string, then a `;`.
17
+ */
18
+ export function lexSqlite(sql: string): { readonly tokens: SqlToken[]; readonly unterminated: number | undefined } {
19
+ const tokens: SqlToken[] = []
20
+ let unterminated: number | undefined
21
+ let line = 1
22
+ let index = 0
23
+ const skipTo = (end: number): void => {
24
+ for (let at = index; at < end && at < sql.length; at++) if (sql[at] === '\n') line++
25
+ index = Math.min(end, sql.length)
26
+ }
27
+ /** The body of a quote that `close` ends, `close` doubled standing for itself; `doubles` false for `[…]`. */
28
+ const quoted = (close: string, doubles: boolean): { readonly text: string; readonly line: number } => {
29
+ const startLine = line
30
+ let at = index + 1
31
+ let text = ''
32
+ while (at < sql.length) {
33
+ if (doubles && sql[at] === close && sql[at + 1] === close) {
34
+ text += close
35
+ at += 2
36
+ } else if (sql[at] === close) break
37
+ else text += sql[at++] ?? ''
38
+ }
39
+ if (at >= sql.length) unterminated ??= startLine
40
+ skipTo(at + 1)
41
+ return { text, line: startLine }
42
+ }
43
+ while (index < sql.length) {
44
+ const char = sql[index] ?? ''
45
+ const next = sql[index + 1] ?? ''
46
+ if (char === '\n') {
47
+ line++
48
+ index++
49
+ } else if (isSpace(char)) {
50
+ index++
51
+ } else if (char === '-' && next === '-') {
52
+ // SQLite ends a comment at a line feed only: a carriage return does not end it.
53
+ const end = sql.indexOf('\n', index + 2)
54
+ skipTo(end === -1 ? sql.length : end)
55
+ } else if (char === '/' && next === '*') {
56
+ const end = sql.indexOf('*/', index + 2)
57
+ if (end === -1) unterminated ??= line
58
+ skipTo(end === -1 ? sql.length : end + 2)
59
+ } else if (char === "'") {
60
+ const body = quoted("'", true)
61
+ tokens.push({ kind: 'string', text: body.text, line: body.line })
62
+ } else if (char === '"' || char === '`') {
63
+ const body = quoted(char, true)
64
+ tokens.push({ kind: 'quoted', text: body.text, line: body.line })
65
+ } else if (char === '[') {
66
+ const body = quoted(']', false)
67
+ tokens.push({ kind: 'quoted', text: body.text, line: body.line })
68
+ } else if (isWordStart(char)) {
69
+ let at = index + 1
70
+ while (at < sql.length && isWordPart(sql[at] ?? '')) at++
71
+ tokens.push({ kind: 'word', text: sql.slice(index, at), line })
72
+ index = at
73
+ } else {
74
+ tokens.push({ kind: 'punct', char, line })
75
+ index++
76
+ }
77
+ }
78
+ return { tokens, unterminated }
79
+ }
@@ -18,6 +18,23 @@ 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
+ };
21
38
  export interface MigrationRefusal {
22
39
  /** What is refused, phrased to precede "is not allowed". */
23
40
  readonly reason: string;
@@ -55,6 +72,8 @@ export interface MigrationClassification {
55
72
  /** One per refused statement, in order. A file with a refusal does not run. */
56
73
  readonly refused: readonly MigrationRefusal[];
57
74
  readonly deviations: readonly MigrationDeviation[];
75
+ /** The file's adoption steps, in order. */
76
+ readonly adoptions: readonly FileAdoption[];
58
77
  /** The objects the file creates. */
59
78
  readonly objects: readonly DatabaseObject[];
60
79
  readonly changes: readonly ManifestChange[];
@@ -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[];
@@ -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 DatabaseObject, type DatabaseObjectKind, declaredFunctions, type DeviationKind, type FileAdoption, type ManifestChange, type MigrationClassification, type MigrationDeviation, 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
6
  export { afterName, closingParenthesis, ddlForeignSchema, dmlForeignSchema, dmlRelations, frameworkReference, type FunctionUse, functionUse, isFrameworkName, isPunct, type NameReference, nameReferences, type NameRole, nameText, nestedStatement, objectNameAt, parenthesizedTarget, refusedFunctionCall, skipWords, splitAtCommas, statementKind, unicodeIdentifier, } from './sql-names';
7
+ export { lexSqlite } from './sqlite-sql';
@@ -0,0 +1,11 @@
1
+ import type { SqlToken } from './migration-sql';
2
+ /**
3
+ * The tokens of `sql` as SQLite reads it, and the line of the first string, quoted name or block comment that never
4
+ * closes. `'…'` (with `''`) is a string; `"…"`, `` `…` `` (each with its doubled quote) and `[…]` (no escape) are quoted
5
+ * names; `--` runs to a line feed and `/* *\/` does not nest. There is no `E''` string and no dollar quoting, so a `\`
6
+ * or a `$` is no quote: `E'\'; DROP …` is a string, then a `;`.
7
+ */
8
+ export declare function lexSqlite(sql: string): {
9
+ readonly tokens: SqlToken[];
10
+ readonly unterminated: number | undefined;
11
+ };