turbine-orm 0.91.0 → 0.92.0-next.4df06d4

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 (54) hide show
  1. package/README.md +23 -24
  2. package/dist/cjs/cli/config.d.ts +5 -0
  3. package/dist/cjs/cli/config.js +1 -0
  4. package/dist/cjs/cli/index.d.ts +17 -17
  5. package/dist/cjs/cli/index.js +34 -27
  6. package/dist/cjs/cli/observe-ui.d.ts +1 -1
  7. package/dist/cjs/cli/observe-ui.js +1 -1
  8. package/dist/cjs/cli/studio-ui.generated.js +1 -1
  9. package/dist/cjs/client.js +33 -15
  10. package/dist/cjs/index.d.ts +1 -0
  11. package/dist/cjs/index.js +4 -1
  12. package/dist/cjs/pipeline.js +12 -7
  13. package/dist/cjs/powdb.d.ts +10 -6
  14. package/dist/cjs/powdb.js +4 -2
  15. package/dist/cjs/powql.js +11 -3
  16. package/dist/cjs/query/builder.d.ts +8 -0
  17. package/dist/cjs/query/builder.js +51 -33
  18. package/dist/cjs/query/relations.d.ts +21 -3
  19. package/dist/cjs/query/relations.js +331 -68
  20. package/dist/cjs/query/utils.d.ts +13 -0
  21. package/dist/cjs/query/utils.js +44 -1
  22. package/dist/cjs/query/where.d.ts +15 -0
  23. package/dist/cjs/query-channel.d.ts +86 -0
  24. package/dist/cjs/query-channel.js +150 -0
  25. package/dist/cjs/query-events.js +5 -1
  26. package/dist/cjs/schema-builder.d.ts +8 -5
  27. package/dist/cjs/transaction-state.js +15 -11
  28. package/dist/cli/config.d.ts +5 -0
  29. package/dist/cli/config.js +1 -0
  30. package/dist/cli/index.d.ts +17 -17
  31. package/dist/cli/index.js +35 -28
  32. package/dist/cli/observe-ui.d.ts +1 -1
  33. package/dist/cli/observe-ui.js +1 -1
  34. package/dist/cli/studio-ui.generated.js +1 -1
  35. package/dist/client.js +33 -15
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.js +2 -0
  38. package/dist/pipeline.js +12 -7
  39. package/dist/powdb.d.ts +10 -6
  40. package/dist/powdb.js +4 -2
  41. package/dist/powql.js +11 -3
  42. package/dist/query/builder.d.ts +8 -0
  43. package/dist/query/builder.js +38 -20
  44. package/dist/query/relations.d.ts +21 -3
  45. package/dist/query/relations.js +330 -69
  46. package/dist/query/utils.d.ts +13 -0
  47. package/dist/query/utils.js +43 -0
  48. package/dist/query/where.d.ts +15 -0
  49. package/dist/query-channel.d.ts +86 -0
  50. package/dist/query-channel.js +143 -0
  51. package/dist/query-events.js +5 -1
  52. package/dist/schema-builder.d.ts +8 -5
  53. package/dist/transaction-state.js +15 -11
  54. package/package.json +2 -1
@@ -19,7 +19,7 @@ import { normalizeKeyColumns, snakeToCamel } from '../schema.js';
19
19
  import { resolveCountRelations, stitchOnlyFields } from './batched-loader.js';
20
20
  import { describeOperand, isJsonPathOrderBy, isOrderBySpec, isPlainRecord, isRelationPickOrderBy, isVectorOrderBy, MAX_NAMED_ORDER_KEYS, normalizeOrderBy, orderByEntries, sortedEntries, } from './filters.js';
21
21
  import { assertDirectionToken, assertOrderDirection } from './types.js';
22
- import { availableClause, canonicalColumnOrder, ownLookup, relationInProjectionMessage, resolveColumnName, resolveRelation, resolveRelationDef, selectNamesNothingMessage, selectOmitExclusiveMessage, suggestKey, unknownFieldMessage, } from './utils.js';
22
+ import { availableClause, CELL_FLOAT, CELL_PLAIN, canonicalColumnOrder, ownLookup, relationInProjectionMessage, resolveColumnName, resolveRelation, resolveRelationDef, selectNamesNothingMessage, selectOmitExclusiveMessage, suggestKey, unknownFieldMessage, } from './utils.js';
23
23
  import { hasWarnedOnce, shouldWarnOnce, WARN_NS } from './warn-registry.js';
24
24
  import * as whereMod from './where.js';
25
25
  import * as writesMod from './writes.js';
