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
@@ -1,13 +1,12 @@
1
1
  import { AGGREGATE_VALUE_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
2
- import { decodeColumn } from '../dialect/hydrateColumn.js';
3
2
  import { getMeta, namesKey } from '../entity/index.js';
4
- import { COUNT_RESULT_KEY } from '../type/index.js';
5
- import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf, isAutoIncrement, isRecord, obtainAttrsPaths, unflatObject, } from '../util/index.js';
3
+ import { buildUpdateResult, chunk, clone, getInsertFieldKeys, insertShapeOf, isAutoIncrement } from '../util/index.js';
6
4
  import { statementOf } from '../util/raw.js';
7
5
  import { UqlUsageError } from '../util/uqlError.js';
8
6
  import { AbstractQuerier } from './abstractQuerier.js';
9
7
  import { streamViaCursor } from './cursorStream.js';
10
8
  import { enrichError } from './queryError.js';
9
+ import { rowReader } from './rowReader.js';
11
10
  /**
12
11
  * Row indexes split by whether the row names its key, the one thing that changes what an insert can
13
12
  * report; coarser than {@link groupByInsertShape} on purpose, since an insert fills a missing column with `DEFAULT`.
@@ -47,8 +46,13 @@ function groupByInsertShape(meta, payload) {
47
46
  */
48
47
  function chunkWithinLimits(meta, payload, group, maxBindValues, maxRows = Infinity) {
49
48
  const width = (indexes) => getInsertFieldKeys(meta, indexes.map((index) => payload[index])).length;
50
- const size = Math.max(1, Math.min(maxRows, Math.floor(maxBindValues / (width(group) || 1))));
51
- return chunk(group, size).flatMap((indexes) => (width(indexes) ? [indexes] : chunk(indexes, 1)));
49
+ const groupWidth = width(group);
50
+ if (!groupWidth) {
51
+ return chunk(group, 1);
52
+ }
53
+ const chunks = chunk(group, Math.max(1, Math.min(maxRows, Math.floor(maxBindValues / groupWidth))));
54
+ // A split can leave a chunk whose rows name no column; one chunk is the whole group, which names some.
55
+ return chunks.length === 1 ? chunks : chunks.flatMap((indexes) => (width(indexes) ? [indexes] : chunk(indexes, 1)));
52
56
  }
53
57
  export class AbstractSqlQuerier extends AbstractQuerier {
54
58
  dialect;
@@ -92,15 +96,10 @@ export class AbstractSqlQuerier extends AbstractQuerier {
92
96
  }
93
97
  }
94
98
  all(...statement) {
95
- return this.query(this.rendering(statement));
99
+ return this.query(statementOf(statement));
96
100
  }
97
101
  run(...statement) {
98
- return this.exec(this.rendering(statement));
99
- }
100
- /** How a statement handed to `all` or `run` writes itself into a context. */
101
- rendering(statement) {
102
- const sql = statementOf(statement);
103
- return (ctx) => this.dialect.getRawValue(ctx, { value: sql });
102
+ return this.exec(statementOf(statement));
104
103
  }
105
104
  /** Refused before the driver fails it, or PGlite answers it and every read after it wrong. */
106
105
  assertBindBudget(values) {
@@ -119,13 +118,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
119
118
  }
120
119
  /** Builds a statement and sends it on the connection, in turn, timed and its failure tagged with it. */
121
120
  async send(build, task) {
122
- const ctx = this.dialect.createContext();
123
- build(ctx);
124
- const { sql, values } = ctx;
121
+ const { sql, values } = this.dialect.compile(build);
125
122
  this.assertBindBudget(values);
126
123
  return this.serialize(async () => {
127
124
  await this.lazyConnect();
128
- return this.timed(sql, values, () => task(sql, this.dialect.normalizeValues(values)));
125
+ return this.timed(sql, values, () => task(sql, values));
129
126
  });
130
127
  }
131
128
  /**
@@ -148,7 +145,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
148
145
  }
149
146
  }
150
147
  async internalFindMany(entity, q, opts) {
151
- return (await this.selectRows(entity, q, opts)).map(this.rowReader(entity));
148
+ return this.selectRows(entity, q, opts);
152
149
  }
153
150
  /** Every row `q` matches past its page, deduplicated where it reads `$distinct`. */
