@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.
- package/README.md +27 -15
- package/dist/types/client/model-handle.d.ts +4 -1
- package/dist/types/connection.d.ts +39 -0
- package/dist/types/crud/database-errors.d.ts +61 -0
- package/dist/types/crud/errors.d.ts +10 -0
- package/dist/types/crud/fast-path.d.ts +73 -0
- package/dist/types/crud/index.d.ts +4 -1
- package/dist/types/crud/insert-many.d.ts +1 -1
- package/dist/types/crud/order.d.ts +28 -0
- package/dist/types/crud/repository.d.ts +5 -3
- package/dist/types/crud/upsert.d.ts +39 -0
- package/dist/types/crud/value.d.ts +39 -0
- package/dist/types/dialect/index.d.ts +1 -1
- package/dist/types/dialect/transaction-guard.d.ts +19 -18
- package/dist/types/domain/compile.d.ts +17 -0
- package/dist/types/fields/filter-value.d.ts +21 -0
- package/dist/types/fields/registry.d.ts +1 -0
- package/dist/types/fields/storage.d.ts +28 -0
- package/dist/types/fields/types/date.d.ts +5 -0
- package/dist/types/fields/types/decimal.d.ts +40 -0
- package/dist/types/global/index.d.ts +1 -0
- package/dist/types/global/transaction.d.ts +10 -13
- package/dist/types/index.d.ts +2 -0
- package/dist/types/meta/snapshot.d.ts +10 -0
- package/dist/types/meta/upsert.d.ts +16 -0
- package/dist/types/migrations/diff.d.ts +25 -2
- package/dist/types/models/constraints.d.ts +27 -0
- package/dist/types/schema/alter-column.d.ts +46 -0
- package/dist/types/schema/build-column.d.ts +11 -0
- package/dist/types/schema/introspect-indexes.d.ts +9 -0
- package/dist/types/transaction/after-commit.d.ts +42 -0
- package/dist/types/transaction/context.d.ts +39 -0
- package/dist/types/uow/entity.d.ts +39 -29
- package/dist/types/uow/hooks.d.ts +6 -1
- package/dist/types/uow/lifecycle.d.ts +82 -0
- package/dist/types/uow/unit-of-work.d.ts +11 -7
- package/package.json +5 -4
- package/src/client/model-handle.js +14 -4
- package/src/client/orm-client.js +10 -5
- package/src/connection.js +34 -4
- package/src/crud/aggregate-filter.js +8 -2
- package/src/crud/aggregate-spec.js +2 -2
- package/src/crud/aggregate.js +16 -5
- package/src/crud/create-many.js +52 -29
- package/src/crud/database-errors.js +107 -0
- package/src/crud/errors.js +14 -0
- package/src/crud/fast-path.js +449 -0
- package/src/crud/index.js +4 -1
- package/src/crud/insert-many.js +25 -7
- package/src/crud/map-filter.js +2 -1
- package/src/crud/order.js +59 -9
- package/src/crud/repository.js +106 -38
- package/src/crud/row-mapping.js +32 -7
- package/src/crud/upsert.js +203 -0
- package/src/crud/value.js +71 -0
- package/src/dialect/index.js +1 -1
- package/src/dialect/transaction-guard.js +216 -45
- package/src/domain/compile.js +85 -12
- package/src/dto/field-schema.js +5 -0
- package/src/fields/default-registry.js +3 -1
- package/src/fields/filter-value.js +87 -0
- package/src/fields/registry.js +1 -0
- package/src/fields/storage.js +50 -0
- package/src/fields/types/date.js +16 -3
- package/src/fields/types/decimal.js +147 -0
- package/src/fields/types/integer.js +7 -0
- package/src/global/connect.js +2 -2
- package/src/global/create-model.js +59 -57
- package/src/global/errors.js +1 -1
- package/src/global/index.js +1 -0
- package/src/global/transaction.js +12 -14
- package/src/index.js +2 -0
- package/src/meta/schema.js +10 -0
- package/src/meta/snapshot.js +5 -0
- package/src/meta/upsert.js +28 -0
- package/src/migrations/describe.js +49 -0
- package/src/migrations/diff.js +50 -7
- package/src/migrations/generate.js +38 -2
- package/src/migrations/render.js +30 -12
- package/src/migrations/runner.js +2 -1
- package/src/models/constraints.js +96 -0
- package/src/models/define-model.js +4 -0
- package/src/models/inheritance.js +4 -1
- package/src/models/registry.js +2 -1
- package/src/relations/cascade-delete.js +2 -1
- package/src/relations/eager-load.js +45 -40
- package/src/reports/report-handle.js +2 -1
- package/src/schema/alter-column.js +219 -0
- package/src/schema/build-column.js +28 -2
- package/src/schema/default-column-builders.js +16 -2
- package/src/schema/introspect-indexes.js +22 -0
- package/src/schema/sync.js +15 -1
- package/src/transaction/after-commit.js +142 -0
- package/src/transaction/context.js +84 -0
- package/src/uow/entity.js +133 -133
- package/src/uow/hooks.js +9 -0
- package/src/uow/lifecycle.js +162 -0
- package/src/uow/unit-of-work.js +44 -56
- 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
|
|
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
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* `
|
|
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
|
-
*
|
|
16
|
-
*
|
|
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
|
package/dist/types/index.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
11
|
-
* entity
|
|
12
|
-
*
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
*
|
|
17
|
-
*
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* `
|
|
32
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
75
|
-
|
|
76
|
-
}): Promise<
|
|
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<
|
|
137
|
+
saveEntity(entity: Record<string, unknown>, options?: {}): Promise<any>;
|
|
133
138
|
/**
|
|
134
|
-
* Called by a tracked entity's `.delete()
|
|
135
|
-
*
|
|
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.
|
|
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
|
-
"
|
|
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
|
-
"
|
|
53
|
+
"framework",
|
|
53
54
|
"postgres",
|
|
54
55
|
"sqlite",
|
|
55
56
|
"backend"
|