@syncular/typegen 0.58.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +96 -43
  2. package/dist/cli.js +8 -3
  3. package/dist/emit-dart.d.ts +4 -3
  4. package/dist/emit-dart.js +40 -100
  5. package/dist/emit-kotlin.d.ts +4 -4
  6. package/dist/emit-kotlin.js +41 -99
  7. package/dist/emit-queries-dart.d.ts +1 -1
  8. package/dist/emit-queries-dart.js +17 -26
  9. package/dist/emit-queries-kotlin.d.ts +1 -1
  10. package/dist/emit-queries-kotlin.js +15 -24
  11. package/dist/emit-queries-rust.d.ts +1 -1
  12. package/dist/emit-queries-rust.js +18 -19
  13. package/dist/emit-queries-swift.d.ts +1 -1
  14. package/dist/emit-queries-swift.js +22 -26
  15. package/dist/emit-queries.d.ts +1 -1
  16. package/dist/emit-queries.js +18 -27
  17. package/dist/emit-swift.d.ts +4 -4
  18. package/dist/emit-swift.js +43 -102
  19. package/dist/emit.d.ts +3 -3
  20. package/dist/emit.js +37 -113
  21. package/dist/errors.d.ts +6 -2
  22. package/dist/errors.js +10 -2
  23. package/dist/fmt.js +11 -2
  24. package/dist/generate.d.ts +4 -3
  25. package/dist/generate.js +61 -73
  26. package/dist/init.js +5 -6
  27. package/dist/ir.d.ts +14 -2
  28. package/dist/ir.js +67 -49
  29. package/dist/lower.d.ts +0 -7
  30. package/dist/lower.js +0 -62
  31. package/dist/lsp.js +6 -1
  32. package/dist/manifest.d.ts +1 -2
  33. package/dist/manifest.js +13 -12
  34. package/dist/migration-lock.d.ts +32 -23
  35. package/dist/migration-lock.js +115 -92
  36. package/dist/naming.d.ts +25 -0
  37. package/dist/naming.js +92 -0
  38. package/dist/query.d.ts +94 -14
  39. package/dist/query.js +642 -461
  40. package/dist/sql.js +18 -3
  41. package/dist/syql-ast.d.ts +2 -0
  42. package/dist/syql-ast.js +7 -1
  43. package/dist/syql-browser.js +7 -6
  44. package/dist/syql-diagnostics.d.ts +1 -0
  45. package/dist/syql-diagnostics.js +1 -0
  46. package/dist/syql-lowering.js +11 -1
  47. package/dist/syql-parser.d.ts +4 -1
  48. package/dist/syql-parser.js +42 -5
  49. package/dist/syql-validator.js +13 -220
  50. package/package.json +3 -3
  51. package/src/cli.ts +9 -3
  52. package/src/emit-dart.ts +44 -116
  53. package/src/emit-kotlin.ts +41 -118
  54. package/src/emit-queries-dart.ts +23 -32
  55. package/src/emit-queries-kotlin.ts +20 -30
  56. package/src/emit-queries-rust.ts +29 -31
  57. package/src/emit-queries-swift.ts +26 -32
  58. package/src/emit-queries.ts +26 -47
  59. package/src/emit-swift.ts +49 -120
  60. package/src/emit.ts +45 -135
  61. package/src/errors.ts +13 -2
  62. package/src/fmt.ts +10 -2
  63. package/src/generate.ts +113 -107
  64. package/src/init.ts +8 -6
  65. package/src/ir.ts +91 -54
  66. package/src/lower.ts +0 -53
  67. package/src/lsp.ts +11 -4
  68. package/src/manifest.ts +22 -18
  69. package/src/migration-lock.ts +192 -137
  70. package/src/naming.ts +154 -0
  71. package/src/query.ts +864 -502
  72. package/src/sql.ts +30 -3
  73. package/src/syql-ast.ts +9 -0
  74. package/src/syql-browser.ts +8 -7
  75. package/src/syql-diagnostics.ts +2 -0
  76. package/src/syql-lowering.ts +16 -1
  77. package/src/syql-parser.ts +73 -8
  78. package/src/syql-validator.ts +21 -279
@@ -2,20 +2,21 @@
2
2
  * Immutable application-migration history.
3
3
  *
4
4
  * `syncular.migrations.lock.json` is a version-controlled baseline of every
5
- * migration that has been accepted so far. Existing entries are immutable;
6
- * generation may only append newly named migrations. Format 2 stores one
7
- * canonical head-schema snapshot for actionable diagnostics instead of a
8
- * cumulative schema copy after every migration. Format 1 remains readable and
9
- * writable until an explicit `migrations upgrade-lock` command replaces it.
5
+ * migration that has been accepted so far, with the schema version each one
6
+ * belongs to. Existing entries are immutable; generation may only append newly
7
+ * named migrations, in a schema version above the highest locked one (§7.4).
8
+ * Format 3 stores one canonical head-schema snapshot for actionable
9
+ * diagnostics. Formats 1 and 2 predate per-migration versions: only the
10
+ * explicit `migrations upgrade-lock` command reads them.
10
11
  */
11
12
  import { createHash } from 'node:crypto';