154
151
  countUnpaged(entity, q, opts) {
@@ -171,8 +168,9 @@ export class AbstractSqlQuerier extends AbstractQuerier {
171
168
  for (const row of rows) {
172
169
  delete row[TOTAL_ALIAS];
173
170
  }
174
- return [rows.map(this.rowReader(entity)), total];
171
+ return [rows, total];
175
172
  }
173
+ /** The rows a read of `entity` matches, each as its statement reads it. */
176
174
  async selectRows(entity, q, opts, totalAlias) {
177
175
  // Guarded rather than awaited unconditionally, here and in the stream below: an `await` on this
178
176
  // path defers a microtask on every read, which reorders the two statements `findManyAndCount`
@@ -180,7 +178,15 @@ export class AbstractSqlQuerier extends AbstractQuerier {
180
178
  if (q.$candidates !== undefined) {
181
179
  await this.applyVectorTuning(entity, q);
182
180
  }
183
- return this.query((ctx) => this.dialect.find(ctx, entity, q, opts, totalAlias));
181
+ return this.readRows((ctx) => this.dialect.find(ctx, entity, q, opts, totalAlias));
182
+ }
183
+ /** The rows of a read the dialect builds, each as the terms it returns say. */
184
+ async readRows(build) {
185
+ let terms = [];
186
+ const rows = await this.query((ctx) => {
187
+ terms = build(ctx);
188
+ });
189
+ return rows.map(rowReader(terms));
184
190
  }
185
191
  /**
186
192
  * The one read not going through `all`, so it checks its budget and connects on its own; its values go as
@@ -188,13 +194,12 @@ export class AbstractSqlQuerier extends AbstractQuerier {
188
194
  */
189
195
  async *internalFindManyStream(entity, q, opts) {
190
196
  const ctx = this.dialect.createContext();
191
- this.dialect.find(ctx, entity, q, opts);
197
+ const read = rowReader(this.dialect.find(ctx, entity, q, opts));
192
198
  this.assertBindBudget(ctx.values);
193
199
  if (q.$candidates !== undefined) {
194
200
  await this.applyVectorTuning(entity, q);
195
201
  }
196
202
  await this.lazyConnect();
197
- const read = this.rowReader(entity);
198
203
  for await (const row of this.timedStream(ctx.sql, ctx.values, this.internalStream(ctx.sql, ctx.values))) {
199
204
  yield read(row);
200
205
  }
@@ -211,68 +216,6 @@ export class AbstractSqlQuerier extends AbstractQuerier {
211
216
  }
212
217
  yield* streamViaCursor((sql, params) => this.internalAll(sql, params), query, values, !!this.scopeHere());
213
218
  }
214
- /**
215
- * How each row of one statement becomes the entity's, for a read, a stream and a to-many alike: its dotted
216
- * columns nested as the first row names them, and its values decoded as `hydratableFields` says, resolved
217
- * once. Both live with the dialect, because a `sparsevec` is only sparse on Postgres.
218
- */
219
- rowReader(entity) {
220
- const meta = getMeta(entity);
221
- const fields = this.dialect.hydratableFields(entity);
222
- let attrsPaths;
223
- return (row) => {
224
- attrsPaths ??= obtainAttrsPaths(row);
225
- const found = unflatObject(row, attrsPaths);
226
- this.hydrateFields(meta, fields, found);
227
- return found;
228
- };
229
- }
230
- /**
231
- * One row of {@link rowReader}. A related row arrives as its parent's statement read it: a to-one
232
- * joined and unflattened, there only when its key is, since an unmatched join still fills a computed
233
- * column or a to-many's empty array; a to-many as a JSON array, which a driver may hand over as text.
234
- * Each is an object of its own, so the walk reaches none twice.
235
- */
236
- hydrateFields(meta, fields, dto) {
237
- const row = dto;
238
- for (const [key, kind] of fields) {
239
- const value = row[key];
240
- if (value != null) {
241
- row[key] = decodeColumn(value, kind);
242
- }
243
- }
244
- // A tally read inside the statement comes back as its driver reads a COUNT, which on some is text.
245
- const counts = row[COUNT_RESULT_KEY];
246
- if (isRecord(counts)) {
247
- for (const relKey in counts) {
248
- counts[relKey] = Number(counts[relKey]);
249
- }
250
- }
251
- // The value is read before the relation's target is resolved: a query that populated nothing
252
- // still walks every relation the entity declares, and `rel.entity()` is a call per row per
253
- // relation that only the populated ones need.
254
- for (const key in meta.relations) {
255
- const value = row[key];
256
- const rel = meta.relations[key];
257
- if (!value || !rel)
258
- continue;
259
- const relEntity = rel.entity();
260
- if (isRecord(value)) {
261
- const relMeta = getMeta(relEntity);
262
- if (value[relMeta.ids[0]] == null) {
263
- delete row[key];
264
- }
265
- else {
266
- this.hydrateFields(relMeta, this.dialect.hydratableFields(relEntity), value);
267
- }
268
- }
269
- else {
270
- // A to-many's rows, as flat as a statement's own.
271
- const rows = Array.isArray(value) ? value : JSON.parse(String(value));
272
- row[key] = rows.map(this.rowReader(relEntity));
273
- }
274
- }
275
- }
276
219
  /**
277
220
  * Runs a statement whose one row carries a {@link AGGREGATE_VALUE_ALIAS} column. `Number` because `COUNT(*)` is BIGINT and
278
221
  * a caller supplying their own `types` replaces the decoding the pools do at the wire, and reads a `NULL`
@@ -289,17 +232,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
289
232
  return this.runCount((ctx) => this.dialect.estimatedCount(ctx, entity));
290
233
  }
291
234
  async internalAggregate(entity, q, opts) {
292
- const rows = await this.query((ctx) => this.dialect.aggregate(ctx, entity, q, opts));
293
- const hydratable = this.dialect.hydratableAggregates(entity, q);
294
- for (const row of rows) {
295
- const cells = row;
296
- for (const [alias, kind] of hydratable) {
297
- if (cells[alias] != null) {
298
- cells[alias] = decodeColumn(cells[alias], kind);
299
- }
300
- }
301
- }
302
- return rows;
235
+ return this.readRows((ctx) => this.dialect.aggregate(ctx, entity, q, opts));
303
236
  }
304
237
  async internalInsertMany(entity, rows) {
305
238
  const meta = getMeta(entity);
@@ -1,13 +1,11 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { QueryRaw, QueryUpdateResult, RawRow, RawValue, SqlQuerier, SqlQuerierPool } from '../type/index.js';
2
+ import type { QueryUpdateResult, RawRow, SqlQuerier, SqlQuerierPool, SqlStatement } from '../type/index.js';
3
3
  import { AbstractQuerierPool } from './abstractQuerierPool.js';
4
4
  /**
5
5
  * Base pool for SQL dialects; implements the raw-SQL surface of {@link SqlQuerierPool}, which owns
6
6
  * the connection-per-call semantics.
7
7
  */
8
8
  export declare abstract class AbstractSqlQuerierPool<Q extends SqlQuerier, D extends AbstractSqlDialect> extends AbstractQuerierPool<Q, D> implements SqlQuerierPool<Q, D> {
9
- all<T extends object = RawRow>(strings: TemplateStringsArray, ...values: RawValue[]): Promise<T[]>;
10
- all<T extends object = RawRow>(sql: QueryRaw): Promise<T[]>;
11
- run(strings: TemplateStringsArray, ...values: RawValue[]): Promise<QueryUpdateResult>;
12
- run(sql: QueryRaw): Promise<QueryUpdateResult>;
9
+ all<T extends object = RawRow>(...statement: SqlStatement): Promise<T[]>;
10
+ run(...statement: SqlStatement): Promise<QueryUpdateResult>;
13
11
  }
@@ -1,4 +1,3 @@
1
- import { statementOf } from '../util/raw.js';
2
1
  import { AbstractQuerierPool } from './abstractQuerierPool.js';
3
2
  /**
4
3
  * Base pool for SQL dialects; implements the raw-SQL surface of {@link SqlQuerierPool}, which owns
@@ -6,11 +5,9 @@ import { AbstractQuerierPool } from './abstractQuerierPool.js';
6
5
  */
7
6
  export class AbstractSqlQuerierPool extends AbstractQuerierPool {
8
7
  all(...statement) {
9
- const sql = statementOf(statement);
10
- return this.withQuerier((querier) => querier.all(sql));
8
+ return this.withQuerier((querier) => querier.all(...statement));
11
9
  }
12
10
  run(...statement) {
13
- const sql = statementOf(statement);
14
- return this.withQuerier((querier) => querier.run(sql));
11
+ return this.withQuerier((querier) => querier.run(...statement));
15
12
  }
16
13
  }
@@ -0,0 +1,8 @@
1
+ import type { SelectTerm } from '../dialect/abstractSqlDialect.js';
2
+ import type { RawRow } from '../type/index.js';
3
+ /**
4
+ * How each row of one statement becomes the entity's, from the terms its SQL was written with: its dotted
5
+ * columns nested, a joined row kept only where its key is, a to-many's rows read by their own terms, and each
6
+ * value the driver leaves to the field decoded. Resolved once per statement, so a row pays for no discovery.
7
+ */
8
+ export declare function rowReader<T>(terms: readonly SelectTerm[]): (row: RawRow) => T;
@@ -0,0 +1,88 @@
1
+ import { DECODERS } from '../dialect/hydrateColumn.js';
2
+ import { isRecord } from '../util/index.js';
3
+ const TOP = [];
4
+ const slotAt = (path) => ({ parent: path.slice(0, -1), key: path[path.length - 1] });
5
+ /**
6
+ * How each row of one statement becomes the entity's, from the terms its SQL was written with: its dotted
7
+ * columns nested, a joined row kept only where its key is, a to-many's rows read by their own terms, and each
8
+ * value the driver leaves to the field decoded. Resolved once per statement, so a row pays for no discovery.
9
+ */
10
+ export function rowReader(terms) {
11
+ const dotted = new Map();
12
+ const joined = [];
13
+ const mapped = [];
14
+ for (const { key, kind, kinds, rows, joinedKey } of terms) {
15
+ for (const [field, fieldKind] of kinds ?? []) {
16
+ mapped.push({ parent: TOP, key: field, map: DECODERS[fieldKind] });
17
+ }
18
+ if (key === undefined) {
19
+ continue;
20
+ }
21
+ const path = key.split('.');
22
+ const slot = slotAt(path);
23
+ if (path.length > 1) {
24
+ dotted.set(key, path);
25
+ if (joinedKey) {
26
+ joined.push({ ...slotAt(slot.parent), idKey: slot.key });
27
+ }
28
+ }
29
+ if (rows) {
30
+ const read = rowReader(rows);
31
+ mapped.push({ ...slot, map: (value) => (Array.isArray(value) ? value : JSON.parse(String(value))).map(read) });
32
+ }
33
+ if (kind) {
34
+ mapped.push({ ...slot, map: DECODERS[kind] });
35
+ }
36
+ }
37
+ const [firstDotted] = dotted.keys();
38
+ return (raw) => {
39
+ // All of a row's columns are flat or none is: SQL Server's `FOR JSON` nests a related row itself.
40
+ const row = firstDotted !== undefined && firstDotted in raw ? nest(raw, dotted) : raw;
41
+ for (const { parent, key, idKey } of joined) {
42
+ const holder = holderAt(row, parent);
43
+ const joinedRow = holder?.[key];
44
+ if (holder && isRecord(joinedRow) && joinedRow[idKey] == null) {
45
+ delete holder[key];
46
+ }
47
+ }
48
+ for (const { parent, key, map } of mapped) {
49
+ const holder = holderAt(row, parent);
50
+ const value = holder?.[key];
51
+ if (holder && value != null) {
52
+ holder[key] = map(value);
53
+ }
54
+ }
55
+ // A raw row becomes the entity here, as a parsed JSON value does: its shape is what the statement selected.
56
+ return row;
57
+ };
58
+ }
59
+ /** `row` with its dotted columns nested under the paths `dotted` names. */
60
+ function nest(row, dotted) {
61
+ const nested = {};
62
+ for (const column in row) {
63
+ const path = dotted.get(column);
64
+ if (!path) {
65
+ nested[column] = row[column];
66
+ continue;
67
+ }
68
+ let target = nested;
69
+ for (let i = 0; i < path.length - 1; i++) {
70
+ const next = target[path[i]];
71
+ target = isRecord(next) ? next : (target[path[i]] = {});
72
+ }
73
+ target[path[path.length - 1]] = row[column];
74
+ }
75
+ return nested;
76
+ }
77
+ /** The object at `path` in `row`, `row` itself for an empty one, if every step to it is one. */
78
+ function holderAt(row, path) {
79
+ let target = row;
80
+ for (const step of path) {
81
+ const next = target[step];
82
+ if (!isRecord(next)) {
83
+ return undefined;
84
+ }
85
+ target = next;
86
+ }
87
+ return target;
88
+ }
@@ -1,4 +1,4 @@
1
- import { AbstractSqlDialect, type DerivedRelation, type RelationRows } from '../dialect/abstractSqlDialect.js';
1
+ import { AbstractSqlDialect, type DerivedRelation, type RelationRows, type SelectTerm } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode, type JsonSlot } from '../dialect/jsonSql.js';
3
3
  import { type EntityMeta, type FieldOptions, type Query, type QueryContext, type QueryTextSearchOptions, type QueryWhere, type SqlDialectFeatures, type SqlValues, type VectorDistance, type VectorMetric } from '../type/index.js';
4
4
  /** What SQLite and the engines derived from it have. */
@@ -43,7 +43,7 @@ export declare class SqliteDialect extends AbstractSqlDialect {
43
43
  /** SQLite's own spelling of no limit. */
44
44
  protected readonly unboundedLimit = "-1";
45
45
  /** `json_group_array` of each row's object, ordered by the sort terms carried out beside them. */
46
- protected appendRelationArray(ctx: QueryContext, rows: RelationRows): void;
46
+ protected appendRelationArray(ctx: QueryContext, rows: RelationRows): readonly SelectTerm[];
47
47
  /**
48
48
  * `json_object` of each key and its column. A row wider than one call takes inserts the rest into it,
49
49
  * addressing each key as one path segment.
@@ -137,8 +137,9 @@ export class SqliteDialect extends AbstractSqlDialect {
137
137
  unboundedLimit = '-1';
138
138
  /** `json_group_array` of each row's object, ordered by the sort terms carried out beside them. */
139
139
  appendRelationArray(ctx, rows) {
140
- const { from, pairs, order } = this.derivedRelation(ctx, rows);
140
+ const { terms, from, pairs, order } = this.derivedRelation(ctx, rows);
141
141
  ctx.append(`(SELECT json_group_array(${this.jsonObject(pairs)}${order ? ` ORDER BY ${order}` : ''}) FROM ${from})`);
142
+ return terms;
142
143
  }
143
144
  /**
144
145
  * `json_object` of each key and its column. A row wider than one call takes inserts the rest into it,
@@ -4,7 +4,7 @@ import type { FieldKey, HookEvent, RelationKey } from './entity.js';
4
4
  import type { LoggingOptions } from './logger.js';
5
5
  import type { NamingStrategy } from './namingStrategy.js';
6
6
  import type { QueryFilter, QueryFindResult, QueryOptions, QueryPage, QuerySearch, QueryUpdateResult, ReturningResult, WriteOptions } from './query.js';
7
- import type { QueryRaw, RawValue } from './queryRaw.js';
7
+ import type { SqlStatement } from './queryRaw.js';
8
8
  import type { ProjectedQuery, ProjectedRead, ProjectedResult, UniversalQuerier } from './universalQuerier.js';
9
9
  import type { BooleanLike, RawRow, Type } from './utility.js';
10
10
  import type { QuerierRaw } from './wire.js';
@@ -105,11 +105,9 @@ export interface SqlQuerier extends Querier {
105
105
  * The rows a statement answers, written as a tag, `all<Row>`SELECT ... WHERE id = ${id}``, each interpolated
106
106
  * value bound, never spliced; or a `raw` built apart.
107
107
  */
108
- all<T extends object = RawRow>(strings: TemplateStringsArray, ...values: RawValue[]): Promise<T[]>;
109
- all<T extends object = RawRow>(sql: QueryRaw): Promise<T[]>;
108
+ all<T extends object = RawRow>(...statement: SqlStatement): Promise<T[]>;
110
109
  /** Runs a statement (INSERT, UPDATE, DELETE, DDL), written as a tag or a `raw`, each interpolated value bound. */
111
- run(strings: TemplateStringsArray, ...values: RawValue[]): Promise<QueryUpdateResult>;
112
- run(sql: QueryRaw): Promise<QueryUpdateResult>;
110
+ run(...statement: SqlStatement): Promise<QueryUpdateResult>;
113
111
  }
114
112
  /**
115
113
  * Type guard to check if a querier supports raw SQL execution
@@ -51,7 +51,10 @@ export declare class QueryRaw {
51
51
  * bind reads - see {@link constantSql}.
52
52
  */
53
53
  readonly [RAW_TEXT]?: string;
54
- constructor(value: QueryRawFn, alias?: string, text?: string);
54
+ constructor(value: QueryRawFn, { alias, text }?: {
55
+ readonly alias?: string;
56
+ readonly text?: string;
57
+ });
55
58
  /** The same expression under an alias, for a `$select` projection. */
56
59
  as(alias: string): QueryRaw;
57
60
  /** Writes the expression into `opts.ctx`. The alias is the projection's to write, after the term. */
@@ -12,14 +12,14 @@ export class QueryRaw {
12
12
  * bind reads - see {@link constantSql}.
13
13
  */
14
14
  [RAW_TEXT];
15
- constructor(value, alias, text) {
15
+ constructor(value, { alias, text } = {}) {
16
16
  this[RAW_VALUE] = value;
17
17
  this[RAW_ALIAS] = alias;
18
18
  this[RAW_TEXT] = text;
19
19
  }
20
20
  /** The same expression under an alias, for a `$select` projection. */
21
21
  as(alias) {
22
- return new QueryRaw(this[RAW_VALUE], alias, this[RAW_TEXT]);
22
+ return new QueryRaw(this[RAW_VALUE], { alias, text: this[RAW_TEXT] });
23
23
  }
24
24
  /** Writes the expression into `opts.ctx`. The alias is the projection's to write, after the term. */
25
25
  render(opts) {
@@ -22,17 +22,8 @@ export declare function getFieldCallbackValue(val: OnFieldCallback): string | nu
22
22
  export declare function getSoftDeleteValue(field: FieldOptions): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QueryRaw | readonly number[] | readonly import("../type/utility.js").JsonBrand[] | Uint8Array<ArrayBufferLike>;
23
23
  /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
24
24
  export declare function fillOnFields<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, payload: R | R[], callbackKey: CallbackKey): R[];
25
- /**
26
- * The relation keys present in `payload` whose cascade configuration allows `action`. Only
27
- * `payload`'s keys are read, so any keys-bearing object works (an entity, an update payload,
28
- * or `meta.relations` itself to enumerate every cascadable relation).
29
- */
30
- export declare function filterPersistableRelationKeys<E>(meta: EntityMeta<E>, payload: object, action: CascadeType): RelationKey<E>[];
31
- /**
32
- * Whether deleting this entity has to delete anything else, which is the reason a delete resolves the
33
- * matching ids before issuing anything: a child is reached through the ids of its parent.
34
- */
35
- export declare function cascadesOnDelete<E>(meta: EntityMeta<E>): boolean;
25
+ /** The relations a write cascades `action` to, in declaration order. */
26
+ export declare function cascadingRelations<E>(meta: EntityMeta<E>, action: CascadeType): RelationKey<E>[];
36
27
  export declare function isCascadable(action: CascadeType, configuration?: boolean | CascadeType): boolean;
37
28
  /**
38
29
  * Whether `q` carries an ordering or a page, so a write has to settle its rows with a read and name
@@ -50,7 +50,7 @@ export function getInsertFieldKeys(meta, payloads) {
50
50
  for (const record of payloads) {
51
51
  addInsertFieldKeys(meta, record, seen, keys);
52
52
  }
53
- return [...keys, ...fieldKeys(meta, (field) => field.onInsert !== undefined).filter((key) => !seen.has(key))];
53
+ return [...keys, ...filledKeys(meta, 'onInsert').filter((key) => !seen.has(key))];
54
54
  }
55
55
  export function getFieldCallbackValue(val) {
56
56
  return typeof val === 'function' ? val() : val;
@@ -65,9 +65,7 @@ export function getSoftDeleteValue(field) {
65
65
  /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
66
66
  export function fillOnFields(meta, payload, callbackKey) {
67
67
  const payloads = Array.isArray(payload) ? payload : [payload];
68
- // By presence, not truthiness, as `addInsertFieldKeys` above reads it: `onInsert: 0` and `onInsert: ''`
69
- // are values a caller meant, and a falsy one was silently never filled.
70
- const keys = fieldKeys(meta, (field) => field[callbackKey] !== undefined);
68
+ const keys = filledKeys(meta, callbackKey);
71
69
  if (keys.length === 0) {
72
70
  return payloads;
73
71
  }
@@ -80,24 +78,13 @@ export function fillOnFields(meta, payload, callbackKey) {
80
78
  }
81
79
  return payloads;
82
80
  }
83
- /**
84
- * The relation keys present in `payload` whose cascade configuration allows `action`. Only
85
- * `payload`'s keys are read, so any keys-bearing object works (an entity, an update payload,
86
- * or `meta.relations` itself to enumerate every cascadable relation).
87
- */
88
- export function filterPersistableRelationKeys(meta, payload, action) {
89
- const keys = getKeys(payload);
90
- return keys.filter((key) => {
91
- const relOpts = meta.relations[key];
92
- return relOpts && isCascadable(action, relOpts.cascade);
93
- });
81
+ /** The fields `callbackKey` fills where the caller left them unset. By presence: `onInsert: 0` is a value meant. */
82
+ function filledKeys(meta, callbackKey) {
83
+ return fieldKeys(meta, (field) => field[callbackKey] !== undefined);
94
84
  }
95
- /**
96
- * Whether deleting this entity has to delete anything else, which is the reason a delete resolves the
97
- * matching ids before issuing anything: a child is reached through the ids of its parent.
98
- */
99
- export function cascadesOnDelete(meta) {
100
- return filterPersistableRelationKeys(meta, meta.relations, 'delete').length > 0;
85
+ /** The relations a write cascades `action` to, in declaration order. */
86
+ export function cascadingRelations(meta, action) {
87
+ return getKeys(meta.relations).filter((key) => isCascadable(action, meta.relations[key]?.cascade));
101
88
  }
102
89
  export function isCascadable(action, configuration) {
103
90
  if (typeof configuration === 'boolean') {
@@ -65,28 +65,36 @@ export function assertWhere(meta, where) {
65
65
  * as no condition at all: `{ email: maybeEmail }` reading any row. `what` names the map in the error.
66
66
  */
67
67
  export function assertNoUndefined(map, what) {
68
- const path = undefinedPath(map, []);
68
+ const path = undefinedPath(map);
69
69
  if (path) {
70
70
  throw new UqlUsageError(`${what} holds undefined at '${path.join('.')}': leave the key out not to filter by it, or name null`);
71
71
  }
72
72
  }
73
- /** The path to the first `undefined` in a plain object or array, read depth first. */
74
- function undefinedPath(value, path) {
73
+ /**
74
+ * The path to the first `undefined` in a plain object or array, read depth first. Built on the way back out,
75
+ * so a filter holding none, which is every one that runs, allocates nothing.
76
+ */
77
+ function undefinedPath(value) {
75
78
  if (value === undefined) {
76
- return path;
79
+ return [];
77
80
  }
78
- if (!Array.isArray(value) && !isPlainObject(value)) {
81
+ if (!isWalkable(value)) {
79
82
  return undefined;
80
83
  }
81
- for (const [key, item] of Object.entries(value)) {
82
- const found = undefinedPath(item, [...path, key]);
84
+ for (const key in value) {
85
+ const found = undefinedPath(value[key]);
83
86
  if (found) {
87
+ found.unshift(key);
84
88
  return found;
85
89
  }
86
90
  }
87
91
  return undefined;
88
92
  }
89
- function isPlainObject(value) {
93
+ /** An array or a plain object: what a filter nests, and not a `Date`, a `raw` or a driver's value. */
94
+ function isWalkable(value) {
95
+ if (Array.isArray(value)) {
96
+ return true;
97
+ }
90
98
  if (!isRecord(value)) {
91
99
  return false;
92
100
  }
package/dist/util/raw.js CHANGED
@@ -3,28 +3,31 @@ import { ColumnRef, QueryRaw, RAW_TEXT, RelationAggregate, TriggerWriteRaw, } fr
3
3
  import { aggregateOf, isInlinedExpression } from './field.util.js';
4
4
  import { entityName, hasKeys } from './object.util.js';
5
5
  import { UqlUsageError } from './uqlError.js';
6
- export function raw(value, ...rest) {
7
- if (!isTemplateStrings(value)) {
8
- return new QueryRaw(value);
6
+ export function raw(source, ...values) {
7
+ if (!isTemplateStrings(source)) {
8
+ return new QueryRaw(source);
9
9
  }
10
- if (rest.some((value) => value === undefined)) {
10
+ if (!values.length) {
11
+ return raw.text(source[0]);
12
+ }
13
+ if (values.some((value) => value === undefined)) {
11
14
  throw new UqlUsageError('a raw template interpolated undefined, which binds nothing: leave it out, or write null');
12
15
  }
13
16
  // Writes joined by whitespace alone are still only writes, so a set-based trigger narrows each one.
14
- const writes = rest.length > 0 && rest.every((v) => v instanceof TriggerWriteRaw) && value.every((part) => !part.trim());
17
+ const writes = values.every((value) => value instanceof TriggerWriteRaw) && source.every((part) => !part.trim());
15
18
  return new (writes ? TriggerWriteRaw : QueryRaw)((opts) => {
16
19
  const { ctx } = opts;
17
- ctx.append(value[0]);
18
- rest.forEach((interpolated, i) => {
19
- if (interpolated instanceof QueryRaw) {
20
- interpolated.render(opts);
20
+ ctx.append(source[0]);
21
+ values.forEach((value, i) => {
22
+ if (value instanceof QueryRaw) {
23
+ value.render(opts);
21
24
  }
22
25
  else {
23
- ctx.addValue(interpolated);
26
+ ctx.addValue(value);
24
27
  }
25
- ctx.append(value[i + 1]);
28
+ ctx.append(source[i + 1]);
26
29
  });
27
- }, undefined, rest.length === 0 ? value[0] : undefined);
30
+ });
28
31
  }
29
32
  /** `parts` one after another, `separator` between each, every part binding its own values: `raw.join(conditions, ' AND ')`. */
30
33
  raw.join = function join(parts, separator = ', ') {
@@ -37,14 +40,14 @@ raw.join = function join(parts, separator = ', ') {
37
40
  });
38
41
  });
39
42
  };
43
+ /** SQL held in a string, run as written, binding nothing: for trusted text only, never built from user input. */
44
+ raw.text = function text(sql) {
45
+ return new QueryRaw(() => sql, { text: sql });
46
+ };
40
47
  /** The statement `all` or `run` was handed: a tagged template's, or a `raw` built apart. */
41
48
  export function statementOf([sql, ...values]) {
42
49
  return sql instanceof QueryRaw ? sql : raw(sql, ...values);
43
50
  }
44
- /** SQL held in a string, run as written, binding nothing: for trusted text only, never built from user input. */
45
- raw.text = function text(sql) {
46
- return new QueryRaw(() => sql, undefined, sql);
47
- };
48
51
  /**
49
52
  * The SQL of a `raw` that names a constant, for a DDL clause with no dialect to render against and
50
53
  * nowhere to bind a value; `undefined` where it interpolates and so needs one.
@@ -1,10 +1,5 @@
1
1
  import type { InsertIdSource, QueryUpdateResult, RawRow } from '../type/index.js';
2
2
  import type { PrimaryKey } from '../type/utility.js';
3
- /** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
4
- export declare function unflatObject<T extends object>(row: RawRow, attrsPaths: Record<string, string[]>): T;
5
- export declare function obtainAttrsPaths<T extends object>(row: T): {
6
- [k: string]: string[];
7
- };
8
3
  /**
9
4
  * A name behind its namespace, or bare where there is none: the one place the two are joined, so a
10
5
  * table's key, its statement operand and its escaped form cannot spell it differently. Never the
@@ -1,38 +1,5 @@
1
1
  import { OWNED_PREFIX } from '../dialect/aliases.js';
2
- import { hasKeys, isRecord } from './object.util.js';
3
2
  import { fnv1a } from './string.util.js';
4
- /** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
5
- export function unflatObject(row, attrsPaths) {
6
- if (!hasKeys(attrsPaths)) {
7
- return row;
8
- }
9
- const dto = {};
10
- for (const col in row) {
11
- const attrPath = attrsPaths[col];
12
- if (attrPath) {
13
- let target = dto;
14
- for (let i = 0; i < attrPath.length - 1; i++) {
15
- const seg = attrPath[i];
16
- const next = target[seg];
17
- target = isRecord(next) ? next : (target[seg] = {});
18
- }
19
- target[attrPath[attrPath.length - 1]] = row[col];
20
- }
21
- else {
22
- dto[col] = row[col];
23
- }
24
- }
25
- return dto;
26
- }
27
- export function obtainAttrsPaths(row) {
28
- const paths = {};
29
- for (const col in row) {
30
- if (col.includes('.')) {
31
- paths[col] = col.split('.');
32
- }
33
- }
34
- return paths;
35
- }
36
3
  /**
37
4
  * A name behind its namespace, or bare where there is none: the one place the two are joined, so a
38
5
  * table's key, its statement operand and its escaped form cannot spell it differently. Never the