@kiri-orm/core 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +27 -15
  2. package/dist/types/client/model-handle.d.ts +4 -1
  3. package/dist/types/connection.d.ts +66 -0
  4. package/dist/types/crud/chunk.d.ts +10 -0
  5. package/dist/types/crud/database-errors.d.ts +61 -0
  6. package/dist/types/crud/errors.d.ts +10 -0
  7. package/dist/types/crud/fast-path.d.ts +73 -0
  8. package/dist/types/crud/index.d.ts +4 -1
  9. package/dist/types/crud/insert-many.d.ts +12 -13
  10. package/dist/types/crud/order.d.ts +28 -0
  11. package/dist/types/crud/repository.d.ts +5 -3
  12. package/dist/types/crud/row-mapping.d.ts +9 -1
  13. package/dist/types/crud/upsert.d.ts +39 -0
  14. package/dist/types/crud/value.d.ts +39 -0
  15. package/dist/types/dialect/date-bucket.d.ts +2 -2
  16. package/dist/types/dialect/index.d.ts +1 -0
  17. package/dist/types/dialect/transaction-guard.d.ts +31 -0
  18. package/dist/types/domain/compile.d.ts +17 -0
  19. package/dist/types/fields/filter-value.d.ts +21 -0
  20. package/dist/types/fields/registry.d.ts +1 -0
  21. package/dist/types/fields/storage.d.ts +28 -0
  22. package/dist/types/fields/types/date.d.ts +6 -6
  23. package/dist/types/fields/types/decimal.d.ts +40 -0
  24. package/dist/types/global/errors.d.ts +3 -0
  25. package/dist/types/global/index.d.ts +2 -0
  26. package/dist/types/global/normalize-dates.d.ts +11 -0
  27. package/dist/types/global/state.d.ts +2 -0
  28. package/dist/types/global/transaction.d.ts +10 -13
  29. package/dist/types/index.d.ts +2 -0
  30. package/dist/types/meta/create-table-once.d.ts +15 -0
  31. package/dist/types/meta/snapshot.d.ts +10 -0
  32. package/dist/types/meta/upsert.d.ts +16 -0
  33. package/dist/types/migrations/diff.d.ts +25 -2
  34. package/dist/types/models/constraints.d.ts +27 -0
  35. package/dist/types/relations/pivot-schema.d.ts +1 -1
  36. package/dist/types/schema/alter-column.d.ts +46 -0
  37. package/dist/types/schema/build-column.d.ts +11 -0
  38. package/dist/types/schema/index.d.ts +1 -0
  39. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  40. package/dist/types/schema/normalize-dates.d.ts +41 -0
  41. package/dist/types/transaction/after-commit.d.ts +42 -0
  42. package/dist/types/transaction/context.d.ts +39 -0
  43. package/dist/types/uow/entity.d.ts +39 -29
  44. package/dist/types/uow/hooks.d.ts +6 -1
  45. package/dist/types/uow/lifecycle.d.ts +82 -0
  46. package/dist/types/uow/unit-of-work.d.ts +11 -7
  47. package/package.json +8 -5
  48. package/src/client/model-handle.js +14 -4
  49. package/src/client/orm-client.js +10 -5
  50. package/src/connection.js +53 -7
  51. package/src/crud/aggregate-filter.js +8 -2
  52. package/src/crud/aggregate-spec.js +2 -2
  53. package/src/crud/aggregate.js +16 -5
  54. package/src/crud/chunk.js +10 -0
  55. package/src/crud/create-many.js +52 -29
  56. package/src/crud/database-errors.js +107 -0
  57. package/src/crud/errors.js +14 -0
  58. package/src/crud/fast-path.js +449 -0
  59. package/src/crud/index.js +4 -1
  60. package/src/crud/insert-many.js +42 -7
  61. package/src/crud/map-filter.js +2 -1
  62. package/src/crud/order.js +59 -9
  63. package/src/crud/repository.js +106 -38
  64. package/src/crud/row-mapping.js +32 -7
  65. package/src/crud/upsert.js +203 -0
  66. package/src/crud/value.js +71 -0
  67. package/src/dialect/index.js +1 -0
  68. package/src/dialect/transaction-guard.js +254 -0
  69. package/src/domain/compile.js +85 -12
  70. package/src/dto/field-schema.js +5 -0
  71. package/src/fields/default-registry.js +3 -1
  72. package/src/fields/filter-value.js +87 -0
  73. package/src/fields/registry.js +1 -0
  74. package/src/fields/storage.js +50 -0
  75. package/src/fields/types/date.js +16 -3
  76. package/src/fields/types/decimal.js +147 -0
  77. package/src/fields/types/integer.js +7 -0
  78. package/src/global/connect.js +25 -1
  79. package/src/global/create-model.js +59 -57
  80. package/src/global/errors.js +1 -1
  81. package/src/global/index.js +2 -0
  82. package/src/global/normalize-dates.js +15 -0
  83. package/src/global/state.js +3 -0
  84. package/src/global/transaction.js +12 -14
  85. package/src/index.js +2 -0
  86. package/src/meta/create-table-once.js +23 -0
  87. package/src/meta/schema.js +15 -6
  88. package/src/meta/snapshot.js +5 -0
  89. package/src/meta/upsert.js +28 -0
  90. package/src/migrations/describe.js +49 -0
  91. package/src/migrations/diff.js +50 -7
  92. package/src/migrations/generate.js +38 -2
  93. package/src/migrations/render.js +30 -12
  94. package/src/migrations/runner.js +40 -6
  95. package/src/models/constraints.js +96 -0
  96. package/src/models/define-model.js +4 -0
  97. package/src/models/inheritance.js +4 -1
  98. package/src/models/registry.js +2 -1
  99. package/src/relations/attach-detach.js +49 -18
  100. package/src/relations/cascade-delete.js +32 -7
  101. package/src/relations/eager-load.js +75 -51
  102. package/src/relations/pivot-schema.js +24 -3
  103. package/src/reports/report-handle.js +2 -1
  104. package/src/schema/alter-column.js +219 -0
  105. package/src/schema/build-column.js +28 -2
  106. package/src/schema/default-column-builders.js +16 -2
  107. package/src/schema/index.js +1 -0
  108. package/src/schema/introspect-indexes.js +22 -0
  109. package/src/schema/normalize-dates.js +58 -0
  110. package/src/schema/sync.js +16 -2
  111. package/src/transaction/after-commit.js +142 -0
  112. package/src/transaction/context.js +84 -0
  113. package/src/uow/entity.js +133 -133
  114. package/src/uow/hooks.js +9 -0
  115. package/src/uow/lifecycle.js +162 -0
  116. package/src/uow/unit-of-work.js +55 -60
  117. package/src/uow/with-unit-of-work.js +2 -1
