@kiri-orm/core 0.1.7 → 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 (99) 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 +39 -0
  4. package/dist/types/crud/database-errors.d.ts +61 -0
  5. package/dist/types/crud/errors.d.ts +10 -0
  6. package/dist/types/crud/fast-path.d.ts +73 -0
  7. package/dist/types/crud/index.d.ts +4 -1
  8. package/dist/types/crud/insert-many.d.ts +1 -1
  9. package/dist/types/crud/order.d.ts +28 -0
  10. package/dist/types/crud/repository.d.ts +5 -3
  11. package/dist/types/crud/upsert.d.ts +39 -0
  12. package/dist/types/crud/value.d.ts +39 -0
  13. package/dist/types/dialect/index.d.ts +1 -1
  14. package/dist/types/dialect/transaction-guard.d.ts +19 -18
  15. package/dist/types/domain/compile.d.ts +17 -0
  16. package/dist/types/fields/filter-value.d.ts +21 -0
  17. package/dist/types/fields/registry.d.ts +1 -0
  18. package/dist/types/fields/storage.d.ts +28 -0
  19. package/dist/types/fields/types/date.d.ts +5 -0
  20. package/dist/types/fields/types/decimal.d.ts +40 -0
  21. package/dist/types/global/index.d.ts +1 -0
  22. package/dist/types/global/transaction.d.ts +10 -13
  23. package/dist/types/index.d.ts +2 -0
  24. package/dist/types/meta/snapshot.d.ts +10 -0
  25. package/dist/types/meta/upsert.d.ts +16 -0
  26. package/dist/types/migrations/diff.d.ts +25 -2
  27. package/dist/types/models/constraints.d.ts +27 -0
  28. package/dist/types/schema/alter-column.d.ts +46 -0
  29. package/dist/types/schema/build-column.d.ts +11 -0
  30. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  31. package/dist/types/transaction/after-commit.d.ts +42 -0
  32. package/dist/types/transaction/context.d.ts +39 -0
  33. package/dist/types/uow/entity.d.ts +39 -29
  34. package/dist/types/uow/hooks.d.ts +6 -1
  35. package/dist/types/uow/lifecycle.d.ts +82 -0
  36. package/dist/types/uow/unit-of-work.d.ts +11 -7
  37. package/package.json +5 -4
  38. package/src/client/model-handle.js +14 -4
  39. package/src/client/orm-client.js +10 -5
  40. package/src/connection.js +34 -4
  41. package/src/crud/aggregate-filter.js +8 -2
  42. package/src/crud/aggregate-spec.js +2 -2
  43. package/src/crud/aggregate.js +16 -5
  44. package/src/crud/create-many.js +52 -29
  45. package/src/crud/database-errors.js +107 -0
  46. package/src/crud/errors.js +14 -0
  47. package/src/crud/fast-path.js +449 -0
  48. package/src/crud/index.js +4 -1
  49. package/src/crud/insert-many.js +25 -7
  50. package/src/crud/map-filter.js +2 -1
  51. package/src/crud/order.js +59 -9
  52. package/src/crud/repository.js +106 -38
  53. package/src/crud/row-mapping.js +32 -7
  54. package/src/crud/upsert.js +203 -0
  55. package/src/crud/value.js +71 -0
  56. package/src/dialect/index.js +1 -1
  57. package/src/dialect/transaction-guard.js +216 -45
  58. package/src/domain/compile.js +85 -12
  59. package/src/dto/field-schema.js +5 -0
  60. package/src/fields/default-registry.js +3 -1
  61. package/src/fields/filter-value.js +87 -0
  62. package/src/fields/registry.js +1 -0
  63. package/src/fields/storage.js +50 -0
  64. package/src/fields/types/date.js +16 -3
  65. package/src/fields/types/decimal.js +147 -0
  66. package/src/fields/types/integer.js +7 -0
  67. package/src/global/connect.js +2 -2
  68. package/src/global/create-model.js +59 -57
  69. package/src/global/errors.js +1 -1
  70. package/src/global/index.js +1 -0
  71. package/src/global/transaction.js +12 -14
  72. package/src/index.js +2 -0
  73. package/src/meta/schema.js +10 -0
  74. package/src/meta/snapshot.js +5 -0
  75. package/src/meta/upsert.js +28 -0
  76. package/src/migrations/describe.js +49 -0
  77. package/src/migrations/diff.js +50 -7
  78. package/src/migrations/generate.js +38 -2
  79. package/src/migrations/render.js +30 -12
  80. package/src/migrations/runner.js +2 -1
  81. package/src/models/constraints.js +96 -0
  82. package/src/models/define-model.js +4 -0
  83. package/src/models/inheritance.js +4 -1
  84. package/src/models/registry.js +2 -1
  85. package/src/relations/cascade-delete.js +2 -1
  86. package/src/relations/eager-load.js +45 -40
  87. package/src/reports/report-handle.js +2 -1
  88. package/src/schema/alter-column.js +219 -0
  89. package/src/schema/build-column.js +28 -2
  90. package/src/schema/default-column-builders.js +16 -2
  91. package/src/schema/introspect-indexes.js +22 -0
  92. package/src/schema/sync.js +15 -1
  93. package/src/transaction/after-commit.js +142 -0
  94. package/src/transaction/context.js +84 -0
  95. package/src/uow/entity.js +133 -133
  96. package/src/uow/hooks.js +9 -0
  97. package/src/uow/lifecycle.js +162 -0
  98. package/src/uow/unit-of-work.js +44 -56
  99. package/src/uow/with-unit-of-work.js +2 -1
