@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
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The value a filter binds for a stored field, given its operator (since 0.2.0). Every filter path
3
+ * uses it - domains, plain-object filters, the direct SQL path and Knex - so they can't disagree.
4
+ *
5
+ * Two types need more than cast-then-store:
6
+ *
7
+ * - `json`: bound as JSON text, exactly as writes store it (`JSON.stringify`). Before, an object
8
+ * reached SQLite's driver as an object (a TypeError), a string reached Postgres' jsonb as bare
9
+ * text (invalid JSON), and a string on SQLite never matched its stored JSON text. SQLite compares
10
+ * the text itself, so an object matches only with its keys in the stored order; Postgres' jsonb
11
+ * ignores key order.
12
+ * - `decimal`: compared exactly. A value with more decimal places than the field's scale used to be
13
+ * rounded first (a number) or refused (a string), so `["price", "<", 2.001]` became `< 2.00` and
14
+ * left out a row at 2.00. See decimalFilterValue().
15
+ *
16
+ * @param {object} field - the field definition
17
+ * @param {string} op - the domain operator ("=" for a plain-object filter)
18
+ * @param {unknown} value - one value (a single item of an `in` list)
19
+ * @param {import('./registry.js').FieldTypeRegistry} fieldTypeRegistry
20
+ */
21
+ export declare function filterValue(field: object, op: string, value: unknown, fieldTypeRegistry: import('./registry.js').FieldTypeRegistry): any;
@@ -41,6 +41,7 @@ export type FieldTypeDefinition = {
41
41
  */
42
42
  export declare class FieldTypeRegistry {
43
43
  #private;
44
+ version: any;
44
45
  /**
45
46
  * @param {FieldTypeDefinition} definition
46
47
  */
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The form a field value takes in the database, when that differs per database (since 0.2.0).
3
+ *
4
+ * A field type can define:
5
+ * - `toStorage(field, value)` -> the value to bind (often a DialectValue, resolved per database);
6
+ * - `fromStorage(field, value, dialect)` -> the stored value turned back into a field value,
7
+ * before cast().
8
+ * `decimal` uses both: SQLite stores it as a scaled integer, Postgres as numeric text.
9
+ */
10
+ /**
11
+ * A bound value that depends on the database: `resolve(dialect)` returns what to send. Writes and
12
+ * filter values carry these; every connection the ORM instruments resolves them when Knex prepares
13
+ * a query's bindings (dialect/transaction-guard.js), so the code building a query never needs to
14
+ * know which database it will run on.
15
+ */
16
+ export declare class DialectValue {
17
+ resolve: (dialect: "sqlite" | "postgres") => unknown;
18
+ /** @param {(dialect: "sqlite"|"postgres") => unknown} resolve */
19
+ constructor(resolve: (dialect: "sqlite" | "postgres") => unknown);
20
+ }
21
+ /** A cast field value in its storage form (a filter binding, a column value to write). */
22
+ export declare function toStorage(field: any, value: any, fieldTypeRegistry: any): any;
23
+ /** A stored value back to what cast() expects. */
24
+ export declare function fromStorage(field: any, value: any, dialect: any, fieldTypeRegistry: any): any;
25
+ /** Resolves DialectValues in a list of bindings for `dialect`; anything else passes through. */
26
+ export declare function resolveDialectValues(bindings: any, dialect: any): any;
27
+ /** "sqlite" | "postgres" for a Knex client (or null for another). */
28
+ export declare function dialectOfClient(client: any): "postgres" | "sqlite" | null;
@@ -1,10 +1,10 @@
1
- /**
2
- * A calendar date (no time component, though the canonical runtime
3
- * representation is still a JS Date - the schema-sync layer in a later
4
- * phase is what maps this to a DATE vs DATETIME column per dialect).
5
- */
6
1
  export declare const dateType: {
7
2
  name: string;
3
+ /**
4
+ * A stored Postgres `date` arrives as a Date the pg driver built at LOCAL midnight of that day,
5
+ * so it is read back with local getters - unlike a Date passed in, which means its UTC day.
6
+ */
7
+ fromStorage(field: any, value: any, dialect: any): any;
8
8
  validate(field: any, value: any): string[];
9
- cast(field: any, value: any): any;
9
+ cast(field: any, value: any): string;
10
10
  };
@@ -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
+ };
@@ -0,0 +1,3 @@
1
+ export declare class SaveDeletedError extends Error {
2
+ constructor(message: any);
3
+ }
@@ -2,6 +2,7 @@ export { connect, getConnection, disconnect } from "./connect.js";
2
2
  export { createModel, extendModel, defineMixin } from "./create-model.js";
3
3
  export { loadModels } from "./load-models.js";
4
4
  export { syncModels } from "./sync-models.js";
5
+ export { normalizeDates } from "./normalize-dates.js";
5
6
  export { syncSequences } from "./sequences.js";
6
7
  export { createReport } from "./create-report.js";
7
8
  export { detectNPlusOne, assertNoNPlusOne, watchNPlusOne } from "./n-plus-one.js";
@@ -10,3 +11,4 @@ export { withIdentityMap } from "./identity-scope.js";
10
11
  export { diffModels, migrateModels, getDefaultModelRegistry } from "./migrate.js";
11
12
  export { generateModelDTOs, generateAllModelDTOs, generateModelJSDoc } from "./dto.js";
12
13
  export { __resetGlobalStateForTests } from "./state.js";
14
+ export { SaveDeletedError } from "./errors.js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Rewrites `date` values written by 0.1.0-0.1.2 (epoch milliseconds on SQLite) as "YYYY-MM-DD"
3
+ * text, for every model created with createModel() - or only `options.models`. Since 0.1.7.
4
+ * See normalizeDateColumns() for the details; on Postgres it does nothing and returns [].
5
+ *
6
+ * @param {{ models?: string[] }} [options]
7
+ * @returns {Promise<import('../schema/normalize-dates.js').NormalizedDateColumn[]>}
8
+ */
9
+ export declare function normalizeDates(options?: {
10
+ models?: string[];
11
+ }): Promise<import('../schema/normalize-dates.js').NormalizedDateColumn[]>;
@@ -22,6 +22,8 @@ import { HookRegistry } from "../uow/hooks.js";
22
22
  */
23
23
  export declare const state: {
24
24
  connection: null;
25
+ /** Whether connect() built `connection` from a config (so it may close it when replaced). */
26
+ ownsConnection: boolean;
25
27
  registry: ModelRegistry;
26
28
  hooks: HookRegistry;
27
29
  wrappers: Map<any, any>;
@@ -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";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Creates one of the ORM's own bookkeeping tables (`_meta_models`, `_meta_fields`,
3
+ * `_meta_migrations`) if it doesn't exist yet.
4
+ *
5
+ * "Check, then create" races when two processes start on a fresh database together (two app
6
+ * instances running `migrate:up` or `syncModels()` on their first deploy): both see no table,
7
+ * and the slower CREATE fails with "already exists" (before 0.1.7 that failed the whole run).
8
+ * The losing CREATE is now ignored when the table turns out to exist after all - the other
9
+ * process made it, with the same definition.
10
+ *
11
+ * @param {import('knex').Knex} db
12
+ * @param {string} name
13
+ * @param {(table: import('knex').Knex.CreateTableBuilder) => void} define
14
+ */
15
+ export declare function createTableOnce(db: import('knex').Knex, name: string, define: (table: import('knex').Knex.CreateTableBuilder) => void): Promise<void>;
@@ -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;
@@ -21,4 +21,4 @@
21
21
  * @param {import('knex').Knex} db
22
22
  * @param {import('../models/registry.js').ModelRegistry} modelRegistry
23
23
  */
24
- export declare function ensurePivotTables(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry): Promise<void>;
24
+ export declare function ensurePivotTables(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, columnBuilderRegistry?: import("../index.js").ColumnBuilderRegistry): Promise<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;
@@ -4,3 +4,4 @@ export { ColumnBuilderRegistry } from "./column-builder-registry.js";
4
4
  export { defaultColumnBuilderRegistry, createDefaultColumnBuilderRegistry, } from "./default-column-builders.js";
5
5
  export { SchemaSyncError } from "./errors.js";
6
6
  export { listForeignKeys } from "./introspect-foreign-keys.js";
7
+ export { normalizeDateColumns } from "./normalize-dates.js";
@@ -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,41 @@
1
+ export type NormalizedDateColumn = {
2
+ model: string;
3
+ field: string;
4
+ table: string;
5
+ column: string;
6
+ /**
7
+ * - values rewritten
8
+ */
9
+ rows: number;
10
+ };
11
+ /**
12
+ * @typedef {Object} NormalizedDateColumn
13
+ * @property {string} model
14
+ * @property {string} field
15
+ * @property {string} table
16
+ * @property {string} column
17
+ * @property {number} rows - values rewritten
18
+ */
19
+ /**
20
+ * Rewrites `date` values that SQLite still holds as epoch milliseconds into the "YYYY-MM-DD"
21
+ * text the ORM has written since 0.1.3. Since 0.1.7.
22
+ *
23
+ * 0.1.0-0.1.2 stored `date` fields as epoch ms (Knex binds a Date as its valueOf() on SQLite).
24
+ * 0.1.6+ reads those rows fine, but a column holding both forms still compares and sorts wrong
25
+ * in SQL - SQLite orders every number before every text - so a filter like
26
+ * `[["on", ">=", "2024-01-01"]]` or `orderBy: "on"` gives wrong results until it's rewritten.
27
+ *
28
+ * Each old value becomes the calendar day the read path already shows for it (see the `date`
29
+ * field type's cast), so nothing visible changes - only the stored form. Runs in one transaction;
30
+ * safe to run again (it only touches numeric values). Postgres stores a real `date` and has
31
+ * nothing to rewrite, so it returns an empty list there.
32
+ *
33
+ * @param {import('knex').Knex} db
34
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
35
+ * @param {{ models?: string[], fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry }} [options]
36
+ * @returns {Promise<NormalizedDateColumn[]>} one entry per date column that had values to rewrite
37
+ */
38
+ export declare function normalizeDateColumns(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, options?: {
39
+ models?: string[];
40
+ fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry;
41
+ }): Promise<NormalizedDateColumn[]>;
@@ -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`