@syncular/typegen 0.31.0 → 0.32.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.
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/typegen",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
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.0"
60
60
  },
61
61
  "devDependencies": {
62
- "@syncular/server": "0.31.0"
62
+ "@syncular/server": "0.32.0"
63
63
  }
64
64
  }
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,