package/README.md CHANGED
@@ -49,6 +49,9 @@ npm install pg # Postgres
49
49
 
50
50
  The package is ES-modules only (`import`, not `require`).
51
51
 
52
+ **Upgrading from 0.1.x?** 0.2 changes hook arguments and a few defaults: read
53
+ https://kiri-orm.vercel.app/guide/upgrading-0-2 first, and upgrade `@kiri-orm/cli` to 0.2.3 with it.
54
+
52
55
  ## Quick start
53
56
 
54
57
  **1. Connect, once, at startup.**
@@ -115,10 +118,12 @@ back as real JavaScript types (`Date`, `boolean`, parsed JSON).
115
118
 
116
119
  ## Field types
117
120
 
118
- `char` · `text` · `integer` · `float` · `boolean` · `date` · `datetime` · `json` · `uuid` · `enum`
121
+ `char` · `text` · `integer` · `float` · `decimal` · `boolean` · `date` · `datetime` · `json` · `uuid` · `enum`
119
122
 
120
123
  Common options: `required`, `unique`, `index`, `default`, `maxLength`. An `enum` takes
121
- `values: [...]` and is enforced by a real `CHECK` constraint.
124
+ `values: [...]` and is enforced by a real `CHECK` constraint. A `decimal` is exact (money):
125
+ `{ type: "decimal", precision: 12, scale: 2 }` holds `"1234.50"`. Uniques and indexes across
126
+ several fields go on the model: `constraints: { unique: [["orgId", "email"]] }`.
122
127
 
123
128
  ## Querying
124
129
 