@@ -0,0 +1,71 @@
1
+ import { castValue } from "../fields/cast-value.js";
2
+ import { toStorage } from "../fields/storage.js";
3
+ import { ValidationError } from "./errors.js";
4
+
5
+ /**
6
+ * Values computed by the database at write time (since 0.2.0), for updates that must not lose
7
+ * concurrent changes:
8
+ *
9
+ * await Post.updateMany({ id }, { views: Value.increment(1) }); // views = views + 1
10
+ * await Account.updateMany({ id }, { balance: Value.decrement("12.50") }); // a decimal field
11
+ *
12
+ * Reading a value, changing it in JavaScript and saving it back loses an update when two requests
13
+ * do it at once: both read 10, both write 11. `Value.increment` sends `SET views = views + 1`, so
14
+ * the database applies each change to whatever the row holds at that moment.
15
+ *
16
+ * Works on integer, float and decimal fields, in updateMany() (and inside transactions); the
17
+ * amount is validated as a value of the field (a decimal amount keeps its exactness).
18
+ */
19
+ export class ValueExpression {
20
+ constructor(kind, amount) {
21
+ this.kind = kind;
22
+ this.amount = amount;
23
+ }
24
+ }
25
+
26
+ export const Value = Object.freeze({
27
+ /** `field = field + amount` (amount defaults to 1). */
28
+ increment: (amount = 1) => new ValueExpression("increment", amount),
29
+ /** `field = field - amount` (amount defaults to 1). */
30
+ decrement: (amount = 1) => new ValueExpression("decrement", amount),
31
+ });
32
+
33
+ const NUMERIC = new Set(["integer", "float", "decimal"]);
34
+
35
+ /**
36
+ * Splits update data into plain values and database expressions. Returns the plain part, plus a
37
+ * function that turns the expressions into Knex raw SET values for a given connection.
38
+ */
39
+ export function splitValueExpressions(model, data, fieldTypeRegistry) {
40
+ const plain = {};
41
+ const expressions = [];
42
+ const errors = {};
43
+ for (const [fieldName, value] of Object.entries(data)) {
44
+ if (!(value instanceof ValueExpression)) {
45
+ plain[fieldName] = value;
46
+ continue;
47
+ }
48
+ const field = model.fields[fieldName];
49
+ if (!field) {
50
+ errors[fieldName] = [`unknown field "${fieldName}" on model "${model.name}"`];
51
+ continue;
52
+ }
53
+ if (!NUMERIC.has(field.type)) {
54
+ errors[fieldName] = [`Value.${value.kind}() needs an integer, float or decimal field; "${fieldName}" is ${field.type}`];
55
+ continue;
56
+ }
57
+ let amount;
58
+ try {
59
+ amount = castValue(field, value.amount, fieldTypeRegistry);
60
+ const typeErrors = field.type === "decimal" ? [] : fieldTypeRegistry.get(field.type).validate({ type: field.type }, amount);
61
+ if (typeErrors.length) throw new Error(typeErrors.join("; "));
62
+ } catch (error) {
63
+ errors[fieldName] = [`Value.${value.kind}(): ${error.message}`];
64
+ continue;
65
+ }
66
+ expressions.push({ column: model.columns[fieldName], operator: value.kind === "increment" ? "+" : "-", amount: toStorage(field, amount, fieldTypeRegistry) });
67
+ }
68
+ if (Object.keys(errors).length > 0) throw new ValidationError(model.name, errors);
69
+ const toSet = (db) => Object.fromEntries(expressions.map((e) => [e.column, db.raw(`?? ${e.operator} ?`, [e.column, e.amount])]));
70
+ return { plain, hasExpressions: expressions.length > 0, toSet, expressions };
71
+ }
@@ -1 +1,2 @@
1
1
  export { DATE_BUCKETS, dateBucketSql, parseBucket } from "./date-bucket.js";
