@syncular/typegen 0.59.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 (47) hide show
  1. package/README.md +53 -18
  2. package/dist/emit-dart.js +7 -18
  3. package/dist/emit-kotlin.d.ts +1 -1
  4. package/dist/emit-kotlin.js +9 -20
  5. package/dist/emit-queries-rust.js +18 -14
  6. package/dist/emit-queries.js +19 -23
  7. package/dist/emit-swift.d.ts +1 -1
  8. package/dist/emit-swift.js +9 -20
  9. package/dist/emit.d.ts +2 -2
  10. package/dist/emit.js +9 -20
  11. package/dist/fmt.js +11 -2
  12. package/dist/generate.js +31 -26
  13. package/dist/init.js +4 -5
  14. package/dist/ir.d.ts +3 -2
  15. package/dist/ir.js +1 -2
  16. package/dist/lsp.js +6 -1
  17. package/dist/manifest.d.ts +1 -2
  18. package/dist/manifest.js +13 -12
  19. package/dist/query.d.ts +40 -0
  20. package/dist/query.js +159 -0
  21. package/dist/syql-ast.d.ts +2 -0
  22. package/dist/syql-ast.js +7 -1
  23. package/dist/syql-browser.js +7 -6
  24. package/dist/syql-diagnostics.d.ts +1 -0
  25. package/dist/syql-diagnostics.js +1 -0
  26. package/dist/syql-lowering.js +1 -0
  27. package/dist/syql-parser.d.ts +4 -1
  28. package/dist/syql-parser.js +42 -5
  29. package/package.json +3 -3
  30. package/src/emit-dart.ts +11 -22
  31. package/src/emit-kotlin.ts +13 -26
  32. package/src/emit-queries-rust.ts +22 -19
  33. package/src/emit-queries.ts +23 -38
  34. package/src/emit-swift.ts +15 -24
  35. package/src/emit.ts +15 -22
  36. package/src/fmt.ts +10 -2
  37. package/src/generate.ts +44 -36
  38. package/src/init.ts +4 -5
  39. package/src/ir.ts +4 -4
  40. package/src/lsp.ts +11 -4
  41. package/src/manifest.ts +22 -18
  42. package/src/query.ts +251 -0
  43. package/src/syql-ast.ts +9 -0
  44. package/src/syql-browser.ts +8 -7
  45. package/src/syql-diagnostics.ts +2 -0
  46. package/src/syql-lowering.ts +1 -0
  47. package/src/syql-parser.ts +73 -8
@@ -6,7 +6,7 @@
6
6
  * from a raw string (fed straight into `SyncularClient.create(schema = …)`),
7
7
  * - one `data class` per table with typed properties (per the six §2.4 column
8
8
  * types + blob_ref/crdt) and a `fromRow(row: JsonValue)` companion factory,
9
- * - a `Subscriptions` object of typed requested-scope builders.
9
+ * - a `Subscriptions` object of typed unit-template builders (SPEC §4.1).
10
10
  *
11
11
  * The row shape is `JsonValue` — the exact type the Kotlin wrapper's
12
12
  * `query`/`readRows` return (each row a `JsonValue.Obj`). The header carries
@@ -89,39 +89,26 @@ function emitDataClass(table: IrTable): string[] {
89
89
  }
90
90
 
