@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
@@ -31,5 +31,10 @@ export declare class HookRegistry {
31
31
  * @param {typeof HOOK_NAMES[number]} hookName
32
32
  * @param {unknown[]} args
33
33
  */
34
- run(modelName: string, hookName: typeof HOOK_NAMES[number], ...args: unknown[]): Promise<void>;
34
+ /**
35
+ * Whether any hook is registered for `modelName` (any of `hookNames`, or any at all). A write with
36
+ * no hooks needs no transaction around it; one with hooks runs them and the write atomically.
37
+ */
38
+ has(modelName: any, hookNames?: string[]): boolean;
39
+ run(modelName: any, hookName: any, ...args: any[]): Promise<void>;
35
40
  }
@@ -0,0 +1,82 @@
1
+ export type HookContext = {
2
+ event: "create" | "update" | "delete" | "upsert";
3
+ isNew: boolean | undefined;
4
+ trx: import('knex').Knex.Transaction | null;
5
+ changes: Record<string, unknown> | null;
6
+ original: Record<string, unknown> | null;
7
+ model: string;
8
+ };
9
+ /**
10
+ * The context every hook receives as its second argument (since 0.2.0):
11
+ * `hook(record, { event, isNew, trx, changes, original, model })`.
12
+ *
13
+ * - `event`: "create" | "update" | "delete" (and "upsert" before an upsert knows which it is)
14
+ * - `isNew`: true for a create, false for an update or delete, undefined before an upsert decides
15
+ * - `trx`: the transaction the write runs in, or null when it runs without one. Model calls in the
16
+ * hook join it on their own; `trx` is there for raw Knex queries and for passing on explicitly.
17
+ * - `changes`: the fields being written (a create's values, an update's changed fields). A
18
+ * before-hook may add to it - the additions are written too.
19
+ * - `original`: the values as read from the database, before this change (null for a create).
20
+ * - `model`: the model's name.
21
+ *
22
+ * @typedef {Object} HookContext
23
+ * @property {"create"|"update"|"delete"|"upsert"} event
24
+ * @property {boolean|undefined} isNew
25
+ * @property {import('knex').Knex.Transaction|null} trx
26
+ * @property {Record<string, unknown>|null} changes
27
+ * @property {Record<string, unknown>|null} original
28
+ * @property {string} model
29
+ */
30
+ /** @returns {HookContext} */
31
+ export declare function hookContext(db: any, event: any, { isNew, changes, original, model }: {
32
+ changes?: null | undefined;
33
+ isNew: any;
34
+ model: any;
35
+ original?: null | undefined;
36
+ }): HookContext;
37
+ /**
38
+ * Runs the after-hooks of a write that just happened on `db`: `after<Event>` and `afterSave` (not for
39
+ * deletes) now, inside the transaction, and `afterCommit` once it commits.
40
+ */
41
+ export declare function runAfterHooks(hooks: any, modelName: any, db: any, event: any, record: any, ctx: any): Promise<void>;
42
+ /**
43
+ * Saves a tracked document's changes - shared by the global API's `doc.save()` and UnitOfWork.
44
+ *
45
+ * When the model has hooks, the before-hooks, the UPDATE and the after-hooks run as one atomic
46
+ * unit: in the open transaction if there is one, else in a transaction of their own. A hook that
47
+ * throws undoes the write and whatever the hooks wrote (since 0.2.0; before, after-hooks ran
48
+ * outside it and a before-hook's own writes survived a failed save).
49
+ *
50
+ * Before-hooks may change the document itself (`record.updatedAt = new Date()`) or add to
51
+ * `ctx.changes`; both are written. On any failure the document's values are put back as they
52
+ * were before save() - nothing was persisted.
53
+ *
54
+ * @param {Object} params
55
+ * @param {Record<string, unknown>} params.entity
56
+ * @param {import('../models/define-model.js').ModelDescriptor} params.model
57
+ * @param {string} params.modelName
58
+ * @param {import('./hooks.js').HookRegistry} [params.hooks]
59
+ * @param {import('knex').Knex} params.db - already resolved (explicit trx / ambient / connection)
60
+ * @param {(db: import('knex').Knex, changes: Record<string, unknown>) => Promise<number>} params.write - the UPDATE; returns rows affected
61
+ */
62
+ export declare function saveEntityLifecycle({ entity, model, modelName, hooks, db, write }: {
63
+ entity: Record<string, unknown>;
64
+ model: import('../models/define-model.js').ModelDescriptor;
65
+ modelName: string;
66
+ hooks?: import('./hooks.js').HookRegistry;
67
+ db: import('knex').Knex;
68
+ write: (db: import('knex').Knex, changes: Record<string, unknown>) => Promise<number>;
69
+ }): Promise<any>;
70
+ /**
71
+ * Deletes a tracked document - shared by the global API's `doc.delete()` and UnitOfWork. Hooks and
72
+ * the DELETE are one atomic unit when the model has hooks, as for saves.
73
+ *
74
+ * @returns {Promise<number>} rows deleted
75
+ */
76
+ export declare function deleteEntityLifecycle({ entity, modelName, hooks, db, write }: {
77
+ db: any;
78
+ entity: any;
79
+ hooks: any;
80
+ modelName: any;
81
+ write: any;
82
+ }): Promise<number>;
@@ -24,6 +24,7 @@ export declare class UnitOfWork {
24
24
  hooks: HookRegistry;
25
25
  trx: import("knex").Knex.Transaction<any, any[]> | undefined;
26
26
  identityMap: Map<any, any>;
27
+ tracksIdentity: boolean;
27
28
  /**
28
29
  * @param {import('knex').Knex} db
29
30
  * @param {import('../models/registry.js').ModelRegistry} modelRegistry
@@ -31,11 +32,14 @@ export declare class UnitOfWork {
31
32
  * @param {import('../fields/registry.js').FieldTypeRegistry} [options.fieldTypeRegistry]
32
33
  * @param {HookRegistry} [options.hooks]
33
34
  * @param {import('knex').Knex.Transaction} [options.trx]
35
+ * @param {boolean} [options.identityMap] - keep one object per row across reads (default true).
36
+ * False: every read returns fresh objects and nothing is retained - for a long-lived unit.
34
37
  */
35
38
  constructor(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, options?: {
36
39
  fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry;
37
40
  hooks?: HookRegistry;
38
41
  trx?: import('knex').Knex.Transaction;
42
+ identityMap?: boolean;
39
43
  });
40
44
  /**
41
45
  * @param {string} modelName
@@ -71,9 +75,10 @@ export declare class UnitOfWork {
71
75
  * @param {{ trx?: import('knex').Knex.Transaction }} [options]
72
76
  * @returns {Promise<Record<string, unknown>>}
73
77
  */
74
- create(modelName: string, data: Record<string, unknown>, options?: {
75
- trx?: import('knex').Knex.Transaction;
76
- }): Promise<Record<string, unknown>>;
78
+ /** Insert or update by `conflict` key, as tracked entities (see crud/upsert.js). Since 0.2.0. */
79
+ upsert(modelName: any, data: any, options?: {}): Promise<any>;
80
+ upsertMany(modelName: any, dataList: any, options?: {}): Promise<any>;
81
+ create(modelName: any, data: any, options?: {}): Promise<object>;
77
82
  /**
78
83
  * Creates many records as tracked entities with a query count that
79
84
  * does not grow with the number of records, including any
@@ -129,11 +134,10 @@ export declare class UnitOfWork {
129
134
  * @param {Record<string, unknown>} entity
130
135
  * @param {{}} [options]
131
136
  */
132
- saveEntity(entity: Record<string, unknown>, options?: {}): Promise<Record<string, unknown>>;
137
+ saveEntity(entity: Record<string, unknown>, options?: {}): Promise<any>;
133
138
  /**
134
- * Called by a tracked entity's `.delete()`. Runs `beforeDelete`,
135
- * issues the DELETE, removes the entity from the identity map, then
136
- * runs `afterDelete`.
139
+ * Called by a tracked entity's `.delete()`: hooks and the DELETE as one unit, then the entity
140
+ * leaves the identity map.
137
141
  *
138
142
  * @param {Record<string, unknown>} entity
139
143
  * @param {{}} [options]
package/package.json CHANGED
@@ -1,20 +1,22 @@
1
1
  {
2
2
  "name": "@kiri-orm/core",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
+ "description": "A JavaScript ORM for SQLite and Postgres, built on Knex: models defined at runtime, migrations, relations, aggregates and hooks - no code generation.",
4
5
  "type": "module",
5
6
  "main": "./src/index.js",
6
7
  "types": "./dist/types/index.d.ts",
7
8
  "exports": {
8
9
  ".": {
10
+ "types": "./dist/types/index.d.ts",
9
11
  "import": "./src/index.js",
10
- "types": "./dist/types/index.d.ts"
12
+ "default": "./src/index.js"
11
13
  }
12
14
  },
13
15
  "dependencies": {
14
16
  "knex": "^3.2.0"
15
17
  },
16
18
  "peerDependencies": {
17
- "better-sqlite3": "^11.0.0",
19
+ "better-sqlite3": "^11.0.0 || ^12.0.0 || ^13.0.0",
18
20
  "pg": "^8.13.0"
19
21
  },
20
22
  "peerDependenciesMeta": {
@@ -48,13 +50,14 @@
48
50
  "migrations",
49
51
  "fast orm",
50
52
  "data",
51
- "framwork",
53
+ "framework",
52
54
  "postgres",
53
55
  "sqlite",
54
56
  "backend"
55
57
  ],
56
58
  "scripts": {
57
- "build": "echo \"no build step - plain JS\"",
59
+ "build": "npm run build:types",
60
+ "build:types": "node -e \"require('fs').rmSync('dist/types',{recursive:true,force:true})\" && tsc -p tsconfig.types.json",
58
61
  "test:unit": "vitest run test/unit",
59
62
  "test:integration": "vitest run test/integration",
60
63
  "test": "vitest run",
@@ -1,6 +1,7 @@
1
1
  import { attachRelation, attachManyRelation, detachRelation } from "../relations/attach-detach.js";
2
2
  import { Repository } from "../crud/repository.js";
3
3
  import { paginateWith } from "../crud/paginate.js";
4
+ import { resolveDb } from "../transaction/context.js";
4
5
 
5
6
  /**
6
7
  * The object behind `client.models.<modelName>`. Wraps a shared
@@ -30,7 +31,7 @@ export class ModelHandle {
30
31
  }
31
32
 
32
33
  get #repo() {
33
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
34
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
34
35
  return new Repository(db, this.#model, this.unitOfWork.fieldTypeRegistry, this.unitOfWork.modelRegistry);
35
36
  }
36
37
 
@@ -71,6 +72,15 @@ export class ModelHandle {
71
72
  return this.unitOfWork.createMany(this.modelName, dataList, options);
72
73
  }
73
74
 
75
+ /** Insert, or update the row with the same `conflict` key (since 0.2.0); see the global Model.upsert(). */
76
+ upsert(data, options) {
77
+ return this.unitOfWork.upsert(this.modelName, data, options);
78
+ }
79
+
80
+ upsertMany(dataList, options) {
81
+ return this.unitOfWork.upsertMany(this.modelName, dataList, options);
82
+ }
83
+
74
84
  /**
75
85
  * Bulk update, bypassing the identity map and per-row hooks - for
76
86
  * "update every row matching this filter" operations where there's
@@ -176,7 +186,7 @@ export class ModelHandle {
176
186
  * @returns {Promise<number>} count of new associations actually inserted
177
187
  */
178
188
  async attach(source, relationName, targetIds) {
179
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
189
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
180
190
  return attachRelation(db, this.#model, this.modelName, source, relationName, targetIds);
181
191
  }
182
192
 
@@ -192,7 +202,7 @@ export class ModelHandle {
192
202
  * @returns {Promise<number>} count of new associations actually inserted
193
203
  */
194
204
  async attachMany(relationName, links) {
195
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
205
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
196
206
  return attachManyRelation(db, this.#model, this.modelName, relationName, links);
197
207
  }
198
208
 
@@ -206,7 +216,7 @@ export class ModelHandle {
206
216
  * @returns {Promise<number>} count of associations removed
207
217
  */
208
218
  async detach(source, relationName, targetIds) {
209
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
219
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
210
220
  return detachRelation(db, this.#model, this.modelName, source, relationName, targetIds);
211
221
  }
212
222
  }
@@ -5,6 +5,7 @@ import { UnitOfWork } from "../uow/unit-of-work.js";
5
5
  import { ModelHandle } from "./model-handle.js";
6
6
  import { ReportHandle } from "../reports/report-handle.js";
7
7
  import { NPlusOneError, scanForNPlusOne, watchForNPlusOne } from "../diagnostics/n-plus-one.js";
8
+ import { resolveDb } from "../transaction/context.js";
8
9
 
9
10
  const RESERVED_CLIENT_PROPERTIES = new Set([
10
11
  "db",
@@ -72,7 +73,10 @@ export class OrmClient {
72
73
  this.db = db;
73
74
  this.modelRegistry = modelRegistry;
74
75
  this.hooks = hooks;
75
- this.unitOfWork = new UnitOfWork(db, modelRegistry, { hooks, trx });
76
+ // One object per row only inside client.transaction(), like the global API's withIdentityMap().
77
+ // Before 0.2.0 a client kept every object it ever read: a long-lived client returned stale
78
+ // values after other writes, and its memory only grew.
79
+ this.unitOfWork = new UnitOfWork(db, modelRegistry, { hooks, trx, identityMap: trx !== undefined });
76
80
  this.models = this.#buildModelsProxy();
77
81
  this.reportDescriptors = reports;
78
82
  this.reports = this.#buildReportsProxy(reports);
@@ -157,7 +161,7 @@ export class OrmClient {
157
161
  * @param {object} [options] - `threshold`, `windowMs`, `statements`
158
162
  */
159
163
  async detectNPlusOne(fn, options = {}) {
160
- return scanForNPlusOne(this.unitOfWork.trx ?? this.db, fn, options);
164
+ return scanForNPlusOne(resolveDb(this.db, this.unitOfWork.trx), fn, options);
161
165
  }
162
166
 
163
167
  /** Like detectNPlusOne(), but throws an NPlusOneError (with `.findings`) if anything repeated. */
@@ -169,7 +173,7 @@ export class OrmClient {
169
173
 
170
174
  /** A live console watcher for development; returns the monitor (`.detach()` to stop). */
171
175
  watchNPlusOne(options = {}) {
172
- return watchForNPlusOne(this.unitOfWork.trx ?? this.db, options);
176
+ return watchForNPlusOne(resolveDb(this.db, this.unitOfWork.trx), options);
173
177
  }
174
178
 
175
179
  async sync() {
@@ -184,7 +188,7 @@ export class OrmClient {
184
188
  * @returns {Promise<Array<{ model: string, table: string, synced: boolean }>>}
185
189
  */
186
190
  async syncSequences() {
187
- return syncRegistrySequences(this.unitOfWork.trx ?? this.db, this.modelRegistry);
191
+ return syncRegistrySequences(resolveDb(this.db, this.unitOfWork.trx), this.modelRegistry);
188
192
  }
189
193
 
190
194
  /**
@@ -202,7 +206,8 @@ export class OrmClient {
202
206
  * @returns {Promise<T>}
203
207
  */
204
208
  async transaction(fn) {
205
- return this.db.transaction(async (trx) => {
209
+ // Inside another transaction (this client's or the global API's), a savepoint in it.
210
+ return resolveDb(this.db).transaction(async (trx) => {
206
211
  const txClient = new OrmClient(this.db, this.modelRegistry, this.hooks, trx, this.moduleServices, this.reportDescriptors);
207
212
  return fn(txClient);
208
213
  });
package/src/connection.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import knexFactory from "knex";
2
+ import { instrumentConnection } from "./dialect/transaction-guard.js";
2
3
 
3
4
  /**
4
5
  * Supported dialects for Phase 0. More can be added later without
@@ -11,6 +12,28 @@ const DIALECTS = /** @type {const} */ (["sqlite", "postgres"]);
11
12
  * @property {"sqlite"|"postgres"} dialect
12
13
  * @property {string} [filename] - sqlite only, e.g. ":memory:" or a file path
13
14
  * @property {string} [connectionString] - postgres only
15
+ * @property {boolean|object} [ssl] - postgres only: passed to the `pg` driver (`true`, or
16
+ * `{ rejectUnauthorized, ca, ... }`). Since 0.1.7.
17
+ * @property {{ min?: number, max?: number, idleTimeoutMillis?: number, afterCreate?: Function }} [pool]
18
+ * - Knex pool settings (Postgres default: min 2, max 10; SQLite: 1 connection). An `afterCreate`
19
+ * of your own runs after the ORM's (SQLite turns foreign keys on there). Since 0.1.7.
20
+ * @property {number} [acquireConnectionTimeout] - ms to wait for a free pooled connection before
21
+ * failing (Knex default 60000). Since 0.1.7.
22
+ * @property {boolean} [wal] - sqlite only, since 0.2.0: a database file is opened in WAL mode with
23
+ * `synchronous = NORMAL` (default `true`) - each write commits without waiting for the disk
24
+ * twice, ~10-20x faster for single writes, and readers in other processes don't block the
25
+ * writer. A committed write can be lost on a power cut or OS crash (never on an app crash), and
26
+ * the database is never corrupted. The `-wal` / `-shm` files next to the database are part of
27
+ * it while it's open. `false` uses SQLite's classic rollback journal (journal_mode = DELETE,
28
+ * synchronous = FULL), switching back a file that was in WAL mode. Ignored for ":memory:".
29
+ * @property {boolean} [preparedStatements] - postgres only, since 0.2.0: find() and findOne() reuse
30
+ * named prepared statements, parsed and planned once per pooled connection (default `true`). Set
31
+ * `false` behind a pooler that doesn't keep one server session per client connection
32
+ * (pgbouncer in transaction mode before 1.21), where a named statement may not exist on the next
33
+ * query's session.
34
+ * @property {boolean} [fastPath] - since 0.2.0: `false` builds every find() with Knex, as before
35
+ * 0.2.0, instead of writing plain finds as SQL directly. Results are the same either way; this is
36
+ * an escape hatch, not a tuning knob.
14
37
  */
15
38
 
16
39
  /**
@@ -28,31 +51,54 @@ export function createConnection(config) {
28
51
  );
29
52
  }
30
53
 
54
+ const shared = config.acquireConnectionTimeout === undefined ? {} : { acquireConnectionTimeout: config.acquireConnectionTimeout };
55
+
31
56
  if (config.dialect === "sqlite") {
32
- return knexFactory({
57
+ const { afterCreate: userAfterCreate, ...pool } = config.pool ?? {};
58
+ return instrumentConnection(knexFactory({
33
59
  client: "better-sqlite3",
34
60
  connection: {
35
61
  filename: config.filename ?? ":memory:",
36
62
  },
37
63
  useNullAsDefault: true,
38
- // SQLite only enforces foreign keys on connections that ask for it (off by default).
64
+ kiriLower: true, // read by the domain compiler's ilike: kiri_lower() exists on these connections
65
+ ...(config.fastPath === false ? { kiriFastPath: false } : {}),
66
+ ...shared,
39
67
  pool: {
68
+ ...pool,
69
+ // SQLite only enforces foreign keys on connections that ask for it (off by default).
40
70
  afterCreate(connection, done) {
41
71
  connection.pragma("foreign_keys = ON");
42
- done(null, connection);
72
+ if (!connection.memory) {
73
+ if (config.wal === false) {
74
+ connection.pragma("journal_mode = DELETE");
75
+ connection.pragma("synchronous = FULL");
76
+ } else {
77
+ connection.pragma("journal_mode = WAL");
78
+ connection.pragma("synchronous = NORMAL");
79
+ }
80
+ }
81
+ // Unicode-aware lower-case for case-insensitive matching (SQLite's lower() only folds A-Z).
82
+ connection.function("kiri_lower", { deterministic: true }, (value) => (typeof value === "string" ? value.toLowerCase() : value));
83
+ if (userAfterCreate) userAfterCreate(connection, done);
84
+ else done(null, connection);
43
85
  },
44
86
  },
45
- });
87
+ }));
46
88
  }
47
89
 
48
90
  if (config.dialect === "postgres") {
49
91
  if (!config.connectionString) {
50
92
  throw new Error("postgres dialect requires a connectionString");
51
93
  }
52
- return knexFactory({
94
+ return instrumentConnection(knexFactory({
53
95
  client: "pg",
54
- connection: config.connectionString,
55
- });
96
+ connection: config.ssl === undefined ? config.connectionString : { connectionString: config.connectionString, ssl: config.ssl },
97
+ ...(config.fastPath === false ? { kiriFastPath: false } : {}),
98
+ ...(config.preparedStatements === false ? { kiriPreparedStatements: false } : {}),
99
+ ...shared,
100
+ ...(config.pool ? { pool: config.pool } : {}),
101
+ }));
56
102
  }
57
103
 
58
104
  // Unreachable given the guard above, but keeps the function honest.
@@ -1,6 +1,7 @@
1
1
  import { parseDomain } from "../domain/parse.js";
2
2
  import { castValue } from "../fields/cast-value.js";
3
3
  import { ValidationError } from "./errors.js";
4
+ import { toStorage } from "../fields/storage.js";
4
5
 
5
6
  /**
6
7
  * WHERE vs HAVING.
@@ -129,10 +130,15 @@ export function compileHaving(model, plan, ast, expressionFor, fieldTypeRegistry
129
130
 
130
131
  // count/sum/avg come out as numbers whatever the column was; min/max keep the column's own type.
131
132
  const castFor = (aggregate) => {
132
- const field = aggregate.fn === "min" || aggregate.fn === "max" ? aggregate.def : { type: "float" };
133
+ // A decimal aggregate (min/max/sum, and avg on SQLite where it's over scaled integers) compares
134
+ // in the column's stored form, so the value goes through the decimal type too.
135
+ const decimal = aggregate.def?.type === "decimal" && aggregate.fn !== "count" && aggregate.fn !== "countDistinct";
136
+ const field = aggregate.fn === "min" || aggregate.fn === "max" || decimal ? aggregate.def : { type: "float" };
133
137
  return (value, op) => {
134
138
  try {
135
- return castValue(field, value, fieldTypeRegistry);
139
+ const cast = castValue(field, value, fieldTypeRegistry);
140
+ if (decimal && aggregate.fn === "avg") return toStorage({ ...field, scale: field.scale ?? 2 }, cast, fieldTypeRegistry);
141
+ return decimal || field === aggregate.def ? toStorage(field, cast, fieldTypeRegistry) : cast;
136
142
  } catch (error) {
137
143
  return fail(`filter on aggregate "${aggregate.alias}" (${op}): ${error.message}`);
138
144
  }
@@ -35,8 +35,8 @@ import { resolvePath } from "./aggregate-paths.js";
35
35
 
36
36
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
37
37
  const FUNCTIONS = ["count", "countDistinct", "sum", "avg", "min", "max"];
38
- const NUMERIC_TYPES = new Set(["integer", "float"]);
39
- const COMPARABLE_TYPES = new Set(["integer", "float", "date", "datetime", "char", "text", "enum"]); // min / max
38
+ const NUMERIC_TYPES = new Set(["integer", "float", "decimal"]);
39
+ const COMPARABLE_TYPES = new Set(["integer", "float", "decimal", "date", "datetime", "char", "text", "enum"]); // min / max
40
40
  const DATE_TYPES = new Set(["date", "datetime"]);
41
41
  const GROUP_OPTION_KEYS = new Set(["field", "bucket", "as"]);
42
42
 
@@ -4,6 +4,7 @@ import { dateBucketSql, parseBucket } from "../dialect/date-bucket.js";
4
4
  import { planAggregate } from "./aggregate-spec.js";
5
5
  import { compileHaving, filterToAst, mentionsResultColumn, splitFilter } from "./aggregate-filter.js";
6
6
  import { resolveWhere } from "./resolve-where.js";
7
+ import { fromStorage, dialectOfClient } from "../fields/storage.js";
7
8
 
8
9
  /**
9
10
  * Builds and runs one aggregate query: groups rows, computes count/sum/avg/min/max, filters
@@ -224,7 +225,7 @@ function buildSubtotalQuery(db, { many, components }) {
224
225
  export async function runAggregate(ctx) {
225
226
  const { query, plan } = buildAggregateQuery(ctx);
226
227
  const rows = await query;
227
- return rows.map((row) => mapRow(plan, row, ctx.fieldTypeRegistry));
228
+ return rows.map((row) => mapRow(plan, row, ctx.fieldTypeRegistry, dialectOfClient(ctx.db.client)));
228
229
  }
229
230
 
230
231
  /**
@@ -247,12 +248,15 @@ const toNumber = (value) => (value === null || value === undefined ? null : Numb
247
248
  * as the column's own type (a Date for a date field). Group keys are cast like any stored value.
248
249
  * Numbers are JS doubles: a count or integer sum beyond 2^53 would lose precision.
249
250
  */
250
- function mapRow(plan, row, fieldTypeRegistry) {
251
+ function mapRow(plan, row, fieldTypeRegistry, dialect) {
251
252
  const result = {};
253
+ // A stored value back to the field's own type (decimal: SQLite's scaled integer to "12.50").
254
+ const asField = (def, value) =>
255
+ value === null || value === undefined ? null : castValue(def, fromStorage(def, value, dialect, fieldTypeRegistry), fieldTypeRegistry);
252
256
  for (const key of plan.keys) {
253
257
  const value = row[key.alias];
254
258
  if (key.kind === "bucket") result[key.alias] = parseBucket(value);
255
- else result[key.alias] = value === null || value === undefined ? null : castValue(key.def, value, fieldTypeRegistry);
259
+ else result[key.alias] = asField(key.def, value);
256
260
  }
257
261
  for (const aggregate of plan.aggregates) {
258
262
  const value = row[aggregate.alias];
@@ -262,11 +266,18 @@ function mapRow(plan, row, fieldTypeRegistry) {
262
266
  result[aggregate.alias] = toNumber(value) ?? 0;
263
267
  break;
264
268
  case "sum":
269
+ // A sum of decimals stays an exact decimal string (SQLite sums the scaled integers exactly).
270
+ result[aggregate.alias] = aggregate.def?.type === "decimal" ? asField(aggregate.def, value) : toNumber(value);
271
+ break;
265
272
  case "avg":
266
- result[aggregate.alias] = toNumber(value);
273
+ // An average is rarely a whole number of cents: always a number (on SQLite, unscaled).
274
+ result[aggregate.alias] =
275
+ aggregate.def?.type === "decimal" && dialect === "sqlite" && value !== null && value !== undefined
276
+ ? Number(value) / 10 ** (aggregate.def.scale ?? 2)
277
+ : toNumber(value);
267
278
  break;
268
279
  default: // min, max
269
- result[aggregate.alias] = value === null || value === undefined ? null : castValue(aggregate.def, value, fieldTypeRegistry);
280
+ result[aggregate.alias] = asField(aggregate.def, value);
270
281
  }
271
282
  }
272
283
  return result;
@@ -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 const IN_LIST_CHUNK = 5000;
@@ -7,6 +7,11 @@ import { attachPairs } from "../relations/attach-detach.js";
7
7
  import { RelationError } from "../relations/errors.js";
8
8
  import { resolveLocalKey } from "../relations/keys.js";
9
9
  import { primaryKeyOf } from "../models/primary-key.js";
10
+ import { resolveDb, inTransactionIf } from "../transaction/context.js";
11
+ import { hookContext, runAfterHooks } from "../uow/lifecycle.js";
12
+ import { ENTITY_META, originalValues, markCreateRolledBack } from "../uow/entity.js";
13
+ import { onRollback } from "../transaction/after-commit.js";
14
+ import { translatingErrors } from "./database-errors.js";
10
15
 
11
16
  /**
12
17
  * Batched record creation - the engine behind `createMany()` (and,
@@ -150,9 +155,10 @@ async function prepareLevel(ctx, model, dataList, labels) {
150
155
  );
151
156
  }
152
157
 
153
- if (runtime.hooks) {
154
- await runtime.hooks.run(model.name, "beforeCreate", data);
155
- await runtime.hooks.run(model.name, "beforeSave", data, undefined);
158
+ if (runtime.hooks?.has(model.name, ["beforeCreate", "beforeSave"])) {
159
+ const hookCtx = hookContext(ctx.db, "create", { isNew: true, changes: data, model: model.name });
160
+ await runtime.hooks.run(model.name, "beforeCreate", data, hookCtx);
161
+ await runtime.hooks.run(model.name, "beforeSave", data, hookCtx);
156
162
  }
157
163
 
158
164
  const { fieldData, relationKeys } = splitRelationKeys(model, data);
@@ -366,35 +372,52 @@ export async function createRecords(runtime, model, dataList, options = {}) {
366
372
  if (dataList.length === 0) return [];
367
373
 
368
374
  const labels = options.labels ?? dataList.map((_, i) => `[${i}]`);
369
- const baseDb = options.trx ?? runtime.db;
370
- const ctx = { runtime, db: baseDb, chunkSize: options.chunkSize, created: [], targets: new Map() };
375
+ const baseDb = resolveDb(runtime.db, options.trx);
376
+
377
+ // One atomic unit whenever more than a lone INSERT is involved: hooks (since 0.2.0 they run
378
+ // inside it, so a hook's own writes and a hook that throws commit or roll back with the rows),
379
+ // nested relation writes, or more rows than one INSERT holds. Inside an open transaction
380
+ // (explicit or ambient) all of it simply joins that one.
381
+ const relationNames = Object.keys(model.relations ?? {});
382
+ const isPayload = (value) => value !== undefined && !(Array.isArray(value) && value.length === 0);
383
+ const hasRelationPayload =
384
+ relationNames.length > 0 && dataList.some((data) => data && typeof data === "object" && relationNames.some((r) => isPayload(data[r])));
385
+ if (hasRelationPayload && !runtime.modelRegistry) {
386
+ // Say so before touching the database (resolveTarget() would, but only inside the transaction).
387
+ throw new RelationError(
388
+ `Writing relations of model "${model.name}" requires a modelRegistry (construct the Repository with one, or use RepositoryFactory / createClient).`
389
+ );
390
+ }
391
+ const statements = Math.ceil(dataList.length / rowsPerStatement(baseDb, Object.keys(model.fields).length, options.chunkSize));
392
+ const needsTransaction = (runtime.hooks?.has(model.name) ?? false) || hasRelationPayload || statements > 1;
371
393
 
372
- // Phase 1 - nothing is written.
373
- const rows = await prepareLevel(ctx, model, dataList, labels);
394
+ return translatingErrors(model, () => inTransactionIf(needsTransaction, baseDb, async (db) => {
395
+ const ctx = { runtime, db, chunkSize: options.chunkSize, created: [], targets: new Map() };
374
396
 
375
- // Phase 2 - a lone INSERT is atomic by itself; anything more needs a transaction.
376
- const hasRelationWork = rows.some((row) => row.commands && Object.values(row.commands).some((ops) => ops.length > 0));
377
- const insertStatements = Math.ceil(rows.length / rowsPerStatement(baseDb, Object.keys(model.fields).length, options.chunkSize));
378
-
379
- let rootEntries;
380
- if (!baseDb.isTransaction && (hasRelationWork || insertStatements > 1)) {
381
- await baseDb.transaction(async (trx) => {
382
- rootEntries = await executeLevel({ ...ctx, db: trx }, model, rows);
383
- });
384
- } else {
385
- rootEntries = await executeLevel(ctx, model, rows);
386
- }
397
+ // Phase 1 - before-hooks, validation, relation payloads; nothing is written.
398
+ const rows = await prepareLevel(ctx, model, dataList, labels);
399
+ // Phase 2 - the INSERTs (and nested relation writes).
400
+ const rootEntries = await executeLevel(ctx, model, rows);
387
401
 
388
- // Phase 3 - committed; now build entities and fire after-hooks.
389
- for (const entry of ctx.created) {
390
- entry.result = runtime.wrap ? runtime.wrap(entry.model.name, entry.record) : entry.record;
391
- }
392
- if (runtime.hooks) {
402
+ // Phase 3 - documents, then after-hooks, still inside the unit; afterCommit waits for the commit.
393
403
  for (const entry of ctx.created) {
394
- await runtime.hooks.run(entry.model.name, "afterCreate", entry.result);
395
- await runtime.hooks.run(entry.model.name, "afterSave", entry.result, undefined);
404
+ entry.result = runtime.wrap ? runtime.wrap(entry.model.name, entry.record) : entry.record;
396
405
  }
397
- }
398
-
399
- return rootEntries.map((entry) => entry.result);
406
+ // If the transaction these INSERTs ran in rolls back, the documents have no rows (since 0.2.0).
407
+ if (db.isTransaction) {
408
+ const documents = ctx.created.map((entry) => entry.result);
409
+ onRollback(db, () => documents.forEach(markCreateRolledBack));
410
+ }
411
+ if (runtime.hooks) {
412
+ for (const entry of ctx.created) {
413
+ if (!runtime.hooks.has(entry.model.name)) continue; // no hooks: nothing to run, no context to build
414
+ // What was written, as its own object: the document (the same object as entry.record once
415
+ // wrapped) may change before afterCommit runs.
416
+ const changes = entry.result[ENTITY_META] ? originalValues(entry.result) : entry.record;
417
+ const hookCtx = hookContext(db, "create", { isNew: true, changes, model: entry.model.name });
418
+ await runAfterHooks(runtime.hooks, entry.model.name, db, "create", entry.result, hookCtx);
419
+ }
420
+ }
421
+ return rootEntries.map((entry) => entry.result);
422
+ }));
400
423
  }