@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
@@ -0,0 +1,40 @@
1
+ import { DialectValue } from "../storage.js";
2
+ /**
3
+ * `decimal` - an exact base-10 number, for money, prices, rates and quantities (since 0.2.0).
4
+ *
5
+ * price: { type: "decimal", precision: 12, scale: 2 } // up to 9,999,999,999.99
6
+ *
7
+ * Its value is always a string in canonical form - "1234.50", "-0.05", "0.00" - exactly `scale`
8
+ * decimal places, never a JavaScript number, so nothing is ever rounded behind your back. Do
9
+ * arithmetic with a decimal library (decimal.js, big.js) or in SQL (atomic updates, sums).
10
+ *
11
+ * Input:
12
+ * - a string is exact: "12.5" becomes "12.50"; more decimal places than `scale` is an error;
13
+ * - a JavaScript number is approximate already (0.1 + 0.2 is 0.30000000000000004), so it is
14
+ * rounded to `scale` places, half away from zero;
15
+ * - a bigint is a whole number.
16
+ *
17
+ * Storage:
18
+ * - Postgres: `numeric(precision, scale)` - exact, and the driver returns it as text.
19
+ * - SQLite has no exact decimal type (a DECIMAL column silently stores floating point), so the
20
+ * value is stored as an integer scaled by 10^scale: "1234.50" with scale 2 is stored as 123450.
21
+ * Exact, sorts and compares correctly, and SUM() stays exact. The ORM converts on the way in
22
+ * (every write and every filter value, through DialectValue) and on the way out.
23
+ *
24
+ * Limits: `precision` (total significant digits) 1-15 and `scale` 0-precision. Fifteen digits is
25
+ * what a SQLite integer read back by the driver keeps exactly (JavaScript numbers are exact up to
26
+ * 2^53); with scale 2 that is 9,999,999,999,999.99. Defaults: precision 15, scale 2.
27
+ */
28
+ export declare const MAX_DECIMAL_PRECISION = 15;
29
+ /** Canonical text -> the integer SQLite stores (exact: at most 15 digits, under 2^53). */
30
+ export declare function toScaledInteger(text: any, scale: any): number;
31
+ export declare const decimalType: {
32
+ name: string;
33
+ validateOptions(field: any): string[];
34
+ validate(field: any, value: any): string[];
35
+ cast(field: any, value: any): string;
36
+ /** The value as the database stores it - resolved per dialect when the query is bound. */
37
+ toStorage(field: any, value: any): DialectValue;
38
+ /** The stored value back to canonical text: SQLite gives the scaled integer, Postgres text. */
39
+ fromStorage(field: any, value: any, dialect: any): any;
40
+ };
@@ -11,3 +11,4 @@ export { withIdentityMap } from "./identity-scope.js";
11
11
  export { diffModels, migrateModels, getDefaultModelRegistry } from "./migrate.js";
12
12
  export { generateModelDTOs, generateAllModelDTOs, generateModelJSDoc } from "./dto.js";
13
13
  export { __resetGlobalStateForTests } from "./state.js";