@@ -233,20 +238,23 @@ await Order.aggregate(
233
238
 
234
239
  ## Transactions
235
240
 
236
- Every method accepts `{ trx }`. If the callback throws, nothing in it is committed.
241
+ Every model call made inside `transaction(fn)` joins it, including calls in your own functions
242
+ and in hooks. If the callback throws, nothing in it is committed.
237
243
 
238
244
  ```js
239
- import { transaction } from "@kiri-orm/core";
240
-
241
- await transaction(async (trx) => {
242
- const order = await Order.create({ customerId: 7 }, { trx });
243
- await OrderItem.createMany(
244
- items.map((i) => ({ orderId: order.id, ...i })),
245
- { trx },
246
- );
245
+ import { transaction, afterCommit } from "@kiri-orm/core";
246
+
247
+ await transaction(async () => {
248
+ const order = await Order.create({ customerId: 7 });
249
+ await OrderItem.createMany(items.map((i) => ({ orderId: order.id, ...i })));
250
+ afterCommit(() => queue.publish("order.placed", order.id)); // only once it's committed
247
251
  });
248
252
  ```
249
253
 
254
+ Also: `upsert()` / `upsertMany()` by a unique key, `Value.increment()` for atomic counters,
255
+ `find(filter, { lock: "update" })` row locks, and the same `UniqueViolationError` (and friends)
256
+ on both databases.
257
+
250
258
  ## Hooks and computed fields
251
259
 
252
260
  ```js
@@ -258,15 +266,19 @@ createModel("post", {
258
266
  beforeCreate(data) {
259
267
  data.slug ??= slugify(data.title);
260
268
  },
261
- afterCreate(post) {
262
- console.log("created", post.id);
269
+ beforeUpdate(post, { changes, original }) {
270
+ if ("status" in changes && original.status === "archived") throw new Error("archived");
271
+ },
272
+ afterCommit(post, ctx) {
273
+ if (ctx.event === "create") search.index(post);
263
274
  },
264
275
  },
265
276
  });
266
277
  ```
267
278
 
268
279
  Hooks: `beforeCreate`, `afterCreate`, `beforeUpdate`, `afterUpdate`, `beforeSave`, `afterSave`,
269
- `beforeDelete`, `afterDelete`.
280
+ `beforeDelete`, `afterDelete`, `afterCommit`. Each receives `(record, ctx)`, and a write and its
281
+ hooks succeed or fail together.
270
282
 
271
283
  A computed field is derived when read, never stored, and can still be filterable:
272
284
 
@@ -322,7 +334,7 @@ export default {
322
334
  ## Two APIs, one engine
323
335
 
324
336
  The examples above use the **Global API**: call `connect()` once and import models anywhere. If
325
- you need several connections at once, or an identity map scoped to a single request, the **Client
337
+ you need several connections at once, or an identity map scoped to a transaction, the **Client
326
338
  API** wraps the same engine in an object you pass around explicitly:
327
339
 
328
340
  ```js
@@ -33,7 +33,7 @@ export declare class ModelHandle {
33
33
  * @param {Record<string, unknown>} data - field values, plus optional `hasMany` /
34
34
  * `belongsToMany` relation values as `Command.*()` entries or ids
35
35
  */
36
- create(data: Record<string, unknown>): Promise<Record<string, unknown>>;
36
+ create(data: Record<string, unknown>): Promise<object>;
37
37
  /**
38
38
  * Creates many records at once, returning tracked entities in input
39
39
  * order. Cost does not grow with the number of records: one
@@ -52,6 +52,9 @@ export declare class ModelHandle {
52
52
  createMany(dataList: Record<string, unknown>[], options?: {
53
53
  chunkSize?: number;
54
54
  }): Promise<Record<string, unknown>[]>;
55
+ /** Insert, or update the row with the same `conflict` key (since 0.2.0); see the global Model.upsert(). */
56
+ upsert(data: any, options: any): Promise<any>;
57
+ upsertMany(dataList: any, options: any): Promise<any>;
55
58
  /**
56
59
  * Bulk update, bypassing the identity map and per-row hooks - for
57
60
  * "update every row matching this filter" operations where there's
@@ -33,6 +33,30 @@ export type ConnectionConfig = {
33
33
  * failing (Knex default 60000). Since 0.1.7.
34
34
  */
35
35
  acquireConnectionTimeout?: number;
36
+ /**
37
+ * - sqlite only, since 0.2.0: a database file is opened in WAL mode with
38
+ * `synchronous = NORMAL` (default `true`) - each write commits without waiting for the disk
39
+ * twice, ~10-20x faster for single writes, and readers in other processes don't block the
40
+ * writer. A committed write can be lost on a power cut or OS crash (never on an app crash), and
41
+ * the database is never corrupted. The `-wal` / `-shm` files next to the database are part of
42
+ * it while it's open. `false` uses SQLite's classic rollback journal (journal_mode = DELETE,
43
+ * synchronous = FULL), switching back a file that was in WAL mode. Ignored for ":memory:".
44
+ */
45
+ wal?: boolean;
46
+ /**
47
+ * - postgres only, since 0.2.0: find() and findOne() reuse
48
+ * named prepared statements, parsed and planned once per pooled connection (default `true`). Set
49
+ * `false` behind a pooler that doesn't keep one server session per client connection
50
+ * (pgbouncer in transaction mode before 1.21), where a named statement may not exist on the next
51
+ * query's session.
52
+ */
53
+ preparedStatements?: boolean;
54
+ /**
55
+ * - since 0.2.0: `false` builds every find() with Knex, as before
56
+ * 0.2.0, instead of writing plain finds as SQL directly. Results are the same either way; this is
57
+ * an escape hatch, not a tuning knob.
58
+ */
59
+ fastPath?: boolean;
36
60
  };
37
61
  /**
38
62
  * @typedef {Object} ConnectionConfig
@@ -46,6 +70,21 @@ export type ConnectionConfig = {
46
70
  * of your own runs after the ORM's (SQLite turns foreign keys on there). Since 0.1.7.
47
71
  * @property {number} [acquireConnectionTimeout] - ms to wait for a free pooled connection before
48
72
  * failing (Knex default 60000). Since 0.1.7.
73
+ * @property {boolean} [wal] - sqlite only, since 0.2.0: a database file is opened in WAL mode with
74
+ * `synchronous = NORMAL` (default `true`) - each write commits without waiting for the disk
75
+ * twice, ~10-20x faster for single writes, and readers in other processes don't block the
76
+ * writer. A committed write can be lost on a power cut or OS crash (never on an app crash), and
77
+ * the database is never corrupted. The `-wal` / `-shm` files next to the database are part of
78
+ * it while it's open. `false` uses SQLite's classic rollback journal (journal_mode = DELETE,
79
+ * synchronous = FULL), switching back a file that was in WAL mode. Ignored for ":memory:".
80
+ * @property {boolean} [preparedStatements] - postgres only, since 0.2.0: find() and findOne() reuse
81
+ * named prepared statements, parsed and planned once per pooled connection (default `true`). Set
82
+ * `false` behind a pooler that doesn't keep one server session per client connection
83
+ * (pgbouncer in transaction mode before 1.21), where a named statement may not exist on the next
84
+ * query's session.
85
+ * @property {boolean} [fastPath] - since 0.2.0: `false` builds every find() with Knex, as before
86
+ * 0.2.0, instead of writing plain finds as SQL directly. Results are the same either way; this is
87
+ * an escape hatch, not a tuning knob.
49
88
  */
50
89
  /**
51
90
  * Creates a Knex instance for the given dialect. This is the single
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Constraint violations reported by the database, as the same errors on both databases (since 0.2.0).
3
+ *
4
+ * try { await User.create({ email }) }
5
+ * catch (error) {
6
+ * if (error instanceof UniqueViolationError) return reply(409, `${error.fields.join(", ")} already taken`);
7
+ * throw error;
8
+ * }
9
+ *
10
+ * Before 0.2.0 the driver's own error came through: `code` "23505" with a `detail` on Postgres,
11
+ * "SQLITE_CONSTRAINT_UNIQUE" with a message on SQLite. These errors keep the driver's `code`
12
+ * (so existing `error.code === "23505"` checks still work) and its error as `cause`.
13
+ */
14
+ export declare class DatabaseConstraintError extends Error {
15
+ model: string;
16
+ fields: string[];
17
+ columns: string[];
18
+ constraint: string | null;
19
+ code: any;
20
+ /**
21
+ * @param {string} message
22
+ * @param {{ model: string, fields?: string[], columns?: string[], constraint?: string|null, cause: any }} info
23
+ */
24
+ constructor(message: string, { model, fields, columns, constraint, cause }: {
25
+ model: string;
26
+ fields?: string[];
27
+ columns?: string[];
28
+ constraint?: string | null;
29
+ cause: any;
30
+ });
31
+ }
32
+ /** A row with the same value(s) for a unique key exists already. `fields` names them when known. */
33
+ export declare class UniqueViolationError extends DatabaseConstraintError {
34
+ }
35
+ /** A foreign key points at a row that doesn't exist (on insert/update) - or one is still referenced. */
36
+ export declare class ForeignKeyViolationError extends DatabaseConstraintError {
37
+ }
38
+ /** A required (NOT NULL) column got no value - usually a raw write or a column added outside the ORM. */
39
+ export declare class NotNullViolationError extends DatabaseConstraintError {
40
+ }
41
+ /** A CHECK constraint failed - e.g. an enum column's allowed values. */
42
+ export declare class CheckViolationError extends DatabaseConstraintError {
43
+ }
44
+ /**
45
+ * A value doesn't fit its column's type (since 0.2.0) - e.g. 3000000000 in an `integer` column on
46
+ * Postgres, which holds 32 bits there. Postgres reports no column for it, so `fields` is empty.
47
+ */
48
+ export declare class OutOfRangeError extends DatabaseConstraintError {
49
+ }
50
+ /**
51
+ * The ORM error for a driver's constraint error, or the error unchanged. Columns are read from
52
+ * Postgres' `detail` ("Key (org_id, email)=(1, a@x) already exists.", or `column` for NOT NULL)
53
+ * and from SQLite's message ("UNIQUE constraint failed: member.org_id, member.email"), then mapped
54
+ * back to field names.
55
+ *
56
+ * @param {any} error
57
+ * @param {import('../models/define-model.js').ModelDescriptor} model
58
+ */
59
+ export declare function translateDatabaseError(error: any, model: import('../models/define-model.js').ModelDescriptor): any;
60
+ /** Runs `fn`, translating a constraint error it throws. */
61
+ export declare function translatingErrors(model: any, fn: any): Promise<any>;
@@ -14,3 +14,13 @@ export declare class ValidationError extends Error {
14
14
  */
15
15
  constructor(modelName: string, fieldErrors: Record<string, string[]>);
16
16
  }
17
+ /**
18
+ * A prepared statement stopped fitting its table while a transaction was using it (since 0.2.0):
19
+ * another process changed the table (a migration, say) after this connection prepared a query on it.
20
+ * Postgres aborts the transaction, so nothing in it can be saved; run the whole transaction again.
21
+ * Outside a transaction the ORM retries the query on its own. The driver's error is `cause`.
22
+ */
23
+ export declare class SchemaChangedError extends Error {
24
+ code: any;
25
+ constructor(message: any, { cause }?: {});
26
+ }
@@ -0,0 +1,73 @@
1
+ export declare const POSTGRES_STATEMENTS_PER_CONNECTION = 256;
2
+ /**
3
+ * The SQL and bound values for a find(), or null when the direct path doesn't handle it (the caller
4
+ * then builds the query with Knex). Throws the errors the Knex path would for a bad filter, order or
5
+ * page - the same functions validate and cast both.
6
+ *
7
+ * @param {import('knex').Knex} baseDb - the connection (not a transaction)
8
+ * @param {object} model
9
+ * @param {Record<string, unknown>|unknown[]} filter
10
+ * @param {string[]|null} columns - planSelect().columns
11
+ * @param {{ orderBy?: unknown, limit?: number, offset?: number, lock?: unknown }} options
12
+ * @param {import('../fields/registry.js').FieldTypeRegistry} registry
13
+ * @returns {{ sql: string, values: unknown[], settings: object } | null}
14
+ */
15
+ export declare function compileFastFind(baseDb: import('knex').Knex, model: object, filter: Record<string, unknown> | unknown[], columns: string[] | null, options: {
16
+ orderBy?: unknown;
17
+ limit?: number;
18
+ offset?: number;
19
+ lock?: unknown;
20
+ }, registry: import('../fields/registry.js').FieldTypeRegistry): {
21
+ sql: string;
22
+ values: unknown[];
23
+ settings: object;
24
+ } | null;
25
+ /**
26
+ * INSERT ... RETURNING for rows already in column form (toRow() output), or null for Knex. Unset
27
+ * columns get the column's DEFAULT on Postgres and NULL on SQLite (Knex's `useNullAsDefault`), as a
28
+ * Knex multi-row insert gives them.
29
+ *
30
+ * @param {import('knex').Knex} db - the connection or a transaction on it
31
+ * @param {object} model
32
+ * @param {Record<string, unknown>[]} rows
33
+ */
34
+ export declare function compileFastInsert(db: import('knex').Knex, model: object, rows: Record<string, unknown>[]): {
35
+ sql: string;
36
+ values: any[];
37
+ settings: any;
38
+ method: string;
39
+ } | null;
40
+ /**
41
+ * UPDATE ... SET ... WHERE, returning the number of rows changed, or null for Knex. `row` is in
42
+ * column form; `expressions` are Value.increment() / decrement() ({ column, operator, amount }).
43
+ * Filters compile as for find(); one that compiles to no condition at all is left to Knex.
44
+ */
45
+ export declare function compileFastUpdate(db: any, model: any, filter: any, row: any, expressions: any, registry: any): {
46
+ sql: string;
47
+ values: any[];
48
+ settings: any;
49
+ method: string;
50
+ } | null;
51
+ /** DELETE ... WHERE, returning the number of rows deleted, or null for Knex. */
52
+ export declare function compileFastDelete(db: any, model: any, filter: any, registry: any): {
53
+ sql: string;
54
+ values: any[];
55
+ settings: any;
56
+ method: string;
57
+ } | null;
58
+ /**
59
+ * Runs a compiled statement on `db` (the connection, or the transaction it resolved to): the rows
60
+ * of a select or an insert ... returning, the number of rows an update or delete changed - or
61
+ * undefined when a cached Postgres statement went stale outside a transaction (it didn't run),
62
+ * in which case the caller runs the query through Knex instead.
63
+ *
64
+ * @param {import('knex').Knex} db
65
+ * @param {{ sql: string, values: unknown[], settings: object, method: string }} compiled
66
+ * @returns {Promise<Record<string, unknown>[] | number | undefined>}
67
+ */
68
+ export declare function runFast(db: import('knex').Knex, { sql, values, settings, method }: {
69
+ sql: string;
70
+ values: unknown[];
71
+ settings: object;
72
+ method: string;
73
+ }): Promise<Record<string, unknown>[] | number | undefined>;
@@ -1,12 +1,15 @@
1
1
  export { Repository, createRepository } from "./repository.js";
2
2
  export { RepositoryFactory } from "./repository-factory.js";
3
3
  export { runInTransaction } from "./transaction.js";
4
- export { ValidationError } from "./errors.js";
4
+ export { ValidationError, SchemaChangedError } from "./errors.js";
5
+ export { DatabaseConstraintError, UniqueViolationError, ForeignKeyViolationError, NotNullViolationError, CheckViolationError, OutOfRangeError, translateDatabaseError } from "./database-errors.js";
5
6
  export { fromRow, toRow } from "./row-mapping.js";
6
7
  export { prepareWrite, assertPrimaryKeyUntouched } from "./prepare-write.js";
7
8
  export { mapFilterToColumns } from "./map-filter.js";
8
9
  export { resolveWhere, isEmptyFilter } from "./resolve-where.js";
9
10
  export { createRecords } from "./create-many.js";
11
+ export { upsertRecords } from "./upsert.js";
12
+ export { Value, ValueExpression } from "./value.js";
10
13
  export { advanceSequence, syncSequence, syncRegistrySequences } from "./sequence.js";
11
14
  export { planAggregate } from "./aggregate-spec.js";
12
15
  export { runAggregate, buildAggregateQuery, countAggregateGroups } from "./aggregate.js";
@@ -58,5 +58,5 @@ export declare function alignToInput(model: import('../models/define-model.js').
58
58
  * @param {import('../models/define-model.js').ModelDescriptor} model
59
59
  * @param {Record<string, unknown>} values
60
60
  */
61
- export declare function serializeJsonFields(model: import('../models/define-model.js').ModelDescriptor, values: Record<string, unknown>): Record<string, unknown>;
61
+ export declare function serializeJsonFields(model: import('../models/define-model.js').ModelDescriptor, values: Record<string, unknown>, fieldTypeRegistry?: import("../fields/registry.js").FieldTypeRegistry): Record<string, unknown>;
62
62
  export declare function insertRecords(db: any, model: any, valuesList: any, fieldTypeRegistry: any, options?: {}): Promise<Record<string, unknown>[]>;
@@ -41,6 +41,21 @@ export declare function validatePaging(model: any, { limit, offset }: {
41
41
  limit: any;
42
42
  offset: any;
43
43
  }): void;
44
+ /**
45
+ * The validated sort keys of a find(), with the primary key appended as the final tie-breaker
46
+ * whenever the caller orders or skips rows (see applyOrderAndPaging()). Validates limit/offset too.
47
+ *
48
+ * @returns {Array<{ field: string, direction: "asc"|"desc", nulls?: "first"|"last" }>}
49
+ */
50
+ export declare function resolveOrder(model: any, { orderBy, limit, offset }: {
51
+ limit: any;
52
+ offset: any;
53
+ orderBy: any;
54
+ }): Array<{
55
+ field: string;
56
+ direction: "asc" | "desc";
57
+ nulls?: "first" | "last";
58
+ }>;
44
59
  /**
45
60
  * Applies ordering and paging to a Knex query builder.
46
61
  *
@@ -56,3 +71,16 @@ export declare function applyOrderAndPaging(query: any, model: any, { orderBy, l
56
71
  offset: any;
57
72
  orderBy: any;
58
73
  }): import('knex').Knex.QueryBuilder;
74
+ /**
75
+ * The `nulls` argument for Knex's orderBy(), or undefined when the database already sorts NULLs that
76
+ * way, or the column can't hold any (required fields, primary keys). On SQLite Knex emulates it with
77
+ * an `(col is null)` sort key, which keeps SQLite from using an index for the ORDER BY - so it is
78
+ * only added where NULLs can actually appear.
79
+ */
80
+ export declare function nullsClause(query: any, field: any, direction: any, nulls: any): any;
81
+ /**
82
+ * query.orderBy(column, direction) with a NULLS FIRST/LAST rule. Not Knex's own `nulls` argument on
83
+ * SQLite: there Knex replaces the column's ordering with the `(col is null)` key alone, so rows come
84
+ * back sorted by nullness only. SQLite gets both keys explicitly; Postgres its native clause.
85
+ */
86
+ export declare function orderWithNulls(query: any, column: any, direction: any, nulls: any): any;
@@ -49,9 +49,11 @@ export declare class Repository {
49
49
  * @returns {Promise<Record<string, unknown>>}
50
50
  * @throws {ValidationError}
51
51
  */
52
- create(data: Record<string, unknown>, options?: {
53
- trx?: import('knex').Knex.Transaction;
54
- }): Promise<Record<string, unknown>>;
52
+ /** Insert, or update the row with the same `conflict` key - see upsertRecords(). Since 0.2.0. */
53
+ upsert(data: any, options?: {}): Promise<any>;
54
+ /** Many upserts, one statement per chunk - see upsertRecords(). Since 0.2.0. */
55
+ upsertMany(dataList: any, options?: {}): Promise<any>;
56
+ create(data: any, options?: {}): Promise<object>;
55
57
  /**
56
58
  * Creates many records at once, with a query count that does not
57
59
  * grow with the number of records: one multi-row INSERT per chunk
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Inserts each record, or - when a row with the same `conflict` key exists - updates that row
3
+ * instead, in one `INSERT ... ON CONFLICT` statement per chunk (since 0.2.0). Atomic per row:
4
+ * two requests upserting the same key at once can't both insert, unlike find-then-create.
5
+ *
6
+ * await User.upsert({ email, name }, { conflict: ["email"] });
7
+ * await User.upsertMany(rows, { conflict: ["orgId", "email"], update: ["name"] });
8
+ * await Tag.upsertMany(names.map((name) => ({ name })), { conflict: ["name"], update: false }); // insert if missing
9
+ *
10
+ * Options:
11
+ * - `conflict` (required): the fields that decide whether a row "already exists". They must form a
12
+ * unique key - the primary key, a `unique: true` field, or a `constraints.unique` entry - because
13
+ * that's what the database checks.
14
+ * - `update`: the fields to overwrite when the row exists. Default: the fields you passed (never
15
+ * the conflict fields or the primary key; defaults for fields you left out aren't written over
16
+ * existing values). An array picks them; `false` means insert-if-missing and leave existing rows alone.
17
+ *
18
+ * Hooks: `beforeSave(record, ctx)` runs first with ctx.event "upsert" and ctx.isNew undefined -
19
+ * whether it will insert isn't known yet. After the write, each row gets `afterCreate` or
20
+ * `afterUpdate` (ctx.event / ctx.isNew say which), then `afterSave` and `afterCommit`, as for
21
+ * create and save. With `update: false`, a row that already existed runs no after-hooks: nothing
22
+ * was written. Postgres reports which rows were inserted; SQLite (one writer at a time) is checked
23
+ * for existing keys inside the same transaction.
24
+ *
25
+ * Returns the stored records (documents, through runtime.wrap) in input order. Relation values
26
+ * aren't accepted here - upsert the related rows separately.
27
+ *
28
+ * @param {import('./create-many.js').CreateRuntime} runtime
29
+ * @param {import('../models/define-model.js').ModelDescriptor} model
30
+ * @param {Record<string, unknown>[]} dataList
31
+ * @param {{ conflict: string[]|string, update?: string[]|false, trx?: import('knex').Knex.Transaction, chunkSize?: number, labels?: string[] }} options
32
+ */
33
+ export declare function upsertRecords(runtime: import('./create-many.js').CreateRuntime, model: import('../models/define-model.js').ModelDescriptor, dataList: Record<string, unknown>[], options?: {
34
+ conflict: string[] | string;
35
+ update?: string[] | false;
36
+ trx?: import('knex').Knex.Transaction;
37
+ chunkSize?: number;
38
+ labels?: string[];
39
+ }): Promise<any>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Values computed by the database at write time (since 0.2.0), for updates that must not lose
3
+ * concurrent changes:
4
+ *
5
+ * await Post.updateMany({ id }, { views: Value.increment(1) }); // views = views + 1
6
+ * await Account.updateMany({ id }, { balance: Value.decrement("12.50") }); // a decimal field
7
+ *
8
+ * Reading a value, changing it in JavaScript and saving it back loses an update when two requests
9
+ * do it at once: both read 10, both write 11. `Value.increment` sends `SET views = views + 1`, so
10
+ * the database applies each change to whatever the row holds at that moment.
11
+ *
12
+ * Works on integer, float and decimal fields, in updateMany() (and inside transactions); the
13
+ * amount is validated as a value of the field (a decimal amount keeps its exactness).
14
+ */
15
+ export declare class ValueExpression {
16
+ kind: any;
17
+ amount: any;
18
+ constructor(kind: any, amount: any);
19
+ }
20
+ export declare const Value: Readonly<{
21
+ /** `field = field + amount` (amount defaults to 1). */
22
+ increment: (amount?: number) => ValueExpression;
23
+ /** `field = field - amount` (amount defaults to 1). */
24
+ decrement: (amount?: number) => ValueExpression;
25
+ }>;
26
+ /**
27
+ * Splits update data into plain values and database expressions. Returns the plain part, plus a
28
+ * function that turns the expressions into Knex raw SET values for a given connection.
29
+ */
30
+ export declare function splitValueExpressions(model: any, data: any, fieldTypeRegistry: any): {
31
+ plain: {};
32
+ hasExpressions: boolean;
33
+ toSet: (db: any) => any;
34
+ expressions: {
35
+ column: any;
36
+ operator: string;
37
+ amount: any;
38
+ }[];
39
+ };
@@ -1,2 +1,2 @@
1
1
  export { DATE_BUCKETS, dateBucketSql, parseBucket } from "./date-bucket.js";
2
- export { guardTransactions, TransactionDeadlockError } from "./transaction-guard.js";
2
+ export { instrumentConnection, guardTransactions, TransactionDeadlockError } from "./transaction-guard.js";
@@ -1,30 +1,31 @@
1
1
  /**
2
- * Thrown when code running inside a transaction issues a query on the connection itself
3
- * (no `{ trx }`) while that transaction holds SQLite's only pooled connection: the query would
4
- * wait for a connection the transaction never gives back, until Knex's acquire timeout (60 s).
2
+ * Thrown when code running inside a transaction issues a raw query on the connection itself while
3
+ * that transaction holds SQLite's only pooled connection: the query would wait for a connection
4
+ * the transaction never gives back. Since 0.2.0 model calls join the open transaction on their
5
+ * own, so this is left for raw Knex queries (`db("table")...` instead of `trx("table")...`).
5
6
  */
6
7
  export declare class TransactionDeadlockError extends Error {
7
8
  constructor(message: any);
8
9
  }
9
10
  /**
10
- * Makes a SQLite connection fail fast, instead of hanging, on the one query pattern that can
11
- * never complete: inside `db.transaction(fn)`, a query that skips the transaction and goes to
12
- * `db` (or the global connection) - a model call without `{ trx }`, or a hook that queries the
13
- * database during a nested create. SQLite's pool has a single connection and the transaction
14
- * holds it, so that query waits forever (until Knex gives up after 60 s, before 0.1.7).
11
+ * Instruments a connection's Knex client so transactions follow the code that runs in them.
12
+ * Idempotent; applied by createConnection(), connect() and every Repository.
15
13
  *
16
- * Only that case is refused. A query from *another* request while a transaction runs is not in
17
- * the transaction's async flow, so it still queues for the connection the normal way. Pools of
18
- * more than one connection (a custom `pool.max`) are left alone: there the query just runs on
19
- * another connection.
20
- *
21
- * Wraps two methods on this connection's Knex client: `transaction()` (to record, per async
22
- * flow, which transaction is open - savepoints go through a separate client and are untouched)
23
- * and `acquireConnection()` (to check that record). Queries made through a transaction never
24
- * call the second one: they reuse the transaction's connection. Idempotent; no-op for Postgres.
14
+ * 1. Scoping (both databases, since 0.2.0). Every transaction started with a container runs that
15
+ * container inside a scope (transaction/context.js), and so does every savepoint inside it -
16
+ * so model calls in it, hooks included, join it without `{ trx }`.
17
+ * 2. After-commit work (since 0.2.0). When an outermost transaction commits, what was queued with
18
+ * afterCommit() runs before `await db.transaction(...)` resumes; on rollback it is dropped.
19
+ * 3. SQLite deadlock guard (since 0.1.7). Inside a transaction's own async flow, a query that skips
20
+ * the transaction and asks the pool for a connection waits forever on SQLite's single
21
+ * connection - it fails at once with TransactionDeadlockError instead. A query from another
22
+ * request isn't in that flow and still waits its turn. Pools of more than one connection are
23
+ * left alone.
25
24
  *
26
25
  * @template {import('knex').Knex} T
27
26
  * @param {T} db
28
27
  * @returns {T}
29
28
  */
30
- export declare function guardTransactions<T extends import('knex').Knex>(db: T): T;
29
+ export declare function instrumentConnection<T extends import('knex').Knex>(db: T): T;
30
+ /** @deprecated since 0.2.0 - the 0.1.7 name of instrumentConnection(). */
31
+ export declare const guardTransactions: typeof instrumentConnection;
@@ -1,3 +1,10 @@
1
+ /**
2
+ * A leaf's value as bound: cast and in storage form (see filterValue()). `computed` leaves keep the
3
+ * 0.2.0 conversion: their value goes to the field's search(), not to a column.
4
+ */
5
+ export declare function castLeafValue(field: any, fieldName: any, op: any, value: any, fieldTypeRegistry: any, { computed }?: {
6
+ computed?: boolean | undefined;
7
+ }): any;
1
8
  /**
2
9
  * Compiles a domain array into a function suitable for
3
10
  * `queryBuilder.where(compileDomain(model, domain))`. Field names are
@@ -28,3 +35,13 @@ export declare function compileDomain(model: import('../models/define-model.js')
28
35
  * @param {import('./parse.js').DomainNode} ast
29
36
  */
30
37
  export declare function compileParsedDomain(model: any, ast: import('./parse.js').DomainNode, fieldTypeRegistry?: import("../fields/registry.js").FieldTypeRegistry, modelRegistry?: undefined): (qb: import('knex').Knex.QueryBuilder) => void;
38
+ /**
39
+ * A `like` / `ilike` pattern in the one form both databases read the same way (since 0.2.0):
40
+ * `%` is any run of characters, `_` any one, and a backslash makes the next character literal -
41
+ * `\\%` is a percent sign, `\\\\` a backslash. That is Postgres' rule (its default LIKE escape);
42
+ * SQLite gets it through likeToGlob() and an explicit `ESCAPE '\\'`. A backslash before any other
43
+ * character is dropped (`\\t` means `t` on both), and a pattern ending in a lone backslash is refused.
44
+ */
45
+ export declare function likePattern(pattern: any, fieldName?: string): string;
46
+ /** A LIKE pattern (see likePattern()) as the equivalent GLOB pattern, other characters literal. */
47
+ export declare function likeToGlob(pattern: any): string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The value a filter binds for a stored field, given its operator (since 0.2.0). Every filter path
3
+ * uses it - domains, plain-object filters, the direct SQL path and Knex - so they can't disagree.
4
+ *
5
+ * Two types need more than cast-then-store:
6
+ *
7
+ * - `json`: bound as JSON text, exactly as writes store it (`JSON.stringify`). Before, an object
8
+ * reached SQLite's driver as an object (a TypeError), a string reached Postgres' jsonb as bare
9
+ * text (invalid JSON), and a string on SQLite never matched its stored JSON text. SQLite compares
10
+ * the text itself, so an object matches only with its keys in the stored order; Postgres' jsonb
11
+ * ignores key order.
12
+ * - `decimal`: compared exactly. A value with more decimal places than the field's scale used to be
13
+ * rounded first (a number) or refused (a string), so `["price", "<", 2.001]` became `< 2.00` and
14
+ * left out a row at 2.00. See decimalFilterValue().
15
+ *
16
+ * @param {object} field - the field definition
17
+ * @param {string} op - the domain operator ("=" for a plain-object filter)
18
+ * @param {unknown} value - one value (a single item of an `in` list)
19
+ * @param {import('./registry.js').FieldTypeRegistry} fieldTypeRegistry
20
+ */
21
+ export declare function filterValue(field: object, op: string, value: unknown, fieldTypeRegistry: import('./registry.js').FieldTypeRegistry): any;
@@ -41,6 +41,7 @@ export type FieldTypeDefinition = {
41
41
  */
42
42
  export declare class FieldTypeRegistry {
43
43
  #private;
44
+ version: any;
44
45
  /**
45
46
  * @param {FieldTypeDefinition} definition
46
47
  */
@@ -0,0 +1,28 @@
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
+ * A bound value that depends on the database: `resolve(dialect)` returns what to send. Writes and
12
+ * filter values carry these; every connection the ORM instruments resolves them when Knex prepares
13
+ * a query's bindings (dialect/transaction-guard.js), so the code building a query never needs to
14
+ * know which database it will run on.
15
+ */
16
+ export declare class DialectValue {
17
+ resolve: (dialect: "sqlite" | "postgres") => unknown;
18
+ /** @param {(dialect: "sqlite"|"postgres") => unknown} resolve */
19
+ constructor(resolve: (dialect: "sqlite" | "postgres") => unknown);
20
+ }
21
+ /** A cast field value in its storage form (a filter binding, a column value to write). */
22
+ export declare function toStorage(field: any, value: any, fieldTypeRegistry: any): any;
23
+ /** A stored value back to what cast() expects. */
24
+ export declare function fromStorage(field: any, value: any, dialect: any, fieldTypeRegistry: any): any;
25
+ /** Resolves DialectValues in a list of bindings for `dialect`; anything else passes through. */
26
+ export declare function resolveDialectValues(bindings: any, dialect: any): any;
27
+ /** "sqlite" | "postgres" for a Knex client (or null for another). */
28
+ export declare function dialectOfClient(client: any): "postgres" | "sqlite" | null;
@@ -1,5 +1,10 @@
1
1
  export declare const dateType: {
2
2
  name: string;
3
+ /**
4
+ * A stored Postgres `date` arrives as a Date the pg driver built at LOCAL midnight of that day,
5
+ * so it is read back with local getters - unlike a Date passed in, which means its UTC day.
6
+ */
7
+ fromStorage(field: any, value: any, dialect: any): any;
3
8
  validate(field: any, value: any): string[];
4
9
  cast(field: any, value: any): string;
5
10
  };