2
+ export { instrumentConnection, guardTransactions, TransactionDeadlockError } from "./transaction-guard.js";
@@ -0,0 +1,254 @@
1
+ import { runInTransactionScope, holdsTransactionFor } from "../transaction/context.js";
2
+ import { flushAfterCommit, discardAfterCommit } from "../transaction/after-commit.js";
3
+ import { resolveDialectValues, dialectOfClient } from "../fields/storage.js";
4
+
5
+ /**
6
+ * Thrown when code running inside a transaction issues a raw query on the connection itself while
7
+ * that transaction holds SQLite's only pooled connection: the query would wait for a connection
8
+ * the transaction never gives back. Since 0.2.0 model calls join the open transaction on their
9
+ * own, so this is left for raw Knex queries (`db("table")...` instead of `trx("table")...`).
10
+ */
11
+ export class TransactionDeadlockError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "TransactionDeadlockError";
15
+ }
16
+ }
17
+
18
+ const INSTRUMENTED = Symbol.for("kiri-orm.transactionGuard");
19
+
20
+ /**
21
+ * Instruments a connection's Knex client so transactions follow the code that runs in them.
22
+ * Idempotent; applied by createConnection(), connect() and every Repository.
23
+ *
24
+ * 1. Scoping (both databases, since 0.2.0). Every transaction started with a container runs that
25
+ * container inside a scope (transaction/context.js), and so does every savepoint inside it -
26
+ * so model calls in it, hooks included, join it without `{ trx }`.
27
+ * 2. After-commit work (since 0.2.0). When an outermost transaction commits, what was queued with
28
+ * afterCommit() runs before `await db.transaction(...)` resumes; on rollback it is dropped.
29
+ * 3. SQLite deadlock guard (since 0.1.7). Inside a transaction's own async flow, a query that skips
30
+ * the transaction and asks the pool for a connection waits forever on SQLite's single
31
+ * connection - it fails at once with TransactionDeadlockError instead. A query from another
32
+ * request isn't in that flow and still waits its turn. Pools of more than one connection are
33
+ * left alone.
34
+ *
35
+ * @template {import('knex').Knex} T
36
+ * @param {T} db
37
+ * @returns {T}
38
+ */
39
+ export function instrumentConnection(db) {
40
+ const client = db?.client;
41
+ if (!client || db.isTransaction || client[INSTRUMENTED] || typeof client.transaction !== "function") return db;
42
+ client[INSTRUMENTED] = true;
43
+ resolveBoundValues(client);
44
+
45
+ const transaction = client.transaction;
46
+ client.transaction = function scopedTransaction(container, config, outerTx) {
47
+ if (typeof container !== "function") return transaction.call(this, container, config, outerTx);
48
+ const state = { trx: null, rolledBack: false };
49
+ const tx = transaction.call(
50
+ this,
51
+ (trx) => {
52
+ opened(state, trx);
53
+ scopeSavepoints(client, trx);
54
+ return runInTransactionScope(client, trx, () => container(trx));
55
+ },
56
+ config,
57
+ outerTx
58
+ );
59
+ return finishWith(tx, state, true);
60
+ };
61
+
62
+ if (isPostgres(client)) {
63
+ const acquireConnection = client.acquireConnection;
64
+ client.acquireConnection = async function serializedAcquireConnection() {
65
+ return serializeQueries(await acquireConnection.call(this));
66
+ };
67
+ }
68
+
69
+ if (isSqlite(client)) {
70
+ const acquireConnection = client.acquireConnection;
71
+ client.acquireConnection = function guardedAcquireConnection() {
72
+ if (poolMax(client) === 1 && holdsTransactionFor(client)) {
73
+ return Promise.reject(
74
+ new TransactionDeadlockError(
75
+ "A query was issued outside the open transaction it runs in. On SQLite the transaction holds the only " +
76
+ "connection, so this query would wait for it forever. Model calls join the open transaction by themselves; " +
77
+ "for a raw Knex query, run it on the transaction: trx(\"table\")... instead of db(\"table\")..."
78
+ )
79
+ );
80
+ }
81
+ return acquireConnection.call(this);
82
+ };
83
+ }
84
+ return db;
85
+ }
86
+
87
+ const BINDINGS_RESOLVED = Symbol.for("kiri-orm.dialectValues");
88
+
89
+ /**
90
+ * Field values whose stored form depends on the database (a `decimal` is a scaled integer on SQLite,
91
+ * numeric text on Postgres) travel through query building as DialectValue objects and are resolved
92
+ * here, when Knex prepares a query's bindings. Patched on the dialect's client class, so it covers
93
+ * the per-transaction clients Knex derives from it too; it only touches DialectValue objects, so other
94
+ * Knex instances in the process are unaffected.
95
+ */
96
+ function resolveBoundValues(client) {
97
+ const proto = Object.getPrototypeOf(client);
98
+ if (!proto || proto[BINDINGS_RESOLVED] || typeof proto.prepBindings !== "function") return;
99
+ const prepBindings = proto.prepBindings;
100
+ proto.prepBindings = function prepBindingsWithDialectValues(bindings) {
101
+ return prepBindings.call(this, resolveDialectValues(bindings, dialectOfClient(this)));
102
+ };
103
+ proto[BINDINGS_RESOLVED] = true;
104
+ }
105
+
106
+ /** @deprecated since 0.2.0 - the 0.1.7 name of instrumentConnection(). */
107
+ export const guardTransactions = instrumentConnection;
108
+
109
+ /**
110
+ * Savepoints (`trx.transaction(fn)`) go through a per-transaction client the instance patch above
111
+ * doesn't reach, so each transaction object gets its own patch: the savepoint's callback runs in
112
+ * its own scope, and its rollback drops what was queued inside it.
113
+ */
114
+ function scopeSavepoints(client, trx) {
115
+ const savepoint = trx.transaction;
116
+ if (typeof savepoint !== "function") return;
117
+ const scoped = function scopedSavepoint(container, options) {
118
+ if (typeof container !== "function") return savepoint.call(this, container, options);
119
+ const state = { trx: null, rolledBack: false };
120
+ const tx = savepoint.call(
121
+ this,
122
+ (inner) => {
123
+ opened(state, inner);
124
+ scopeSavepoints(client, inner);
125
+ return runInTransactionScope(client, inner, () => container(inner));
126
+ },
127
+ options
128
+ );
129
+ return finishWith(tx, state, false);
130
+ };
131
+ // Knex defines `transaction` on the transaction object as read-only (but configurable).
132
+ Object.defineProperty(trx, "transaction", { value: scoped, writable: false, configurable: true });
133
+ trx.savepoint = scoped;
134
+ }
135
+
136
+ /**
137
+ * Records a transaction as it opens, and catches an explicit `trx.rollback()`: with Knex's
138
+ * doNotRejectOnRollback that settles the transaction successfully, which must not run its
139
+ * after-commit work.
140
+ */
141
+ function opened(state, trx) {
142
+ state.trx = trx;
143
+ const rollback = trx.rollback;
144
+ trx.rollback = function (...args) {
145
+ state.rolledBack = true;
146
+ return rollback.apply(this, args);
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Hooks the end of a Knex Transaction (a thenable whose `_promise` settles when it commits or rolls
152
+ * back) without changing what the caller receives.
153
+ */
154
+ function finishWith(tx, state, outermost) {
155
+ if (!tx || typeof tx.then !== "function" || !("_promise" in tx)) return tx;
156
+ tx._promise = tx._promise.then(
157
+ async (value) => {
158
+ if (state.trx && state.rolledBack) discardAfterCommit(state.trx);
159
+ else if (state.trx && outermost) await flushAfterCommit(state.trx);
160
+ return value;
161
+ },
162
+ (error) => {
163
+ if (state.trx) discardAfterCommit(state.trx);
164
+ throw error;
165
+ }
166
+ );
167
+ return tx;
168
+ }
169
+
170
+ const SERIALIZED = Symbol.for("kiri-orm.serializedQueries");
171
+
172
+ /**
173
+ * Makes a pg connection run one query at a time (since 0.2.0). Model calls inside one transaction
174
+ * share its connection, and `Promise.all([...])` there would otherwise hand pg a query while another
175
+ * is still running - which pg 8 queues with a deprecation warning and pg 9 removes. Each query now
176
+ * starts when the one before it has finished; a lone query starts at once. Streams and cursors
177
+ * (objects with `submit`) and a connection in pipeline mode are passed straight through.
178
+ */
179
+ function serializeQueries(connection) {
180
+ if (!connection || connection[SERIALIZED] || typeof connection.query !== "function") return connection;
181
+ const query = connection.query;
182
+ const waiting = [];
183
+ let busy = false;
184
+ const start = (task) => {
185
+ busy = true;
186
+ task();
187
+ };
188
+ const done = () => {
189
+ busy = false;
190
+ const next = waiting.shift();
191
+ if (next) start(next);
192
+ };
193
+ connection.query = function serializedQuery(...args) {
194
+ if (this.pipeline || (args[0] && typeof args[0].submit === "function")) return query.apply(this, args);
195
+ const last = args.length - 1;
196
+ if (typeof args[last] === "function") {
197
+ const callback = args[last];
198
+ const run = () => {
199
+ args[last] = (...result) => {
200
+ done();
201
+ callback(...result);
202
+ };
203
+ try {
204
+ query.apply(connection, args);
205
+ } catch (error) {
206
+ done();
207
+ callback(error);
208
+ }
209
+ };
210
+ if (busy) waiting.push(run);
211
+ else start(run);
212
+ return undefined;
213
+ }
214
+ return new Promise((resolve, reject) => {
215
+ const run = () => {
216
+ let result;
217
+ try {
218
+ result = query.apply(connection, args);
219
+ } catch (error) {
220
+ done();
221
+ reject(error);
222
+ return;
223
+ }
224
+ Promise.resolve(result).then(
225
+ (value) => {
226
+ done();
227
+ resolve(value);
228
+ },
229
+ (error) => {
230
+ done();
231
+ reject(error);
232
+ }
233
+ );
234
+ };
235
+ if (busy) waiting.push(run);
236
+ else start(run);
237
+ });
238
+ };
239
+ Object.defineProperty(connection, SERIALIZED, { value: true });
240
+ return connection;
241
+ }
242
+
243
+ function isPostgres(client) {
244
+ return dialectOfClient(client) === "postgres";
245
+ }
246
+
247
+ function isSqlite(client) {
248
+ const name = client.config?.client;
249
+ return typeof name === "string" ? name.includes("sqlite") : /sqlite/i.test(client.dialect ?? "");
250
+ }
251
+
252
+ function poolMax(client) {
253
+ return client.pool?.max ?? client.config?.pool?.max ?? 1;
254
+ }
@@ -4,6 +4,8 @@ import { parseDomain } from "./parse.js";
4
4
  import { DomainValidationError } from "./errors.js";
5
5
  import { resolveLocalKey } from "../relations/keys.js";
6
6
  import { primaryKeyOf } from "../models/primary-key.js";
7
+ import { toStorage, DialectValue } from "../fields/storage.js";
8
+ import { filterValue } from "../fields/filter-value.js";
7
9
 
8
10
  const OPERATOR_HANDLERS = {
9
11
  "=": (qb, column, value) => (value === null ? qb.whereNull(column) : qb.where(column, "=", value)),
@@ -12,27 +14,44 @@ const OPERATOR_HANDLERS = {
12
14
  ">=": (qb, column, value) => qb.where(column, ">=", value),
13
15
  "<": (qb, column, value) => qb.where(column, "<", value),
14
16
  "<=": (qb, column, value) => qb.where(column, "<=", value),
15
- in: (qb, column, value) => qb.whereIn(column, value),
16
- "not in": (qb, column, value) => qb.whereNotIn(column, value),
17
- like: (qb, column, value) => qb.where(column, "like", value),
18
- // Portable case-insensitive match across sqlite and postgres (postgres
19
- // has native ILIKE, but LOWER()/LOWER() works identically on both,
20
- // so one code path covers both dialects rather than branching).
21
- ilike: (qb, column, value) => qb.whereRaw("LOWER(??) LIKE LOWER(?)", [column, value]),
17
+ // Postgres: one array parameter (since 0.2.0), so a list of any length is one statement and lists
18
+ // past the 65,535-parameter limit work. Same NULL semantics as IN / NOT IN.
19
+ in: (qb, column, value) => (isPostgresQuery(qb) ? qb.whereRaw("?? = ANY(?)", [column, asArrayBinding(value)]) : qb.whereIn(column, value)),
20
+ "not in": (qb, column, value) => (isPostgresQuery(qb) ? qb.whereRaw("?? <> ALL(?)", [column, asArrayBinding(value)]) : qb.whereNotIn(column, value)),
21
+ // `like` is case-sensitive on both databases since 0.2.0. Postgres' LIKE is; SQLite's ignores
22
+ // case for A-Z, so there the pattern runs as the equivalent GLOB, which doesn't.
23
+ like: (qb, column, value) => (isSqliteQuery(qb) ? qb.whereRaw("?? GLOB ?", [column, likeToGlob(value)]) : qb.where(column, "like", value)),
24
+ // Case-insensitive. Postgres has it built in: ILIKE (since 0.2.0; before, LOWER(col) LIKE LOWER(?),
25
+ // which lower-cased every row it scanned - about 7x slower on an unindexed search, same results).
26
+ // SQLite has no ILIKE, and its lower() only folds A-Z, so there both sides are lower-cased with
27
+ // kiri_lower(), JavaScript's toLowerCase(), registered on connections the ORM creates - "Émile"
28
+ // matches "émile" on both databases. A SQLite Knex instance you built yourself falls back to LOWER().
29
+ ilike: (qb, column, value) => {
30
+ if (!isSqliteQuery(qb)) return qb.whereRaw("?? ILIKE ?", [column, value]);
31
+ const lower = qb.client?.config?.kiriLower ? "kiri_lower" : "LOWER";
32
+ return qb.whereRaw(`${lower}(??) LIKE ${lower}(?) ESCAPE '\\'`, [column, value]);
33
+ },
22
34
  };
23
35
 
24
- function castLeafValue(field, fieldName, op, value, fieldTypeRegistry) {
36
+ /**
37
+ * A leaf's value as bound: cast and in storage form (see filterValue()). `computed` leaves keep the
38
+ * 0.2.0 conversion: their value goes to the field's search(), not to a column.
39
+ */
40
+ export function castLeafValue(field, fieldName, op, value, fieldTypeRegistry, { computed = false } = {}) {
41
+ const convert = computed
42
+ ? (v) => toStorage(field, castValue(field, v, fieldTypeRegistry), fieldTypeRegistry)
43
+ : (v) => filterValue(field, op, v, fieldTypeRegistry);
25
44
  if (op === "in" || op === "not in") {
26
45
  if (!Array.isArray(value)) {
27
46
  throw new DomainValidationError(`Operator "${op}" on field "${fieldName}" requires an array value`);
28
47
  }
29
- return value.map((v) => (v === null ? null : castValue(field, v, fieldTypeRegistry)));
48
+ return value.map((v) => (v === null ? null : convert(v)));
30
49
  }
31
50
  if (op === "like" || op === "ilike") {
32
- return String(value); // a pattern, not a field value - don't run it through type coercion
51
+ return likePattern(String(value), fieldName); // a pattern, not a field value - don't run it through type coercion
33
52
  }
34
53
  if (value === null) return null;
35
- return castValue(field, value, fieldTypeRegistry);
54
+ return convert(value);
36
55
  }
37
56
 
38
57
  /**
@@ -61,7 +80,7 @@ function compileComputedLeaf(node, computed, model, fieldTypeRegistry, modelRegi
61
80
  throw new DomainValidationError(`Circular search on computed fields: ${[...expanding, key].join(" -> ")}`);
62
81
  }
63
82
 
64
- const value = castLeafValue(computed, node.field, node.op, node.value, fieldTypeRegistry);
83
+ const value = castLeafValue(computed, node.field, node.op, node.value, fieldTypeRegistry, { computed: true });
65
84
  const domain = computed.search(node.op, value);
66
85
  if (!Array.isArray(domain)) {
67
86
  throw new DomainValidationError(
@@ -274,3 +293,57 @@ export function compileDomain(model, domain, fieldTypeRegistry = defaultFieldTyp
274
293
  export function compileParsedDomain(model, ast, fieldTypeRegistry = defaultFieldTypeRegistry, modelRegistry = undefined) {
275
294
  return compileNode(ast, model, fieldTypeRegistry, modelRegistry);
276
295
  }
296
+
297
+ function isPostgresQuery(qb) {
298
+ return String(qb.client?.config?.client ?? "") === "pg";
299
+ }
300
+
301
+ /** An `in` list as one bound array, its decimal (DialectValue) items resolved when the query is bound. */
302
+ function asArrayBinding(list) {
303
+ return list.some((v) => v instanceof DialectValue) ? new DialectValue((dialect) => list.map((v) => (v instanceof DialectValue ? v.resolve(dialect) : v))) : list;
304
+ }
305
+
306
+ function isSqliteQuery(qb) {
307
+ return String(qb.client?.config?.client ?? "").includes("sqlite");
308
+ }
309
+
310
+ /**
311
+ * A `like` / `ilike` pattern in the one form both databases read the same way (since 0.2.0):
312
+ * `%` is any run of characters, `_` any one, and a backslash makes the next character literal -
313
+ * `\\%` is a percent sign, `\\\\` a backslash. That is Postgres' rule (its default LIKE escape);
314
+ * SQLite gets it through likeToGlob() and an explicit `ESCAPE '\\'`. A backslash before any other
315
+ * character is dropped (`\\t` means `t` on both), and a pattern ending in a lone backslash is refused.
316
+ */
317
+ export function likePattern(pattern, fieldName = "") {
318
+ let out = "";
319
+ for (let i = 0; i < pattern.length; i++) {
320
+ const char = pattern[i];
321
+ if (char !== "\\") {
322
+ out += char;
323
+ continue;
324
+ }
325
+ const next = pattern[++i];
326
+ if (next === undefined) {
327
+ throw new DomainValidationError(
328
+ `like pattern for "${fieldName}" ends with a lone backslash, which escapes nothing. Write "\\\\\\\\" (two backslashes) for a literal backslash.`
329
+ );
330
+ }
331
+ out += next === "%" || next === "_" || next === "\\" ? `\\${next}` : next;
332
+ }
333
+ return out;
334
+ }
335
+
336
+ /** A LIKE pattern (see likePattern()) as the equivalent GLOB pattern, other characters literal. */
337
+ export function likeToGlob(pattern) {
338
+ let glob = "";
339
+ const literal = (char) => (char === "*" || char === "?" || char === "[" ? `[${char}]` : char);
340
+ const chars = [...String(pattern)];
341
+ for (let i = 0; i < chars.length; i++) {
342
+ const char = chars[i];
343
+ if (char === "\\" && i + 1 < chars.length) glob += literal(chars[++i]);
344
+ else if (char === "%") glob += "*";
345
+ else if (char === "_") glob += "?";
346
+ else glob += literal(char);
347
+ }
348
+ return glob;
349
+ }
@@ -30,6 +30,11 @@ export function fieldToJsonSchema(field) {
30
30
  if (field.max !== undefined) schema.maximum = field.max;
31
31
  return schema;
32
32
  }
33
+ case "decimal": {
34
+ // Exact numbers travel as text ("12.50"), never as a JSON number that would round.
35
+ const scale = field.scale ?? 2;
36
+ return { type: "string", pattern: scale > 0 ? `^-?\\d+\\.\\d{${scale}}$` : "^-?\\d+$" };
37
+ }
33
38
  case "boolean":
34
39
  return { type: "boolean" };
35
40
  case "date":
@@ -9,6 +9,7 @@ import { datetimeType } from "./types/datetime.js";
9
9
  import { jsonType } from "./types/json.js";
10
10
  import { enumType } from "./types/enum.js";
11
11
  import { uuidType } from "./types/uuid.js";
12
+ import { decimalType } from "./types/decimal.js";
12
13
 
13
14
  /**
14
15
  * The registry used by defineField()/validateValue()/castValue() when
@@ -28,7 +29,8 @@ export function createDefaultFieldTypeRegistry() {
28
29
  .register(datetimeType)
29
30
  .register(jsonType)
30
31
  .register(enumType)
31
- .register(uuidType);
32
+ .register(uuidType)
33
+ .register(decimalType);
32
34
  return registry;
33
35
  }
34
36
 
@@ -0,0 +1,87 @@
1
+ import { castValue } from "./cast-value.js";
2
+ import { toStorage, DialectValue } from "./storage.js";
3
+
4
+ /**
5
+ * The value a filter binds for a stored field, given its operator (since 0.2.0). Every filter path
6
+ * uses it - domains, plain-object filters, the direct SQL path and Knex - so they can't disagree.
7
+ *
8
+ * Two types need more than cast-then-store:
9
+ *
10
+ * - `json`: bound as JSON text, exactly as writes store it (`JSON.stringify`). Before, an object
11
+ * reached SQLite's driver as an object (a TypeError), a string reached Postgres' jsonb as bare
12
+ * text (invalid JSON), and a string on SQLite never matched its stored JSON text. SQLite compares
13
+ * the text itself, so an object matches only with its keys in the stored order; Postgres' jsonb
14
+ * ignores key order.
15
+ * - `decimal`: compared exactly. A value with more decimal places than the field's scale used to be
16
+ * rounded first (a number) or refused (a string), so `["price", "<", 2.001]` became `< 2.00` and
17
+ * left out a row at 2.00. See decimalFilterValue().
18
+ *
19
+ * @param {object} field - the field definition
20
+ * @param {string} op - the domain operator ("=" for a plain-object filter)
21
+ * @param {unknown} value - one value (a single item of an `in` list)
22
+ * @param {import('./registry.js').FieldTypeRegistry} fieldTypeRegistry
23
+ */
24
+ export function filterValue(field, op, value, fieldTypeRegistry) {
25
+ if (value === null || value === undefined) return value;
26
+ if (field.type === "json") return JSON.stringify(castValue(field, value, fieldTypeRegistry));
27
+ if (field.type === "decimal") {
28
+ const exact = decimalFilterValue(field, op, value);
29
+ if (exact !== undefined) return exact;
30
+ }
31
+ return toStorage(field, castValue(field, value, fieldTypeRegistry), fieldTypeRegistry);
32
+ }
33
+
34
+ const DECIMAL_TEXT = /^\s*([+-]?)(\d*)(?:\.(\d*))?\s*$/;
35
+
36
+ /** A number, string or bigint as an exact decimal { negative, digits, places }, trailing zeros dropped; null if it isn't one. */
37
+ function exactDecimal(value) {
38
+ let negative = false;
39
+ let int = "";
40
+ let frac = "";
41
+ if (typeof value === "bigint") {
42
+ negative = value < 0n;
43
+ int = (negative ? -value : value).toString();
44
+ } else if (typeof value === "number") {
45
+ if (!Number.isFinite(value)) return null;
46
+ negative = value < 0;
47
+ // The decimal text JavaScript prints, as the decimal type itself reads numbers (2.001 is "2.001").
48
+ [int, frac = ""] = Math.abs(value).toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 }).split(".");
49
+ } else if (typeof value === "string") {
50
+ const match = DECIMAL_TEXT.exec(value);
51
+ if (!match || (match[2] === "" && (match[3] ?? "") === "")) return null;
52
+ negative = match[1] === "-";
53
+ int = match[2];
54
+ frac = match[3] ?? "";
55
+ } else {
56
+ return null;
57
+ }
58
+ frac = frac.replace(/0+$/, "");
59
+ const digits = BigInt((int || "0") + frac);
60
+ return { negative: negative && digits !== 0n, digits, places: frac.length };
61
+ }
62
+
63
+ /**
64
+ * A decimal filter value with more places than the field's scale, compared exactly; undefined when
65
+ * the value fits the scale (the ordinary cast handles it) or isn't a decimal (the cast reports it).
66
+ *
67
+ * - Postgres: `numeric` compares exactly, so the exact text is bound.
68
+ * - SQLite stores value x 10^scale as an integer, and the bound value can't be one: the comparison is
69
+ * moved to the nearest integer on the side that keeps it true (`< 200.1` is `< 201`, `<= 200.1` is
70
+ * `<= 200`, `> 200.1` is `> 200`, `>= 200.1` is `>= 201`). For `=`, `!=` and `in` the scaled
71
+ * value itself is bound: it isn't a whole number, so it equals no stored value.
72
+ */
73
+ function decimalFilterValue(field, op, value) {
74
+ const exact = exactDecimal(value);
75
+ const scale = field.scale ?? 2;
76
+ if (exact === null || exact.places <= scale) return undefined;
77
+ const signed = exact.negative ? -exact.digits : exact.digits;
78
+ const text = `${exact.negative ? "-" : ""}${exact.digits.toString().padStart(exact.places + 1, "0").replace(new RegExp(`(\\d{${exact.places}})$`), ".$1")}`;
79
+ return new DialectValue((dialect) => {
80
+ if (dialect !== "sqlite") return text;
81
+ const factor = 10n ** BigInt(exact.places - scale);
82
+ const floor = signed / factor - (signed % factor < 0n ? 1n : 0n);
83
+ if (op === "<" || op === ">=") return Number(floor + 1n);
84
+ if (op === "<=" || op === ">") return Number(floor);
85
+ return Number(signed) / Number(factor);
86
+ });
87
+ }
@@ -45,6 +45,7 @@ export class FieldTypeRegistry {
45
45
  );
46
46
  }
47
47
  this.#types.set(definition.name, definition);
48
+ this.version = (this.version ?? 0) + 1; // read plans cached per registry (crud/row-mapping.js) check it
48
49
  return this;
49
50
  }
