@syncular/typegen 0.65.2 → 0.66.1

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.
@@ -1143,10 +1143,10 @@ class Validator {
1143
1143
  return bounded;
1144
1144
  }
1145
1145
  /**
1146
- * Proves the result identity per SELECT scope. Each physical relation of a
1147
- * scope contributes its primary key and each CTE relation the identity of
1148
- * its body, except that a physical relation joined by a required inner
1149
- * `ON rel.pk = cte.key` equality to a CTE is determined by that CTE row.
1146
+ * Proves the result identity per SELECT scope (SYQL §14.2). Each CTE
1147
+ * relation contributes the identity of its body and each physical relation
1148
+ * its primary key, except that a relation bound by an ON equality on its
1149
+ * primary key contributes it only when the scope projects it.
1150
1150
  */
1151
1151
  #proveIdentity(query, sql, relations, analysis, boundedCtes) {
1152
1152
  const unproven = () => this.#fail('SYQL6003_NONDETERMINISTIC_SQL', query.statement.span, 'a CTE LIMIT requires a proven CTE identity and a body ORDER BY that ends with it');
@@ -1161,37 +1161,12 @@ class Validator {
1161
1161
  resultNames.add(column.name);
1162
1162
  }
1163
1163
  const cleaned = stripCommentsAndStrings(sql);
