uql-orm 0.100.1 → 0.100.3

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 (57) hide show
  1. package/README.md +8 -70
  2. package/dist/browser/uql-browser.min.js.map +1 -1
  3. package/dist/bunSql/bunSqlQuerierPool.js +3 -1
  4. package/dist/dialect/abstractSqlDialect.d.ts +32 -22
  5. package/dist/dialect/abstractSqlDialect.js +65 -59
  6. package/dist/dialect/hydrateColumn.d.ts +4 -5
  7. package/dist/dialect/hydrateColumn.js +2 -8
  8. package/dist/dialect/mysqlLikeSqlDialect.d.ts +4 -4
  9. package/dist/dialect/mysqlLikeSqlDialect.js +7 -6
  10. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -2
  11. package/dist/dialect/pgLikeSqlDialect.js +11 -3
  12. package/dist/http/fetchHandler.d.ts +1 -1
  13. package/dist/http/fetchHandler.js +1 -1
  14. package/dist/mariadb/mariaDialect.d.ts +2 -2
  15. package/dist/mariadb/mariaDialect.js +1 -0
  16. package/dist/migrate/cli-config.d.ts +2 -4
  17. package/dist/migrate/cli-config.js +4 -4
  18. package/dist/migrate/codegen/migrationFile.d.ts +1 -4
  19. package/dist/migrate/codegen/migrationFile.js +3 -5
  20. package/dist/migrate/codegen/sourceLiteral.d.ts +5 -3
  21. package/dist/migrate/codegen/sourceLiteral.js +8 -5
  22. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +1 -3
  23. package/dist/mongodb/mongoDialect.js +9 -7
  24. package/dist/mssql/mssqlDialect.d.ts +2 -2
  25. package/dist/mssql/mssqlDialect.js +1 -0
  26. package/dist/pglite/pgliteQuerierPool.js +6 -12
  27. package/dist/postgres/abstractPgQuerierPool.d.ts +0 -1
  28. package/dist/postgres/abstractPgQuerierPool.js +0 -3
  29. package/dist/postgres/pgQuerier.d.ts +6 -0
  30. package/dist/postgres/pgQuerier.js +10 -0
  31. package/dist/postgres/pgWireTypes.d.ts +11 -7
  32. package/dist/postgres/pgWireTypes.js +47 -11
  33. package/dist/querier/abstractPoolQuerier.d.ts +2 -0
  34. package/dist/querier/abstractPoolQuerier.js +5 -1
  35. package/dist/querier/abstractQuerier.d.ts +1 -5
  36. package/dist/querier/abstractQuerier.js +18 -17
  37. package/dist/querier/abstractSqlQuerier.d.ts +6 -20
  38. package/dist/querier/abstractSqlQuerier.js +27 -94
  39. package/dist/querier/abstractSqlQuerierPool.d.ts +3 -5
  40. package/dist/querier/abstractSqlQuerierPool.js +2 -5
  41. package/dist/querier/rowReader.d.ts +8 -0
  42. package/dist/querier/rowReader.js +88 -0
  43. package/dist/sqlite/sqliteDialect.d.ts +2 -2
  44. package/dist/sqlite/sqliteDialect.js +2 -1
  45. package/dist/type/querier.d.ts +3 -5
  46. package/dist/type/queryRaw.d.ts +4 -1
  47. package/dist/type/queryRaw.js +2 -2
  48. package/dist/util/dialect.util.d.ts +2 -11
  49. package/dist/util/dialect.util.js +8 -21
  50. package/dist/util/query.util.js +16 -8
  51. package/dist/util/raw.js +19 -16
  52. package/dist/util/sql.util.d.ts +0 -5
  53. package/dist/util/sql.util.js +0 -33
  54. package/dist/util/wideNumber.d.ts +4 -3
  55. package/dist/util/wideNumber.js +17 -6
  56. package/package.json +3 -4
  57. package/skills/uql-orm/SKILL.md +2 -2
