@syncular/typegen 0.31.0 → 0.32.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.
package/dist/emit-dart.js CHANGED
@@ -11,12 +11,14 @@ const DART_TYPE = {
11
11
  blob_ref: 'String',
12
12
  crdt: 'List<int>',
13
13
  };
14
- /** §5.11: app-side Dart type — declaredType for an encrypted column. */
15
- function appDartType(column) {
16
- const type = column.encrypted === true && column.declaredType !== undefined
14
+ function appColumnType(column) {
15
+ return column.encrypted === true && column.declaredType !== undefined
17
16
  ? column.declaredType
18
17
  : column.type;
19
- return DART_TYPE[type];
18
+ }
19
+ /** §5.11: app-side Dart type — declaredType for an encrypted column. */
20
+ function appDartType(column) {
21
+ return DART_TYPE[appColumnType(column)];
20
22
  }
21
23
  function pascalCase(name) {
22
24
  return name
@@ -81,7 +83,7 @@ function emitSchemaValue(ir, indent) {
81
83
  /** The accessor lifting a §2.4 value out of a `Map<String, Object?>` row. */
82
84
  function rowAccessor(column) {
83
85
  const key = `row[${quote(column.name)}]`;
84
- switch (column.type) {
86
+ switch (appColumnType(column)) {
85
87
  case 'string':
86
88
  case 'json':
87
89
  case 'blob_ref':
@@ -184,7 +186,7 @@ export function emitDartModule(ir, hash) {
184
186
  // them. An unused private helper is an ANALYZER diagnostic (unused_element),
185
187
  // which the `type=lint` ignore above does not cover, so a schema without
186
188
  // boolean or bytes/crdt columns would fail a fatal-warnings `dart analyze`.
187
- const columnTypes = new Set(ir.tables.flatMap((table) => table.columns.map((column) => column.type)));
189
+ const columnTypes = new Set(ir.tables.flatMap((table) => table.columns.map((column) => appColumnType(column))));
188
190
  if (columnTypes.has('boolean')) {
189
191
  parts.push([
190
192
  '/// Lift a SQLite boolean: a real bool, or 0/1 as a number.',
@@ -11,12 +11,14 @@ const KOTLIN_TYPE = {
11
11
  blob_ref: 'String',
12
12
  crdt: 'ByteArray',
13
13
  };
14
- /** §5.11: app-side Kotlin type — declaredType for an encrypted column. */
15
- function appKotlinType(column) {
16
- const type = column.encrypted === true && column.declaredType !== undefined
14
+ function appColumnType(column) {
15
+ return column.encrypted === true && column.declaredType !== undefined
17
16
  ? column.declaredType
18
17
  : column.type;
19
- return KOTLIN_TYPE[type];
18
+ }
19
+ /** §5.11: app-side Kotlin type — declaredType for an encrypted column. */
20
+ function appKotlinType(column) {
21
+ return KOTLIN_TYPE[appColumnType(column)];
20
22
  }
21
23
  function pascalCase(name) {
22
24
  return name
@@ -83,7 +85,7 @@ function emitSchemaValue(ir, indent) {
83
85
  /** The accessor lifting a §2.4 value out of a row `JsonValue`. */
84
86
  function rowAccessor(column) {
85
87
  const key = `row[${quote(column.name)}]`;
86
- switch (column.type) {
88
+ switch (appColumnType(column)) {
87
89
  case 'string':
88
90
  case 'json':
89
91
  case 'blob_ref':
@@ -192,7 +194,7 @@ export function emitKotlinModule(ir, hash, packageName, objectName) {
192
194
  // generated file and an "is never used" inspection in every IDE. The
193
195
  // query emitter is unaffected — it declares its own queryRowBool/
194
196
  // queryRowBytes copies under distinct names.
195
- const columnTypes = new Set(ir.tables.flatMap((table) => table.columns.map((column) => column.type)));
197
+ const columnTypes = new Set(ir.tables.flatMap((table) => table.columns.map((column) => appColumnType(column))));
196
198
  if (columnTypes.has('boolean')) {
197
199
  parts.push([
198
200
  '/** Lift a SQLite boolean: a real JSON bool, or 0/1 as a number. */',
@@ -14,12 +14,14 @@ const SWIFT_TYPE = {
14
14
  blob_ref: 'String',
15
15
  crdt: '[UInt8]',
16
16
  };
17
- /** §5.11: app-side Swift type — declaredType for an encrypted column. */
18
- function appSwiftType(column) {
19
- const type = column.encrypted === true && column.declaredType !== undefined
17
+ function appColumnType(column) {
18
+ return column.encrypted === true && column.declaredType !== undefined
20
19
  ? column.declaredType
21
20
  : column.type;
22
- return SWIFT_TYPE[type];
21
+ }
22
+ /** §5.11: app-side Swift type — declaredType for an encrypted column. */
23
+ function appSwiftType(column) {
24
+ return SWIFT_TYPE[appColumnType(column)];
23
25
  }
24
26
  function pascalCase(name) {
25
27
  return name
@@ -87,7 +89,7 @@ function emitSchemaValue(ir, indent) {
87
89
  /** The accessor that lifts a §2.4 value out of a `[String: JSONValue]` row. */
88
90
  function rowAccessor(column) {
89
91
  const key = `row[${quote(column.name)}]`;
90
- switch (column.type) {
92
+ switch (appColumnType(column)) {
91
93
  case 'string':
92
94
  case 'json':
93
95
  case 'blob_ref':
@@ -121,7 +123,7 @@ function emitStruct(table) {
121
123
  // Memberwise init (public, so app code can build rows too).
122
124
  const params = table.columns
123
125
  .map((c) => {
124
- const swift = SWIFT_TYPE[c.type];
126
+ const swift = appSwiftType(c);
125
127
  const opt = c.nullable ? '? = nil' : '';
126
128
  return `${camelCase(c.name)}: ${swift}${opt}`;
127
129
  })
package/dist/lower.js CHANGED
@@ -208,6 +208,98 @@ function expandStar(item, qualifier, refs, ir, location) {
208
208
  const prefix = qualifier !== undefined ? `${qualifier}.` : '';
209
209
  return table.columns.map((c) => `${prefix}${c.name}`);
210
210
  }
211
+ /**
212
+ * Rewrite bare references to renamed select aliases in the depth-0 ORDER BY
213
+ * and GROUP BY terms of `tail` (the SQL after the outer SELECT list). SQLite
214
+ * resolves an identifier in those clauses to a select alias before any column,
215
+ * so the rewrite preserves the authored meaning. A GROUP BY after a compound
216
+ * operator belongs to another SELECT and keeps its text; subqueries sit at
217
+ * depth ≥ 1 and cannot see the outer aliases.
218
+ */
219
+ function renameAliasRefs(tail, renamed) {
220
+ if (renamed.size === 0)
221
+ return tail;
222
+ let out = '';
223
+ let depth = 0;
224
+ let clause = null;
225
+ let compound = false;
226
+ let prevWord = '';
227
+ let i = 0;
228
+ while (i < tail.length) {
229
+ const ch = tail[i];
230
+ const next = tail[i + 1];
231
+ let end = i + 1;
232
+ if (ch === '-' && next === '-') {
233
+ const nl = tail.indexOf('\n', i);
234
+ end = nl === -1 ? tail.length : nl + 1;
235
+ }
236
+ else if (ch === '/' && next === '*') {
237
+ const close = tail.indexOf('*/', i + 2);
238
+ end = close === -1 ? tail.length : close + 2;
239
+ }
240
+ else if (ch === "'" || ch === '"') {
241
+ for (;;) {
242
+ if (end >= tail.length)
243
+ break;
244
+ if (tail[end] === ch) {
245
+ if (tail[end + 1] === ch)
246
+ end += 2;
247
+ else {
248
+ end += 1;
249
+ break;
250
+ }
251
+ }
252
+ else
253
+ end += 1;
254
+ }
255
+ }
256
+ else if (ch === '(') {
257
+ depth += 1;
258
+ }
259
+ else if (ch === ')') {
260
+ depth -= 1;
261
+ }
262
+ else if (WORD_RE.test(ch)) {
263
+ while (end < tail.length && /[A-Za-z0-9_]/.test(tail[end])) {
264
+ end += 1;
265
+ }
266
+ const word = tail.slice(i, end);
267
+ const lower = word.toLowerCase();
268
+ const following = /^\s*(.?)/.exec(tail.slice(end))?.[1];
269
+ if (depth === 0) {
270
+ if (lower === 'by' && prevWord === 'order')
271
+ clause = 'order';
272
+ else if (lower === 'by' && prevWord === 'group')
273
+ clause = 'group';
274
+ else if (['having', 'limit', 'offset', 'window'].includes(lower)) {
275
+ clause = null;
276
+ }
277
+ else if (['union', 'intersect', 'except'].includes(lower)) {
278
+ compound = true;
279
+ clause = null;
280
+ }
281
+ }
282
+ const alias = renamed.get(lower);
283
+ if (alias !== undefined &&
284
+ depth === 0 &&
285
+ (clause === 'order' || (clause === 'group' && !compound)) &&
286
+ out.trimEnd().slice(-1) !== '.' &&
287
+ following !== '.' &&
288
+ following !== '(') {
289
+ out += alias;
290
+ }
291
+ else {
292
+ out += word;
293
+ }
294
+ prevWord = lower;
295
+ i = end;
296
+ continue;
297
+ }
298
+ out += tail.slice(i, end);
299
+ i = end;
300
+ }
301
+ return out;
302
+ }
211
303
  /**
212
304
  * Rewrite the top-level projection of `sql` so every result column's runtime
213
305
  * key equals its language-facing name. `analyze` prepares a candidate SQL
@@ -251,6 +343,9 @@ export function lowerProjection(sql, refs, ir, location, analyze, buildMap) {
251
343
  }
252
344
  const langNames = buildMap(names);
253
345
  let changed = expanded;
346
+ // Authored aliases that were renamed; ORDER BY / GROUP BY references to them
347
+ // follow the rename below.
348
+ const renamedAliases = new Map();
254
349
  const rewritten = flatItems.map((text, index) => {
255
350
  const resultName = names[index];
256
351
  const langName = langNames[index];
@@ -263,11 +358,13 @@ export function lowerProjection(sql, refs, ir, location, analyze, buildMap) {
263
358
  const alias = `"${langName.replaceAll('"', '""')}"`;
264
359
  const explicit = EXPLICIT_ALIAS_RE.exec(text);
265
360
  if (explicit !== null && explicit[2] === resultName) {
361
+ renamedAliases.set(resultName.toLowerCase(), alias);
266
362
  return `${explicit[1].trim()} AS ${alias}`;
267
363
  }
268
364
  const implicit = TRAILING_IDENT_RE.exec(text);
269
365
  if (implicit !== null && implicit[2] === resultName) {
270
366
  // Implicit alias (`expr name`) — swap the trailing identifier.
367
+ renamedAliases.set(resultName.toLowerCase(), alias);
271
368
  return `${implicit[1].trim()} AS ${alias}`;
272
369
  }
273
370
  return `${text} AS ${alias}`;
@@ -279,7 +376,7 @@ export function lowerProjection(sql, refs, ir, location, analyze, buildMap) {
279
376
  if (span2 === null)
280
377
  throw new Error('unreachable: projection vanished');
281
378
  return {
282
- sql: `${expandedSql.slice(0, span2.start)} ${rewritten.join(', ')} ${expandedSql.slice(span2.end)}`,
379
+ sql: `${expandedSql.slice(0, span2.start)} ${rewritten.join(', ')} ${renameAliasRefs(expandedSql.slice(span2.end), renamedAliases)}`,
283
380
  changed: true,
284
381
  sqlNames: names,
285
382
  langNames,
package/dist/query.js CHANGED
@@ -990,11 +990,15 @@ function inferReactiveMetadata(sql, refs, ir, params, columns) {
990
990
  stack.push(cursor);
991
991
  else if (char === ')')
992
992
  stack.pop();
993
+ const atBoundary = cursor === 0 || !/[A-Za-z0-9_:]/.test(cleaned[cursor - 1] ?? '');
993
994
  if (cursor > index &&
995
+ atBoundary &&
994
996
  /^(?:GROUP\s+BY|ORDER\s+BY|LIMIT|HAVING)\b/i.test(cleaned.slice(cursor))) {
995
997
  break;
996
998
  }
997
- if (/^OR\b/i.test(cleaned.slice(cursor)) &&
999
+ if (atBoundary &&
1000
+ /^OR\b/i.test(cleaned.slice(cursor)) &&
1001
+ stack.length <= matchStack.length &&
998
1002
  stack.every((open, stackIndex) => matchStack[stackIndex] === open)) {
999
1003
  return false;
1000
1004
  }
@@ -1016,8 +1020,8 @@ function inferReactiveMetadata(sql, refs, ir, params, columns) {
1016
1020
  for (const scope of table.scopes) {
1017
1021
  const column = scope.column.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1018
1022
  const qualified = qualifier === undefined
1019
- ? `(?:${IDENT}\\.)?${column}`
1020
- : `(?:${qualifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.)?${column}`;
1023
+ ? `(?<![A-Za-z0-9_.:])(?:${IDENT}\\.)?${column}\\b`
1024
+ : `(?<![A-Za-z0-9_.:])(?:${qualifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.)?${column}\\b`;
1021
1025
  const found = [];
1022
1026
  const equality = new RegExp(`${qualified}\\s*(?:=|==|\\bIS\\b)\\s*:(${IDENT})\\b|:(${IDENT})\\b\\s*(?:=|==)\\s*${qualified}`, 'gi');
1023
1027
  for (const match of sql.matchAll(equality)) {
@@ -892,7 +892,8 @@ class Validator {
892
892
  stack.push(cursor);
893
893
  else if (char === ')')
894
894
  stack.pop();
895
- if (/^OR\b/i.test(cleaned.slice(cursor)) &&
895
+ if ((cursor === 0 || !/[A-Za-z0-9_:]/.test(cleaned[cursor - 1] ?? '')) &&
896
+ /^OR\b/i.test(cleaned.slice(cursor)) &&
896
897
  stack.length <= matchStack.length &&
897
898
  stack.every((open, stackIndex) => matchStack[stackIndex] === open)) {
898
899
  return false;
@@ -1072,8 +1073,8 @@ class Validator {
1072
1073
  return other?.columns.some((item) => item.name === scope.column);
1073
1074
  }).length;
1074
1075
  const subject = unqualifiedMatches === 1
1075
- ? `(?:${alias}\\.)?${column}`
1076
- : `${alias}\\.${column}`;
1076
+ ? `(?<![A-Za-z0-9_.:])(?:${alias}\\.)?${column}\\b`
1077
+ : `(?<![A-Za-z0-9_.:])${alias}\\.${column}\\b`;
1077
1078
  const found = [];
1078
1079
  const equality = new RegExp(`${subject}\\s*(?:=|==|\\bIS\\b)\\s*:([A-Za-z_][A-Za-z0-9_]*)\\b|:([A-Za-z_][A-Za-z0-9_]*)\\b\\s*(?:=|==)\\s*${subject}`, 'gi');
1079
1080
  const inScope = (index) => markerScopes.scopeAt(index) === refScope(ref) && requiredAt(index);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/typegen",
3
- "version": "0.31.0",
3
+ "version": "0.32.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.31.0"
59
+ "@syncular/core": "0.32.1"
60
60
  },
61
61
  "devDependencies": {
62
- "@syncular/server": "0.31.0"
62
+ "@syncular/server": "0.32.1"
63
63
  }
64
64
  }
package/src/emit-dart.ts CHANGED
@@ -29,13 +29,15 @@ const DART_TYPE: Readonly<Record<IrColumnType, string>> = {
29
29
  crdt: 'List<int>',
30
30
  };
31
31
 
32
+ function appColumnType(column: IrTable['columns'][number]): IrColumnType {
33
+ return column.encrypted === true && column.declaredType !== undefined
34
+ ? column.declaredType
35
+ : column.type;
36
+ }
37
+
32
38
  /** §5.11: app-side Dart type — declaredType for an encrypted column. */
33
39
  function appDartType(column: IrTable['columns'][number]): string {
34
- const type =
35
- column.encrypted === true && column.declaredType !== undefined
36
- ? column.declaredType
37
- : column.type;
38
- return DART_TYPE[type];
40
+ return DART_TYPE[appColumnType(column)];
39
41
  }
40
42
 
41
43
  function pascalCase(name: string): string {
@@ -109,9 +111,9 @@ function emitSchemaValue(ir: IrDocument, indent: string): string[] {
109
111
  }
110
112
 
111
113
  /** The accessor lifting a §2.4 value out of a `Map<String, Object?>` row. */
112
- function rowAccessor(column: { type: IrColumnType; name: string }): string {
114
+ function rowAccessor(column: IrTable['columns'][number]): string {
113
115
  const key = `row[${quote(column.name)}]`;
114
- switch (column.type) {
116
+ switch (appColumnType(column)) {
115
117
  case 'string':
116
118
  case 'json':
117
119
  case 'blob_ref':
@@ -227,7 +229,9 @@ export function emitDartModule(ir: IrDocument, hash: string): string {
227
229
  // which the `type=lint` ignore above does not cover, so a schema without
228
230
  // boolean or bytes/crdt columns would fail a fatal-warnings `dart analyze`.
229
231
  const columnTypes = new Set(
230
- ir.tables.flatMap((table) => table.columns.map((column) => column.type)),
232
+ ir.tables.flatMap((table) =>
233
+ table.columns.map((column) => appColumnType(column)),
234
+ ),
231
235
  );
232
236
  if (columnTypes.has('boolean')) {
233
237
  parts.push(
@@ -28,13 +28,15 @@ const KOTLIN_TYPE: Readonly<Record<IrColumnType, string>> = {
28
28
  crdt: 'ByteArray',
29
29
  };
30
30
 
31
+ function appColumnType(column: IrTable['columns'][number]): IrColumnType {
32
+ return column.encrypted === true && column.declaredType !== undefined
33
+ ? column.declaredType
34
+ : column.type;
35
+ }
36
+
31
37
  /** §5.11: app-side Kotlin type — declaredType for an encrypted column. */
32
38
  function appKotlinType(column: IrTable['columns'][number]): string {
33
- const type =
34
- column.encrypted === true && column.declaredType !== undefined
35
- ? column.declaredType
36
- : column.type;
37
- return KOTLIN_TYPE[type];
39
+ return KOTLIN_TYPE[appColumnType(column)];
38
40
  }
39
41
 
40
42
  function pascalCase(name: string): string {
@@ -112,9 +114,9 @@ function emitSchemaValue(ir: IrDocument, indent: string): string[] {
112
114
  }
113
115
 
114
116
  /** The accessor lifting a §2.4 value out of a row `JsonValue`. */
115
- function rowAccessor(column: { type: IrColumnType; name: string }): string {
117
+ function rowAccessor(column: IrTable['columns'][number]): string {
116
118
  const key = `row[${quote(column.name)}]`;
117
- switch (column.type) {
119
+ switch (appColumnType(column)) {
118
120
  case 'string':
119
121
  case 'json':
120
122
  case 'blob_ref':
@@ -247,7 +249,9 @@ export function emitKotlinModule(
247
249
  // query emitter is unaffected — it declares its own queryRowBool/
248
250
  // queryRowBytes copies under distinct names.
249
251
  const columnTypes = new Set(
250
- ir.tables.flatMap((table) => table.columns.map((column) => column.type)),
252
+ ir.tables.flatMap((table) =>
253
+ table.columns.map((column) => appColumnType(column)),
254
+ ),
251
255
  );
252
256
  if (columnTypes.has('boolean')) {
253
257
  parts.push(
package/src/emit-swift.ts CHANGED
@@ -33,13 +33,15 @@ const SWIFT_TYPE: Readonly<Record<IrColumnType, string>> = {
33
33
  crdt: '[UInt8]',
34
34
  };
35
35
 
36
+ function appColumnType(column: IrTable['columns'][number]): IrColumnType {
37
+ return column.encrypted === true && column.declaredType !== undefined
38
+ ? column.declaredType
39
+ : column.type;
40
+ }
41
+
36
42
  /** §5.11: app-side Swift type — declaredType for an encrypted column. */
37
43
  function appSwiftType(column: IrTable['columns'][number]): string {
38
- const type =
39
- column.encrypted === true && column.declaredType !== undefined
40
- ? column.declaredType
41
- : column.type;
42
- return SWIFT_TYPE[type];
44
+ return SWIFT_TYPE[appColumnType(column)];
43
45
  }
44
46
 
45
47
  function pascalCase(name: string): string {
@@ -116,13 +118,9 @@ function emitSchemaValue(ir: IrDocument, indent: string): string[] {
116
118
  }
117
119
 
118
120
  /** The accessor that lifts a §2.4 value out of a `[String: JSONValue]` row. */
119
- function rowAccessor(column: {
120
- type: IrColumnType;
121
- name: string;
122
- nullable: boolean;
123
- }): string {
121
+ function rowAccessor(column: IrTable['columns'][number]): string {
124
122
  const key = `row[${quote(column.name)}]`;
125
- switch (column.type) {
123
+ switch (appColumnType(column)) {
126
124
  case 'string':
127
125
  case 'json':
128
126
  case 'blob_ref':
@@ -157,7 +155,7 @@ function emitStruct(table: IrTable): string[] {
157
155
  // Memberwise init (public, so app code can build rows too).
158
156
  const params = table.columns
159
157
  .map((c) => {
160
- const swift = SWIFT_TYPE[c.type];
158
+ const swift = appSwiftType(c);
161
159
  const opt = c.nullable ? '? = nil' : '';
162
160
  return `${camelCase(c.name)}: ${swift}${opt}`;
163
161
  })
package/src/lower.ts CHANGED
@@ -232,6 +232,90 @@ function expandStar(
232
232
  return table.columns.map((c) => `${prefix}${c.name}`);
233
233
  }
234
234
 
235
+ /**
236
+ * Rewrite bare references to renamed select aliases in the depth-0 ORDER BY
237
+ * and GROUP BY terms of `tail` (the SQL after the outer SELECT list). SQLite
238
+ * resolves an identifier in those clauses to a select alias before any column,
239
+ * so the rewrite preserves the authored meaning. A GROUP BY after a compound
240
+ * operator belongs to another SELECT and keeps its text; subqueries sit at
241
+ * depth ≥ 1 and cannot see the outer aliases.
242
+ */
243
+ function renameAliasRefs(
244
+ tail: string,
245
+ renamed: ReadonlyMap<string, string>,
246
+ ): string {
247
+ if (renamed.size === 0) return tail;
248
+ let out = '';
249
+ let depth = 0;
250
+ let clause: 'order' | 'group' | null = null;
251
+ let compound = false;
252
+ let prevWord = '';
253
+ let i = 0;
254
+ while (i < tail.length) {
255
+ const ch = tail[i] as string;
256
+ const next = tail[i + 1];
257
+ let end = i + 1;
258
+ if (ch === '-' && next === '-') {
259
+ const nl = tail.indexOf('\n', i);
260
+ end = nl === -1 ? tail.length : nl + 1;
261
+ } else if (ch === '/' && next === '*') {
262
+ const close = tail.indexOf('*/', i + 2);
263
+ end = close === -1 ? tail.length : close + 2;
264
+ } else if (ch === "'" || ch === '"') {
265
+ for (;;) {
266
+ if (end >= tail.length) break;
267
+ if (tail[end] === ch) {
268
+ if (tail[end + 1] === ch) end += 2;
269
+ else {
270
+ end += 1;
271
+ break;
272
+ }
273
+ } else end += 1;
274
+ }
275
+ } else if (ch === '(') {
276
+ depth += 1;
277
+ } else if (ch === ')') {
278
+ depth -= 1;
279
+ } else if (WORD_RE.test(ch)) {
280
+ while (end < tail.length && /[A-Za-z0-9_]/.test(tail[end] as string)) {
281
+ end += 1;
282
+ }
283
+ const word = tail.slice(i, end);
284
+ const lower = word.toLowerCase();
285
+ const following = /^\s*(.?)/.exec(tail.slice(end))?.[1];
286
+ if (depth === 0) {
287
+ if (lower === 'by' && prevWord === 'order') clause = 'order';
288
+ else if (lower === 'by' && prevWord === 'group') clause = 'group';
289
+ else if (['having', 'limit', 'offset', 'window'].includes(lower)) {
290
+ clause = null;
291
+ } else if (['union', 'intersect', 'except'].includes(lower)) {
292
+ compound = true;
293
+ clause = null;
294
+ }
295
+ }
296
+ const alias = renamed.get(lower);
297
+ if (
298
+ alias !== undefined &&
299
+ depth === 0 &&
300
+ (clause === 'order' || (clause === 'group' && !compound)) &&
301
+ out.trimEnd().slice(-1) !== '.' &&
302
+ following !== '.' &&
303
+ following !== '('
304
+ ) {
305
+ out += alias;
306
+ } else {
307
+ out += word;
308
+ }
309
+ prevWord = lower;
310
+ i = end;
311
+ continue;
312
+ }
313
+ out += tail.slice(i, end);
314
+ i = end;
315
+ }
316
+ return out;
317
+ }
318
+
235
319
  export interface LoweredProjection {
236
320
  /** The rewritten SQL (identical to the input when nothing needed
237
321
  * aliasing). */
@@ -301,6 +385,9 @@ export function lowerProjection(
301
385
  const langNames = buildMap(names);
302
386
 
303
387
  let changed = expanded;
388
+ // Authored aliases that were renamed; ORDER BY / GROUP BY references to them
389
+ // follow the rename below.
390
+ const renamedAliases = new Map<string, string>();
304
391
  const rewritten = flatItems.map((text, index) => {
305
392
  const resultName = names[index] as string;
306
393
  const langName = langNames[index] as string;
@@ -312,11 +399,13 @@ export function lowerProjection(
312
399
  const alias = `"${langName.replaceAll('"', '""')}"`;
313
400
  const explicit = EXPLICIT_ALIAS_RE.exec(text);
314
401
  if (explicit !== null && explicit[2] === resultName) {
402
+ renamedAliases.set(resultName.toLowerCase(), alias);
315
403
  return `${(explicit[1] as string).trim()} AS ${alias}`;
316
404
  }
317
405
  const implicit = TRAILING_IDENT_RE.exec(text);
318
406
  if (implicit !== null && implicit[2] === resultName) {
319
407
  // Implicit alias (`expr name`) — swap the trailing identifier.
408
+ renamedAliases.set(resultName.toLowerCase(), alias);
320
409
  return `${(implicit[1] as string).trim()} AS ${alias}`;
321
410
  }
322
411
  return `${text} AS ${alias}`;
@@ -327,7 +416,7 @@ export function lowerProjection(
327
416
  const span2 = expanded ? findProjection(expandedSql) : span;
328
417
  if (span2 === null) throw new Error('unreachable: projection vanished');
329
418
  return {
330
- sql: `${expandedSql.slice(0, span2.start)} ${rewritten.join(', ')} ${expandedSql.slice(span2.end)}`,
419
+ sql: `${expandedSql.slice(0, span2.start)} ${rewritten.join(', ')} ${renameAliasRefs(expandedSql.slice(span2.end), renamedAliases)}`,
331
420
  changed: true,
332
421
  sqlNames: names,
333
422
  langNames,
package/src/query.ts CHANGED
@@ -1432,14 +1432,19 @@ function inferReactiveMetadata(
1432
1432
  const char = cleaned[cursor];
1433
1433
  if (char === '(') stack.push(cursor);
1434
1434
  else if (char === ')') stack.pop();
1435
+ const atBoundary =
1436
+ cursor === 0 || !/[A-Za-z0-9_:]/.test(cleaned[cursor - 1] ?? '');
1435
1437
  if (
1436
1438
  cursor > index &&
1439
+ atBoundary &&
1437
1440
  /^(?:GROUP\s+BY|ORDER\s+BY|LIMIT|HAVING)\b/i.test(cleaned.slice(cursor))
1438
1441
  ) {
1439
1442
  break;
1440
1443
  }
1441
1444
  if (
1445
+ atBoundary &&
1442
1446
  /^OR\b/i.test(cleaned.slice(cursor)) &&
1447
+ stack.length <= matchStack.length &&
1443
1448
  stack.every((open, stackIndex) => matchStack[stackIndex] === open)
1444
1449
  ) {
1445
1450
  return false;
@@ -1471,8 +1476,8 @@ function inferReactiveMetadata(
1471
1476
  const column = scope.column.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1472
1477
  const qualified =
1473
1478
  qualifier === undefined
1474
- ? `(?:${IDENT}\\.)?${column}`
1475
- : `(?:${qualifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.)?${column}`;
1479
+ ? `(?<![A-Za-z0-9_.:])(?:${IDENT}\\.)?${column}\\b`
1480
+ : `(?<![A-Za-z0-9_.:])(?:${qualifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.)?${column}\\b`;
1476
1481
  const found: string[] = [];
1477
1482
  const equality = new RegExp(
1478
1483
  `${qualified}\\s*(?:=|==|\\bIS\\b)\\s*:(${IDENT})\\b|:(${IDENT})\\b\\s*(?:=|==)\\s*${qualified}`,
@@ -1372,6 +1372,7 @@ class Validator {
1372
1372
  if (char === '(') stack.push(cursor);
1373
1373
  else if (char === ')') stack.pop();
1374
1374
  if (
1375
+ (cursor === 0 || !/[A-Za-z0-9_:]/.test(cleaned[cursor - 1] ?? '')) &&
1375
1376
  /^OR\b/i.test(cleaned.slice(cursor)) &&
1376
1377
  stack.length <= matchStack.length &&
1377
1378
  stack.every((open, stackIndex) => matchStack[stackIndex] === open)
@@ -1585,8 +1586,8 @@ class Validator {
1585
1586
  }).length;
1586
1587
  const subject =
1587
1588
  unqualifiedMatches === 1
1588
- ? `(?:${alias}\\.)?${column}`
1589
- : `${alias}\\.${column}`;
1589
+ ? `(?<![A-Za-z0-9_.:])(?:${alias}\\.)?${column}\\b`
1590
+ : `(?<![A-Za-z0-9_.:])${alias}\\.${column}\\b`;
1590
1591
  const found: Array<{ name: string; operator: 'equal' | 'in' }> = [];
1591
1592
  const equality = new RegExp(
1592
1593
  `${subject}\\s*(?:=|==|\\bIS\\b)\\s*:([A-Za-z_][A-Za-z0-9_]*)\\b|:([A-Za-z_][A-Za-z0-9_]*)\\b\\s*(?:=|==)\\s*${subject}`,