1164
- const simple = (text) => !/\b(?:DISTINCT|GROUP\s+BY|UNION|INTERSECT|EXCEPT|LEFT\s+JOIN|RIGHT\s+JOIN|FULL\s+JOIN)\b/i.test(text) &&
1164
+ const simple = (text) => !/\b(?:DISTINCT|GROUP\s+BY|UNION|INTERSECT|EXCEPT|(?:RIGHT|FULL)(?:\s+OUTER)?\s+JOIN)\b/i.test(text) &&
1165
1165
  !/\b(?:count|sum|total|avg|min|max|group_concat)\s*\(/i.test(text) &&
1166
1166
  (text.match(/\bSELECT\b/gi)?.length ?? 0) === 1;
1167
1167
  const refs = relations.tables;
1168
- if (relations.cteScopes.length === 0) {
1169
- if (!simple(cleaned) ||
1170
- refs.length === 0 ||
1171
- new Set(refs.map((ref) => ref.table)).size !== refs.length) {
1172
- return undefined;
1173
- }
1174
- const inferred = [];
1175
- for (const ref of refs) {
1176
- const primaryKey = this.#primaryKey(ref.table);
1177
- const column = analysis.columns.find((candidate) => primaryKey !== undefined &&
1178
- candidate.origin?.table === ref.table &&
1179
- candidate.origin.column === primaryKey &&
1180
- !candidate.nullable);
1181
- if (column === undefined || primaryKey === undefined)
1182
- return undefined;
1183
- inferred.push({
1184
- field: column.langName,
1185
- qualifier: ref.alias,
1186
- column: primaryKey,
1187
- relation: ref.table,
1188
- });
1189
- }
1190
- return inferred;
1191
- }
1192
- // A statement with CTEs: every SELECT is a scope, and each scope proves
1193
- // its keys syntactically from its own projection.
1194
- const lastCte = relations.cteScopes.at(-1);
1168
+ // Every SELECT is a scope, and each scope proves its keys syntactically
1169
+ // from its own projection.
1195
1170
  if (relations.recursive ||
1196
1171
  (cleaned.match(/\bSELECT\b/gi)?.length ?? 0) !==
1197
1172
  relations.cteScopes.length + 1) {
@@ -1200,43 +1175,53 @@ class Validator {
1200
1175
  return undefined;
1201
1176
  }
1202
1177
  const cteKeys = new Map();
1203
- const scopeKeys = (scope, text) => {
1178
+ const scopeKeys = (scope, start, end) => {
1179
+ const text = cleaned.slice(start, end);
1204
1180
  if (!simple(text))
1205
1181
  return undefined;
1206
1182
  const tables = refs.filter((ref) => relations.scopeAt(ref.start) === scope);
1207
1183
  const ctes = relations.cteRefs.filter((ref) => relations.scopeAt(ref.start) === scope);
1208
- const aliases = [...tables, ...ctes].map((ref) => ref.alias.toLowerCase());
1209
- if (tables.length + ctes.length === 0 ||
1210
- new Set(tables.map((ref) => ref.table)).size !== tables.length ||
1211
- new Set(aliases).size !== aliases.length) {
1184
+ const joined = [...tables, ...ctes].sort((a, b) => a.start - b.start);
1185
+ const aliases = joined.map((ref) => ref.alias.toLowerCase());
1186
+ if (joined.length === 0 || new Set(aliases).size !== aliases.length) {
1212
1187
  return undefined;
1213
1188
  }
1214
- const items = splitSelectList(text);
1215
- if (items === null)
1189
+ const selected = splitSelectList(text);
1190
+ if (selected === null)
1216
1191
  return undefined;
1217
- const projected = (qualifier, column) => items.findIndex((item) => {
1218
- const plain = PLAIN_REF_RE.exec(item.expr);
1219
- return (plain !== null &&
1220
- plain[2]?.toLowerCase() === column.toLowerCase() &&
1221
- (plain[1] === undefined
1222
- ? aliases.length === 1
1223
- : plain[1].toLowerCase() === qualifier.toLowerCase()));
1224
- });
1225
- // Required inner-join equalities: depth-0 AND conjuncts of ON clauses.
1226
- const conjuncts = [];
1227
- const tokens = significant(lexSyqlSqlSource('query SQL', text));
1228
- let depth = 0;
1192
+ // A star item shifts result positions, so no item locates a key.
1193
+ const items = selected.some((item) => item.expr.endsWith('*'))
1194
+ ? []
1195
+ : selected;
1196
+ const projected = (qualifier, column, relation) => {
1197
+ const index = items.findIndex((item) => {
1198
+ const plain = PLAIN_REF_RE.exec(item.expr);
1199
+ return (plain !== null &&
1200
+ plain[2]?.toLowerCase() === column.toLowerCase() &&
1201
+ (plain[1] === undefined
1202
+ ? aliases.length === 1
1203
+ : plain[1].toLowerCase() === qualifier.toLowerCase()));
1204
+ });
1205
+ // Without CTEs, the schema origin of a result column also locates
1206
+ // the key of a table the statement reads once.
1207
+ return index >= 0 ||
1208
+ relations.cteScopes.length > 0 ||
1209
+ refs.filter((ref) => ref.table === relation).length !== 1
1210
+ ? index
1211
+ : analysis.columns.findIndex((candidate) => candidate.origin?.table === relation &&
1212
+ candidate.origin.column === column);
1213
+ };
1214
+ const ons = [];
1229
1215
  let on;
1230
1216
  const flush = () => {
1231
- if (on === undefined)
1232
- return;
1233
- const parts = on.map((part) => part.join('').toLowerCase());
1234
- if (!parts.some((part) => /\b(?:or|not|select|case|between|collate)\b/.test(part))) {
1235
- conjuncts.push(...parts.map((part) => part.replace(/\s+/g, '')));
1217
+ if (on !== undefined &&
1218
+ !on.conjuncts.some((conjunct) => conjunct.some((token) => ['or', 'not', 'select', 'case', 'between', 'collate'].includes(tokenLower(token) ?? '')))) {
1219
+ ons.push(on);
1236
1220
  }
1237
1221
  on = undefined;
1238
1222
  };
1239
- for (const token of tokens) {
1223
+ let depth = 0;
1224
+ for (const token of significant(lexSyqlSqlSource('query SQL', sql.slice(start, end)))) {
1240
1225
  if (token.text === ')')
1241
1226
  depth -= 1;
1242
1227
  const lower = tokenLower(token);
@@ -1252,39 +1237,68 @@ class Validator {
1252
1237
  'window',
1253
1238
  'inner',
1254
1239
  'cross',
1240
+ 'left',
1255
1241
  ].includes(lower ?? '')) {
1256
1242
  flush();
1257
- if (lower === 'on')
1258
- on = [[]];
1243
+ if (lower === 'on') {
1244
+ const at = start + token.span.start.offset;
1245
+ on = {
1246
+ owner: joined.findLast((ref) => ref.start < at),
1247
+ conjuncts: [[]],
1248
+ };
1249
+ }
1259
1250
  }
1260
1251
  else if (on !== undefined) {
1261
1252
  if (depth === 0 && lower === 'and')
1262
- on.push([]);
1253
+ on.conjuncts.push([]);
1263
1254
  else
1264
- on.at(-1)?.push(token.kind === 'identifier' ? `${token.text} ` : token.text);
1255
+ on.conjuncts.at(-1)?.push(token);
1265
1256
  }
1266
1257
  if (token.text === '(')
1267
1258
  depth += 1;
1268
1259
  }
1269
1260
  flush();
1261
+ const column = (side) => side.length === 3 &&
1262
+ side[0]?.kind === 'identifier' &&
1263
+ side[1]?.text === '.' &&
1264
+ side[2]?.kind === 'identifier'
1265
+ ? [side[0].text.toLowerCase(), side[2].text.toLowerCase()]
1266
+ : undefined;
1267
+ // A relation is bound when an ON conjunct equates its primary key with
1268
+ // a parameter, a literal, a column of an earlier relation, or a column
1269
+ // of a CTE. The conjunct stands in the relation's own ON clause or in
1270
+ // the required ON clause of an inner join.
1271
+ const bound = (ref, primaryKey) => ons.some(({ owner, conjuncts }) => (owner === ref || owner?.nullable === false) &&
1272
+ conjuncts.some((conjunct) => {
1273
+ const at = conjunct.findIndex((token) => token.text === '=' || token.text === '==');
1274
+ const sides = [conjunct.slice(0, at), conjunct.slice(at + 1)];
1275
+ return (at > 0 &&
1276
+ sides.some((side, index) => {
1277
+ const key = column(side);
1278
+ const other = sides[1 - index];
1279
+ const source = column(other);
1280
+ return (key?.[0] === ref.alias.toLowerCase() &&
1281
+ key[1] === primaryKey.toLowerCase() &&
1282
+ ((other.length === 1 &&
1283
+ ['bind', 'number', 'string'].includes(other[0]?.kind ?? '')) ||
1284
+ joined.some((relation) => relation.alias.toLowerCase() === source?.[0] &&
1285
+ (!('table' in relation) ||
1286
+ relation.start < ref.start))));
1287
+ }));
1288
+ }));
1270
1289
  const keys = [];
1271
1290
  for (const ref of tables) {
1272
1291
  const primaryKey = this.#primaryKey(ref.table);
1273
1292
  if (primaryKey === undefined)
1274
1293
  return undefined;
1275
- const left = `${ref.alias}.${primaryKey}`.toLowerCase();
1276
- const determined = ctes.some((cte) => (cteKeys.get(cte.name) ?? []).some((key) => {
1277
- const right = `${cte.alias}.${key}`.toLowerCase();
1278
- return (conjuncts.includes(`${left}=${right}`) ||
1279
- conjuncts.includes(`${left}==${right}`) ||
1280
- conjuncts.includes(`${right}=${left}`) ||
1281
- conjuncts.includes(`${right}==${left}`));
1282
- }));
1283
- if (determined)
1284
- continue;
1285
- const index = projected(ref.alias, primaryKey);
1286
- if (index < 0)
1294
+ const index = projected(ref.alias, primaryKey, ref.table);
1295
+ // A bound relation adds its key only when the scope projects it
1296
+ // from a relation that cannot be null-extended.
1297
+ if (index < 0 || ref.nullable) {
1298
+ if (bound(ref, primaryKey))
1299
+ continue;
1287
1300
  return undefined;
1301
+ }
1288
1302
  keys.push({
1289
1303
  index,
1290
1304
  term: {
@@ -1296,10 +1310,10 @@ class Validator {
1296
1310
  }
1297
1311
  for (const cte of ctes) {
1298
1312
  const bodyKeys = cteKeys.get(cte.name);
1299
- if (bodyKeys === undefined)
1313
+ if (bodyKeys === undefined || cte.nullable)
1300
1314
  return undefined;
1301
1315
  for (const key of bodyKeys) {
1302
- const index = projected(cte.alias, key);
1316
+ const index = projected(cte.alias, key, cte.name);
1303
1317
  if (index < 0)
1304
1318
  return undefined;
1305
1319
  keys.push({
@@ -1318,7 +1332,7 @@ class Validator {
1318
1332
  continue;
1319
1333
  }
1320
1334
  const text = cleaned.slice(cte.start, cte.end);
1321
- const keys = scopeKeys(`cte:${cte.name}`, text);
1335
+ const keys = scopeKeys(`cte:${cte.name}`, cte.start, cte.end);
1322
1336
  const items = splitSelectList(text);
1323
1337
  if (keys === undefined || items === null) {
1324
1338
  if (bounded !== undefined)
@@ -1351,7 +1365,7 @@ class Validator {
1351
1365
  return item.alias ?? PLAIN_REF_RE.exec(item.expr)?.[2];
1352
1366
  }));
1353
1367
  }
1354
- const main = scopeKeys('main', cleaned.slice(lastCte.end + 1));
1368
+ const main = scopeKeys('main', (relations.cteScopes.at(-1)?.end ?? -1) + 1, sql.length);
1355
1369
  if (main === undefined || main.length === 0)
1356
1370
  return undefined;
1357
1371
  const inferred = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/typegen",
3
- "version": "0.65.2",
3
+ "version": "0.66.1",
4
4
  "description": "Syncular schema-to-TypeScript type generator and the `syncular` CLI",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -56,9 +56,9 @@
56
56
  "!dist/**/*.test.d.ts"
57
57
  ],
58
58
  "dependencies": {
59
- "@syncular/core": "0.65.2"
59
+ "@syncular/core": "0.66.1"
60
60
  },
61
61
  "devDependencies": {
62
- "@syncular/server": "0.65.2"
62
+ "@syncular/server": "0.66.1"
63
63
  }
64
64
  }
@@ -10,7 +10,7 @@ import {
10
10
  type QueryNamingOptions,
11
11
  type QueryReactiveMetadata,
12
12
  type QueryScopeBinding,
13
- type CteScope,
13
+ type CteRef,
14
14
  PLAIN_REF_RE,
15
15
  type SelectItem,
16
16
  type ScopeColumn,
@@ -1737,10 +1737,10 @@ class Validator {
1737
1737
  }
1738
1738
 
1739
1739
  /**
1740
- * Proves the result identity per SELECT scope. Each physical relation of a
1741
- * scope contributes its primary key and each CTE relation the identity of
1742
- * its body, except that a physical relation joined by a required inner
1743
- * `ON rel.pk = cte.key` equality to a CTE is determined by that CTE row.
1740
+ * Proves the result identity per SELECT scope (SYQL §14.2). Each CTE
1741
+ * relation contributes the identity of its body and each physical relation
1742
+ * its primary key, except that a relation bound by an ON equality on its
1743
+ * primary key contributes it only when the scope projects it.
1744
1744
  */
1745
1745
  #proveIdentity(
1746
1746
  query: SyqlQueryDeclaration,
@@ -1776,44 +1776,14 @@ class Validator {
1776
1776
 
1777
1777
  const cleaned = stripCommentsAndStrings(sql);
1778
1778
  const simple = (text: string): boolean =>
1779
- !/\b(?:DISTINCT|GROUP\s+BY|UNION|INTERSECT|EXCEPT|LEFT\s+JOIN|RIGHT\s+JOIN|FULL\s+JOIN)\b/i.test(
1779
+ !/\b(?:DISTINCT|GROUP\s+BY|UNION|INTERSECT|EXCEPT|(?:RIGHT|FULL)(?:\s+OUTER)?\s+JOIN)\b/i.test(
1780
1780
  text,
1781
1781
  ) &&
1782
1782
  !/\b(?:count|sum|total|avg|min|max|group_concat)\s*\(/i.test(text) &&
1783
1783
  (text.match(/\bSELECT\b/gi)?.length ?? 0) === 1;
1784
1784
  const refs = relations.tables;
1785
- if (relations.cteScopes.length === 0) {
1786
- if (
1787
- !simple(cleaned) ||
1788
- refs.length === 0 ||
1789
- new Set(refs.map((ref) => ref.table)).size !== refs.length
1790
- ) {
1791
- return undefined;
1792
- }
1793
- const inferred: IdentityTerm[] = [];
1794
- for (const ref of refs) {
1795
- const primaryKey = this.#primaryKey(ref.table);
1796
- const column = analysis.columns.find(
1797
- (candidate) =>
1798
- primaryKey !== undefined &&
1799
- candidate.origin?.table === ref.table &&
1800
- candidate.origin.column === primaryKey &&
1801
- !candidate.nullable,
1802
- );
1803
- if (column === undefined || primaryKey === undefined) return undefined;
1804
- inferred.push({
1805
- field: column.langName,
1806
- qualifier: ref.alias,
1807
- column: primaryKey,
1808
- relation: ref.table,
1809
- });
1810
- }
1811
- return inferred;
1812
- }
1813
-
1814
- // A statement with CTEs: every SELECT is a scope, and each scope proves
1815
- // its keys syntactically from its own projection.
1816
- const lastCte = relations.cteScopes.at(-1) as CteScope;
1785
+ // Every SELECT is a scope, and each scope proves its keys syntactically
1786
+ // from its own projection.
1817
1787
  if (
1818
1788
  relations.recursive ||
1819
1789
  (cleaned.match(/\bSELECT\b/gi)?.length ?? 0) !==
@@ -1825,10 +1795,12 @@ class Validator {
1825
1795
  const cteKeys = new Map<string, readonly string[]>();
1826
1796
  const scopeKeys = (
1827
1797
  scope: string,
1828
- text: string,
1798
+ start: number,
1799
+ end: number,
1829
1800
  ):
1830
1801
  | { readonly index: number; readonly term: Omit<IdentityTerm, 'field'> }[]
1831
1802
  | undefined => {
1803
+ const text = cleaned.slice(start, end);
1832
1804
  if (!simple(text)) return undefined;
1833
1805
  const tables = refs.filter(
1834
1806
  (ref) => relations.scopeAt(ref.start) === scope,
@@ -1836,20 +1808,23 @@ class Validator {
1836
1808
  const ctes = relations.cteRefs.filter(
1837
1809
  (ref) => relations.scopeAt(ref.start) === scope,
1838
1810
  );
1839
- const aliases = [...tables, ...ctes].map((ref) =>
1840
- ref.alias.toLowerCase(),
1841
- );
1842
- if (
1843
- tables.length + ctes.length === 0 ||
1844
- new Set(tables.map((ref) => ref.table)).size !== tables.length ||
1845
- new Set(aliases).size !== aliases.length
1846
- ) {
1811
+ const joined = [...tables, ...ctes].sort((a, b) => a.start - b.start);
1812
+ const aliases = joined.map((ref) => ref.alias.toLowerCase());
1813
+ if (joined.length === 0 || new Set(aliases).size !== aliases.length) {
1847
1814
  return undefined;
1848
1815
  }
1849
- const items = splitSelectList(text);
1850
- if (items === null) return undefined;
1851
- const projected = (qualifier: string, column: string): number =>
1852
- items.findIndex((item) => {
1816
+ const selected = splitSelectList(text);
1817
+ if (selected === null) return undefined;
1818
+ // A star item shifts result positions, so no item locates a key.
1819
+ const items = selected.some((item) => item.expr.endsWith('*'))
1820
+ ? []
1821
+ : selected;
1822
+ const projected = (
1823
+ qualifier: string,
1824
+ column: string,
1825
+ relation: string,
1826
+ ): number => {
1827
+ const index = items.findIndex((item) => {
1853
1828
  const plain = PLAIN_REF_RE.exec(item.expr);
1854
1829
  return (
1855
1830
  plain !== null &&
@@ -1859,24 +1834,46 @@ class Validator {
1859
1834
  : plain[1].toLowerCase() === qualifier.toLowerCase())
1860
1835
  );
1861
1836
  });
1862
- // Required inner-join equalities: depth-0 AND conjuncts of ON clauses.
1863
- const conjuncts: string[] = [];
1864
- const tokens = significant(lexSyqlSqlSource('query SQL', text));
1865
- let depth = 0;
1866
- let on: string[][] | undefined;
1837
+ // Without CTEs, the schema origin of a result column also locates
1838
+ // the key of a table the statement reads once.
1839
+ return index >= 0 ||
1840
+ relations.cteScopes.length > 0 ||
1841
+ refs.filter((ref) => ref.table === relation).length !== 1
1842
+ ? index
1843
+ : analysis.columns.findIndex(
1844
+ (candidate) =>
1845
+ candidate.origin?.table === relation &&
1846
+ candidate.origin.column === column,
1847
+ );
1848
+ };
1849
+ // Depth-0 ON clauses, split into AND conjuncts and kept with the
1850
+ // relation each one joins. An ON clause with OR, NOT, CASE, BETWEEN,
1851
+ // COLLATE, or a subquery binds nothing.
1852
+ type On = {
1853
+ readonly owner: TableRef | CteRef | undefined;
1854
+ readonly conjuncts: SyqlToken[][];
1855
+ };
1856
+ const ons: On[] = [];
1857
+ let on: On | undefined;
1867
1858
  const flush = (): void => {
1868
- if (on === undefined) return;
1869
- const parts = on.map((part) => part.join('').toLowerCase());
1870
1859
  if (
1871
- !parts.some((part) =>
1872
- /\b(?:or|not|select|case|between|collate)\b/.test(part),
1860
+ on !== undefined &&
1861
+ !on.conjuncts.some((conjunct) =>
1862
+ conjunct.some((token) =>
1863
+ ['or', 'not', 'select', 'case', 'between', 'collate'].includes(
1864
+ tokenLower(token) ?? '',
1865
+ ),
1866
+ ),
1873
1867
  )
1874
1868
  ) {
1875
- conjuncts.push(...parts.map((part) => part.replace(/\s+/g, '')));
1869
+ ons.push(on);
1876
1870
  }
1877
1871
  on = undefined;
1878
1872
  };
1879
- for (const token of tokens) {
1873
+ let depth = 0;
1874
+ for (const token of significant(
1875
+ lexSyqlSqlSource('query SQL', sql.slice(start, end)),
1876
+ )) {
1880
1877
  if (token.text === ')') depth -= 1;
1881
1878
  const lower = tokenLower(token);
1882
1879
  if (
@@ -1892,39 +1889,81 @@ class Validator {
1892
1889
  'window',
1893
1890
  'inner',
1894
1891
  'cross',
1892
+ 'left',
1895
1893
  ].includes(lower ?? '')
1896
1894
  ) {
1897
1895
  flush();
1898
- if (lower === 'on') on = [[]];
1896
+ if (lower === 'on') {
1897
+ const at = start + token.span.start.offset;
1898
+ on = {
1899
+ owner: joined.findLast((ref) => ref.start < at),
1900
+ conjuncts: [[]],
1901
+ };
1902
+ }
1899
1903
  } else if (on !== undefined) {
1900
- if (depth === 0 && lower === 'and') on.push([]);
1901
- else
1902
- on.at(-1)?.push(
1903
- token.kind === 'identifier' ? `${token.text} ` : token.text,
1904
- );
1904
+ if (depth === 0 && lower === 'and') on.conjuncts.push([]);
1905
+ else on.conjuncts.at(-1)?.push(token);
1905
1906
  }
1906
1907
  if (token.text === '(') depth += 1;
1907
1908
  }
1908
1909
  flush();
1910
+ const column = (
1911
+ side: readonly SyqlToken[],
1912
+ ): readonly [string, string] | undefined =>
1913
+ side.length === 3 &&
1914
+ side[0]?.kind === 'identifier' &&
1915
+ side[1]?.text === '.' &&
1916
+ side[2]?.kind === 'identifier'
1917
+ ? [side[0].text.toLowerCase(), side[2].text.toLowerCase()]
1918
+ : undefined;
1919
+ // A relation is bound when an ON conjunct equates its primary key with
1920
+ // a parameter, a literal, a column of an earlier relation, or a column
1921
+ // of a CTE. The conjunct stands in the relation's own ON clause or in
1922
+ // the required ON clause of an inner join.
1923
+ const bound = (ref: TableRef, primaryKey: string): boolean =>
1924
+ ons.some(
1925
+ ({ owner, conjuncts }) =>
1926
+ (owner === ref || owner?.nullable === false) &&
1927
+ conjuncts.some((conjunct) => {
1928
+ const at = conjunct.findIndex(
1929
+ (token) => token.text === '=' || token.text === '==',
1930
+ );
1931
+ const sides = [conjunct.slice(0, at), conjunct.slice(at + 1)];
1932
+ return (
1933
+ at > 0 &&
1934
+ sides.some((side, index) => {
1935
+ const key = column(side);
1936
+ const other = sides[1 - index] as SyqlToken[];
1937
+ const source = column(other);
1938
+ return (
1939
+ key?.[0] === ref.alias.toLowerCase() &&
1940
+ key[1] === primaryKey.toLowerCase() &&
1941
+ ((other.length === 1 &&
1942
+ ['bind', 'number', 'string'].includes(
1943
+ other[0]?.kind ?? '',
1944
+ )) ||
1945
+ joined.some(
1946
+ (relation) =>
1947
+ relation.alias.toLowerCase() === source?.[0] &&
1948
+ (!('table' in relation) ||
1949
+ relation.start < ref.start),
1950
+ ))
1951
+ );
1952
+ })
1953
+ );
1954
+ }),
1955
+ );
1909
1956
  const keys: { index: number; term: Omit<IdentityTerm, 'field'> }[] = [];
1910
1957
  for (const ref of tables) {
1911
1958
  const primaryKey = this.#primaryKey(ref.table);
1912
1959
  if (primaryKey === undefined) return undefined;
1913
- const left = `${ref.alias}.${primaryKey}`.toLowerCase();
1914
- const determined = ctes.some((cte) =>
1915
- (cteKeys.get(cte.name) ?? []).some((key) => {
1916
- const right = `${cte.alias}.${key}`.toLowerCase();
1917
- return (
1918
- conjuncts.includes(`${left}=${right}`) ||
1919
- conjuncts.includes(`${left}==${right}`) ||
1920
- conjuncts.includes(`${right}=${left}`) ||
1921
- conjuncts.includes(`${right}==${left}`)
1922
- );
1923
- }),
1924
- );
1925
- if (determined) continue;
1926
- const index = projected(ref.alias, primaryKey);
1927
- if (index < 0) return undefined;
1960
+ const index = projected(ref.alias, primaryKey, ref.table);
1961
+ // A bound relation adds its key only when the scope projects it
1962
+ // from a relation that cannot be null-extended.
1963
+ if (index < 0 || ref.nullable) {
1964
+ if (bound(ref, primaryKey)) continue;
1965
+ return undefined;
1966
+ }
1928
1967
  keys.push({
1929
1968
  index,
1930
1969
  term: {
@@ -1936,9 +1975,9 @@ class Validator {
1936
1975
  }
1937
1976
  for (const cte of ctes) {
1938
1977
  const bodyKeys = cteKeys.get(cte.name);
1939
- if (bodyKeys === undefined) return undefined;
1978
+ if (bodyKeys === undefined || cte.nullable) return undefined;
1940
1979
  for (const key of bodyKeys) {
1941
- const index = projected(cte.alias, key);
1980
+ const index = projected(cte.alias, key, cte.name);
1942
1981
  if (index < 0) return undefined;
1943
1982
  keys.push({
1944
1983
  index,
@@ -1955,7 +1994,7 @@ class Validator {
1955
1994
  continue;
1956
1995
  }
1957
1996
  const text = cleaned.slice(cte.start, cte.end);
1958
- const keys = scopeKeys(`cte:${cte.name}`, text);
1997
+ const keys = scopeKeys(`cte:${cte.name}`, cte.start, cte.end);
1959
1998
  const items = splitSelectList(text);
1960
1999
  if (keys === undefined || items === null) {
1961
2000
  if (bounded !== undefined) unproven();
@@ -1996,7 +2035,11 @@ class Validator {
1996
2035
  }),
1997
2036
  );
1998
2037
  }
1999
- const main = scopeKeys('main', cleaned.slice(lastCte.end + 1));
2038
+ const main = scopeKeys(
2039
+ 'main',
2040
+ (relations.cteScopes.at(-1)?.end ?? -1) + 1,
2041
+ sql.length,
2042
+ );
2000
2043
  if (main === undefined || main.length === 0) return undefined;
2001
2044
  const inferred: IdentityTerm[] = [];
2002
2045
  for (const { index, term } of main) {