14
+ export { SaveDeletedError } from "./errors.js";
@@ -1,19 +1,16 @@
1
1
  /**
2
- * Runs `fn` inside a transaction on the default connection, passing
3
- * the transaction object through so it can be handed to any Model
4
- * method's `{ trx }` option (`Order.create(data, { trx })`) to
5
- * include it in the same atomic unit. Every `Model` method - `create`,
6
- * `find`, `findOne`, `updateMany`, `deleteMany`, `attach`, `detach`,
7
- * and a document's own `save()`/`delete()` - accepts `{ trx }` for
8
- * exactly this reason.
2
+ * Runs `fn` inside a transaction on the default connection.
9
3
  *
10
- * Without this, a multi-step write across Models (e.g. creating an
11
- * order plus each of its line items) has no way to be atomic: each
12
- * `Model.create()` call would hit the default connection directly,
13
- * with no way to roll every step back together if a later one fails.
4
+ * Since 0.2.0 every model call made while `fn` runs joins the transaction on its own - in `fn`,
5
+ * in a helper it calls, in a hook - so `{ trx }` no longer has to be passed along (it still works,
6
+ * and `fn` still receives the transaction for raw Knex queries: `trx("table")...`).
14
7
  *
15
- * If `fn` throws (or returns a rejected promise), Knex rolls the
16
- * transaction back automatically and the rejection propagates here.
8
+ * Called while a transaction is already open in this async flow, it opens a savepoint inside it:
9
+ * if `fn` throws, only the savepoint's work is undone and the error propagates to the outer code.
10
+ *
11
+ * Writes and their before/after hooks commit or roll back together. `afterCommit` hooks run once
12
+ * the outermost transaction has committed, before this promise resolves (an error there rejects it,
13
+ * though the data stays committed).
17
14
  *
18
15
  * @template T
19
16
  * @param {(trx: import('knex').Knex.Transaction) => Promise<T>} fn
@@ -14,3 +14,5 @@ export * from "./uow/index.js";
14
14
  export * from "./client/index.js";
15
15
  export * from "./global/index.js";
16
16
  export * from "./dto/index.js";
17
+ export { afterCommit } from "./transaction/after-commit.js";
18
+ export { resolveDb, ambientTransaction } from "./transaction/context.js";
@@ -1,6 +1,16 @@
1
1
  export type ModelMetaSnapshot = {
2
2
  table_name: string;
3
3
  removed: boolean;
4
+ /**
5
+ * - since 0.2.0;
6
+ * absent in migrations generated before, which then leave the stored value alone
7
+ */
8
+ constraints?: Array<{
9
+ kind: string;
10
+ name: string;
11
+ fields: string[];
12
+ columns: string[];
13
+ }>;
4
14
  /**
5
15
  * - ordered by name
6
16
  */