@@ -1405,6 +1405,22 @@ export function parseNestedRow(qi, row, table, fromJson = false) {
1405
1405
  const meta = qi.schema.tables[table];
1406
1406
  if (!meta)
1407
1407
  return qi.parseRow(row, table);
1408
+ const parsed = parseScalarColumns(qi, row, table, meta, fromJson);
1409
+ for (const [relName, relDef] of getRelationEntries(qi, table, meta)) {
1410
+ const rawValue = row[relName];
1411
+ if (rawValue === undefined)
1412
+ continue;
1413
+ parsed[relName] = parseRelationValue(qi, relName, relDef, rawValue);
1414
+ }
1415
+ return parsed;
1416
+ }
1417
+ /**
1418
+ * The scalar half of {@link parseNestedRow}: the row through `parseRow` (after
1419
+ * the JSON-wire decode when `fromJson`), with any `_count__<rel>` columns
1420
+ * folded into a `_count` object. Relation columns are copied through as they
1421
+ * are; the caller replaces each one it parses.
1422
+ */
1423
+ function parseScalarColumns(qi, row, table, meta, fromJson) {
1408
1424
  const parsed = qi.parseRow(fromJson ? decodeJsonWireRow(qi, row, table, meta) : row, table);
1409
1425
  // Assemble reserved `_count__<rel>` scalar columns into a `_count` object.
1410
1426
  // parseRow copies these unknown columns through under their raw key.
@@ -1431,75 +1447,66 @@ export function parseNestedRow(qi, row, table, fromJson = false) {
1431
1447
  delete parsed[`${COUNT_PREFIX}${rel}`];
1432
1448
  parsed._count = countObj;
1433
1449
  }
1434
- for (const [relName, relDef] of getRelationEntries(qi, table, meta)) {
1435
- const rawValue = row[relName];
1436
- if (rawValue === undefined)
1437
- continue;
1438
- // --- Short-circuit: skip JSON.parse for common empty/null cases ---
1439
- // hasMany returns '[]' (from COALESCE(..., '[]'::json)); belongsTo/hasOne returns null
1440
- if (rawValue === null || rawValue === 'null') {
1441
- parsed[relName] = null;
1442
- continue;
1443
- }
1444
- if (rawValue === '[]') {
1445
- parsed[relName] = [];
1446
- continue;
1447
- }
1448
- if (Array.isArray(rawValue) && rawValue.length === 0) {
1449
- parsed[relName] = [];
1450
- continue;
1451
- }
1452
- // --- Non-empty values: full parse path ---
1453
- if (typeof rawValue === 'string') {
1454
- try {
1455
- const jsonVal = JSON.parse(rawValue);
1456
- // After parsing, recurse via parseNestedRow so each item gets date
1457
- // coercion AND its own sub-relations parsed at arbitrary depth.
1458
- if (Array.isArray(jsonVal)) {
1459
- parsed[relName] = jsonVal.map((item) => typeof item === 'object' && item !== null
1460
- ? parseNestedRow(qi, item, relDef.to, true)
1461
- : item);
1462
- }
1463
- else if (typeof jsonVal === 'object' && jsonVal !== null) {
1464
- parsed[relName] = parseNestedRow(qi, jsonVal, relDef.to, true);
1465
- }
1466
- else {
1467
- parsed[relName] = jsonVal;
1468
- }
1450
+ return parsed;
1451
+ }
1452
+ /**
1453
+ * The relation half of {@link parseNestedRow}: one relation column's value
1454
+ * (never `undefined`, which the caller skips) as the parsed relation.
1455
+ */
1456
+ function parseRelationValue(qi, relName, relDef, rawValue) {
1457
+ // --- Short-circuit: skip JSON.parse for common empty/null cases ---
1458
+ // hasMany returns '[]' (from COALESCE(..., '[]'::json)); belongsTo/hasOne returns null
1459
+ if (rawValue === null || rawValue === 'null')
1460
+ return null;
1461
+ if (rawValue === '[]')
1462
+ return [];
1463
+ if (Array.isArray(rawValue) && rawValue.length === 0)
1464
+ return [];
1465
+ // --- Non-empty values: full parse path ---
1466
+ if (typeof rawValue === 'string') {
1467
+ try {
1468
+ const jsonVal = JSON.parse(rawValue);
1469
+ // After parsing, recurse via parseNestedRow so each item gets date
1470
+ // coercion AND its own sub-relations parsed at arbitrary depth.
1471
+ if (Array.isArray(jsonVal)) {
1472
+ return jsonVal.map((item) => typeof item === 'object' && item !== null
1473
+ ? parseNestedRow(qi, item, relDef.to, true)
1474
+ : item);
1469
1475
  }
1470
- catch (err) {
1471
- // A relation column that does not parse is a bug in the emitted SQL or
1472
- // a driver-level corruption, not a recoverable condition. Handing back
1473
- // the raw string satisfied the assignment and violated the generated
1474
- // type: callers got a `string` where `Post[]` was promised, and found
1475
- // out at the first `.map`. Throw instead, with the context needed to
1476
- // find it.
1477
- //
1478
- // The warn is gated and deduped because this sits in parseNestedRow's
1479
- // per-relation loop: one 10,000-row page was 10,000 warnings. The
1480
- // parse error stays out of the entry: its message quotes the payload,
1481
- // which is row data.
1482
- const log = whereMod.adviceLogger(qi);
1483
- if (log && shouldWarnOnce(WARN_NS.relationParseFailure, `${qi.table}.${relName}`)) {
1484
- logTo(log, 'warn', `Relation "${relName}" on "${qi.table}" returned a payload that is not valid JSON. ` +
1485
- `This is a bug; please report it with the emitted SQL.`, { code: 'relation-payload-json', table: qi.table, relation: relName });
1486
- }
1487
- throw new InvariantError('relation-payload-json', `Relation "${relName}" on table "${qi.table}" returned a payload that could not be parsed as JSON.`, { cause: err });
1476
+ if (typeof jsonVal === 'object' && jsonVal !== null) {
1477
+ return parseNestedRow(qi, jsonVal, relDef.to, true);
1488
1478
  }
1489
- }
1490
- else if (Array.isArray(rawValue)) {
1491
- parsed[relName] = rawValue.map((item) => typeof item === 'object' && item !== null
1492
- ? parseNestedRow(qi, item, relDef.to, true)
1493
- : item);
1494
- }
1495
- else if (typeof rawValue === 'object' && rawValue !== null) {
1496
- parsed[relName] = parseNestedRow(qi, rawValue, relDef.to, true);
1497
- }
1498
- else {
1499
- parsed[relName] = rawValue;
1479
+ return jsonVal;
1480
+ }
1481
+ catch (err) {
1482
+ // A relation column that does not parse is a bug in the emitted SQL or
1483
+ // a driver-level corruption, not a recoverable condition. Handing back
1484
+ // the raw string satisfied the assignment and violated the generated
1485
+ // type: callers got a `string` where `Post[]` was promised, and found
1486
+ // out at the first `.map`. Throw instead, with the context needed to
1487
+ // find it.
1488
+ //
1489
+ // The warn is gated and deduped because this sits in parseNestedRow's
1490
+ // per-relation loop: one 10,000-row page was 10,000 warnings. The
1491
+ // parse error stays out of the entry: its message quotes the payload,
1492
+ // which is row data.
1493
+ const log = whereMod.adviceLogger(qi);
1494
+ if (log && shouldWarnOnce(WARN_NS.relationParseFailure, `${qi.table}.${relName}`)) {
1495
+ logTo(log, 'warn', `Relation "${relName}" on "${qi.table}" returned a payload that is not valid JSON. ` +
1496
+ `This is a bug; please report it with the emitted SQL.`, { code: 'relation-payload-json', table: qi.table, relation: relName });
1497
+ }
1498
+ throw new InvariantError('relation-payload-json', `Relation "${relName}" on table "${qi.table}" returned a payload that could not be parsed as JSON.`, { cause: err });
1500
1499
  }
1501
1500
  }
1502
- return parsed;
1501
+ if (Array.isArray(rawValue)) {
1502
+ return rawValue.map((item) => typeof item === 'object' && item !== null
1503
+ ? parseNestedRow(qi, item, relDef.to, true)
1504
+ : item);
1505
+ }
1506
+ if (typeof rawValue === 'object' && rawValue !== null) {
1507
+ return parseNestedRow(qi, rawValue, relDef.to, true);
1508
+ }
1509
+ return rawValue;
1503
1510
  }
1504
1511
  /**
1505
1512
  * Resolve the emitted column list for a relation, honoring `select` / `omit`.
@@ -1685,9 +1692,12 @@ export function buildRelationShape(qi, relDef, spec, parentMeta, includePii) {
1685
1692
  }
1686
1693
  /**
1687
1694
  * Build the row parser for a `with` clause. In object mode this is just
1688
- * {@link parseNestedRow}. In positional mode it decodes each relation's
1689
- * positional arrays into the object form first (shapes built once, not per
1690
- * row), then delegates to parseNestedRow for date/snake-camel coercion.
1695
+ * {@link parseNestedRow}. In positional mode the relation shapes are built
1696
+ * once (not per row) and compiled into a decode plan
1697
+ * ({@link makePositionalRowParser}) that turns each positional array straight
1698
+ * into its parsed row. A query whose shapes the plan declines takes the
1699
+ * reference path instead, which decodes each positional array into the object
1700
+ * form and hands it to parseNestedRow.
1691
1701
  */
1692
1702
  export function makeNestedParser(qi, withClause, includePii, flattenPlan) {
1693
1703
  // A flatten plan and the positional encoding are mutually exclusive (the
@@ -1699,6 +1709,16 @@ export function makeNestedParser(qi, withClause, includePii, flattenPlan) {
1699
1709
  return (row) => parseNestedRow(qi, row, qi.table);
1700
1710
  }
1701
1711
  const shapes = buildRelationShapes(qi, qi.table, withClause, includePii);
1712
+ return makePositionalRowParser(qi, qi.table, shapes) ?? makeReferencePositionalParser(qi, shapes);
1713
+ }
1714
+ /**
1715
+ * The positional parser the plan in {@link makePositionalRowParser} is held to:
1716
+ * decode each relation's arrays into the object representation, then parse
1717
+ * that exactly as an object-encoded row is parsed. It is the path for every
1718
+ * query the plan declines, and is exported so the differential tests can
1719
+ * compare the two.
1720
+ */
1721
+ export function makeReferencePositionalParser(qi, shapes) {
1702
1722
  return (row) => parseNestedRow(qi, decodePositionalRelations(qi, row, shapes), qi.table);
1703
1723
  }
1704
1724
  /**
@@ -1753,6 +1773,247 @@ export function decodePositionalObject(qi, arr, shape) {
1753
1773
  }
1754
1774
  return obj;
1755
1775
  }
1776
+ /**
1777
+ * A key the reference path treats as an ordinary own property: not one that
1778
+ * resolves through `Object.prototype` when read off a plain object (`__proto__`
1779
+ * included), and not an integer-like key, which `Object.keys` lists ahead of
1780
+ * every other key whatever order it was written in.
1781
+ */
1782
+ function isPlainKey(key) {
1783
+ return typeof key === 'string' && !(key in Object.prototype) && !/^\d+$/.test(key);
1784
+ }
1785
+ /**
1786
+ * Does `name` reach `parseRow`'s answer for a top-level column? Any overlap
1787
+ * with a column name, field name, reverse-map key or date column means the
1788
+ * reference would give the relation column a field or cell kind of its own.
1789
+ */
1790
+ function nameTouchesColumns(qi, table, meta, name) {
1791
+ if (Object.hasOwn(meta.reverseColumnMap, name) || meta.dateColumns.has(name))
1792
+ return true;
1793
+ if (getCamelDateFields(qi, table, meta).has(name))
1794
+ return true;
1795
+ return meta.columns.some((column) => column.name === name || column.field === name);
1796
+ }
1797
+ /** The indexes of `relations` in `entries` order, or `null` when that is their own order. */
1798
+ function relationDecodeOrder(relations, entries) {
1799
+ const order = [];
1800
+ for (const [name] of entries) {
1801
+ const index = relations.findIndex((rel) => rel.name === name);
1802
+ if (index !== -1)
1803
+ order.push(index);
1804
+ }
1805
+ return order.every((index, i) => index === i) ? null : order;
1806
+ }
1807
+ /** The plan for one relation shape, or `undefined` when the plan cannot take it. */
1808
+ function planPositionalRow(qi, table, shape) {
1809
+ const meta = qi.schema.tables[table];
1810
+ if (!meta || !qi.rowDecodePlan)
1811
+ return undefined;
1812
+ const keys = shape.keys;
1813
+ if (new Set(keys).size !== keys.length || !keys.every(isPlainKey))
1814
+ return undefined;
1815
+ const rowPlan = qi.rowDecodePlan(table, keys);
1816
+ if (!rowPlan)
1817
+ return undefined;
1818
+ const entries = getRelationEntries(qi, table, meta);
1819
+ if (!entries.every(([name]) => isPlainKey(name)))
1820
+ return undefined;
1821
+ const relationNames = new Set(entries.map(([name]) => name));
1822
+ const wireFields = jsonWireFields(qi, table, meta);
1823
+ const wireOrder = wireFields ? [...wireFields.keys()] : [];
1824
+ const fields = [];
1825
+ const wire = [];
1826
+ const cellPositions = [];
1827
+ const cellKinds = [];
1828
+ const relations = [];
1829
+ let lastWireRank = -1;
1830
+ for (let i = 0; i < keys.length; i++) {
1831
+ const key = keys[i];
1832
+ const field = rowPlan.fields[i];
1833
+ const kind = rowPlan.kinds[i];
1834
+ // parseNestedRow folds a `_count__` field into `_count`; the plan does not.
1835
+ if (!isPlainKey(field) || field.startsWith(COUNT_PREFIX))
1836
+ return undefined;
1837
+ const nested = shape.nested[key];
1838
+ if (nested) {
1839
+ const def = ownLookup(meta.relations, key);
1840
+ // The reference copies the slot through parseRow before replacing it, so
1841
+ // the slot must be a plain cell under its own name, and no wire field.
1842
+ if (!def || field !== key || kind !== CELL_PLAIN || wireFields?.has(key))
1843
+ return undefined;
1844
+ const row = planPositionalRow(qi, def.to, nested);
1845
+ if (!row)
1846
+ return undefined;
1847
+ relations.push({ name: key, def, many: nested.cardinality === 'many', position: i, row });
1848
+ continue;
1849
+ }
1850
+ // buildRelationShape puts every scalar ahead of every relation slot, and a
1851
+ // scalar named like one of the table's relations would be re-read as it.
1852
+ if (relations.length > 0 || relationNames.has(key))
1853
+ return undefined;
1854
+ const rule = wireFields?.get(key);
1855
+ if (rule !== undefined) {
1856
+ // The reference decodes wire columns in table-column order before any
1857
+ // cell decode; the plan does them in key order, so the two must agree.
1858
+ const rank = wireOrder.indexOf(key);
1859
+ if (rank < lastWireRank)
1860
+ return undefined;
1861
+ lastWireRank = rank;
1862
+ }
1863
+ fields.push(field);
1864
+ wire.push(rule);
1865
+ if (kind !== CELL_PLAIN) {
1866
+ cellPositions.push(i);
1867
+ cellKinds.push(kind);
1868
+ }
1869
+ }
1870
+ // Two keys landing on one field, or a scalar field named like a relation
1871
+ // slot, would collapse into one property in a different order.
1872
+ const written = new Set(fields);
1873
+ if (written.size !== fields.length || relations.some((rel) => written.has(rel.name)))
1874
+ return undefined;
1875
+ return {
1876
+ table,
1877
+ fields,
1878
+ wire,
1879
+ cellPositions,
1880
+ cellKinds,
1881
+ relations,
1882
+ relationOrder: relationDecodeOrder(relations, entries),
1883
+ };
1884
+ }
1885
+ /**
1886
+ * Compile a top-level positional parser for `shapes`, or `undefined` when any
1887
+ * part of it is a shape the plan does not take (the caller then uses
1888
+ * {@link makeReferencePositionalParser}). Rows are identical to the
1889
+ * reference's on every shape it does take.
1890
+ */
1891
+ export function makePositionalRowParser(qi, table, shapes) {
1892
+ const meta = qi.schema.tables[table];
1893
+ if (!meta || !qi.rowDecodePlan || !qi.decodeCell)
1894
+ return undefined;
1895
+ const entries = getRelationEntries(qi, table, meta);
1896
+ if (!entries.every(([name]) => isPlainKey(name)))
1897
+ return undefined;
1898
+ const plans = [];
1899
+ for (const [name, def] of entries) {
1900
+ const shape = Object.hasOwn(shapes, name) ? shapes[name] : undefined;
1901
+ if (!shape) {
1902
+ plans.push(null);
1903
+ continue;
1904
+ }
1905
+ // The reference runs the top-level row through parseRow with the relation
1906
+ // columns already decoded; the plan runs it with them raw and replaces them
1907
+ // after. Those agree only while parseRow copies a relation column through
1908
+ // untouched, under its own name, and the `_count` fold never reads it.
1909
+ if (name.startsWith(COUNT_PREFIX) || nameTouchesColumns(qi, table, meta, name))
1910
+ return undefined;
1911
+ const row = planPositionalRow(qi, def.to, shape);
1912
+ if (!row)
1913
+ return undefined;
1914
+ plans.push({ name, def, many: shape.cardinality === 'many', position: -1, row });
1915
+ }
1916
+ const isOwnEnumerable = Object.prototype.propertyIsEnumerable;
1917
+ return (row) => {
1918
+ const parsed = parseScalarColumns(qi, row, table, meta, false);
1919
+ for (let i = 0; i < entries.length; i++) {
1920
+ const [name, def] = entries[i];
1921
+ // The reference reads relation columns off a `{ ...row }` copy, which
1922
+ // holds exactly the row's own enumerable properties.
1923
+ if (!isOwnEnumerable.call(row, name))
1924
+ continue;
1925
+ const plan = plans[i];
1926
+ if (plan !== null) {
1927
+ parsed[name] = decodePlannedRelation(qi, row[name], plan);
1928
+ continue;
1929
+ }
1930
+ const raw = row[name];
1931
+ if (raw !== undefined)
1932
+ parsed[name] = parseRelationValue(qi, name, def, raw);
1933
+ }
1934
+ return parsed;
1935
+ };
1936
+ }
1937
+ /**
1938
+ * One relation value through the plan: exactly what the reference produces by
1939
+ * {@link decodePositionalValue} followed by {@link parseRelationValue}. Every
1940
+ * value that is not the well-formed positional shape (a payload that is not
1941
+ * JSON, a to-many that is not an array, a to-one that is not an array) is
1942
+ * handed to `parseRelationValue` as the reference would hand it, so it
1943
+ * decodes, or throws, identically.
1944
+ */
1945
+ function decodePlannedRelation(qi, raw, rel) {
1946
+ let value = raw;
1947
+ if (typeof value === 'string') {
1948
+ try {
1949
+ value = JSON.parse(value);
1950
+ }
1951
+ catch {
1952
+ return parseRelationValue(qi, rel.name, rel.def, raw);
1953
+ }
1954
+ }
1955
+ if (value === null || value === undefined)
1956
+ return rel.many ? [] : null;
1957
+ if (!rel.many) {
1958
+ return Array.isArray(value)
1959
+ ? decodePlannedRow(qi, value, rel.row)
1960
+ : parseRelationValue(qi, rel.name, rel.def, value);
1961
+ }
1962
+ if (!Array.isArray(value))
1963
+ return parseRelationValue(qi, rel.name, rel.def, value);
1964
+ const out = [];
1965
+ for (let i = 0; i < value.length; i++) {
1966
+ const item = value[i];
1967
+ out.push(Array.isArray(item)
1968
+ ? decodePlannedRow(qi, item, rel.row)
1969
+ : typeof item === 'object' && item !== null
1970
+ ? parseNestedRow(qi, item, rel.def.to, true)
1971
+ : item);
1972
+ }
1973
+ return out;
1974
+ }
1975
+ /** One positional array through its row plan, into the parsed row. */
1976
+ function decodePlannedRow(qi, arr, plan) {
1977
+ const out = {};
1978
+ const { fields, wire, cellPositions, cellKinds, relations, table } = plan;
1979
+ for (let i = 0; i < fields.length; i++) {
1980
+ let value = arr[i];
1981
+ const rule = wire[i];
1982
+ if (rule !== undefined && typeof value === 'string')
1983
+ value = rule.decode(value);
1984
+ out[fields[i]] = value;
1985
+ }
1986
+ if (cellPositions.length > 0) {
1987
+ // `decodeCell` is present: the plan is only built when it is.
1988
+ const decodeCell = qi.decodeCell;
1989
+ for (let c = 0; c < cellPositions.length; c++) {
1990
+ const field = fields[cellPositions[c]];
1991
+ const kind = cellKinds[c];
1992
+ const value = out[field];
1993
+ // parseRow's own skip: a float the driver already made a number.
1994
+ if (kind === CELL_FLOAT && typeof value !== 'string')
1995
+ continue;
1996
+ out[field] = decodeCell(kind, value, table, field);
1997
+ }
1998
+ }
1999
+ if (relations.length > 0) {
2000
+ const order = plan.relationOrder;
2001
+ if (order === null) {
2002
+ for (const rel of relations)
2003
+ out[rel.name] = decodePlannedRelation(qi, arr[rel.position], rel);
2004
+ }
2005
+ else {
2006
+ // Claim the keys in key order first, then decode in the reference's order.
2007
+ for (const rel of relations)
2008
+ out[rel.name] = undefined;
2009
+ for (const index of order) {
2010
+ const rel = relations[index];
2011
+ out[rel.name] = decodePlannedRelation(qi, arr[rel.position], rel);
2012
+ }
2013
+ }
2014
+ }
2015
+ return out;
2016
+ }
1756
2017
  // ---------------------------------------------------------------------------
1757
2018
  // relationLoadStrategy: 'flatten', to-one relations compiled as LEFT JOINs
1758
2019
  // ---------------------------------------------------------------------------
@@ -423,6 +423,19 @@ export declare function coerceTemporalValue(dbType: string | undefined, value: u
423
423
  * as-is.
424
424
  */
425
425
  export declare function parseDbDate(value: string): Date;
426
+ /**
427
+ * Per-cell decode work in a row decode plan (`RowDecodePlan` in builder.ts).
428
+ * Defined here rather than in builder.ts because the positional nested-row
429
+ * plan in relations.ts reads the same codes, and relations.ts cannot import
430
+ * builder.ts.
431
+ */
432
+ export declare const CELL_PLAIN = 0;
433
+ export declare const CELL_TEMPORAL = 1;
434
+ export declare const CELL_FLOAT = 2;
435
+ export declare const CELL_FLOAT_ARRAY = 3;
436
+ export declare const CELL_TEXT_ARRAY = 4;
437
+ /** The dialect's own decode for a type whose storage differs (see `Dialect.decodeColumnValue`). */
438
+ export declare const CELL_DIALECT = 5;
426
439
  /**
427
440
  * A float column's value as the driver reads it. JSON has no NaN or infinity,
428
441
  * so `json_build_object` renders them as the strings "NaN", "Infinity" and
@@ -824,6 +824,13 @@ function renderTemporal(value, kind) {
824
824
  * or a `±HH`, `±HHMM`, `±HH:MM` offset.
825
825
  */
826
826
  const TZ_SUFFIX_RE = /(?:Z|[+-]\d{2}(?::?\d{2})?)$/;
827
+ const COLON_CHAR = 58;
828
+ const PLUS_CHAR = 43;
829
+ const MINUS_CHAR = 45;
830
+ /** `0`-`9` as a char code. */
831
+ function isDigitCode(code) {
832
+ return code >= 48 && code <= 57;
833
+ }
827
834
  /**
828
835
  * Parse a database date-time string deterministically.
829
836
  *
@@ -846,6 +853,29 @@ export function parseDbDate(value) {
846
853
  return Number.isNaN(date.getTime()) ? (parseDbDateGeneral(value) ?? date) : date;
847
854
  }
848
855
  function parseDbDateCommon(value) {
856
+ // Fast path for the shape `timestamptz` arrives in, a trailing `±HH:MM`
857
+ // offset (`2026-07-07T17:15:41.896+00:00`). It is exactly the general path's
858
+ // answer for that shape, not an approximation of it: the string contains a
859
+ // ':' (at length-3), TZ_SUFFIX_RE matches, and neither normalizing replace
860
+ // below can fire (the first needs four digits after the sign, the second two
861
+ // digits at the very end after it), so that path also ends in
862
+ // `new Date(value)`. All six offset characters are checked, so a near miss
863
+ // (`+0a:00`, `05:30` without a sign) still takes the general path. It skips
864
+ // one regex test and two regex replaces per value, which on a nested read is
865
+ // the single largest cost in the decode. The invalid-date fallback in
866
+ // parseDbDate still runs on the result, so a BC or five-digit year is
867
+ // unchanged.
868
+ const n = value.length;
869
+ if (n >= 6 && value.charCodeAt(n - 3) === COLON_CHAR) {
870
+ const sign = value.charCodeAt(n - 6);
871
+ if ((sign === PLUS_CHAR || sign === MINUS_CHAR) &&
872
+ isDigitCode(value.charCodeAt(n - 5)) &&
873
+ isDigitCode(value.charCodeAt(n - 4)) &&
874
+ isDigitCode(value.charCodeAt(n - 2)) &&
875
+ isDigitCode(value.charCodeAt(n - 1))) {
876
+ return new Date(value);
877
+ }
878
+ }
849
879
  // Date-only values (`2026-07-07`, from `date` columns in json_agg output)
850
880
  // have no time to zone-pin, and their `-07` tail must not be read as an
851
881
  // offset. JS parses bare ISO dates as UTC midnight already.
@@ -885,6 +915,19 @@ function parseDbDateGeneral(value) {
885
915
  }
886
916
  return date;
887
917
  }
918
+ /**
919
+ * Per-cell decode work in a row decode plan (`RowDecodePlan` in builder.ts).
920
+ * Defined here rather than in builder.ts because the positional nested-row
921
+ * plan in relations.ts reads the same codes, and relations.ts cannot import
922
+ * builder.ts.
923
+ */
924
+ export const CELL_PLAIN = 0;
925
+ export const CELL_TEMPORAL = 1;
926
+ export const CELL_FLOAT = 2;
927
+ export const CELL_FLOAT_ARRAY = 3;
928
+ export const CELL_TEXT_ARRAY = 4;
929
+ /** The dialect's own decode for a type whose storage differs (see `Dialect.decodeColumnValue`). */
930
+ export const CELL_DIALECT = 5;
888
931
  /**
889
932
  * A float column's value as the driver reads it. JSON has no NaN or infinity,
890
933
  * so `json_build_object` renders them as the strings "NaN", "Infinity" and
@@ -133,6 +133,21 @@ export interface BuilderCtx {
133
133
  toColumn(field: string): string;
134
134
  castAgg(expr: string, target: 'int' | 'float'): string;
135
135
  parseRow(row: Record<string, unknown>, table: string): Record<string, unknown>;
136
+ /**
137
+ * The field name and cell kind {@link parseRow} applies to each key of a row
138
+ * whose keys are exactly `keys`, in order (`undefined` for a table with no
139
+ * metadata). Read once per relation shape by the positional nested-row plan
140
+ * in relations.ts, so a nested row decodes by the same answers `parseRow`
141
+ * would give. Optional, like the members above, so a hand-built ctx keeps
142
+ * compiling; without it (or {@link decodeCell}) the nested parser takes the
143
+ * general path.
144
+ */
145
+ rowDecodePlan?(table: string, keys: readonly string[]): {
146
+ readonly fields: readonly string[];
147
+ readonly kinds: readonly number[];
148
+ } | undefined;
149
+ /** {@link parseRow}'s decode of one cell whose kind is not `CELL_PLAIN` (see utils.ts). */
150
+ decodeCell?(kind: number, value: unknown, table: string, field: string): unknown;
136
151
  nullsSuffix(nulls: 'first' | 'last' | undefined): string;
137
152
  isRelationOrderByValue(value: unknown): boolean;
138
153
  resolveOrderByColumn(table: string, meta: TableMetadata, key: string): string;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * turbine-orm, the `turbine:query` tracing channel.
3
+ *
4
+ * Every statement that emits a `$on('query')` event, and the transaction
5
+ * control and `$notify` statements Turbine sends on its own (which emit none),
6
+ * is published on the Node `diagnostics_channel` tracing channel named
7
+ * {@link QUERY_CHANNEL}, so a tracer or APM agent can turn Turbine queries
8
+ * into spans without any setup in the application: it subscribes to the
9
+ * channel, and the application never passes it a client.
10
+ *
11
+ * The events follow the TracingChannel lifecycle for an async call: `start`
12
+ * and `end` when the statement is handed to the driver, then `error` (on
13
+ * failure), `asyncStart` and `asyncEnd` when it settles. All five carry the
14
+ * same context object, so a subscriber can key its own state on it. `start`
15
+ * runs in the caller's async context, so the active span there is the
16
+ * statement's parent.
17
+ *
18
+ * The context never carries a bound parameter value: `sql` is the
19
+ * parametrized text Turbine built (`$1`, `$2`, ...), without the `sqlComment`,
20
+ * and `paramCount` is how many values were bound. Result rows are not
21
+ * attached either. That is why the events are published directly rather than
22
+ * through `tracePromise`, which would put the driver result on the context.
23
+ * A consequence: stores bound with `bindStore` are not entered, so read the
24
+ * caller's async context in the `start` subscriber instead.
25
+ *
26
+ * Cost without a subscriber: one `hasSubscribers` read per statement, and no
27
+ * object is built. The channel is looked up once, through
28
+ * `process.getBuiltinModule`, so no Node builtin is imported statically and
29
+ * the edge entry stays builtin-free. Where that function is missing (Node
30
+ * before 20.16 or 22.3, edge runtimes) nothing is published.
31
+ */
32
+ /** The tracing channel name. Subscribe with `diagnostics_channel.tracingChannel('turbine:query')`. */
33
+ export declare const QUERY_CHANNEL = "turbine:query";
34
+ /**
35
+ * The `operation` of a transaction-control statement Turbine sends on its own:
36
+ * `BEGIN`, `COMMIT`, `ROLLBACK`, savepoints and `sessionContext` settings. Its
37
+ * `model` is `'$raw'`, the `RAW_QUERY_MODEL` of query-events.ts (not imported:
38
+ * query-events.ts imports this module).
39
+ */
40
+ export declare const TRANSACTION_CONTROL_OPERATION = "$transaction";
41
+ /**
42
+ * The context object published on every `turbine:query` event. `rowCount` and
43
+ * `durationMs` are set before `asyncStart`, and `error` before the `error`
44
+ * event; the start events see only the identity fields.
45
+ */
46
+ export interface QueryChannelContext {
47
+ /** The table, or `'$raw'` for raw SQL and transaction control. */
48
+ model: string;
49
+ /** The entry point: `findMany`, `create`, `raw`, `$queryRaw` ..., or `'$transaction'` for transaction control. */
50
+ operation: string;
51
+ /** The parametrized statement, never its values, and without the `sqlComment`. */
52
+ sql: string;
53
+ /** How many values were bound to `sql`. */
54
+ paramCount: number;
55
+ /** Rows returned or affected. 0 for a failed statement. */
56
+ rowCount?: number;
57
+ /** Wall time of the statement, in ms. In a pipeline, the batch's time split evenly across its statements. */
58
+ durationMs?: number;
59
+ /** The error the caller receives, on failure. */
60
+ error?: Error;
61
+ /** `'pipeline'` or `'transaction'` for a statement sent as part of a batch. */
62
+ batch?: 'pipeline' | 'transaction';
63
+ /** Set on a failed first attempt of a read that Turbine sent once more on a fresh connection. */
64
+ retried?: true;
65
+ }
66
+ /** True when something subscribes to `turbine:query`. */
67
+ export declare function queryChannelActive(): boolean;
68
+ /**
69
+ * Publish `start` and `end` for a statement about to be sent, and return the
70
+ * context to settle with {@link settleQueryTrace}. Undefined, and nothing
71
+ * built, when nobody subscribes. Never throws.
72
+ */
73
+ export declare function startQueryTrace(model: string, operation: string, sql: string, paramCount: number, batch?: 'pipeline' | 'transaction'): QueryChannelContext | undefined;
74
+ /**
75
+ * Publish `error` (on failure), `asyncStart` and `asyncEnd` for a statement
76
+ * started with {@link startQueryTrace}. A no-op for an undefined context.
77
+ * Never throws.
78
+ */
79
+ export declare function settleQueryTrace(context: QueryChannelContext | undefined, rowCount: number, durationMs: number, error?: Error, retried?: boolean): void;
80
+ /**
81
+ * Run a statement Turbine sends on its own (transaction control, `$notify`)
82
+ * with a `turbine:query` trace around it. `run` should throw the error the
83
+ * caller receives, so the trace carries that one. Without a subscriber it is
84
+ * `run()` and nothing else.
85
+ */
86
+ export declare function traceStatement<R>(operation: string, sql: string, paramCount: number, run: () => Promise<R>): Promise<R>;