12
13
  import { existsSync, readFileSync } from 'node:fs';
13
14
  import { resolve } from 'node:path';
14
15
  import { TypegenError } from './errors.js';
16
+ import { MANIFEST_FILENAME } from './manifest.js';
15
17
  import { applyMigrationSql } from './sql.js';
16
18
  export const MIGRATION_LOCK_FILENAME = 'syncular.migrations.lock.json';
17
- export const MIGRATION_LOCK_FORMAT_VERSION = 2;
18
- export const LEGACY_MIGRATION_LOCK_FORMAT_VERSION = 1;
19
+ export const MIGRATION_LOCK_FORMAT_VERSION = 3;
19
20
  function normalizedSql(sql) {
20
21
  return sql.replace(/\r\n?/g, '\n');
21
22
  }
@@ -44,46 +45,60 @@ function snapshotTables(tables) {
44
45
  export function lockedMigrationNames(lock) {
45
46
  return new Set(lock.migrations.map((migration) => migration.name));
46
47
  }
48
+ /** Resolve the manifest's `schemaVersions` (each naming the last migration
49
+ * it includes) into the migrations every version adds (§1.5). */
50
+ export function buildSchemaVersions(declared, migrations) {
51
+ const names = migrations.map((m) => m.name);
52
+ let cursor = 0;
53
+ const out = declared.map((entry) => {
54
+ const index = names.indexOf(entry.through, cursor);
55
+ if (index === -1) {
56
+ throw new TypegenError(MANIFEST_FILENAME, `schemaVersions: version ${entry.version} names migration ${JSON.stringify(entry.through)}, which does not exist after ${JSON.stringify(names[cursor - 1] ?? '(start)')} (migrations: ${names.join(', ')})`);
57
+ }
58
+ const covered = names.slice(cursor, index + 1);
59
+ cursor = index + 1;
60
+ return { version: entry.version, migrations: covered };
61
+ });
62
+ if (cursor !== names.length) {
63
+ throw new TypegenError(MANIFEST_FILENAME, `schemaVersions: migrations ${names.slice(cursor).join(', ')} are not covered by any schema version — the last entry's "through" must be the last migration`);
64
+ }
65
+ return out;
66
+ }
47
67
  /** Replay a complete migration sequence with ephemeral diagnostic snapshots.
48
68
  * Migrations named in `lockedNames` replay as deployed history; rules that
49
69
  * only appended migrations must satisfy are skipped for them. */
50
70
  function buildMigrationHistory(migrations, lockedNames) {
51
71
  const tables = new Map();
52
72
  const droppedTables = new Set();
53
- const entries = [];
54
- for (const migration of migrations) {
73
+ return migrations.map((migration) => {
55
74
  applyMigrationSql(tables, migration.sql, `${migration.name}/up.sql`, droppedTables, { lockedHistory: lockedNames?.has(migration.name) === true });
56
- entries.push({
75
+ return {
57
76
  name: migration.name,
58
77
  sha256: checksum(migration.sql),
59
78
  tables: snapshotTables(tables),
60
- });
61
- }
62
- return { migrations: entries };
79
+ };
80
+ });
63
81
  }
64
- function lockFromHistory(history, formatVersion) {
65
- if (history.migrations.length === 0) {
82
+ function lockFromHistory(history, schemaVersions) {
83
+ const head = history.at(-1);
84
+ if (head === undefined)
66
85
  failLock('cannot lock an empty migration history');
67
- }
68
- if (formatVersion === LEGACY_MIGRATION_LOCK_FORMAT_VERSION) {
69
- return {
70
- formatVersion: LEGACY_MIGRATION_LOCK_FORMAT_VERSION,
71
- migrations: history.migrations,
72
- };
73
- }
74
- const head = history.migrations.at(-1);
75
86
  return {
76
87
  formatVersion: MIGRATION_LOCK_FORMAT_VERSION,
77
- migrations: history.migrations.map(({ name, sha256 }) => ({
78
- name,
79
- sha256,
80
- })),
88
+ migrations: history.map(({ name, sha256 }) => {
89
+ const version = schemaVersions.find((v) => v.migrations.includes(name));
90
+ if (version === undefined) {
91
+ throw new Error(`unreachable: migration ${name} has no schema version`);
92
+ }
93
+ return { name, sha256, schemaVersion: version.version };
94
+ }),
81
95
  head: { tables: head.tables },
82
96
  };
83
97
  }
84
- /** Build a deterministic lock document for a complete migration sequence. */
85
- export function buildMigrationLock(migrations, formatVersion = MIGRATION_LOCK_FORMAT_VERSION, lockedNames) {
86
- return lockFromHistory(buildMigrationHistory(migrations, lockedNames), formatVersion);
98
+ /** Build a deterministic lock document for a complete migration sequence;
99
+ * `declared` is the manifest's `schemaVersions`. */
100
+ export function buildMigrationLock(migrations, declared) {
101
+ return lockFromHistory(buildMigrationHistory(migrations), buildSchemaVersions(declared, migrations));
87
102
  }
88
103
  /** Fixed-order, byte-deterministic serialization for clean code review. */
89
104
  export function serializeMigrationLock(lock) {
@@ -151,27 +166,14 @@ function parseEntry(value, index) {
151
166
  const context = `migrations[${index}]`;
152
167
  if (!isRecord(value))
153
168
  failLock(`${context} must be an object`);
154
- const { name, sha256 } = value;
169
+ const { name, sha256, schemaVersion } = value;
155
170
  if (typeof name !== 'string' || name.length === 0) {
156
171
  failLock(`${context}.name must be a non-empty string`);
157
172
  }
158
173
  if (typeof sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(sha256)) {
159
174
  failLock(`${context}.sha256 must be a lowercase SHA-256 digest`);
160
175
  }
161
- return { name, sha256 };
162
- }
163
- function parseLegacyEntry(value, index) {
164
- const context = `migrations[${index}]`;
165
- const entry = parseEntry(value, index);
166
- if (!isRecord(value))
167
- failLock(`${context} must be an object`);
168
- const { tables } = value;
169
- if (!Array.isArray(tables))
170
- failLock(`${context}.tables must be an array`);
171
- return {
172
- ...entry,
173
- tables: tables.map((table, tableIndex) => parseTable(table, `${context}.tables[${tableIndex}]`)),
174
- };
176
+ return { name, sha256, schemaVersion };
175
177
  }
176
178
  function parseHead(value) {
177
179
  if (!isRecord(value))
@@ -182,15 +184,6 @@ function parseHead(value) {
182
184
  tables: value.tables.map((table, index) => parseTable(table, `head.tables[${index}]`)),
183
185
  };
184
186
  }
185
- function assertUniqueMigrationNames(migrations) {
186
- const names = new Set();
187
- for (const migration of migrations) {
188
- if (names.has(migration.name)) {
189
- failLock(`migration ${JSON.stringify(migration.name)} appears twice`);
190
- }
191
- names.add(migration.name);
192
- }
193
- }
194
187
  /** Parse and structurally validate a committed lock document. */
195
188
  export function parseMigrationLock(source) {
196
189
  let raw;
@@ -202,23 +195,39 @@ export function parseMigrationLock(source) {
202
195
  }
203
196
  if (!isRecord(raw))
204
197
  failLock('root must be an object');
205
- if (raw.formatVersion !== LEGACY_MIGRATION_LOCK_FORMAT_VERSION &&
206
- raw.formatVersion !== MIGRATION_LOCK_FORMAT_VERSION) {
207
- failLock(`formatVersion must be ${LEGACY_MIGRATION_LOCK_FORMAT_VERSION} or ${MIGRATION_LOCK_FORMAT_VERSION}, got ${JSON.stringify(raw.formatVersion)}`);
198
+ const { formatVersion } = raw;
199
+ if (formatVersion !== 1 &&
200
+ formatVersion !== 2 &&
201
+ formatVersion !== MIGRATION_LOCK_FORMAT_VERSION) {
202
+ failLock(`formatVersion must be 1, 2, or ${MIGRATION_LOCK_FORMAT_VERSION}, got ${JSON.stringify(formatVersion)}`);
208
203
  }
209
204
  if (!Array.isArray(raw.migrations) || raw.migrations.length === 0) {
210
205
  failLock('migrations must be a non-empty array');
211
206
  }
212
- if (raw.formatVersion === LEGACY_MIGRATION_LOCK_FORMAT_VERSION) {
213
- const migrations = raw.migrations.map(parseLegacyEntry);
214
- assertUniqueMigrationNames(migrations);
207
+ const entries = raw.migrations.map(parseEntry);
208
+ const names = new Set();
209
+ for (const { name } of entries) {
210
+ if (names.has(name)) {
211
+ failLock(`migration ${JSON.stringify(name)} appears twice`);
212
+ }
213
+ names.add(name);
214
+ }
215
+ if (formatVersion !== MIGRATION_LOCK_FORMAT_VERSION) {
215
216
  return {
216
- formatVersion: LEGACY_MIGRATION_LOCK_FORMAT_VERSION,
217
- migrations,
217
+ formatVersion,
218
+ migrations: entries.map(({ name, sha256 }) => ({ name, sha256 })),
218
219
  };
219
220
  }
220
- const migrations = raw.migrations.map(parseEntry);
221
- assertUniqueMigrationNames(migrations);
221
+ let previous = 1;
222
+ const migrations = entries.map(({ name, sha256, schemaVersion }, index) => {
223
+ if (typeof schemaVersion !== 'number' ||
224
+ !Number.isInteger(schemaVersion) ||
225
+ schemaVersion < previous) {
226
+ failLock(`migrations[${index}].schemaVersion must be an integer, at least 1 and at least the previous entry's`);
227
+ }
228
+ previous = schemaVersion;
229
+ return { name, sha256, schemaVersion };
230
+ });
222
231
  return {
223
232
  formatVersion: MIGRATION_LOCK_FORMAT_VERSION,
224
233
  migrations,
@@ -274,10 +283,10 @@ function describeColumnDifference(tableName, locked, current) {
274
283
  return undefined;
275
284
  }
276
285
  function firstSchemaDifference(locked, current) {
277
- const length = Math.max(locked.tables.length, current.tables.length);
286
+ const length = Math.max(locked.length, current.length);
278
287
  for (let index = 0; index < length; index++) {
279
- const before = locked.tables[index];
280
- const after = current.tables[index];
288
+ const before = locked[index];
289
+ const after = current[index];
281
290
  if (before === undefined && after !== undefined) {
282
291
  return `table ${JSON.stringify(after.name)} was added`;
283
292
  }
@@ -304,9 +313,8 @@ const REPAIR_HINT = 'deployed migrations are immutable; restore the locked migra
304
313
  * New migrations may be appended; existing names and bytes may never change.
305
314
  */
306
315
  function validateMigrationHistory(locked, current) {
307
- for (let index = 0; index < locked.migrations.length; index++) {
308
- const before = locked.migrations[index];
309
- const after = current.migrations[index];
316
+ locked.migrations.forEach((before, index) => {
317
+ const after = current[index];
310
318
  if (after === undefined) {
311
319
  failLock(`history drift at migration ${JSON.stringify(before.name)}: the locked migration is missing; ${REPAIR_HINT}`);
312
320
  }
@@ -314,33 +322,48 @@ function validateMigrationHistory(locked, current) {
314
322
  failLock(`history drift at position ${index + 1}: locked ${JSON.stringify(before.name)} but found ${JSON.stringify(after.name)}; migrations cannot be removed, renamed, or reordered; ${REPAIR_HINT}`);
315
323
  }
316
324
  if (before.sha256 !== after.sha256) {
317
- const diagnosticBefore = locked.formatVersion === LEGACY_MIGRATION_LOCK_FORMAT_VERSION
318
- ? locked.migrations[index]
319
- : {
320
- ...before,
321
- tables: locked.head.tables,
322
- };
323
- // Format 2 keeps one schema snapshot after the complete locked prefix.
324
- // Compare it with the current schema at that same boundary, excluding
325
- // valid newly appended migrations from the diagnostic.
326
- const diagnosticAfter = locked.formatVersion === LEGACY_MIGRATION_LOCK_FORMAT_VERSION
327
- ? after
328
- : (current.migrations[locked.migrations.length - 1] ?? after);
329
- failLock(`history drift in migration ${JSON.stringify(before.name)}: checksum changed; first schema difference: ${firstSchemaDifference(diagnosticBefore, diagnosticAfter)}; ${REPAIR_HINT}`);
325
+ // The head snapshot is the schema after the complete locked prefix:
326
+ // compare it with the current schema at that same boundary, excluding
327
+ // valid newly appended migrations. A legacy lock is read without one.
328
+ const difference = locked.formatVersion === MIGRATION_LOCK_FORMAT_VERSION
329
+ ? `; first schema difference: ${firstSchemaDifference(locked.head.tables, (current[locked.migrations.length - 1] ?? after).tables)}`
330
+ : '';
331
+ failLock(`history drift in migration ${JSON.stringify(before.name)}: checksum changed${difference}; ${REPAIR_HINT}`);
330
332
  }
331
- }
333
+ });
332
334
  }
333
335
  /**
334
- * Validate a committed lock against migration inputs and build its exact next
335
- * document. Ordinary generation preserves the committed format; upgrading a
336
- * version-1 lock is always an explicit command.
336
+ * Validate a committed lock against the migration inputs and their schema
337
+ * versions, and build its exact next document. A locked migration keeps its
338
+ * schema version; an appended migration belongs to a version above the
339
+ * highest locked one, because a deployed version never changes (§7.4).
337
340
  */
338
- export function updateMigrationLock(locked, migrations) {
341
+ export function updateMigrationLock(locked, migrations, declared) {
342
+ if (locked.formatVersion !== MIGRATION_LOCK_FORMAT_VERSION) {
343
+ throw new TypegenError(MIGRATION_LOCK_FILENAME, 'the lock predates per-migration schema versions; run `syncular migrations upgrade-lock` once and commit the lock', 'typegen.migration_lock_outdated', { formatVersion: locked.formatVersion });
344
+ }
339
345
  const current = buildMigrationHistory(migrations, lockedMigrationNames(locked));
340
346
  validateMigrationHistory(locked, current);
341
- return lockFromHistory(current, locked.formatVersion);
347
+ const next = lockFromHistory(current, buildSchemaVersions(declared, migrations));
348
+ const highestLockedVersion = locked.migrations.at(-1)?.schemaVersion ?? 0;
349
+ next.migrations.forEach(({ name, schemaVersion }, index) => {
350
+ const lockedVersion = locked.migrations[index]?.schemaVersion;
351
+ if (lockedVersion !== undefined && lockedVersion !== schemaVersion) {
352
+ throw new TypegenError(MIGRATION_LOCK_FILENAME, 'a locked migration moved to another schema version; a locked version keeps its migration set (§7.4)', 'typegen.migration_version_changed', { migration: name, lockedVersion, schemaVersion });
353
+ }
354
+ if (lockedVersion === undefined && schemaVersion <= highestLockedVersion) {
355
+ throw new TypegenError(MIGRATION_LOCK_FILENAME, 'an appended migration joins a locked schema version; declare a schema version above the highest locked one (§7.4)', 'typegen.schema_version_locked', { migration: name, schemaVersion, highestLockedVersion });
356
+ }
357
+ });
358
+ return next;
342
359
  }
343
- /** Validate without changing the committed lock format. */
344
- export function validateMigrationLock(locked, migrations) {
345
- validateMigrationHistory(locked, buildMigrationHistory(migrations, lockedMigrationNames(locked)));
360
+ /**
361
+ * Convert a format-1 or format-2 lock to the current format: validate its
362
+ * locked prefix and record the schema version the manifest's `declared`
363
+ * versions assign each locked migration. Appended migrations stay unlocked for generation.
364
+ */
365
+ export function upgradeMigrationLock(locked, migrations, declared) {
366
+ const current = buildMigrationHistory(migrations, lockedMigrationNames(locked));
367
+ validateMigrationHistory(locked, current);
368
+ return lockFromHistory(current.slice(0, locked.migrations.length), buildSchemaVersions(declared, migrations));
346
369
  }
package/dist/naming.d.ts CHANGED
@@ -1,8 +1,17 @@
1
+ import type { IrTable } from './ir.js';
1
2
  /** Manifest `"naming"`: camelCase emission (default) or SQL-truth names. */
2
3
  export type NamingMode = 'camel' | 'preserve';
3
4
  /** The pinned §12 snake→camel conversion. Non-identifier names (computed
4
5
  * result columns like `count(*)`) are returned unchanged. */
5
6
  export declare function snakeToCamel(name: string): string;
7
+ /** Generated type name of a table or subscription: `_`/`-` separated parts,
8
+ * each with its first character upper-cased (`project_tasks` →
9
+ * `ProjectTasks`). */
10
+ export declare function pascalCase(name: string): string;
11
+ /** `value` as a string literal of a schema emitter's language. Swift and
12
+ * Kotlin delimit with `"`, TS and Dart with `'`; Kotlin and Dart also escape
13
+ * the `$` that would start an interpolation. */
14
+ export declare function stringLiteral(value: string, target: Exclude<NamingTarget, 'rust'>): string;
6
15
  /** The emitter targets whose keyword sets we police. `ts` is included for
7
16
  * completeness (its emitters can quote any property, so its list is the
8
17
  * small set that breaks generated FUNCTION/const identifiers). */
@@ -30,3 +39,19 @@ export interface NameMapping {
30
39
  * run generates — keyword hazards are only real on targets that exist.
31
40
  */
32
41
  export declare function buildNamingMap(sqlNames: readonly string[], mode: NamingMode, context: string, scope: string, targets: readonly NamingTarget[]): NameMapping[];
42
+ /**
43
+ * The schema identifier rules for every configured target in both naming
44
+ * modes. Table names, and column names within a table, stay distinct under
45
+ * SQLite's case-insensitive comparison; generated type names
46
+ * (`pascalCase(table)`) stay distinct; each target's emitted column names
47
+ * stay distinct and clear of its reserved words. Swift, Kotlin, and Dart
48
+ * always emit camelCase fields; TS and Rust follow the naming mode.
49
+ */
50
+ export declare function validateSchemaIdentifiers(tables: readonly IrTable[], mode: NamingMode, targets: readonly NamingTarget[], context: string): void;
51
+ /**
52
+ * Refuse a query name, result column, or query input that some configured
53
+ * target cannot emit: TS uses the name as is, Rust its snake_case form, and
54
+ * Swift, Kotlin, and Dart its camelCase form. Each must be an identifier
55
+ * clear of the target's reserved words; Dart also refuses a leading `_`.
56
+ */
57
+ export declare function validateQueryIdentifier(name: string, targets: readonly NamingTarget[], context: string, scope: string): void;
package/dist/naming.js CHANGED
@@ -40,6 +40,31 @@ export function snakeToCamel(name) {
40
40
  .map((s) => s.charAt(0).toUpperCase() + s.slice(1));
41
41
  return lead + first + rest.join('') + trail;
42
42
  }
43
+ /** Generated type name of a table or subscription: `_`/`-` separated parts,
44
+ * each with its first character upper-cased (`project_tasks` →
45
+ * `ProjectTasks`). */
46
+ export function pascalCase(name) {
47
+ return name
48
+ .split(/[_-]+/)
49
+ .filter((part) => part.length > 0)
50
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
51
+ .join('');
52
+ }
53
+ /** `value` as a string literal of a schema emitter's language. Swift and
54
+ * Kotlin delimit with `"`, TS and Dart with `'`; Kotlin and Dart also escape
55
+ * the `$` that would start an interpolation. */
56
+ export function stringLiteral(value, target) {
57
+ const delimiter = target === 'swift' || target === 'kotlin' ? '"' : "'";
58
+ const interpolates = target === 'kotlin' || target === 'dart';
59
+ let body = '';
60
+ for (const char of value) {
61
+ body +=
62
+ char === '\\' || char === delimiter || (interpolates && char === '$')
63
+ ? `\\${char}`
64
+ : char;
65
+ }
66
+ return `${delimiter}${body}${delimiter}`;
67
+ }
43
68
  /** Reserved words that cannot be a generated field/property name on each
44
69
  * target. Deliberately the core keyword lists — mechanical and predictable
45
70
  * beats exhaustive; an escape hatch (`AS` alias / "preserve") always exists. */
@@ -362,3 +387,70 @@ export function buildNamingMap(sqlNames, mode, context, scope, targets) {
362
387
  langName: bySqlName.get(sqlName),
363
388
  }));
364
389
  }
390
+ /**
391
+ * The schema identifier rules for every configured target in both naming
392
+ * modes. Table names, and column names within a table, stay distinct under
393
+ * SQLite's case-insensitive comparison; generated type names
394
+ * (`pascalCase(table)`) stay distinct; each target's emitted column names
395
+ * stay distinct and clear of its reserved words. Swift, Kotlin, and Dart
396
+ * always emit camelCase fields; TS and Rust follow the naming mode.
397
+ */
398
+ export function validateSchemaIdentifiers(tables, mode, targets, context) {
399
+ const distinct = (names, key, code, message, details = {}) => {
400
+ const seen = new Map();
401
+ for (const name of names) {
402
+ const other = seen.get(key(name));
403
+ if (other !== undefined) {
404
+ throw new TypegenError(context, message, code, {
405
+ ...details,
406
+ names: [other, name],
407
+ });
408
+ }
409
+ seen.set(key(name), name);
410
+ }
411
+ };
412
+ const caseless = (name) => name.toLowerCase();
413
+ const tableNames = tables.map((table) => table.name);
414
+ distinct(tableNames, caseless, 'typegen.duplicate_identifier', 'two table names differ only in letter case; SQLite compares identifiers case-insensitively');
415
+ distinct(tableNames, pascalCase, 'typegen.identifier_collision', 'two tables map to one generated type name');
416
+ for (const table of tables) {
417
+ const columnNames = table.columns.map((column) => column.name);
418
+ distinct(columnNames, caseless, 'typegen.duplicate_identifier', 'two column names differ only in letter case; SQLite compares identifiers case-insensitively', { table: table.name });
419
+ for (const target of targets) {
420
+ const emit = (name) => {
421
+ const langName = mode === 'camel' || (target !== 'ts' && target !== 'rust')
422
+ ? snakeToCamel(name)
423
+ : name;
424
+ return target === 'rust' ? rustSnakeCase(langName) : langName;
425
+ };
426
+ distinct(columnNames, emit, 'typegen.identifier_collision', 'two columns map to one generated field name', { target, table: table.name });
427
+ for (const column of columnNames) {
428
+ const emitted = emit(column);
429
+ if (TARGET_KEYWORDS[target].has(emitted) ||
430
+ (target === 'dart' && emitted.startsWith('_'))) {
431
+ throw new TypegenError(context, 'a column maps to a generated field name that is a reserved word or library-private on an emitter target; rename the column', 'typegen.reserved_identifier', { target, table: table.name, column, emitted });
432
+ }
433
+ }
434
+ }
435
+ }
436
+ }
437
+ /**
438
+ * Refuse a query name, result column, or query input that some configured
439
+ * target cannot emit: TS uses the name as is, Rust its snake_case form, and
440
+ * Swift, Kotlin, and Dart its camelCase form. Each must be an identifier
441
+ * clear of the target's reserved words; Dart also refuses a leading `_`.
442
+ */
443
+ export function validateQueryIdentifier(name, targets, context, scope) {
444
+ for (const target of targets) {
445
+ const emitted = target === 'rust'
446
+ ? rustSnakeCase(name)
447
+ : target === 'ts'
448
+ ? name
449
+ : snakeToCamel(name);
450
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(emitted) ||
451
+ TARGET_KEYWORDS[target].has(emitted) ||
452
+ (target === 'dart' && emitted.startsWith('_'))) {
453
+ throw new TypegenError(context, 'a query name, result column, or query input is not a valid identifier on an emitter target; rename it or alias it in SQL (AS)', 'typegen.invalid_query_identifier', { target, scope, name, emitted });
454
+ }
455
+ }
456
+ }
package/dist/query.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type SyqlToken } from './syql-lexer.js';
1
2
  import type { IrColumnType, IrDocument } from './ir.js';
2
3
  import { type NamingMode, type NamingTarget } from './naming.js';
3
4
  /** A param type is one of the §2.4 types (the columns params compare to). */
@@ -20,7 +21,7 @@ export interface QueryColumn {
20
21
  readonly type: IrColumnType;
21
22
  readonly nullable: boolean;
22
23
  /** `exact` = resolved to an IR column (plain ref); `fallback` = a computed
23
- * expression typed by the documented honest fallback. */
24
+ * expression typed by its `CAST` or `count()` (SYQL §14.1). */
24
25
  readonly fidelity: 'exact' | 'fallback';
25
26
  /** Proven physical origin for reactive row identity and diagnostics. */
26
27
  readonly origin?: {
@@ -43,6 +44,20 @@ export interface QueryCoverageBinding {
43
44
  readonly params: readonly string[];
44
45
  }[];
45
46
  }
47
+ /** The window bases (SPEC §4.8) a query's coverage needs, for generated
48
+ * descriptors. A base names no table, so tables proven by the same base share
49
+ * one entry; a fixed scope bound to several params yields one base per value
50
+ * combination, since a base holds one value per fixed variable. Ordered by
51
+ * code point of the JSON so emitted metadata is byte-identical across
52
+ * locales. */
53
+ export declare function windowBases(coverage: readonly QueryCoverageBinding[]): {
54
+ readonly variable: string;
55
+ readonly units: readonly string[];
56
+ readonly fixedScopes: readonly {
57
+ variable: string;
58
+ param: string;
59
+ }[];
60
+ }[];
46
61
  export interface QueryReactiveMetadata {
47
62
  readonly dependencies: readonly {
48
63
  readonly table: string;
@@ -162,6 +177,16 @@ export interface QueryRelation {
162
177
  readonly end: number;
163
178
  readonly alias?: string;
164
179
  }
180
+ /** The findings of the query plan check (`docs/SYQL.md` §14.5). */
181
+ export declare const QUERY_PLAN_FINDINGS: readonly ['scan', 'automatic_index', 'unbounded', 'many_tables'];
182
+ export type QueryPlanFinding = (typeof QUERY_PLAN_FINDINGS)[number];
183
+ /** An author's acknowledgement of one plan finding, with its reason. */
184
+ export interface QueryAcknowledgement {
185
+ readonly finding: QueryPlanFinding;
186
+ /** Absent for `many_tables`. */
187
+ readonly table?: string;
188
+ readonly reason: string;
189
+ }
165
190
  export interface AnalyzedQuery {
166
191
  /** camelCase function name (path-derived, or a `-- name:` override). */
167
192
  readonly name: string;
@@ -187,7 +212,11 @@ export interface AnalyzedQuery {
187
212
  /** Revision-1 frontend/public-input and physical execution contract. When
188
213
  * present, emitters use this instead of treating `params` as the API. */
189
214
  readonly syql?: QuerySyqlMetadata;
215
+ /** Plan findings the author acknowledged on the statement. */
216
+ readonly acknowledgements: readonly QueryAcknowledgement[];
190
217
  }
218
+ /** The public SYQL input an emitter binds by name. */
219
+ export declare function syqlInput(query: AnalyzedQuery, name: string): QuerySyqlPublicInput;
191
220
  /**
192
221
  * Path-relative default name. `billing/invoices/list.sql` → `billingInvoicesList`;
193
222
  * a flat `list-todos.sql` → `listTodos` (unchanged). Every folder segment AND
@@ -206,19 +235,19 @@ export interface SplitStatement {
206
235
  /** 1-based line number of the statement's first character in the file. */
207
236
  readonly startLine: number;
208
237
  }
209
- /** Split file content into statements on top-level `;` (string/comment-aware).
210
- * Blank/comment-only tails are dropped; each statement keeps its own leading
211
- * comment block (everything between the previous `;` and this SQL). */
212
- export declare function splitStatements(content: string): SplitStatement[];
238
+ /** Split file content into statements on top-level `;` tokens. A statement
239
+ * keeps its leading comment block; comment-only parts are dropped. The
240
+ * SELECT-only subset has no BEGIN/END blocks, so every `;` token ends one
241
+ * statement and a trailing `;` is optional. */
242
+ export declare function splitStatements(content: string, file?: string): SplitStatement[];
213
243
  /** The `-- name:` override in a statement's leading comment block, or null. */
214
244
  export declare function parseStatementName(statementText: string, location: string): string | null;
215
- /** Strip `--` and block comments so identifier scans don't hit commented SQL,
216
- * and string literals so `':x'` inside a string isn't read as a param. */
245
+ /** Blank comments and string/blob literals with spaces (newlines kept), so
246
+ * offset-preserving text scans never read inside them. */
217
247
  export declare function stripCommentsAndStrings(sql: string): string;
218
- /** Rewrite `:name` → positional placeholders AND strip comments + collapse
219
- * whitespace, producing a clean single-line SQL string suitable for
220
- * embedding in a generated string literal. String literals are preserved
221
- * verbatim (their inner whitespace is not collapsed).
248
+ /** The emitted single-line statement: `:name` binds become positional, every
249
+ * whitespace/comment run between tokens becomes one space, and every other
250
+ * token (string literals, quoted identifiers) keeps its exact text.
222
251
  *
223
252
  * When every param occurs exactly once, plain `?` is emitted. When ANY
224
253
  * param repeats (the §7 neutralization guards mention a param in the guard
@@ -236,6 +265,8 @@ export interface TableRef {
236
265
  /** True when an enclosing flat join chain can null-extend this relation. */
237
266
  readonly nullable: boolean;
238
267
  }
268
+ /** The name a plain or quoted identifier token spells. */
269
+ export declare function sqlIdentifier(token: SyqlToken | undefined): string | undefined;
239
270
  /** A common table expression read in a FROM/JOIN position. */
240
271
  export interface CteRef {
241
272
  /** Lowercased CTE name. */
@@ -268,6 +299,41 @@ export declare function scanTableRefs(sql: string, ir: IrDocument, lowered?: boo
268
299
  /** `lowered` scans emitted SQL, whose FTS mapping reads
269
300
  * ({@link lowerFtsSourceIds}) are internal and not relations of the query. */
270
301
  export declare function scanRelations(sql: string, ir: IrDocument, lowered?: boolean): SqlRelations;
302
+ /** A declared scope column of one table instance: the instance's SELECT scope
303
+ * ({@link SqlRelations.scopeAt}), lowercased alias, and lowercased column. */
304
+ export interface ScopeColumn {
305
+ readonly scope: string;
306
+ readonly alias: string;
307
+ readonly column: string;
308
+ }
309
+ export interface ScopeProofs {
310
+ /** `column = :bind`, `:bind = column`, `column IS :bind`, and
311
+ * `column IN (:a, :b)` conjuncts of a WHERE clause. */
312
+ readonly binds: readonly (ScopeColumn & {
313
+ readonly operator: 'equal' | 'in';
314
+ readonly params: readonly string[];
315
+ })[];
316
+ /** Qualified `a.x = b.y` conjuncts. A symmetric equality (a WHERE conjunct
317
+ * or an inner-join ON conjunct) proves each operand from the other; an
318
+ * outer-join ON conjunct proves only `target` from `source`. */
319
+ readonly equalities: readonly {
320
+ readonly target: ScopeColumn;
321
+ readonly source: ScopeColumn;
322
+ readonly symmetric: boolean;
323
+ }[];
324
+ }
325
+ /**
326
+ * The scope-proof rule shared by `.sql` and `.syql` queries (SYQL §13). A
327
+ * comparison proves a scope only when it is a whole top-level conjunct of
328
+ * the WHERE clause of the SELECT scope that reads the instance: the outer
329
+ * statement or a top-level CTE body. Parentheses around a whole conjunct are
330
+ * transparent. Nothing else is a proof: a WHERE clause with a top-level OR, a
331
+ * compound SELECT scope, a nested subquery, and any other conjunct shape (NOT,
332
+ * a comparison of the comparison, a function, CASE, COLLATE, IS after the
333
+ * bind, a literal in an IN list). Column equalities also come from the
334
+ * conjuncts of an ON clause without OR, NOT, or a subquery.
335
+ */
336
+ export declare function scopeProofs(sql: string, ir: IrDocument): ScopeProofs;
271
337
  export interface SelectItem {
272
338
  /** The raw expression text (before any `AS alias`). */
273
339
  readonly expr: string;
@@ -279,11 +345,11 @@ export interface SelectItem {
279
345
  export declare function splitSelectList(sql: string): SelectItem[] | null;
280
346
  export declare const PLAIN_REF_RE: RegExp;
281
347
  /**
282
- * Return every revision-1 column/LIKE type constraint for one bind. Unlike
283
- * `inferParamType` (the legacy first-match helper), SYQL uses the complete set
284
- * so conflicting checked uses cannot be silently accepted.
348
+ * Every column/LIKE/MATCH type constraint on one bind, in pattern order. A
349
+ * `.sql` query takes the first; SYQL rejects conflicting evidence.
285
350
  */
286
351
  export declare function inferParamTypeEvidence(paramName: string, sql: string, refs: readonly TableRef[], ir: IrDocument): readonly IrColumnType[];
352
+ export declare const AGGREGATE_FUNCTIONS: Set<string>;
287
353
  export interface QueryDb {
288
354
  /** Prepare + return the result columns / declared types / param count.
289
355
  * Throws (with SQLite's message) when the SQL is invalid against the DDL. */
@@ -292,6 +358,14 @@ export interface QueryDb {
292
358
  declaredTypes: readonly (string | null)[];
293
359
  paramsCount: number;
294
360
  };
361
+ /** The `EXPLAIN QUERY PLAN` rows of `sql`. With `index`, a `CREATE INDEX`
362
+ * statement, SQLite plans as if that index existed; the database keeps no
363
+ * trace of it afterwards. */
364
+ plan(sql: string, index?: string): readonly {
365
+ id: number;
366
+ parent: number;
367
+ detail: string;
368
+ }[];
295
369
  }
296
370
  /** Synthesize the schema DDL from the IR (the reverse of the migration
297
371
  * parser): a `CREATE TABLE` per IR table with each column's declared SQLite
@@ -337,3 +411,9 @@ export declare function analyzeQueryFile(relPath: string, content: string, ir: I
337
411
  * (or a `-- name:` override) and analyze. Rejects a `;`-separated file loudly
338
412
  * — use {@link analyzeQueryFile} for the multi-statement contract. */
339
413
  export declare function analyzeQuery(file: string, raw: string, ir: IrDocument, db: QueryDb, naming?: QueryNamingOptions): AnalyzedQuery;
414
+ /**
415
+ * The query plan check (`docs/SYQL.md` §14.5): plan every physical statement
416
+ * against the schema database and fail on the first finding the query does
417
+ * not acknowledge, then on the first acknowledgement that matches no finding.
418
+ */
419
+ export declare function checkQueryPlan(query: AnalyzedQuery, ir: IrDocument, db: QueryDb): void;