50
51
 
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The form a field value takes in the database, when that differs per database (since 0.2.0).
3
+ *
4
+ * A field type can define:
5
+ * - `toStorage(field, value)` -> the value to bind (often a DialectValue, resolved per database);
6
+ * - `fromStorage(field, value, dialect)` -> the stored value turned back into a field value,
7
+ * before cast().
8
+ * `decimal` uses both: SQLite stores it as a scaled integer, Postgres as numeric text.
9
+ */
10
+
11
+ /**
12
+ * A bound value that depends on the database: `resolve(dialect)` returns what to send. Writes and
13
+ * filter values carry these; every connection the ORM instruments resolves them when Knex prepares
14
+ * a query's bindings (dialect/transaction-guard.js), so the code building a query never needs to
15
+ * know which database it will run on.
16
+ */
17
+ export class DialectValue {
18
+ /** @param {(dialect: "sqlite"|"postgres") => unknown} resolve */
19
+ constructor(resolve) {
20
+ this.resolve = resolve;
21
+ }
22
+ }
23
+
24
+ /** A cast field value in its storage form (a filter binding, a column value to write). */
25
+ export function toStorage(field, value, fieldTypeRegistry) {
26
+ if (value === null || value === undefined) return value;
27
+ const typeDef = fieldTypeRegistry.has(field.type) ? fieldTypeRegistry.get(field.type) : null;
28
+ return typeDef?.toStorage ? typeDef.toStorage(field, value) : value;
29
+ }
30
+
31
+ /** A stored value back to what cast() expects. */
32
+ export function fromStorage(field, value, dialect, fieldTypeRegistry) {
33
+ if (value === null || value === undefined || !dialect) return value;
34
+ const typeDef = fieldTypeRegistry.has(field.type) ? fieldTypeRegistry.get(field.type) : null;
35
+ return typeDef?.fromStorage ? typeDef.fromStorage(field, value, dialect) : value;
36
+ }
37
+
38
+ /** Resolves DialectValues in a list of bindings for `dialect`; anything else passes through. */
39
+ export function resolveDialectValues(bindings, dialect) {
40
+ if (!Array.isArray(bindings) || !bindings.some((b) => b instanceof DialectValue)) return bindings;
41
+ return bindings.map((b) => (b instanceof DialectValue ? b.resolve(dialect) : b));
42
+ }
43
+
44
+ /** "sqlite" | "postgres" for a Knex client (or null for another). */
45
+ export function dialectOfClient(client) {
46
+ const name = String(client?.config?.client ?? client?.dialect ?? "");
47
+ if (name.includes("sqlite")) return "sqlite";
48
+ if (name === "pg" || name.includes("postgres")) return "postgres";
49
+ return null;
50
+ }