@@ -150,6 +150,17 @@ export class AbstractSqlDialect extends VectorSqlDialect {
150
150
  createContext(options = {}) {
151
151
  return new SqlQueryContext(this, [], undefined, options.inlineValues);
152
152
  }
153
+ /** A statement as it is sent: the SQL `build` writes, or a `raw` renders, and the values it binds. */
154
+ compile(build) {
155
+ const ctx = this.createContext();
156
+ if (build instanceof QueryRaw) {
157
+ this.getRawValue(ctx, { value: build });
158
+ }
159
+ else {
160
+ build(ctx);
161
+ }
162
+ return { sql: ctx.sql, values: ctx.values };
163
+ }
153
164
  /**
154
165
  * The SQL `build` writes, as text to embed rather than appended to `ctx`. It binds into `ctx`'s own values
155
166
  * and aliases, so `$n` placeholders number against the whole statement.
@@ -198,12 +209,6 @@ export class AbstractSqlDialect extends VectorSqlDialect {
198
209
  }
199
210
  return value;
200
211
  }
201
- /**
202
- * Normalizes a list of parameter values.
203
- */
204
- normalizeValues(values) {
205
- return values?.map((v) => this.normalizeValue(v));
206
- }
207
212
  placeholder(_index) {
208
213
  return '?';
209
214
  }
@@ -254,7 +259,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
254
259
  const missingIds = opts.joined ? meta.ids.filter((key) => !selected.includes(key)) : [];
255
260
  const keys = missingIds.length ? [...missingIds, ...selected] : selected;
256
261
  if (!keys.length) {
257
- return [{ sql: `${this.escapeId(opts.prefix, true, true)}*`, bare: true }];
262
+ const kinds = definedEntries(meta.fields).flatMap(([key, field]) => {
263
+ const kind = this.fieldKind(meta, field);
264
+ return kind ? [[key, kind]] : [];
265
+ });
266
+ return [{ sql: `${this.escapeId(opts.prefix, true, true)}*`, bare: true, kinds }];
258
267
  }
259
268
  return keys.map((key) => key instanceof QueryRaw
260
269
  ? { sql: this.rawFragment(ctx, key, opts.prefix), key: key[RAW_ALIAS] }
@@ -263,17 +272,18 @@ export class AbstractSqlDialect extends VectorSqlDialect {
263
272
  /** One field's column, or the expression an inlined one stands for, as the projection reads it. */
264
273
  fieldTerm(ctx, meta, key, opts) {
265
274
  const field = fieldOf(meta, key);
275
+ const kind = this.fieldKind(meta, field, opts.json);
266
276
  if (isInlinedExpression(field)) {
267
277
  // Qualified even when nothing else in this statement is: the expression is spliced in, and one
268
278
  // that opens a correlated subquery has the inner table's columns in scope, so a bare `"id"`
269
279
  // would bind to *that* table instead of this one.
270
280
  const sql = this.rawFragment(ctx, field.computed, opts.prefix ?? this.resolveTableAlias(meta), meta.entity);
271
- return { sql: opts.json ? this.carried(`(${sql})`, field) : sql, key };
281
+ return { sql: opts.json ? this.carried(`(${sql})`, field) : sql, key, kind };
272
282
  }
273
283
  const columnName = this.resolveColumnName(key, field);
274
284
  const column = this.escapeId(opts.prefix, true, true) + this.escapeId(columnName);
275
285
  const sql = opts.json ? this.carried(column, field) : this.selectFieldExpr(column, field);
276
- return { sql, key, bare: sql === column && columnName === key };
286
+ return { sql, key, bare: sql === column && columnName === key, kind };
277
287
  }
278
288
  /**
279
289
  * What follows `SELECT` before the projection. Empty everywhere but SQL Server, whose `FETCH` will
@@ -449,8 +459,16 @@ export class AbstractSqlDialect extends VectorSqlDialect {
449
459
  ...this.selectTerms(ctx, join.entity, join.query.$select, opts, join.query.$exclude),
450
460
  ...this.selectToManyRelations(ctx, join.meta, join.query.$populate, join.alias, distinct),
451
461
  ];
462
+ const [idKey] = join.meta.ids;
452
463
  for (const term of row) {
453
- terms.push({ sql: term.sql, key: `${join.path}.${relationTermKey(term)}` });
464
+ const key = relationTermKey(term);
465
+ terms.push({
466
+ sql: term.sql,
467
+ kind: term.kind,
468
+ rows: term.rows,
469
+ key: `${join.path}.${key}`,
470
+ joinedKey: key === idKey,
471
+ });
454
472
  }
455
473
  }
456
474
  return terms;
@@ -1058,6 +1076,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1058
1076
  // may name these and nothing else, so one map answers both "is this legal?" and "what do I
1059
1077
  // emit for it?".
1060
1078
  const emittedColumns = {};
1079
+ const kinds = [];
1061
1080
  for (const { entry, value } of reads) {
1062
1081
  const column = derived ? this.escapeId(entry.alias) : value.sql;
1063
1082
  const expr = entry.kind === 'key' ? column : this.aggregateFn(entry.op, value.sql === '*' ? '*' : column, entry.distinct);
@@ -1066,6 +1085,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1066
1085
  }
1067
1086
  emittedColumns[entry.alias] = expr;
1068
1087
  selectParts.push(named(expr, entry.alias));
1088
+ const kind = this.groupEntryKind(meta, joins, entry);
1089
+ if (kind) {
1090
+ kinds.push([entry.alias, kind]);
1091
+ }
1069
1092
  }
1070
1093
  const columns = reads.flatMap(({ entry, value }) => (value.sql === '*' ? [] : [named(value.sql, entry.alias)]));
1071
1094
  ctx.append(`SELECT ${selectParts.join(', ')} FROM ${derived ? `(SELECT ${columns.join(', ')} FROM ` : ''}${table.ref}`);
@@ -1080,6 +1103,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1080
1103
  this.having(ctx, q.$having ?? {}, emittedColumns);
1081
1104
  const sorted = this.aggregateSort(ctx, q.$sort, emittedColumns);
1082
1105
  this.pager(ctx, q, sorted);
1106
+ return [{ sql: selectParts.join(', '), kinds }];
1083
1107
  }
1084
1108
  /**
1085
1109
  * What one entry reads: a grouped field, through the join its path passes, or an aggregate's argument,
@@ -1173,13 +1197,14 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1173
1197
  * LIMIT/OFFSET, so what it counts is the whole match rather than the page cut out of it.
1174
1198
  */
1175
1199
  totalOverExpr = 'COUNT(*) OVER ()';
1200
+ /** A read, answering with the terms its rows answer under, which say how each reads back. */
1176
1201
  find(ctx, entity, q = {}, opts, totalAlias) {
1177
1202
  const meta = getMeta(entity);
1178
1203
  const read = this.readOptions(ctx, meta, opts);
1179
1204
  // The one statement that can join, so the one that resolves the join set; everything else renders
1180
1205
  // against `NO_JOINS` and rejects a `$sort` that would need one. The joins claim their aliases after
1181
1206
  // the table's own.
1182
- this.read(ctx, entity, q, read, resolveQueryJoins(meta, q, (path) => ctx.claimAlias(path)), totalAlias);
1207
+ return this.read(ctx, entity, q, read, resolveQueryJoins(meta, q, (path) => ctx.claimAlias(path)), totalAlias).terms;
1183
1208
  }
1184
1209
  /**
1185
1210
  * A read's whole statement. The lock is appended here rather than in `search`, which `count`,
@@ -1567,46 +1592,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1567
1592
  const family = columnFamily(field?.type);
1568
1593
  return family === 'json' || family === 'vector' ? family : 'plain';
1569
1594
  }
1570
- /**
1571
- * The columns a read decodes, and how, cached per entity and revision. They are the ones the wire cannot
1572
- * decide alone: a boolean stored as an integer, a decimal read as text, a `BigInt`, and a related row's
1573
- * values, which cross JSON as text.
1574
- */
1575
- hydratableFields(entity) {
1576
- const meta = getMeta(entity);
1577
- const cached = this.hydratable.get(entity);
1578
- // Against the revision, not merely present: a field added to an entity already read - a content
1579
- // type the admin extended - would otherwise decode by the list its columns are missing from.
1580
- if (cached?.[0] === meta.revision) {
1581
- return cached[1];
1582
- }
1583
- const decoded = [];
1584
- for (const [key, field] of Object.entries(meta.fields)) {
1585
- const kind = this.fieldKind(meta, field);
1586
- if (kind) {
1587
- decoded.push([key, kind]);
1588
- }
1595
+ /** How an aggregate's entry decodes: as the column it reads, or a number where it reads none (a tally, a mean). */
1596
+ groupEntryKind(meta, joins, entry) {
1597
+ const source = aggregateColumnField(meta, joins, entry);
1598
+ if (!source) {
1599
+ return 'number';
1589
1600
  }
1590
- this.hydratable.set(entity, [meta.revision, decoded]);
1591
- return decoded;
1592
- }
1593
- /** The same for an aggregate's row, per query: each alias decodes by {@link aggregateKind}. */
1594
- hydratableAggregates(entity, q) {
1595
- const meta = getMeta(entity);
1596
- const { joins } = resolveGroupJoins(meta, q);
1597
- const decoded = [];
1598
- for (const entry of parseGroupMap(q.$group, q.$select)) {
1599
- const source = aggregateColumnField(meta, joins, entry);
1600
- const kind = !source
1601
- ? 'number'
1602
- : source.join
1603
- ? this.fieldKind(source.join.meta, source.field)
1604
- : this.fieldKind(meta, source.field);
1605
- if (kind) {
1606
- decoded.push([entry.alias, kind]);
1607
- }
1608
- }
1609
- return decoded;
1601
+ return source.join
1602
+ ? this.fieldKind(source.join.meta, source.field, true)
1603
+ : this.fieldKind(meta, source.field, true);
1610
1604
  }
1611
1605
  /**
1612
1606
  * What an aggregate's value decodes as, which the engine widens beyond the column it read: a tally
@@ -1619,14 +1613,18 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1619
1613
  aggregateKind(op, fieldKind) {
1620
1614
  return op === '$count' || op === '$avg' ? 'number' : fieldKind;
1621
1615
  }
1622
- /** What a field decodes as: its column's kind, or a relation aggregate's {@link aggregateKind} over the target's column. */
1623
- fieldKind(meta, field) {
1616
+ /**
1617
+ * What a field decodes as: its column's kind, or a relation aggregate's {@link aggregateKind}. `undecoded` is a
1618
+ * value the driver decodes nothing of, one crossing JSON or an aggregate; on the wire it may decode some itself.
1619
+ */
1620
+ fieldKind(meta, field, undecoded) {
1624
1621
  const spec = aggregateOf(field);
1625
1622
  if (!spec) {
1626
- return this.hydrateKind(field);
1623
+ const kind = this.hydrateKind(field);
1624
+ return kind && !undecoded && this.decodedAtWire(kind, field) ? undefined : kind;
1627
1625
  }
1628
1626
  const target = getMeta(relationOf(meta, spec.relation).entity());
1629
- return this.aggregateKind(spec.op, spec.field ? this.fieldKind(target, target.fields[spec.field]) : undefined);
1627
+ return this.aggregateKind(spec.op, spec.field ? this.fieldKind(target, target.fields[spec.field], true) : undefined);
1630
1628
  }
1631
1629
  /** What one column decodes as, the inverse of {@link persistKind}. `BigInt` first, since it shares the numeric family. */
1632
1630
  hydrateKind(field) {
@@ -1654,7 +1652,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1654
1652
  return undefined;
1655
1653
  }
1656
1654
  }
1657
- hydratable = new WeakMap();
1655
+ /** Whether this dialect's drivers hand a column of `kind` back decoded already, as a row on the wire. */
1656
+ decodedAtWire(_kind, _field) {
1657
+ return false;
1658
+ }
1658
1659
  /** The one type dispatch for a persisted value, over a column kind decided by the caller. */
1659
1660
  writePersistableValue(ctx, kind, field, value) {
1660
1661
  if (value instanceof QueryRaw) {
@@ -1937,15 +1938,19 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1937
1938
  selectToManyRelations(ctx, meta, populate, parent, distinct) {
1938
1939
  return getRelationRequestSummary(meta, populate).toManyKeys.map((relKey) => {
1939
1940
  const { query } = parseRelationAtKey(relKey, populate);
1940
- const sql = this.buildFragment(ctx, (fragmentCtx) => this.appendToManyRelation(fragmentCtx, meta, relKey, query, parent, distinct));
1941
- return { sql, key: relKey };
1941
+ let rows = [];
1942
+ const sql = this.buildFragment(ctx, (fragmentCtx) => {
1943
+ rows = this.appendToManyRelation(fragmentCtx, meta, relKey, query, parent, distinct);
1944
+ });
1945
+ return { sql, key: relKey, rows };
1942
1946
  });
1943
1947
  }
1944
1948
  /** Each relation a read's `$count` tallies, as a correlated count of its select list. */
1945
1949
  selectRelationCounts(ctx, meta, count, parent) {
1946
1950
  return countedRelations(meta, count).map(({ relKey, relation, where }) => {
1947
1951
  const sql = this.buildFragment(ctx, (fragmentCtx) => this.appendRelationSubquery(fragmentCtx, meta, relKey, relation, { prefix: parent }, { op: '$count', where }));
1948
- return { sql, key: `${COUNT_RESULT_KEY}.${relKey}` };
1952
+ // A tally comes back as its driver reads a COUNT, which on some is text.
1953
+ return { sql, key: `${COUNT_RESULT_KEY}.${relKey}`, kind: 'number' };
1949
1954
  });
1950
1955
  }
1951
1956
  /**
@@ -1961,7 +1966,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1961
1966
  const correlation = raw(({ ctx: rowsCtx }) => this.appendCorrelation(rowsCtx, meta, relation, parent, alias));
1962
1967
  const rows = { ...query, $where: whereAnd(query.$where, [correlation]) };
1963
1968
  const joins = resolveQueryJoins(relMeta, rows, (path) => ctx.claimAlias(path));
1964
- this.appendRelationArray(ctx, { entity, query: rows, alias, joins, distinct });
1969
+ return this.appendRelationArray(ctx, { entity, query: rows, alias, joins, distinct });
1965
1970
  }
1966
1971
  /**
1967
1972
  * A relation that deduplicates its rows is sorted only by what it selects: `SELECT DISTINCT` orders by
@@ -2017,6 +2022,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
2017
2022
  const { terms, order = [] } = this.read(rowsCtx, rows.entity, rows.query, readOpts, rows.joins);
2018
2023
  const alias = this.escapeId(rows.alias, true);
2019
2024
  return {
2025
+ terms,
2020
2026
  from: `(${rowsCtx.sql}) ${alias}`,
2021
2027
  pairs: terms.map((term) => {
2022
2028
  const key = relationTermKey(term);
@@ -7,13 +7,12 @@ import { type VectorCast } from './vectorCast.js';
7
7
  * a vector bound as bytes (`DialectFeatures.vectorBytes`).
8
8
  */
9
9
  export type HydrateKind = 'json' | 'boolean' | 'number' | 'bigint' | 'decimal' | 'date' | 'bytes' | 'float32' | VectorCast;
10
- /**
11
- * Decodes one non-null cell. A no-op where the driver already decoded it, since that varies per driver,
12
- * and untouched where it does not match its column's format.
13
- */
14
- export declare function decodeColumn(value: unknown, kind: HydrateKind): unknown;
10
+ type Decoder = (value: unknown) => unknown;
11
+ /** How a non-null cell of each kind decodes, keeping one already decoded or not in its kind's format. */
12
+ export declare const DECODERS: Readonly<Record<HydrateKind, Decoder>>;
15
13
  /**
16
14
  * What bytes crossing JSON start with, before two hex digits per byte: Postgres's own text for `bytea`,
17
15
  * which every dialect spells, so a string a driver reads from a column on its own is never mistaken.
18
16
  */
19
17
  export declare const BYTES_PREFIX = "\\x";
18
+ export {};
@@ -2,13 +2,6 @@ import { hexToBytes } from '../util/bytes.js';
2
2
  import { decodeDate } from '../util/date.js';
3
3
  import { decodeWideNumber } from '../util/wideNumber.js';
4
4
  import { decodeFloat32s, parseVectorLiteral } from './vectorCast.js';
5
- /**
6
- * Decodes one non-null cell. A no-op where the driver already decoded it, since that varies per driver,
7
- * and untouched where it does not match its column's format.
8
- */
9
- export function decodeColumn(value, kind) {
10
- return DECODERS[kind](value);
11
- }
12
5
  /** A decoder of the text a driver returned; anything else it already decoded, and is kept. */
13
6
  function fromText(decode) {
14
7
  return (value) => {
@@ -30,7 +23,8 @@ const float32Decoder = (value) => {
30
23
  }
31
24
  return value instanceof Uint8Array ? decodeFloat32s(value) : denseVector(value);
32
25
  };
33
- const DECODERS = {
26
+ /** How a non-null cell of each kind decodes, keeping one already decoded or not in its kind's format. */
27
+ export const DECODERS = {
34
28
  // 0/1 from SQLite's INTEGER or MySQL's TINYINT(1). Already a boolean on Postgres.
35
29
  boolean: (value) => (typeof value === 'boolean' ? value : Boolean(value)),
36
30
  date: (value) => (typeof value === 'string' ? decodeDate(value) : value),
@@ -1,5 +1,5 @@
1
1
  import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, Type, UpdatePayload } from '../type/index.js';
2
- import { AbstractSqlDialect, type DerivedRelation, type RelationRows } from './abstractSqlDialect.js';
2
+ import { AbstractSqlDialect, type DerivedRelation, type RelationRows, type SelectTerm } from './abstractSqlDialect.js';
3
3
  import { type JsonSlot } from './jsonSql.js';
4
4
  /** Declared apart so MariaDB, which has no `FOR UPDATE OF`, can restate that one part of it. */
5
5
  export declare const MYSQL_ROW_LOCKS: RowLockFeatures;
@@ -52,9 +52,9 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
52
52
  * An ordered `GROUP_CONCAT` of each row's object, which reads as a JSON array: MySQL's `JSON_ARRAYAGG`
53
53
  * takes no `ORDER BY`, and as a window over the rows it rebuilds the array for every one of them.
54
54
  */
55
- protected appendRelationArray(ctx: QueryContext, rows: RelationRows): void;
55
+ protected appendRelationArray(ctx: QueryContext, rows: RelationRows): readonly SelectTerm[];
56
56
  /** A read's statement, with the settings it needs applied to it alone. */
57
- find<E>(ctx: QueryContext, entity: Type<E>, q?: Query<E>, opts?: QueryOptions, totalAlias?: string): void;
57
+ find<E>(ctx: QueryContext, entity: Type<E>, q?: Query<E>, opts?: QueryOptions, totalAlias?: string): readonly SelectTerm[];
58
58
  /** A `$distinct` read's count, which reads the relations the read does. */
59
59
  countDistinct<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts?: QueryOptions): void;
60
60
  private settled;
@@ -76,7 +76,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
76
76
  blob: (expr: string) => string;
77
77
  vector: (expr: string, field: import("../type/entity.js").FieldOptions) => string;
78
78
  };
79
- /** Bytes as the hex text `decodeColumn` reads back, whole. */
79
+ /** Bytes as the hex text `DECODERS.bytes` reads back, whole. */
80
80
  protected bytesAsText(expr: string): string;
81
81
  escape(value: unknown): string;
82
82
  /** A date as UTC text, which a `DATETIME` stores as is, where a driver would convert it to its own zone. */
@@ -139,13 +139,14 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
139
139
  * takes no `ORDER BY`, and as a window over the rows it rebuilds the array for every one of them.
140
140
  */
141
141
  appendRelationArray(ctx, rows) {
142
- const { from, pairs, order } = this.derivedRelation(ctx, rows);
142
+ const { terms, from, pairs, order } = this.derivedRelation(ctx, rows);
143
143
  const objects = `${this.jsonObject(pairs)}${order ? ` ORDER BY ${order}` : ''} SEPARATOR ','`;
144
144
  ctx.append(`(SELECT COALESCE(CONCAT('[', GROUP_CONCAT(${objects}), ']'), '[]') FROM ${from})`);
145
+ return terms;
145
146
  }
146
147
  /** A read's statement, with the settings it needs applied to it alone. */
147
148
  find(ctx, entity, q = {}, opts, totalAlias) {
148
- this.settled(ctx, entity, q, (statement) => super.find(statement, entity, q, opts, totalAlias));
149
+ return this.settled(ctx, entity, q, (statement) => super.find(statement, entity, q, opts, totalAlias));
149
150
  }
150
151
  /** A `$distinct` read's count, which reads the relations the read does. */
151
152
  countDistinct(ctx, entity, q, opts) {
@@ -154,12 +155,12 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
154
155
  settled(ctx, entity, q, build) {
155
156
  const settings = this.statementSettings(entity, q);
156
157
  if (!settings.length) {
157
- build(ctx);
158
- return;
158
+ return build(ctx);
159
159
  }
160
160
  const statement = ctx.createFragment();
161
- build(statement);
161
+ const built = build(statement);
162
162
  ctx.append(this.applySettings(statement.sql, settings));
163
+ return built;
163
164
  }
164
165
  /**
165
166
  * `name=value` for each variable a read's statement sets for itself alone. `GROUP_CONCAT`, and
@@ -181,7 +182,7 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
181
182
  blob: (expr) => this.bytesAsText(expr),
182
183
  vector: (expr, field) => this.selectFieldExpr(expr, field),
183
184
  };
184
- /** Bytes as the hex text `decodeColumn` reads back, whole. */
185
+ /** Bytes as the hex text `DECODERS.bytes` reads back, whole. */
185
186
  bytesAsText(expr) {
186
187
  return `CONCAT(${this.escape(BYTES_PREFIX)}, HEX(${expr}))`;
187
188
  }
@@ -2,7 +2,8 @@ import type { IndexType } from '../schema/types.js';
2
2
  import type { SqlDialectName, SqlValues } from '../type/index.js';
3
3
  import { type DriverCapabilities, type EntityMeta, type FieldOptions, type JsonColumnType, type Query, type QueryContext, type QueryTextSearchOptions, type SqlDialectFeatures, type VectorDistance, type VectorMetric } from '../type/index.js';
4
4
  import type { DialectOptions } from './abstractDialect.js';
5
- import { AbstractSqlDialect, type RelationRows } from './abstractSqlDialect.js';
5
+ import { AbstractSqlDialect, type RelationRows, type SelectTerm } from './abstractSqlDialect.js';
6
+ import { type HydrateKind } from './hydrateColumn.js';
6
7
  import { type JsonAccessMode, type JsonSlot } from './jsonSql.js';
7
8
  /** A Postgres-wire dialect's options: the base's, and how its driver binds a parameter. */
8
9
  export type PgLikeDialectOptions = DialectOptions & {
@@ -32,7 +33,12 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
32
33
  * builds it, so a wide row meets no argument limit. `json` has no equality, so under a parent's
33
34
  * `DISTINCT` the array is compared as `jsonb`.
34
35
  */
35
- protected appendRelationArray(ctx: QueryContext, rows: RelationRows): void;
36
+ protected appendRelationArray(ctx: QueryContext, rows: RelationRows): readonly SelectTerm[];
37
+ /**
38
+ * Every Postgres-wire pool hands back a `BOOLEAN`, a date and an integer column decoded (an `INT8` by the
39
+ * pools' own wide-number rule); a `NUMERIC`, a float and anything crossing JSON still decode as the base says.
40
+ */
41
+ protected decodedAtWire(kind: HydrateKind, field: FieldOptions | undefined): boolean;
36
42
  /**
37
43
  * What JSON would round or cannot spell crosses it as text, for the field's own decode to read back:
38
44
  * a column declared numeric, whatever it decodes as, a vector, and bytes as hex.
@@ -1,9 +1,9 @@
1
1
  import { QueryRaw, } from '../type/index.js';
2
2
  import { bytesToHex } from '../util/bytes.js';
3
3
  import { fulltextConfig, fulltextIndexOver, hasVectorNear, textSearchFields } from '../util/dialect.util.js';
4
- import { jsonPathKeys } from '../util/field.util.js';
4
+ import { isIntegerColumn, jsonPathKeys } from '../util/field.util.js';
5
5
  import { escapePgSqlLiteral, PG_UTC } from '../util/sqlLiteral.js';
6
- import { ANSI_SQL_VALUES, AbstractSqlDialect } from './abstractSqlDialect.js';
6
+ import { ANSI_SQL_VALUES, AbstractSqlDialect, } from './abstractSqlDialect.js';
7
7
  import { JSON_PULL_ALIAS, RELATION_ROW_ALIAS } from './aliases.js';
8
8
  import { BYTES_PREFIX } from './hydrateColumn.js';
9
9
  import { jsonSetTarget } from './jsonSql.js';
@@ -84,11 +84,19 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
84
84
  * `DISTINCT` the array is compared as `jsonb`.
85
85
  */
86
86
  appendRelationArray(ctx, rows) {
87
- const { from, pairs, order } = this.derivedRelation(ctx, rows);
87
+ const { terms, from, pairs, order } = this.derivedRelation(ctx, rows);
88
88
  const row = this.escapeId(RELATION_ROW_ALIAS, true);
89
89
  const columns = pairs.map(([, column]) => column).join(', ');
90
90
  const array = /*sql*/ `(SELECT COALESCE(JSON_AGG(${row}${order ? ` ORDER BY ${order}` : ''}), '[]'::json) FROM ${from} CROSS JOIN LATERAL (SELECT ${columns}) ${row})`;
91
91
  ctx.append(rows.distinct ? `${array}::jsonb` : array);
92
+ return terms;
93
+ }
94
+ /**
95
+ * Every Postgres-wire pool hands back a `BOOLEAN`, a date and an integer column decoded (an `INT8` by the
96
+ * pools' own wide-number rule); a `NUMERIC`, a float and anything crossing JSON still decode as the base says.
97
+ */
98
+ decodedAtWire(kind, field) {
99
+ return kind === 'boolean' || kind === 'date' || (kind === 'number' && !!field && isIntegerColumn(field));
92
100
  }
93
101
  /**
94
102
  * What JSON would round or cannot spell crosses it as text, for the field's own decode to read back:
@@ -8,6 +8,6 @@ export type FetchHandlerOptions = RequestHandlerOptions<Request> & {
8
8
  /**
9
9
  * Web-standard adapter over {@link createRequestHandler}: mount the returned
10
10
  * `(request: Request) => Promise<Response>` in any fetch-native runtime
11
- * (Hono, Next.js route handlers, Bun.serve, Deno.serve, Cloudflare Workers, SvelteKit).
11
+ * (Hono, Next.js route handlers, Bun.serve, Cloudflare Workers, SvelteKit).
12
12
  */
13
13
  export declare function createFetchHandler(opts: FetchHandlerOptions): (request: Request) => Promise<Response>;
@@ -4,7 +4,7 @@ import { createRequestHandler } from './handler.js';
4
4
  /**
5
5
  * Web-standard adapter over {@link createRequestHandler}: mount the returned
6
6
  * `(request: Request) => Promise<Response>` in any fetch-native runtime
7
- * (Hono, Next.js route handlers, Bun.serve, Deno.serve, Cloudflare Workers, SvelteKit).
7
+ * (Hono, Next.js route handlers, Bun.serve, Cloudflare Workers, SvelteKit).
8
8
  */
9
9
  export function createFetchHandler(opts) {
10
10
  const { basePath = '', ...handlerOpts } = opts;
@@ -1,4 +1,4 @@
1
- import { type RelationRows } from '../dialect/abstractSqlDialect.js';
1
+ import { type RelationRows, type SelectTerm } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode } from '../dialect/jsonSql.js';
3
3
  import { MysqlLikeSqlDialect } from '../dialect/mysqlLikeSqlDialect.js';
4
4
  import type { FieldOptions, Query, QueryContext, SqlDialectFeatures, SqlValues, Type, VectorDistance, VectorMetric } from '../type/index.js';
@@ -17,7 +17,7 @@ export declare class MariaDialect extends MysqlLikeSqlDialect {
17
17
  * A derived table here reads no column of the statement around it, so the aggregate reads the
18
18
  * related table itself, and orders and pages inside `JSON_ARRAYAGG`, which takes both.
19
19
  */
20
- protected appendRelationArray(ctx: QueryContext, { entity, query, alias, joins }: RelationRows): void;
20
+ protected appendRelationArray(ctx: QueryContext, { entity, query, alias, joins }: RelationRows): readonly SelectTerm[];
21
21
  /**
22
22
  * `JSON_EXTRACT` for the value and `JSON_VALUE` for its text, which every version has: MySQL's `->`/`->>`
23
23
  * arrive only in 13.1.
@@ -38,6 +38,7 @@ export class MariaDialect extends MysqlLikeSqlDialect {
38
38
  const object = this.jsonObject(terms.map((term) => [relationTermKey(term), term.sql]));
39
39
  const rows = `${query.$distinct ? 'DISTINCT ' : ''}${object}${order}${page}`;
40
40
  ctx.append(`COALESCE((SELECT JSON_ARRAYAGG(${rows}) FROM ${this.tableRef(meta, alias).ref}${from}), JSON_ARRAY())`);
41
+ return terms;
41
42
  }
42
43
  /**
43
44
  * `JSON_EXTRACT` for the value and `JSON_VALUE` for its text, which every version has: MySQL's `->`/`->>`
@@ -2,21 +2,19 @@ import type { Config } from '../type/index.js';
2
2
  import { UqlUsageError } from '../util/uqlError.js';
3
3
  /**
4
4
  * The project's own `tsx/esm/api` where Node must load a TypeScript config: Node's type stripping runs
5
- * no decorators, and Bun and Deno transform them natively. uql bundles no transpiler, so the project's
5
+ * no decorators, and Bun transforms them natively. uql bundles no transpiler, so the project's
6
6
  * loader reads the project's `tsconfig.json`. Registered for the process, never imported through: an
7
7
  * import of its own would load the config's `uql-orm` apart from the CLI's, whose objects the other misreads.
8
8
  */
9
9
  export declare function tsxApiFor(path: string, versions: {
10
10
  bun?: string;
11
- deno?: string;
12
11
  }): string | undefined;
13
12
  /**
14
13
  * Why `path` failed to import. Only plain Node, which strips types without running decorators, can fail on
15
- * those, so only there does it point at a runtime that runs them: Bun, Deno, or the project's tsx.
14
+ * those, so only there does it point at a runtime that runs them: Bun or the project's tsx.
16
15
  */
17
16
  export declare function importFailure(path: string, cause: unknown, versions: {
18
17
  bun?: string;
19
- deno?: string;
20
18
  }, tsxApi: string | undefined): UqlUsageError;
21
19
  /** The config at `customPath`, or the first of {@link CONFIG_FILES} in the working directory; the CLI validates it. */
22
20
  export declare function loadConfig(customPath?: string): Promise<Config>;
@@ -5,12 +5,12 @@ import { pathToFileURL } from 'node:url';
5
5
  import { UqlUsageError } from '../util/uqlError.js';
6
6
  /**
7
7
  * The project's own `tsx/esm/api` where Node must load a TypeScript config: Node's type stripping runs
8
- * no decorators, and Bun and Deno transform them natively. uql bundles no transpiler, so the project's
8
+ * no decorators, and Bun transforms them natively. uql bundles no transpiler, so the project's
9
9
  * loader reads the project's `tsconfig.json`. Registered for the process, never imported through: an
10
10
  * import of its own would load the config's `uql-orm` apart from the CLI's, whose objects the other misreads.
11
11
  */
12
12
  export function tsxApiFor(path, versions) {
13
- if (!/\.[mc]?ts$/.test(path) || versions.bun || versions.deno) {
13
+ if (!/\.[mc]?ts$/.test(path) || versions.bun) {
14
14
  return undefined;
15
15
  }
16
16
  try {
@@ -36,11 +36,11 @@ async function importConfig(path) {
36
36
  }
37
37
  /**
38
38
  * Why `path` failed to import. Only plain Node, which strips types without running decorators, can fail on
39
- * those, so only there does it point at a runtime that runs them: Bun, Deno, or the project's tsx.
39
+ * those, so only there does it point at a runtime that runs them: Bun or the project's tsx.
40
40
  */
41
41
  export function importFailure(path, cause, versions, tsxApi) {
42
42
  const message = cause instanceof Error ? cause.message : String(cause);
43
- const hint = tsxApi || versions.bun || versions.deno
43
+ const hint = tsxApi || versions.bun
44
44
  ? ''
45
45
  : '\nIf it reaches entity classes, their decorators need a runtime that transforms TypeScript, not ' +
46
46
  'just one that strips its types. Run the CLI with `bun`, or install tsx (`npm i -D tsx`), which the ' +
@@ -12,10 +12,7 @@ export type MigrationModuleOptions = {
12
12
  /** Indented body inside `async down` (including newlines). */
13
13
  downInner: string;
14
14
  };
15
- /**
16
- * One `await querier.run`...`` line, the SQL a template binding nothing, so its lines and quotes read as
17
- * written; a backslash, a backtick and a `${` are escaped.
18
- */
15
+ /** One `await querier.run`...`` line, its SQL as written. */
19
16
  export declare function emitSqlRunCall(sql: string): string;
20
17
  /** Indented `up`/`down` body: one `await querier.run`...`` per SQL string. */
21
18
  export declare function emitSqlRunCalls(statements: string[]): string;
@@ -1,10 +1,8 @@
1
1
  import { mongoCommandSource } from '../../mongodb/mongoCommand.js';
2
- /**
3
- * One `await querier.run`...`` line, the SQL a template binding nothing, so its lines and quotes read as
4
- * written; a backslash, a backtick and a `${` are escaped.
5
- */
2
+ import { templateOf } from './sourceLiteral.js';
3
+ /** One `await querier.run`...`` line, its SQL as written. */
6
4
  export function emitSqlRunCall(sql) {
7
- return /*ts*/ ` await querier.run\`${sql.replace(/[\\`]|\$\{/g, (char) => `\\${char}`)}\`;`;
5
+ return /*ts*/ ` await querier.run${templateOf(sql)};`;
8
6
  }
9
7
  /** Indented `up`/`down` body: one `await querier.run`...`` per SQL string. */
10
8
  export function emitSqlRunCalls(statements) {
@@ -9,8 +9,10 @@ export declare function quoted(text: string): string;
9
9
  /** `user.email`, or `user['first-name']` for a property name that is no identifier. */
10
10
  export declare function memberSource(param: string, property: string): string;
11
11
  /**
12
- * SQL as a `raw` tagged template. A database reprints an expression as arbitrary text, and exactly
13
- * three sequences can end or interpolate a template literal, so escaping those is the whole job.
14
- * Newlines need none, which keeps a multi-line expression readable in the generated entity.
12
+ * SQL as a template literal binding nothing. A database reprints an expression as arbitrary text, and
13
+ * exactly three sequences can end or interpolate a template, so escaping those is the whole job. Newlines
14
+ * need none, which keeps multi-line SQL readable in the generated file.
15
15
  */
16
+ export declare function templateOf(sql: string): string;
17
+ /** SQL as a `raw` tagged template. */
16
18
  export declare function rawTag(sql: string): string;
@@ -15,11 +15,14 @@ export function memberSource(param, property) {
15
15
  return isIdentifierName(property) ? `${param}.${property}` : `${param}[${quoted(property)}]`;
16
16
  }
17
17
  /**
18
- * SQL as a `raw` tagged template. A database reprints an expression as arbitrary text, and exactly
19
- * three sequences can end or interpolate a template literal, so escaping those is the whole job.
20
- * Newlines need none, which keeps a multi-line expression readable in the generated entity.
18
+ * SQL as a template literal binding nothing. A database reprints an expression as arbitrary text, and
19
+ * exactly three sequences can end or interpolate a template, so escaping those is the whole job. Newlines
20
+ * need none, which keeps multi-line SQL readable in the generated file.
21
21
  */
22
+ export function templateOf(sql) {
23
+ return `\`${sql.replace(/[\\`]|\$\{/g, (char) => `\\${char}`)}\``;
24
+ }
25
+ /** SQL as a `raw` tagged template. */
22
26
  export function rawTag(sql) {
23
- const escaped = sql.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
24
- return `raw\`${escaped}\``;
27
+ return `raw${templateOf(sql)}`;
25
28
  }
@@ -160,9 +160,7 @@ function uniqueColumns(indexes) {
160
160
  function createTableRowReader(querier) {
161
161
  const sent = new Map();
162
162
  return (sql) => {
163
- const ctx = querier.dialect.createContext();
164
- querier.dialect.getRawValue(ctx, { value: sql });
165
- const key = `${ctx.sql}\u0000${JSON.stringify(ctx.values)}`;
163
+ const key = JSON.stringify(querier.dialect.compile(sql));
166
164
  let rows = sent.get(key);
167
165
  if (!rows) {
168
166
  rows = querier.all(sql);