@@ -79,3 +79,19 @@ export declare function flagRemovedModels(trx: import('knex').Knex, modelRegistr
79
79
  * @returns {Promise<string[]>} field names newly flagged as removed
80
80
  */
81
81
  export declare function flagRemovedFields(trx: import('knex').Knex, modelId: number, currentFieldNames: Set<string>, now: Date): Promise<string[]>;
82
+ /**
83
+ * A model's multi-field constraints as stored in `_meta_models.constraints` (since 0.2.0):
84
+ * `[{ kind: "unique"|"index", name, fields, columns }]`, as JSON text.
85
+ *
86
+ * @param {import('../models/constraints.js').ModelConstraints|undefined} constraints
87
+ */
88
+ export declare function serializeConstraints(constraints: import('../models/constraints.js').ModelConstraints | undefined): string;
89
+ /** @returns {Array<{ kind: string, name: string, fields: string[], columns: string[] }>} */
90
+ export declare function constraintList(constraints: any): Array<{
91
+ kind: string;
92
+ name: string;
93
+ fields: string[];
94
+ columns: string[];
95
+ }>;
96
+ /** The stored constraints of a `_meta_models` row; a row from before 0.2.0 has none. */
97
+ export declare function parseStoredConstraints(value: any): any;
@@ -63,9 +63,25 @@ export type FieldChangePlan = {
63
63
  columnRenames: Object[];
64
64
  /**
65
65
  * - { fieldName, from, to } - flagged
66
- * but never auto-migrated (see generateMigration).
66
+ * but never auto-migrated (see generateMigration). A decimal's precision or scale counts as
67
+ * its type ("decimal(12,2)" -> "decimal(12,4)"): on SQLite the stored integers would need rescaling.
67
68
  */
68
69
  typeChanges: Object[];
70
+ /**
71
+ * - { fieldName, column, changes, from, to } (since 0.2.0): the
72
+ * column options that changed (required, unique, index, default, maxLength, enum values), with
73
+ * the recorded and current descriptors; applied with alterColumn() (schema/alter-column.js).
74
+ */
75
+ optionChanges: Object[];
76
+ /**
77
+ * - model constraints (constraints: { unique, index }) not
78
+ * recorded yet: { kind, name, fields, columns } (since 0.2.0)
79
+ */
80
+ addConstraints: Object[];
81
+ /**
82
+ * - recorded ones the model no longer declares, same shape
83
+ */
84
+ dropConstraints: Object[];
69
85
  /**
70
86
  * -
71
87
  * advisory only, same rationale as possibleModelRenames but at the
@@ -112,7 +128,14 @@ export type FieldChangePlan = {
112
128
  * (e.g. an explicit `column` option was added/changed). Not a
113
129
  * heuristic guess, same reasoning as renameModels above.
114
130
  * @property {Object[]} typeChanges - { fieldName, from, to } - flagged
115
- * but never auto-migrated (see generateMigration).
131
+ * but never auto-migrated (see generateMigration). A decimal's precision or scale counts as
132
+ * its type ("decimal(12,2)" -> "decimal(12,4)"): on SQLite the stored integers would need rescaling.
133
+ * @property {Object[]} optionChanges - { fieldName, column, changes, from, to } (since 0.2.0): the
134
+ * column options that changed (required, unique, index, default, maxLength, enum values), with
135
+ * the recorded and current descriptors; applied with alterColumn() (schema/alter-column.js).
136
+ * @property {Object[]} addConstraints - model constraints (constraints: { unique, index }) not
137
+ * recorded yet: { kind, name, fields, columns } (since 0.2.0)
138
+ * @property {Object[]} dropConstraints - recorded ones the model no longer declares, same shape
116
139
  * @property {{removed: string[], added: string[]}|null} possibleFieldRenames -
117
140
  * advisory only, same rationale as possibleModelRenames but at the
118
141
  * field level (e.g. `customerId` renamed to `clientId` in code).
@@ -0,0 +1,27 @@
1
+ export type ModelConstraint = {
2
+ fields: string[];
3
+ columns: string[];
4
+ name: string;
5
+ };
6
+ export type ModelConstraints = {
7
+ unique: ModelConstraint[];
8
+ index: ModelConstraint[];
9
+ };
10
+ /** @returns {ModelConstraints} */
11
+ export declare function defineConstraints(modelName: any, tableName: any, input: any, fields: any, columns: any): ModelConstraints;
12
+ /** Folds constraint declarations from mixins and extension layers into one. */
13
+ export declare function mergeConstraintInputs(target: any, input: any): any;
14
+ export declare function constraintName(tableName: any, columns: any, kind: any): string;
15
+ /** Adds a model's constraints to a Knex table builder (create or alter). */
16
+ export declare function addConstraints(table: any, constraints: any, only?: null): void;
17
+ /** Adds or drops one stored constraint ({ kind, name, columns }) on a Knex table builder. */
18
+ export declare function addConstraint(table: any, { kind, name, columns }: {
19
+ columns: any;
20
+ kind: any;
21
+ name: any;
22
+ }): void;
23
+ export declare function dropConstraint(table: any, { kind, name, columns }: {
24
+ columns: any;
25
+ kind: any;
26
+ name: any;
27
+ }): void;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The column options a migration can change in place (since 0.2.0), compared between a field's
3
+ * recorded descriptor and its current one. Everything else about a column is either its type
4
+ * (never auto-migrated) or JS-side only (validation, casting).
5
+ *
6
+ * @param {import('../fields/define-field.js').FieldDescriptor} field
7
+ */
8
+ export declare function columnOptions(field: import('../fields/define-field.js').FieldDescriptor): {
9
+ required: boolean;
10
+ unique: boolean;
11
+ index: boolean;
12
+ default: {} | null;
13
+ maxLength: any;
14
+ values: any[] | null;
15
+ };
16
+ /** The names of the options that differ between two descriptors of the same field. */
17
+ export declare function changedColumnOptions(from: any, to: any): string[];
18
+ /**
19
+ * Changes one column from field descriptor `from` to `to`: NOT NULL, DEFAULT, varchar length,
20
+ * an enum's allowed values (its CHECK), and the column's single-field unique / index. Used by
21
+ * generated migrations (the `alterColumn` helper), because Knex's own `.alter()` can't do this on
22
+ * either database: on Postgres it emits invalid SQL for an enum, and on SQLite it keeps the old
23
+ * CHECK next to the new one.
24
+ *
25
+ * - Postgres: plain ALTER COLUMN / constraint statements, in place.
26
+ * - SQLite: the table is rebuilt with only this column's definition replaced (create a copy, copy
27
+ * the rows, drop, rename, recreate the indexes). Foreign key enforcement must be off for that
28
+ * (SQLite would otherwise run ON DELETE actions for the dropped table) - it is inside the
29
+ * migration runner's transaction. Called outside a transaction, this turns it off around its
30
+ * own transaction and checks the foreign keys before committing.
31
+ *
32
+ * Making a column required with a static default first fills existing NULLs with the default;
33
+ * otherwise a constraint the existing rows break (NULLs, duplicates, an enum value no longer
34
+ * allowed, text longer than the new length on Postgres) fails the statement, and the migration
35
+ * rolls back.
36
+ *
37
+ * @param {import('knex').Knex} db
38
+ * @param {string} tableName
39
+ * @param {string} columnName
40
+ * @param {import('../fields/define-field.js').FieldDescriptor} from
41
+ * @param {import('../fields/define-field.js').FieldDescriptor} to
42
+ * @param {import('./column-builder-registry.js').ColumnBuilderRegistry} [registry]
43
+ */
44
+ export declare function alterColumn(db: import('knex').Knex, tableName: string, columnName: string, from: import('../fields/define-field.js').FieldDescriptor, to: import('../fields/define-field.js').FieldDescriptor, registry?: import('./column-builder-registry.js').ColumnBuilderRegistry): Promise<void>;
45
+ /** Splits a CREATE TABLE body at its top-level commas, respecting quotes and parentheses. */
46
+ export declare function splitTopLevel(body: any): any[];
@@ -16,3 +16,14 @@
16
16
  * @returns {import('knex').Knex.ColumnBuilder}
17
17
  */
18
18
  export declare function buildColumn(table: import('knex').Knex.CreateTableBuilder, columnName: string, field: import('../fields/define-field.js').FieldDescriptor, registry?: import('./column-builder-registry.js').ColumnBuilderRegistry): import('knex').Knex.ColumnBuilder;
19
+ /**
20
+ * A static default in the column's stored form, for the SQL DEFAULT clause: a decimal as its
21
+ * scaled integer on SQLite; a `date` as "YYYY-MM-DD" and a `datetime` Date as epoch milliseconds
22
+ * on SQLite / ISO text on Postgres - what the ORM itself writes. Before 0.2.0 a Date default went
23
+ * in as its toString() ("Sat Jun 01 2024 ... GMT+0900"): unreadable rows from raw inserts on
24
+ * SQLite, and syncModels() failing on Postgres.
25
+ *
26
+ * @param {boolean|import('knex').Knex.CreateTableBuilder} sqliteOrTable - a table builder, or whether the database is SQLite
27
+ * @param {import('../fields/define-field.js').FieldDescriptor} field
28
+ */
29
+ export declare function storedDefault(sqliteOrTable: boolean | import('knex').Knex.CreateTableBuilder, field: import('../fields/define-field.js').FieldDescriptor): {} | null | undefined;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Names of the indexes on `table` (unique constraints included: both databases back them with an
3
+ * index of the constraint's name). Null for a dialect it can't introspect.
4
+ *
5
+ * @param {import('knex').Knex} db
6
+ * @param {string} table
7
+ * @returns {Promise<Set<string>|null>}
8
+ */
9
+ export declare function listIndexNames(db: import('knex').Knex, table: string): Promise<Set<string> | null>;
@@ -0,0 +1,42 @@
1
+ export declare function outermostTransaction(trx: any): any;
2
+ /**
3
+ * Runs `fn` after `db` commits, or now when `db` isn't a transaction. The ORM's own entry point
4
+ * (the `afterCommit` hook), with the connection it resolved.
5
+ *
6
+ * @param {import('knex').Knex} db
7
+ * @param {() => unknown} fn
8
+ */
9
+ export declare function queueAfterCommit(db: import('knex').Knex, fn: () => unknown): Promise<void>;
10
+ /**
11
+ * Runs `fn` once the transaction open in this async flow commits - the outermost one, so a
12
+ * savepoint's release doesn't count - or right away outside a transaction:
13
+ *
14
+ * await transaction(async () => {
15
+ * const order = await Order.create(data);
16
+ * afterCommit(() => queue.publish("order.created", { id: order.id }));
17
+ * });
18
+ *
19
+ * A rollback (of the transaction, or of the savepoint the call was made in) drops `fn`. An error it
20
+ * throws reaches whoever awaited the outermost `transaction()`. Outside a transaction it returns a
21
+ * promise of `fn`'s result. `afterCommit(trx, fn)` (0.2.0's form) queues on `trx`.
22
+ *
23
+ * @param {(() => unknown) | import('knex').Knex} fnOrTrx
24
+ * @param {() => unknown} [fn]
25
+ * @returns {Promise<unknown>}
26
+ */
27
+ export declare function afterCommit(fnOrTrx: (() => unknown) | import('knex').Knex, fn?: () => unknown): Promise<unknown>;
28
+ /**
29
+ * Registers `fn` to run if `db` - or the transaction it is part of - rolls back (since 0.2.0). The
30
+ * ORM uses it to put tracked documents back to what the database holds after a rollback undid
31
+ * their save(). Callbacks are synchronous and run in reverse order of registration, so several
32
+ * saves of one document unwind to its value before the first. Nothing is registered outside a
33
+ * transaction (an autocommitted write can't roll back).
34
+ *
35
+ * @param {import('knex').Knex} db
36
+ * @param {() => void} fn
37
+ */
38
+ export declare function onRollback(db: import('knex').Knex, fn: () => void): void;
39
+ /** Runs everything queued on a committed outermost transaction, in order. */
40
+ export declare function flushAfterCommit(root: any): Promise<void>;
41
+ /** Drops what was queued inside `trx` (and the savepoints inside it), because it rolled back. */
42
+ export declare function discardAfterCommit(trx: any): void;
@@ -0,0 +1,39 @@
1
+ /** Runs `fn` inside a scope where `trx` is the open transaction for `baseClient`. */
2
+ export declare function runInTransactionScope(baseClient: any, trx: any, fn: any): any;
3
+ /**
4
+ * The transaction open in this async flow for `db`'s connection, or null. A `db` that is already a
5
+ * transaction is used as given (null here). A finished transaction is never returned: code still
6
+ * running after its commit (a timer started inside it, say) goes back to the connection itself.
7
+ *
8
+ * @param {import('knex').Knex} db
9
+ * @returns {import('knex').Knex.Transaction | null}
10
+ */
11
+ export declare function ambientTransaction(db: import('knex').Knex): import('knex').Knex.Transaction | null;
12
+ /**
13
+ * Which connection an operation runs on: an explicit `{ trx }` first, then the transaction open in
14
+ * this async flow, then `db` itself. Every ORM entry point resolves its connection through this.
15
+ *
16
+ * @param {import('knex').Knex} db
17
+ * @param {import('knex').Knex.Transaction} [trx]
18
+ */
19
+ export declare function resolveDb(db: import('knex').Knex, trx?: import('knex').Knex.Transaction): import("knex").Knex<any, any[]>;
20
+ /**
21
+ * The innermost unfinished transaction open in this async flow, on any connection, or null. For
22
+ * APIs that take no connection at all, like the public `afterCommit(fn)`.
23
+ *
24
+ * @returns {import('knex').Knex.Transaction | null}
25
+ */
26
+ export declare function currentTransaction(): import('knex').Knex.Transaction | null;
27
+ /** Whether a transaction for `client` is open (and unfinished) in this async flow. */
28
+ export declare function holdsTransactionFor(client: any): boolean;
29
+ /**
30
+ * Runs `fn(db)` in a transaction when `needed` and `db` isn't one already; otherwise on `db` as is.
31
+ * Used to make a write and its hooks one atomic unit only when there are hooks to protect.
32
+ *
33
+ * @template T
34
+ * @param {boolean} needed
35
+ * @param {import('knex').Knex} db
36
+ * @param {(db: import('knex').Knex) => Promise<T>} fn
37
+ * @returns {Promise<T>}
38
+ */
39
+ export declare function inTransactionIf<T>(needed: boolean, db: import('knex').Knex, fn: (db: import('knex').Knex) => Promise<T>): Promise<T>;
@@ -6,35 +6,48 @@
6
6
  * shape to work with.
7
7
  */
8
8
  export declare const ENTITY_META: unique symbol;
9
+ /** @returns {unknown} the snapshot form of `value` */
10
+ export declare function toSnapshot(value: any, field: any): unknown;
9
11
  /**
10
- * Wraps a plain record (as returned by Repository) into a tracked
11
- * entity: same enumerable field properties, plus a hidden snapshot of
12
- * the values as-loaded and non-enumerable save()/delete() methods
13
- * that call whatever `handlers.save`/`handlers.delete` functions the
14
- * caller supplies.
12
+ * The entity's as-loaded values as a plain object (fresh Dates and json values), e.g. a hook's
13
+ * `ctx.original`. `entity[ENTITY_META].original` returns the same: a copy, so writing to it
14
+ * changes nothing (use markClean()).
15
+ */
16
+ export declare function originalValues(entity: any): {};
17
+ /** One as-loaded value (e.g. the primary key a save/delete targets). */
18
+ export declare function originalValue(entity: any, fieldName: any): any;
19
+ /** Whether `fieldName` still holds its as-loaded (last saved) value. */
20
+ export declare function isFieldClean(entity: any, fieldName: any): boolean;
21
+ /**
22
+ * Undoes, in memory, a save() whose transaction rolled back (since 0.2.0): each saved field goes
23
+ * back to `before` - its value in the database again - both as the document's value and as its
24
+ * snapshot. A field the caller changed again after that save keeps the newer value, and stays
25
+ * dirty against `before`, so the next save() writes it.
15
26
  *
16
- * Deliberately decoupled from any particular coordinator object
17
- * (originally this took a `UnitOfWork` instance directly and called
18
- * `unitOfWork.saveEntity(entity, ...)`) - `handlers` just needs
19
- * `save(entity, options)` and `delete(entity, options)` functions,
20
- * which lets a document be fully self-contained: it can carry
21
- * everything it needs to save/delete itself without requiring an
22
- * external identity-map-holding object to mediate. `UnitOfWork` still
23
- * supplies handlers bound to itself (for identity-mapped, per-
24
- * transaction use), but the global Mongoose-style `createModel()` API
25
- * supplies handlers with no external coordinator at all - just a
26
- * shared connection and hook registry captured in a closure.
27
+ * @param {Record<string, unknown>} entity
28
+ * @param {Record<string, unknown>} before - field name -> value before the save
29
+ */
30
+ export declare function revertSave(entity: Record<string, unknown>, before: Record<string, unknown>): void;
31
+ /** Marks a document whose INSERT was rolled back: it has no row, and save() says why. */
32
+ export declare function markCreateRolledBack(entity: any): void;
33
+ /** Records `value` as the stored value of `fieldName`: the field is clean again. */
34
+ export declare function markClean(entity: any, fieldName: any, value: any): void;
35
+ /**
36
+ * Turns a plain record into a tracked entity: same enumerable field properties, plus a hidden
37
+ * snapshot of the values as loaded and non-enumerable save()/delete() methods that call whatever
38
+ * `handlers.save`/`handlers.delete` functions the caller supplies.
27
39
  *
28
- * The entity's live values and its `original` snapshot are built as
29
- * two SEPARATE clones for mutable field types (see cloneFieldValue) -
30
- * critical for correctness: without this, `entity.dueDate` and
31
- * `original.dueDate` would be the same Date object, and mutating one
32
- * in place would silently mutate the other too, making every
33
- * in-place edit invisible to diffEntity(). A dedicated test
34
- * (`flags a date field as dirty when mutated in place`) caught this
35
- * exact bug during development.
40
+ * The record itself becomes the entity (since 0.2.0; before, its values were copied onto a new
41
+ * object): every record handed in here is a fresh fromRow() result nothing else holds, and its
42
+ * computed getters already read the record itself. What makes in-place edits visible
43
+ * (`entity.dueDate.setDate(...)`, `entity.meta.tags.push(...)`) is the snapshot: it's taken by
44
+ * value (see toSnapshot), never shares an object with the live record.
36
45
  *
37
- * @param {Record<string, unknown>} record
46
+ * Decoupled from any particular coordinator: `handlers` just needs `save(entity, options)` and
47
+ * `delete(entity, options)`. UnitOfWork supplies handlers bound to itself, the global API ones
48
+ * closing over the connection and hook registry.
49
+ *
50
+ * @param {Record<string, unknown>} record - a fresh fromRow() result; becomes the entity
38
51
  * @param {import('../models/define-model.js').ModelDescriptor} model
39
52
  * @param {string} modelName
40
53
  * @param {{ save: (entity: object, options?: object) => Promise<unknown>, delete: (entity: object, options?: object) => Promise<unknown> }} handlers
@@ -42,10 +55,7 @@ export declare const ENTITY_META: unique symbol;
42
55
  export declare function createEntity(record: Record<string, unknown>, model: import('../models/define-model.js').ModelDescriptor, modelName: string, handlers: {
43
56
  save: (entity: object, options?: object) => Promise<unknown>;
44
57
  delete: (entity: object, options?: object) => Promise<unknown>;
45
- }): {
46
- readonly save: (options: any) => Promise<unknown>;
47
- readonly delete: (options: any) => Promise<unknown>;
48
- };
58
+ }): Record<string, unknown>;
49
59
  /**
50
60
  * Computes the set of fields whose current value differs from the
51
61
  * entity's original (as-loaded) snapshot. Only fields in `model.fields`
@@ -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,21 +1,22 @@
1
1
  {
2
2
  "name": "@kiri-orm/core",
3
- "version": "0.1.7",
3
+ "version": "0.2.0",
4
4
  "description": "A JavaScript ORM for SQLite and Postgres, built on Knex: models defined at runtime, migrations, relations, aggregates and hooks - no code generation.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
7
  "types": "./dist/types/index.d.ts",
8
8
  "exports": {
9
9
  ".": {
10
+ "types": "./dist/types/index.d.ts",
10
11
  "import": "./src/index.js",
11
- "types": "./dist/types/index.d.ts"
12
+ "default": "./src/index.js"
12
13
  }
13
14
  },
14
15
  "dependencies": {
15
16
  "knex": "^3.2.0"
16
17
  },
17
18
  "peerDependencies": {
18
- "better-sqlite3": "^11.0.0",
19
+ "better-sqlite3": "^11.0.0 || ^12.0.0 || ^13.0.0",
19
20
  "pg": "^8.13.0"
20
21
  },
21
22
  "peerDependenciesMeta": {
@@ -49,7 +50,7 @@
49
50
  "migrations",
50
51
  "fast orm",
51
52
  "data",
52
- "framwork",
53
+ "framework",
53
54
  "postgres",
54
55
  "sqlite",
55
56
  "backend"