@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
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
@@ -13,12 +13,78 @@ export type ConnectionConfig = {
13
13
  * - postgres only
14
14
  */
15
15
  connectionString?: string;
16
+ /**
17
+ * - postgres only: passed to the `pg` driver (`true`, or
18
+ * `{ rejectUnauthorized, ca, ... }`). Since 0.1.7.
19
+ */
20
+ ssl?: boolean | object;
21
+ /**
22
+ * - Knex pool settings (Postgres default: min 2, max 10; SQLite: 1 connection). An `afterCreate`
23
+ * of your own runs after the ORM's (SQLite turns foreign keys on there). Since 0.1.7.
24
+ */
25
+ pool?: {
26
+ min?: number;
27
+ max?: number;
28
+ idleTimeoutMillis?: number;
29
+ afterCreate?: Function;
30
+ };
31
+ /**
32
+ * - ms to wait for a free pooled connection before
33
+ * failing (Knex default 60000). Since 0.1.7.
34
+ */
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;
16
60
  };
17
61
  /**
18
62
  * @typedef {Object} ConnectionConfig
19
63
  * @property {"sqlite"|"postgres"} dialect
20
64
  * @property {string} [filename] - sqlite only, e.g. ":memory:" or a file path
21
65
  * @property {string} [connectionString] - postgres only
66
+ * @property {boolean|object} [ssl] - postgres only: passed to the `pg` driver (`true`, or
67
+ * `{ rejectUnauthorized, ca, ... }`). Since 0.1.7.
68
+ * @property {{ min?: number, max?: number, idleTimeoutMillis?: number, afterCreate?: Function }} [pool]
69
+ * - Knex pool settings (Postgres default: min 2, max 10; SQLite: 1 connection). An `afterCreate`
70
+ * of your own runs after the ORM's (SQLite turns foreign keys on there). Since 0.1.7.
71
+ * @property {number} [acquireConnectionTimeout] - ms to wait for a free pooled connection before
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.
22
88
  */
23
89
  /**
24
90
  * Creates a Knex instance for the given dialect. This is the single
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Most values bound into one `WHERE column IN (...)` list.
3
+ *
4
+ * Every value is a bound parameter, and both databases cap parameters per statement: SQLite at
5
+ * 32,766, Postgres at 65,535. A list built from user data (eager loading 70k parents, cascading
6
+ * a delete through 40k children, detaching thousands of targets) went past those caps before
7
+ * 0.1.7 and failed. Lists are now split into chunks of this size, leaving plenty of room for the
8
+ * statement's other bindings.
9
+ */
10
+ export declare const IN_LIST_CHUNK = 5000;
@@ -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";
@@ -44,20 +44,19 @@ export declare function chunkArray<T>(items: T[], size: number): T[][];
44
44
  */
45
45
  export declare function alignToInput(model: import('../models/define-model.js').ModelDescriptor, valuesList: Record<string, unknown>[], records: Record<string, unknown>[]): Record<string, unknown>[];
46
46
  /**
47
- * Inserts many already-validated rows with as few statements as the
48
- * dialect allows - one INSERT ... RETURNING per chunk - and returns
49
- * the stored records, cast back into field values, in input order.
47
+ * JSON columns need their value serialized explicitly on a bulk insert.
50
48
  *
51
- * This does NOT open a transaction: with more than one chunk the
52
- * caller is responsible for atomicity (see createRecords()).
49
+ * Knex serializes an object bound to a single-row INSERT, but not one
50
+ * inside the `SELECT ... UNION ALL SELECT ...` it compiles multi-row
51
+ * SQLite inserts to - better-sqlite3 then rejects the raw object
52
+ * ("can only bind numbers, strings, bigints, buffers, and null"). On
53
+ * Postgres, `pg` sends a JS *array* as a Postgres array literal rather
54
+ * than JSON, which a json column refuses. Passing the JSON text
55
+ * ourselves is correct on both, and reads back through fromRow()
56
+ * unchanged (it parses SQLite's text and Postgres hands back objects).
53
57
  *
54
- * @param {import('knex').Knex} db - connection or transaction
55
58
  * @param {import('../models/define-model.js').ModelDescriptor} model
56
- * @param {Record<string, unknown>[]} valuesList - output of prepareWrite(...).values, one per row
57
- * @param {import('../fields/registry.js').FieldTypeRegistry} fieldTypeRegistry
58
- * @param {{ chunkSize?: number }} [options]
59
- * @returns {Promise<Record<string, unknown>[]>}
59
+ * @param {Record<string, unknown>} values
60
60
  */