91
91
  function emitSubscription(sub: IrSubscription): string[] {
92
- const params: string[] = [];
93
- for (const scope of sub.scopes) {
94
- for (const value of scope.values) {
95
- if (value.kind === 'parameter' && !params.includes(value.name)) {
96
- params.push(value.name);
97
- }
98
- }
99
- }
92
+ const params = [
93
+ ...new Set(
94
+ sub.scopes.flatMap(({ value }) =>
95
+ value.kind === 'parameter' ? [value.name] : [],
96
+ ),
97
+ ),
98
+ ];
100
99
  const lines: string[] = [];
101
100
  lines.push(
102
- ` /** Requested-scope template for the ${stringLiteral(sub.name, 'kotlin')} subscription. */`,
101
+ ` /** Unit template for the ${stringLiteral(sub.name, 'kotlin')} subscription (SPEC §4.1). */`,
103
102
  );
104
103
  lines.push(` object ${pascalCase(sub.name)} {`);
105
104
  lines.push(
106
105
  ` const val name = ${stringLiteral(sub.name, 'kotlin')}`,
107
106
  );
108
- lines.push(
109
- ` const val table = ${stringLiteral(sub.table, 'kotlin')}`,
110
- );
111
107
  const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
112
- lines.push(
113
- ` fun scopes(${args}): Map<String, List<String>> = mapOf(`,
114
- );
115
- for (const scope of sub.scopes) {
116
- const values = scope.values
117
- .map((value) =>
118
- value.kind === 'literal'
119
- ? stringLiteral(value.value, 'kotlin')
120
- : snakeToCamel(value.name),
121
- )
122
- .join(', ');
108
+ lines.push(` fun scopes(${args}): Map<String, String> = mapOf(`);
109
+ for (const { variable, value } of sub.scopes) {
123
110
  lines.push(
124
- ` ${stringLiteral(scope.variable, 'kotlin')} to listOf(${values}),`,
111
+ ` ${stringLiteral(variable, 'kotlin')} to ${value.kind === 'literal' ? stringLiteral(value.value, 'kotlin') : snakeToCamel(value.name)},`,
125
112
  );
126
113
  }
127
114
  lines.push(' )');
@@ -166,7 +153,7 @@ export function emitKotlinModule(
166
153
  schemaLines.push(' )');
167
154
  schemaLines.push('');
168
155
  schemaLines.push(
169
- ' /** Typed requested-scope builders per subscription. */',
156
+ ' /** Typed unit-template builders per subscription (SPEC §4.1). */',
170
157
  );
171
158
  schemaLines.push(' object Subscriptions {');
172
159
  if (ir.subscriptions.length === 0) {
@@ -13,6 +13,7 @@ import {
13
13
  type QuerySyqlPlanBind,
14
14
  type QuerySyqlPublicInput,
15
15
  syqlInput,
16
+ windowBases,
16
17
  } from './query';
17
18
 
18
19
  const RUST_TYPE: Readonly<Record<IrColumnType, string>> = {
@@ -526,32 +527,33 @@ function emitDependencies(query: AnalyzedQuery): string[] {
526
527
  }
527
528
 
528
529
  function emitCoverage(query: AnalyzedQuery): string[] {
529
- const usesParams = query.reactive.coverage.some(
530
- (coverage) =>
531
- coverage.units.length > 0 ||
532
- coverage.fixedScopes.some((scope) => scope.params.length > 0),
533
- );
530
+ const coverage = windowBases(query.reactive.coverage);
534
531
  const lines = [
535
- ` pub fn coverage(${usesParams ? 'params' : '_params'}: &Params) -> Vec<WindowCoverage> {`,
532
+ ` pub fn coverage(${coverage.length > 0 ? 'params' : '_params'}: &Params) -> Vec<WindowCoverage> {`,
536
533
  ' vec![',
537
534
  ];
538
- for (const coverage of query.reactive.coverage) {
539
- const fixed = coverage.fixedScopes.map((scope) => {
540
- const values = scope.params
541
- .map((param) => reactiveParam(query, param))
542
- .join(', ');
543
- return `(${quote(scope.variable)}.to_owned(), vec![${values}])`;
544
- });
545
- const units = coverage.units
535
+ for (const entry of coverage) {
536
+ const fixed = entry.fixedScopes.map(
537
+ (scope) =>
538
+ `(${quote(scope.variable)}.to_owned(), ${reactiveParam(query, scope.param)})`,
539
+ );
540
+ const units = entry.units
546
541
  .map((param) => reactiveParam(query, param))
547
542
  .join(', ');
543
+ const fixedLine = ` fixed_scopes: UnitScopes::from([${fixed.join(', ')}]),`;
548
544
  lines.push(
549
545
  ' WindowCoverage {',
550
546
  ' base: WindowBase {',
551
- ` table: ${quote(coverage.table)}.to_owned(),`,
552
- ` variable: ${quote(coverage.variable)}.to_owned(),`,
553
- ` fixed_scopes: vec![${fixed.join(', ')}],`,
554
- ' params: None,',
547
+ ` variable: ${quote(entry.variable)}.to_owned(),`,
548
+ ...(fixed.length === 0
549
+ ? [' fixed_scopes: UnitScopes::new(),']
550
+ : fixedLine.length <= 100
551
+ ? [fixedLine]
552
+ : [
553
+ ' fixed_scopes: UnitScopes::from([',
554
+ ...fixed.map((pair) => ` ${pair},`),
555
+ ' ]),',
556
+ ]),
555
557
  ' },',
556
558
  ` units: vec![${units}],`,
557
559
  ' },',
@@ -715,7 +717,8 @@ function emitSupport(clientCrate: string): string {
715
717
  'use std::error::Error;',
716
718
  'use std::fmt;',
717
719
  `use ${clientCrate}::{`,
718
- ' CoverageSnapshot, QueryOwner, QueryRow, QueryValue, SyncClient, WindowBase, WindowCoverage,',
720
+ ' CoverageSnapshot, QueryOwner, QueryRow, QueryValue, SyncClient, UnitScopes, WindowBase,',
721
+ ' WindowCoverage,',
719
722
  '};',
720
723
  '',
721
724
  '#[derive(Debug, Clone, PartialEq, Eq, Default)]',
@@ -23,6 +23,7 @@ import {
23
23
  type QueryParam,
24
24
  type QuerySyqlPlanBind,
25
25
  syqlInput,
26
+ windowBases,
26
27
  } from './query';
27
28
 
28
29
  const TS_TYPE: Readonly<Record<IrColumnType, string>> = {
@@ -98,6 +99,24 @@ function reactiveParam(query: AnalyzedQuery, name: string): string {
98
99
  return `String(params.${propertyKey(param.langName)})`;
99
100
  }
100
101
 
102
+ /** The `coverage` member's opening line and one line per window base. */
103
+ function emitCoverage(query: AnalyzedQuery): string[] {
104
+ const coverage = windowBases(query.reactive.coverage);
105
+ return [
106
+ ` coverage: (${coverage.length > 0 ? 'params' : ''}) => [`,
107
+ ...coverage.map((entry) => {
108
+ const fixed = entry.fixedScopes
109
+ .map(
110
+ (scope) =>
111
+ `${propertyKey(scope.variable)}: ${reactiveParam(query, scope.param)}`,
112
+ )
113
+ .join(', ');
114
+ const fixedPart = fixed.length > 0 ? `, fixedScopes: { ${fixed} }` : '';
115
+ return ` { base: { variable: ${quote(entry.variable)}${fixedPart} }, units: [${entry.units.map((param) => reactiveParam(query, param)).join(', ')}] },`;
116
+ }),
117
+ ];
118
+ }
119
+
101
120
  function syqlTsValueType(type: IrColumnType, nullable: boolean): string {
102
121
  return `${SYQL_PARAM_TS_TYPE[type]}${nullable ? ' | null' : ''}`;
103
122
  }
@@ -412,23 +431,7 @@ function emitSyqlQuery(query: AnalyzedQuery, hash: string): string {
412
431
  );
413
432
  }
414
433
  lines.push(' ],');
415
- const coverageUsesParams = query.reactive.coverage.some(
416
- (coverage) =>
417
- coverage.units.length > 0 ||
418
- coverage.fixedScopes.some((scope) => scope.params.length > 0),
419
- );
420
- lines.push(` coverage: (${coverageUsesParams ? 'params' : ''}) => [`);
421
- for (const coverage of query.reactive.coverage) {
422
- const fixed = coverage.fixedScopes
423
- .map(
424
- (scope) =>
425
- `${propertyKey(scope.variable)}: [${scope.params.map((param) => reactiveParam(query, param)).join(', ')}]`,
426
- )
427
- .join(', ');
428
- lines.push(
429
- ` { base: { table: ${quote(coverage.table)}, variable: ${quote(coverage.variable)}${fixed.length > 0 ? `, fixedScopes: { ${fixed} }` : ''} }, units: [${coverage.units.map((param) => reactiveParam(query, param)).join(', ')}] },`,
430
- );
431
- }
434
+ lines.push(...emitCoverage(query));
432
435
  lines.push(
433
436
  ' ],',
434
437
  hasParams
@@ -556,24 +559,7 @@ function emitQuery(query: AnalyzedQuery, hash: string): string {
556
559
  );
557
560
  }
558
561
  lines.push(' ],');
559
- const coverageUsesParams = query.reactive.coverage.some(
560
- (coverage) =>
561
- coverage.units.length > 0 ||
562
- coverage.fixedScopes.some((scope) => scope.params.length > 0),
563
- );
564
- lines.push(` coverage: (${coverageUsesParams ? 'params' : ''}) => [`);
565
- for (const coverage of query.reactive.coverage) {
566
- const fixed = coverage.fixedScopes
567
- .map(
568
- (scope) =>
569
- `${propertyKey(scope.variable)}: [${scope.params.map((param) => reactiveParam(query, param)).join(', ')}]`,
570
- )
571
- .join(', ');
572
- const fixedPart = fixed.length > 0 ? `, fixedScopes: { ${fixed} }` : '';
573
- lines.push(
574
- ` { base: { table: ${quote(coverage.table)}, variable: ${quote(coverage.variable)}${fixedPart} }, units: [${coverage.units.map((param) => reactiveParam(query, param)).join(', ')}] },`,
575
- );
576
- }
562
+ lines.push(...emitCoverage(query));
577
563
  lines.push(' ],');
578
564
  if (hasParams) {
579
565
  lines.push(` bind: (params: ${Params}) => ${positional},`);
@@ -714,12 +700,11 @@ export function emitQueriesModule(
714
700
  ' readonly nullable: boolean;',
715
701
  '}',
716
702
  '',
703
+ '/** A window base (SPEC §4.8) and the unit values a query reads. */',
717
704
  'export interface WindowCoverage {',
718
705
  ' readonly base: {',
719
- ' readonly table: string;',
720
706
  ' readonly variable: string;',
721
- ' readonly fixedScopes?: Readonly<Record<string, readonly string[]>>;',
722
- ' readonly params?: string;',
707
+ ' readonly fixedScopes?: Readonly<Record<string, string>>;',
723
708
  ' };',
724
709
  ' readonly units: readonly string[];',
725
710
  '}',
package/src/emit-swift.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * types, plus blob_ref/crdt in their honest Swift shapes) and a
9
9
  * `init?(row:)` from a `[String: JSONValue]` (the shape `query`/`readRows`
10
10
  * return),
11
- * - a `subscriptions` namespace of typed requested-scope builders.
11
+ * - a `subscriptions` namespace of typed unit-template builders (SPEC §4.1).
12
12
  *
13
13
  * The file imports only `Syncular` (for `JSONValue`). The header carries the
14
14
  * IR hash so `--check` verifies freshness byte-exactly, exactly like the TS
@@ -113,40 +113,29 @@ function emitStruct(table: IrTable): string[] {
113
113
  }
114
114
 
115
115
  function emitSubscription(sub: IrSubscription): string[] {
116
- const params: string[] = [];
117
- for (const scope of sub.scopes) {
118
- for (const value of scope.values) {
119
- if (value.kind === 'parameter' && !params.includes(value.name)) {
120
- params.push(value.name);
121
- }
122
- }
123
- }
116
+ const params = [
117
+ ...new Set(
118
+ sub.scopes.flatMap(({ value }) =>
119
+ value.kind === 'parameter' ? [value.name] : [],
120
+ ),
121
+ ),
122
+ ];
124
123
  const lines: string[] = [];
125
124
  lines.push(
126
- ` /// Requested-scope template for the ${stringLiteral(sub.name, 'swift')} subscription.`,
125
+ ` /// Unit template for the ${stringLiteral(sub.name, 'swift')} subscription (SPEC §4.1).`,
127
126
  );
128
127
  lines.push(` public enum ${pascalCase(sub.name)} {`);
129
128
  lines.push(
130
129
  ` public static let name = ${stringLiteral(sub.name, 'swift')}`,
131
130
  );
132
- lines.push(
133
- ` public static let table = ${stringLiteral(sub.table, 'swift')}`,
134
- );
135
131
  const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
136
132
  lines.push(
137
- ` public static func scopes(${args}) -> [String: [String]] {`,
133
+ ` public static func scopes(${args}) -> [String: String] {`,
138
134
  );
139
135
  lines.push(' [');
140
- for (const scope of sub.scopes) {
141
- const values = scope.values
142
- .map((value) =>
143
- value.kind === 'literal'
144
- ? stringLiteral(value.value, 'swift')
145
- : snakeToCamel(value.name),
146
- )
147
- .join(', ');
136
+ for (const { variable, value } of sub.scopes) {
148
137
  lines.push(
149
- ` ${stringLiteral(scope.variable, 'swift')}: [${values}],`,
138
+ ` ${stringLiteral(variable, 'swift')}: ${value.kind === 'literal' ? stringLiteral(value.value, 'swift') : snakeToCamel(value.name)},`,
150
139
  );
151
140
  }
152
141
  lines.push(' ]');
@@ -194,7 +183,9 @@ export function emitSwiftModule(
194
183
  schemaLines.push(' """)');
195
184
  schemaLines.push('');
196
185
  // Subscriptions namespace nested in the schema enum.
197
- schemaLines.push(' /// Typed requested-scope builders per subscription.');
186
+ schemaLines.push(
187
+ ' /// Typed unit-template builders per subscription (SPEC §4.1).',
188
+ );
198
189
  schemaLines.push(' public enum subscriptions {');
199
190
  if (ir.subscriptions.length === 0) {
200
191
  schemaLines.push(' // (no subscriptions declared)');
package/src/emit.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  * - a `<Table>Row` interface per table,
7
7
  * - `<Table>Insert` / `<Table>Update` mutation-input shapes honoring
8
8
  * nullability,
9
- * - a `<name>Subscription` helper constant per manifest subscription with
10
- * a typed requested-scopes builder.
9
+ * - a `<name>Subscription` helper constant per manifest unit template with
10
+ * a typed builder of its unit scope map (SPEC §4.1).
11
11
  *
12
12
  * The header carries the IR hash so `--check` verifies freshness
13
13
  * byte-exactly.
@@ -117,14 +117,13 @@ function emitTableDescriptor(table: IrTable, naming: NamingMode): string {
117
117
  }
118
118
 
119
119
  function emitSubscription(sub: IrSubscription): string {
120
- const params: string[] = [];
121
- for (const scope of sub.scopes) {
122
- for (const value of scope.values) {
123
- if (value.kind === 'parameter' && !params.includes(value.name)) {
124
- params.push(value.name);
125
- }
126
- }
127
- }
120
+ const params = [
121
+ ...new Set(
122
+ sub.scopes.flatMap(({ value }) =>
123
+ value.kind === 'parameter' ? [value.name] : [],
124
+ ),
125
+ ),
126
+ ];
128
127
  const lines: string[] = [];
129
128
  const paramsType = `${pascalCase(sub.name)}Params`;
130
129
  if (params.length > 0) {
@@ -136,22 +135,16 @@ function emitSubscription(sub: IrSubscription): string {
136
135
  lines.push('');
137
136
  }
138
137
  lines.push(
139
- `/** Requested-scope template for the ${stringLiteral(sub.name, 'ts')} subscription. */`,
138
+ `/** Unit template for the ${stringLiteral(sub.name, 'ts')} subscription (SPEC §4.1). */`,
140
139
  );
141
140
  lines.push(`export const ${sub.name}Subscription = {`);
142
141
  lines.push(` name: ${stringLiteral(sub.name, 'ts')},`);
143
- lines.push(` table: ${stringLiteral(sub.table, 'ts')},`);
144
142
  const args = params.length > 0 ? `params: ${paramsType}` : '';
145
- lines.push(` scopes: (${args}): Record<string, string[]> => ({`);
146
- for (const scope of sub.scopes) {
147
- const values = scope.values
148
- .map((value) =>
149
- value.kind === 'literal'
150
- ? stringLiteral(value.value, 'ts')
151
- : `params.${propertyKey(value.name)}`,
152
- )
153
- .join(', ');
154
- lines.push(` ${propertyKey(scope.variable)}: [${values}],`);
143
+ lines.push(` scopes: (${args}): Record<string, string> => ({`);
144
+ for (const { variable, value } of sub.scopes) {
145
+ lines.push(
146
+ ` ${propertyKey(variable)}: ${value.kind === 'literal' ? stringLiteral(value.value, 'ts') : `params.${propertyKey(value.name)}`},`,
147
+ );
155
148
  }
156
149
  lines.push(' }),');
157
150
  lines.push('} as const;');
package/src/fmt.ts CHANGED
@@ -267,6 +267,7 @@ function formatTokens(parsed: SyqlSyntaxFile): string {
267
267
  let importList = false;
268
268
  let justClosedImportList = false;
269
269
  let seenTopLevel = false;
270
+ let acknowledging = false;
270
271
  let pendingBetween = 0;
271
272
  let inlineParameterRecord = false;
272
273
  let justClosedInlineParameterRecord = false;
@@ -284,10 +285,17 @@ function formatTokens(parsed: SyqlSyntaxFile): string {
284
285
  (lower === 'import' ||
285
286
  lower === 'predicate' ||
286
287
  lower === 'query' ||
287
- lower === 'sync') &&
288
+ lower === 'sync' ||
289
+ (lower === 'allow' &&
290
+ (previous === undefined ||
291
+ previous.kind === 'string' ||
292
+ previous.text === '}'))) &&
288
293
  !(lower === 'query' && previous?.text === 'sync');
289
294
  if (topLevelDeclaration) {
290
- if (seenTopLevel) writer.blankline();
295
+ // Acknowledgements sit on their own lines directly above their query.
296
+ if (acknowledging) writer.newline();
297
+ else if (seenTopLevel) writer.blankline();
298
+ acknowledging = lower === 'allow';
291
299
  seenTopLevel = true;
292
300
  previous = undefined;
293
301
  awaitsDeclarationParameters = lower === 'predicate' || lower === 'query';
package/src/generate.ts CHANGED
@@ -28,7 +28,6 @@ import {
28
28
  type IrColumn,
29
29
  type IrDocument,
30
30
  type IrScope,
31
- type IrScopeValue,
32
31
  type IrSubscription,
33
32
  type IrSubscriptionScope,
34
33
  type IrTable,
@@ -56,6 +55,7 @@ import { type NamingTarget, validateSchemaIdentifiers } from './naming';
56
55
  import {
57
56
  type AnalyzedQuery,
58
57
  analyzeQueryFile,
58
+ checkQueryPlan,
59
59
  type QueryDb,
60
60
  type QueryNamingOptions,
61
61
  synthesizeDdl,
@@ -305,45 +305,38 @@ function buildSubscription(
305
305
  sub: Manifest['subscriptions'][number],
306
306
  tables: readonly IrTable[],
307
307
  ): IrSubscription {
308
- const table = tables.find((t) => t.name === sub.table);
309
- if (table === undefined) {
308
+ const variables = Object.keys(sub.scopes).sort();
309
+ if (
310
+ !tables.some((table) =>
311
+ variables.every((variable) =>
312
+ table.scopes.some((scope) => scope.variable === variable),
313
+ ),
314
+ )
315
+ ) {
310
316
  throw new TypegenError(
311
317
  MANIFEST_FILENAME,
312
- `subscription ${sub.name}: unknown table ${JSON.stringify(sub.table)}`,
318
+ 'a unit template covers no table: no table declares all of its scope variables (SPEC §4.1)',
319
+ 'typegen.subscription_uncovered',
320
+ { subscription: sub.name, variables },
313
321
  );
314
322
  }
315
- const declared = new Set(table.scopes.map((s) => s.variable));
316
- const scopes: IrSubscriptionScope[] = Object.entries(sub.scopes)
317
- .map(([variable, values]): IrSubscriptionScope => {
318
- if (!declared.has(variable)) {
319
- throw new TypegenError(
320
- MANIFEST_FILENAME,
321
- `subscription ${sub.name}: ${JSON.stringify(variable)} is not a scope variable of table ${sub.table} (declared: ${[...declared].join(', ')})`,
322
- );
323
- }
324
- const irValues: IrScopeValue[] = values.map((value) => {
325
- const param = PARAM_RE.exec(value);
326
- if (param?.[1] !== undefined) {
327
- return { kind: 'parameter', name: param[1] };
328
- }
329
- if (value.includes('{') || value.includes('}')) {
330
- throw new TypegenError(
331
- MANIFEST_FILENAME,
332
- `subscription ${sub.name}: scope value ${JSON.stringify(value)} mixes literals and placeholders — a value is either a literal or exactly '{param}'`,
333
- );
334
- }
335
- if (value === '*') {
336
- throw new TypegenError(
337
- MANIFEST_FILENAME,
338
- `subscription ${sub.name}: '*' is rejected in requested scopes (§3.2)`,
339
- );
340
- }
341
- return { kind: 'literal', value };
342
- });
343
- return { variable, values: irValues };
344
- })
345
- .sort((a, b) => (a.variable < b.variable ? -1 : 1));
346
- return { name: sub.name, table: sub.table, scopes };
323
+ const scopes = variables.map((variable): IrSubscriptionScope => {
324
+ const value = sub.scopes[variable] as string;
325
+ const param = PARAM_RE.exec(value);
326
+ if (param?.[1] !== undefined) {
327
+ return { variable, value: { kind: 'parameter', name: param[1] } };
328
+ }
329
+ if (value.includes('{') || value.includes('}') || value === '*') {
330
+ throw new TypegenError(
331
+ MANIFEST_FILENAME,
332
+ "a unit template value is a literal other than '*' (§3.2) or exactly '{param}'",
333
+ 'typegen.subscription_invalid_value',
334
+ { subscription: sub.name, variable, value },
335
+ );
336
+ }
337
+ return { variable, value: { kind: 'literal', value } };
338
+ });
339
+ return { name: sub.name, scopes };
347
340
  }
348
341
 
349
342
  /** Pure IR construction — the testable heart of the generator. Migrations
@@ -525,6 +518,20 @@ export function makeQueryDb(ir: IrDocument): {
525
518
  stmt.finalize();
526
519
  }
527
520
  },
521
+ plan(sql, index) {
522
+ if (index !== undefined) sqlite.run(`SAVEPOINT plan_probe; ${index}`);
523
+ try {
524
+ return sqlite
525
+ .query<{ id: number; parent: number; detail: string }, []>(
526
+ `EXPLAIN QUERY PLAN ${sql}`,
527
+ )
528
+ .all();
529
+ } finally {
530
+ if (index !== undefined) {
531
+ sqlite.run('ROLLBACK TO plan_probe; RELEASE plan_probe');
532
+ }
533
+ }
534
+ },
528
535
  };
529
536
  return { db, close: () => sqlite.close() };
530
537
  }
@@ -590,6 +597,7 @@ export function analyzeQueries(
590
597
  }
591
598
  seen.set(q.name, q.file);
592
599
  }
600
+ for (const query of analyzed) checkQueryPlan(query, ir, db);
593
601
  return analyzed;
594
602
  } finally {
595
603
  close();
package/src/init.ts CHANGED
@@ -27,11 +27,7 @@ const STARTER_MANIFEST = `{
27
27
  "schemaVersions": [{ "version": 1, "through": "0001_initial" }],
28
28
  "tables": [{ "name": "notes", "scopes": ["list:{list_id}"] }],
29
29
  "subscriptions": [
30
- {
31
- "name": "notesInList",
32
- "table": "notes",
33
- "scopes": { "list_id": ["{listId}"] }
34
- }
30
+ { "name": "notesInList", "scopes": { "list_id": "{listId}" } }
35
31
  ]
36
32
  }
37
33
  `;
@@ -44,6 +40,9 @@ CREATE TABLE notes (
44
40
  body TEXT NOT NULL,
45
41
  updated_at_ms INTEGER NOT NULL
46
42
  );
43
+
44
+ -- The starter query reads one list; this index lets SQLite search it.
45
+ CREATE INDEX idx_notes_list ON notes (list_id);
47
46
  `;
48
47
 
49
48
  // A starter NAMED query (the typed .sql read tier). typegen type-checks it
package/src/ir.ts CHANGED
@@ -116,12 +116,13 @@ export type IrScopeValue =
116
116
 
117
117
  export interface IrSubscriptionScope {
118
118
  readonly variable: string;
119
- readonly values: readonly IrScopeValue[];
119
+ readonly value: IrScopeValue;
120
120
  }
121
121
 
122
+ /** A unit template (SPEC §4.1): one value per scope variable. The unit
123
+ * covers every table that declares all of its variables. */
122
124
  export interface IrSubscription {
123
125
  readonly name: string;
124
- readonly table: string;
125
126
  /** Sorted by variable for stable diffs. */
126
127
  readonly scopes: readonly IrSubscriptionScope[];
127
128
  }
@@ -233,10 +234,9 @@ export function serializeIr(ir: IrDocument): string {
233
234
  })),
234
235
  subscriptions: ir.subscriptions.map((sub) => ({
235
236
  name: sub.name,
236
- table: sub.table,
237
237
  scopes: sub.scopes.map((scope) => ({
238
238
  variable: scope.variable,
239
- values: scope.values.map(canonicalScopeValue),
239
+ value: canonicalScopeValue(scope.value),
240
240
  })),
241
241
  })),
242
242
  extensions: canonicalizeExtensions(ir.extensions),
package/src/lsp.ts CHANGED
@@ -8,7 +8,7 @@ import { buildIr, loadMigrations, loadQueries, makeQueryDb } from './generate';
8
8
  import type { IrDocument } from './ir';
9
9
  import { MANIFEST_FILENAME, parseManifest } from './manifest';
10
10
  import { lockedMigrationNames, readMigrationLock } from './migration-lock';
11
- import type { QueryDb, QueryNamingOptions } from './query';
11
+ import { checkQueryPlan, type QueryDb, type QueryNamingOptions } from './query';
12
12
  import { syqlDiagnosticRemedy } from './syql-diagnostics';
13
13
  import { SyqlFrontendError, type SyqlSourceSpan } from './syql-lexer';
14
14
  import type { SyqlLoweredQuery } from './syql-lowering';
@@ -356,9 +356,16 @@ export class SyqlLanguageServer {
356
356
  project.ir,
357
357
  project.db,
358
358
  project.naming,
359
- ).queries.map((query) =>
360
- lowerSyqlQuery(query, project.ir, project.db, project.naming),
361
- );
359
+ ).queries.map((query) => {
360
+ const result = lowerSyqlQuery(
361
+ query,
362
+ project.ir,
363
+ project.db,
364
+ project.naming,
365
+ );
366
+ checkQueryPlan(result.analysis, project.ir, project.db);
367
+ return result;
368
+ });
362
369
  return { root, file, module, semantic, lowered };
363
370
  }
364
371