61
- export declare function insertRecords(db: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, valuesList: Record<string, unknown>[], fieldTypeRegistry: import('../fields/registry.js').FieldTypeRegistry, options?: {
62
- chunkSize?: number;
63
- }): Promise<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
+ 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
@@ -20,16 +20,24 @@ export declare const PARTIAL: unique symbol;
20
20
  * (a string is technically valid JSON too), so the string case is
21
21
  * parsed here first, before the value ever reaches castValue().
22
22
  *
23
+ * That extra parse must only happen where the driver hands back JSON *text*. On Postgres the
24
+ * driver has already parsed the column, so a string there IS the stored value - a JSON string
25
+ * scalar like `"hello"` or `"123"`. Parsing it a second time turned `"123"` into the number 123
26
+ * and made `"hello"` throw, breaking every read of the table (fixed in 0.1.6). Callers inside the
27
+ * ORM pass `jsonParsed: isPostgres(db)`; a caller that omits it gets the SQLite behavior.
28
+ *
23
29
  * @param {import('../models/define-model.js').ModelDescriptor} model
24
30
  * @param {Record<string, unknown>} row
25
31
  * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
26
- * @param {{ computed?: Set<string>|null }} [options] - `computed`: which computed fields to define
32
+ * @param {{ computed?: Set<string>|null, jsonParsed?: boolean }} [options] - `jsonParsed`: the driver already
33
+ * parsed json columns (Postgres), so a string value is a JSON string, not JSON text. `computed`: which computed fields to define
27
34
  * (default: all). A row read with `select` only defines the ones whose dependencies it carries; the
28
35
  * choice is remembered under PARTIAL so an entity built from the record can make the same one.
29
36
  * @returns {Record<string, unknown>}
30
37
  */
31
38
  export declare function fromRow(model: import('../models/define-model.js').ModelDescriptor, row: Record<string, unknown>, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry, options?: {
32
39
  computed?: Set<string> | null;
40
+ jsonParsed?: boolean;
33
41
  }): Record<string, unknown>;
34
42
  /**
35
43
  * Converts a record keyed by field name into a plain object keyed by
@@ -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
+ };
@@ -3,8 +3,8 @@
3
3
  * month, quarter or year, so rows can be grouped by period.
4
4
  *
5
5
  * Postgres and SQLite spell this completely differently (`date_trunc` vs `strftime`), and
6
- * store dates differently (a real `timestamptz`/`date` vs epoch milliseconds in an integer
7
- * column), so the SQL lives here, once, behind one function. Both return the bucket the
6
+ * store dates differently (a real `timestamptz`/`date` vs epoch milliseconds or "YYYY-MM-DD"
7
+ * text - see sqliteBucket()), so the SQL lives here, once, behind one function. Both return the bucket the
8
8
  * same way - an ISO-8601 UTC string, `2024-03-01T00:00:00Z` - which the caller turns
9
9
  * into a Date. Returning a string instead of letting each driver hand back its own
10
10
  * timestamp type is what keeps the result identical on both databases.
@@ -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,31 @@
1
+ /**
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")...`).
6
+ */
7
+ export declare class TransactionDeadlockError extends Error {
8
+ constructor(message: any);
9
+ }
10
+ /**
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.
13
+ *
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.
24
+ *
25
+ * @template {import('knex').Knex} T
26
+ * @param {T} db
27
+ * @returns {T}
28
+ */
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;