@kiri-orm/core 0.1.0 → 0.1.1
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/dist/types/client/create-client.d.ts +32 -0
- package/dist/types/client/index.d.ts +4 -0
- package/dist/types/client/model-handle.d.ts +148 -0
- package/dist/types/client/module.d.ts +54 -0
- package/dist/types/client/orm-client.d.ts +107 -0
- package/dist/types/connection.d.ts +40 -0
- package/dist/types/crud/aggregate-filter.d.ts +36 -0
- package/dist/types/crud/aggregate-paths.d.ts +74 -0
- package/dist/types/crud/aggregate-spec.d.ts +36 -0
- package/dist/types/crud/aggregate.d.ts +59 -0
- package/dist/types/crud/create-many.d.ts +42 -0
- package/dist/types/crud/errors.d.ts +16 -0
- package/dist/types/crud/index.d.ts +12 -0
- package/dist/types/crud/insert-many.d.ts +63 -0
- package/dist/types/crud/map-filter.d.ts +18 -0
- package/dist/types/crud/order.d.ts +58 -0
- package/dist/types/crud/paginate.d.ts +55 -0
- package/dist/types/crud/prepare-write.d.ts +55 -0
- package/dist/types/crud/repository-factory.d.ts +27 -0
- package/dist/types/crud/repository.d.ts +297 -0
- package/dist/types/crud/resolve-where.d.ts +24 -0
- package/dist/types/crud/row-mapping.d.ts +45 -0
- package/dist/types/crud/select.d.ts +74 -0
- package/dist/types/crud/sequence.d.ts +56 -0
- package/dist/types/crud/transaction.d.ts +19 -0
- package/dist/types/diagnostics/index.d.ts +1 -0
- package/dist/types/diagnostics/n-plus-one.d.ts +108 -0
- package/dist/types/dialect/date-bucket.d.ts +46 -0
- package/dist/types/dialect/index.d.ts +1 -0
- package/dist/types/domain/compile.d.ts +30 -0
- package/dist/types/domain/errors.d.ts +20 -0
- package/dist/types/domain/index.d.ts +4 -0
- package/dist/types/domain/parse.d.ts +30 -0
- package/dist/types/dto/field-schema.d.ts +12 -0
- package/dist/types/dto/index.d.ts +3 -0
- package/dist/types/dto/jsdoc-generator.d.ts +29 -0
- package/dist/types/dto/schema-generator.d.ts +59 -0
- package/dist/types/fields/auto-id.d.ts +27 -0
- package/dist/types/fields/cast-value.d.ts +19 -0
- package/dist/types/fields/computed-access.d.ts +22 -0
- package/dist/types/fields/default-for.d.ts +11 -0
- package/dist/types/fields/default-registry.d.ts +9 -0
- package/dist/types/fields/define-computed-field.d.ts +57 -0
- package/dist/types/fields/define-field.d.ts +35 -0
- package/dist/types/fields/errors.d.ts +30 -0
- package/dist/types/fields/index.d.ts +7 -0
- package/dist/types/fields/registry.d.ts +55 -0
- package/dist/types/fields/types/boolean.d.ts +5 -0
- package/dist/types/fields/types/char.d.ts +12 -0
- package/dist/types/fields/types/date.d.ts +10 -0
- package/dist/types/fields/types/datetime.d.ts +11 -0
- package/dist/types/fields/types/enum.d.ts +11 -0
- package/dist/types/fields/types/float.d.ts +11 -0
- package/dist/types/fields/types/integer.d.ts +11 -0
- package/dist/types/fields/types/json.d.ts +9 -0
- package/dist/types/fields/types/text.d.ts +10 -0
- package/dist/types/fields/types/uuid.d.ts +14 -0
- package/dist/types/fields/validate-value.d.ts +14 -0
- package/dist/types/global/connect.d.ts +29 -0
- package/dist/types/global/create-model.d.ts +189 -0
- package/dist/types/global/create-report.d.ts +32 -0
- package/dist/types/global/dto.d.ts +31 -0
- package/dist/types/global/glob.d.ts +12 -0
- package/dist/types/global/identity-scope.d.ts +18 -0
- package/dist/types/global/index.d.ts +12 -0
- package/dist/types/global/load-models.d.ts +31 -0
- package/dist/types/global/migrate.d.ts +68 -0
- package/dist/types/global/n-plus-one.d.ts +42 -0
- package/dist/types/global/sequences.d.ts +19 -0
- package/dist/types/global/state.d.ts +38 -0
- package/dist/types/global/sync-models.d.ts +11 -0
- package/dist/types/global/transaction.d.ts +22 -0
- package/dist/types/index.d.ts +16 -0
- package/dist/types/meta/index.d.ts +5 -0
- package/dist/types/meta/query.d.ts +34 -0
- package/dist/types/meta/reserved-tables.d.ts +10 -0
- package/dist/types/meta/schema.d.ts +18 -0
- package/dist/types/meta/snapshot.d.ts +35 -0
- package/dist/types/meta/sync-meta.d.ts +42 -0
- package/dist/types/meta/upsert.d.ts +81 -0
- package/dist/types/migrations/apply.d.ts +18 -0
- package/dist/types/migrations/describe.d.ts +11 -0
- package/dist/types/migrations/diff.d.ts +141 -0
- package/dist/types/migrations/errors.d.ts +23 -0
- package/dist/types/migrations/foreign-keys-plan.d.ts +27 -0
- package/dist/types/migrations/generate.d.ts +51 -0
- package/dist/types/migrations/index.d.ts +7 -0
- package/dist/types/migrations/render.d.ts +45 -0
- package/dist/types/migrations/runner.d.ts +118 -0
- package/dist/types/models/define-model.d.ts +52 -0
- package/dist/types/models/errors.d.ts +23 -0
- package/dist/types/models/index.d.ts +4 -0
- package/dist/types/models/inheritance.d.ts +73 -0
- package/dist/types/models/naming.d.ts +44 -0
- package/dist/types/models/primary-key.d.ts +39 -0
- package/dist/types/models/registry.d.ts +112 -0
- package/dist/types/relations/attach-detach.d.ts +76 -0
- package/dist/types/relations/cascade-delete.d.ts +29 -0
- package/dist/types/relations/commands.d.ts +84 -0
- package/dist/types/relations/define-relation.d.ts +106 -0
- package/dist/types/relations/eager-load.d.ts +28 -0
- package/dist/types/relations/errors.d.ts +21 -0
- package/dist/types/relations/foreign-keys.d.ts +76 -0
- package/dist/types/relations/index.d.ts +7 -0
- package/dist/types/relations/keys.d.ts +14 -0
- package/dist/types/relations/pivot-schema.d.ts +24 -0
- package/dist/types/relations/with-spec.d.ts +33 -0
- package/dist/types/reports/define-report.d.ts +37 -0
- package/dist/types/reports/errors.d.ts +9 -0
- package/dist/types/reports/index.d.ts +3 -0
- package/dist/types/reports/report-handle.d.ts +58 -0
- package/dist/types/schema/build-column.d.ts +18 -0
- package/dist/types/schema/column-builder-registry.d.ts +30 -0
- package/dist/types/schema/default-column-builders.d.ts +9 -0
- package/dist/types/schema/errors.d.ts +9 -0
- package/dist/types/schema/foreign-keys.d.ts +33 -0
- package/dist/types/schema/index.d.ts +6 -0
- package/dist/types/schema/introspect-foreign-keys.d.ts +23 -0
- package/dist/types/schema/sync.d.ts +63 -0
- package/dist/types/uow/entity.d.ts +80 -0
- package/dist/types/uow/errors.d.ts +8 -0
- package/dist/types/uow/hooks.d.ts +35 -0
- package/dist/types/uow/index.d.ts +5 -0
- package/dist/types/uow/unit-of-work.d.ts +142 -0
- package/dist/types/uow/with-unit-of-work.d.ts +23 -0
- package/package.json +9 -3
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A report definition that doesn't hold up - bad shape (caught when it is defined) or not
|
|
3
|
+
* matching the models it reads (caught the first time it is used, since the models may be
|
|
4
|
+
* registered after the report). `cause` carries the underlying ValidationError, if any.
|
|
5
|
+
*/
|
|
6
|
+
export declare class ReportDefinitionError extends Error {
|
|
7
|
+
reportName: any;
|
|
8
|
+
constructor(reportName: any, message: any, options?: {});
|
|
9
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs a report (see defineReport()). Every call is one SQL statement, whatever the grain,
|
|
3
|
+
* the number of aggregates, or the relations they cross.
|
|
4
|
+
*
|
|
5
|
+
* It is a thin layer over `aggregate()`: the report's fields are translated into `groupBy` /
|
|
6
|
+
* `aggregates`, its `where` is ANDed in front of the caller's filter, and computed fields are applied to
|
|
7
|
+
* the rows afterwards. So everything aggregate() guarantees holds here too - to-many aggregates
|
|
8
|
+
* can't inflate each other, a filter on an aggregate becomes HAVING, buckets are UTC, nulls sort last.
|
|
9
|
+
*
|
|
10
|
+
* The filter you pass to `find()` is written in terms of the REPORT's fields:
|
|
11
|
+
* `[["customerName", "=", "Ada"], ["revenue", ">", 1000]]`. A condition on a key field filters rows
|
|
12
|
+
* before grouping; on an aggregate, groups after.
|
|
13
|
+
*
|
|
14
|
+
* Models are looked up on first use, not at definition, so a report may be defined before the
|
|
15
|
+
* models it reads. The first use also validates the whole definition against them.
|
|
16
|
+
*/
|
|
17
|
+
export declare class ReportHandle {
|
|
18
|
+
#private;
|
|
19
|
+
/**
|
|
20
|
+
* @param {import('./define-report.js').ReportDescriptor} descriptor
|
|
21
|
+
* @param {object} env - how to reach the database and models, looked up at call time so a report
|
|
22
|
+
* follows its client (and a transaction) rather than capturing one connection
|
|
23
|
+
* @param {() => import('knex').Knex} env.db
|
|
24
|
+
* @param {() => import('../models/registry.js').ModelRegistry} env.registry
|
|
25
|
+
* @param {import('../fields/registry.js').FieldTypeRegistry} [env.fieldTypeRegistry]
|
|
26
|
+
*/
|
|
27
|
+
constructor(descriptor: import('./define-report.js').ReportDescriptor, env: {
|
|
28
|
+
db: () => import('knex').Knex;
|
|
29
|
+
registry: () => import('../models/registry.js').ModelRegistry;
|
|
30
|
+
fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry;
|
|
31
|
+
});
|
|
32
|
+
get name(): string;
|
|
33
|
+
/** The (frozen) definition: `{ name, from, where, orderBy, fields }`. */
|
|
34
|
+
get descriptor(): import("./define-report.js").ReportDescriptor;
|
|
35
|
+
/**
|
|
36
|
+
* The rows of the report matching `filter`.
|
|
37
|
+
*
|
|
38
|
+
* @param {Record<string, unknown>|unknown[]} [filter] - in terms of the report's fields
|
|
39
|
+
* @param {{ orderBy?: unknown, limit?: number, offset?: number, trx?: import('knex').Knex.Transaction }} [options]
|
|
40
|
+
* `orderBy` defaults to the report's own. Computed fields can't be filtered or sorted by.
|
|
41
|
+
* @returns {Promise<Array<Record<string, unknown>>>} plain objects, fields in the order the report declares them
|
|
42
|
+
*/
|
|
43
|
+
find(filter?: Record<string, unknown> | unknown[], options?: {
|
|
44
|
+
orderBy?: unknown;
|
|
45
|
+
limit?: number;
|
|
46
|
+
offset?: number;
|
|
47
|
+
trx?: import('knex').Knex.Transaction;
|
|
48
|
+
}): Promise<Array<Record<string, unknown>>>;
|
|
49
|
+
/** The first row (in the report's order) matching `filter`, or `null`. */
|
|
50
|
+
findOne(filter?: {}, options?: {}): Promise<Record<string, unknown>>;
|
|
51
|
+
/**
|
|
52
|
+
* How many rows (groups) the report has for `filter` - ignoring orderBy and paging. One statement.
|
|
53
|
+
* @returns {Promise<number>}
|
|
54
|
+
*/
|
|
55
|
+
count(filter?: {}, options?: {}): Promise<number>;
|
|
56
|
+
/** The SQL (and bindings) `find()` would run, without running it. Handy for inspecting or EXPLAINing a report. */
|
|
57
|
+
toSQL(filter?: {}, options?: {}): import("knex").Knex.SqlNative;
|
|
58
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adds one column to a Knex table builder for the given field, then
|
|
3
|
+
* applies the modifiers common to every field type.
|
|
4
|
+
*
|
|
5
|
+
* Only static defaults become a DB-level DEFAULT clause. Factory
|
|
6
|
+
* function defaults (`default: () => new Date()`) are a JS-side
|
|
7
|
+
* concept for per-record generation (see Phase 1's defaultFor()) and
|
|
8
|
+
* are deliberately NOT translated into SQL here - applying them is a
|
|
9
|
+
* write-path concern for a later phase (the repository/save layer),
|
|
10
|
+
* not a schema concern.
|
|
11
|
+
*
|
|
12
|
+
* @param {import('knex').Knex.CreateTableBuilder} table
|
|
13
|
+
* @param {string} columnName
|
|
14
|
+
* @param {import('../fields/define-field.js').FieldDescriptor} field
|
|
15
|
+
* @param {import('./column-builder-registry.js').ColumnBuilderRegistry} [registry]
|
|
16
|
+
* @returns {import('knex').Knex.ColumnBuilder}
|
|
17
|
+
*/
|
|
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;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type ColumnBuilderFn = (table: import('knex').Knex.CreateTableBuilder, columnName: string, field: object) => import('knex').Knex.ColumnBuilder;
|
|
2
|
+
/**
|
|
3
|
+
* @typedef {(table: import('knex').Knex.CreateTableBuilder, columnName: string, field: object) => import('knex').Knex.ColumnBuilder} ColumnBuilderFn
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Holds field-type -> Knex column-builder mappings. Kept separate from
|
|
7
|
+
* the field type registry (Phase 1) because "how do I validate/cast
|
|
8
|
+
* this value in JS" and "what SQL column does this become" are
|
|
9
|
+
* different concerns - a field type can exist without ever being
|
|
10
|
+
* persisted (a purely computed field, added in a later phase), and a
|
|
11
|
+
* plugin adding a new field type needs to supply both independently.
|
|
12
|
+
*
|
|
13
|
+
* A class rather than a bare object so custom/plugin field types can
|
|
14
|
+
* register their own column builder without mutating a shared global,
|
|
15
|
+
* matching the pattern used by FieldTypeRegistry and ModelRegistry.
|
|
16
|
+
*/
|
|
17
|
+
export declare class ColumnBuilderRegistry {
|
|
18
|
+
#private;
|
|
19
|
+
/**
|
|
20
|
+
* @param {string} fieldType
|
|
21
|
+
* @param {ColumnBuilderFn} buildFn
|
|
22
|
+
*/
|
|
23
|
+
register(fieldType: string, buildFn: ColumnBuilderFn): this;
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} fieldType
|
|
26
|
+
* @returns {ColumnBuilderFn}
|
|
27
|
+
*/
|
|
28
|
+
get(fieldType: string): ColumnBuilderFn;
|
|
29
|
+
has(fieldType: any): boolean;
|
|
30
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ColumnBuilderRegistry } from "./column-builder-registry.js";
|
|
2
|
+
/**
|
|
3
|
+
* Each builder only creates the column itself (type-specific shape).
|
|
4
|
+
* Common modifiers - nullable/unique/index/default - are applied
|
|
5
|
+
* uniformly afterward in build-column.js, so builders here don't
|
|
6
|
+
* repeat that logic per type.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createDefaultColumnBuilderRegistry(): ColumnBuilderRegistry;
|
|
9
|
+
export declare const defaultColumnBuilderRegistry: ColumnBuilderRegistry;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown when a field type has no registered column builder, or when
|
|
3
|
+
* sync() encounters a schema-level problem it can't resolve safely
|
|
4
|
+
* (e.g. a column exists with an incompatible shape it wasn't told how
|
|
5
|
+
* to reconcile - additive-only sync never attempts to fix that itself).
|
|
6
|
+
*/
|
|
7
|
+
export declare class SchemaSyncError extends Error {
|
|
8
|
+
constructor(message: any);
|
|
9
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema-side helpers for foreign keys: the one knex call that declares them, and the order
|
|
3
|
+
* tables must be created in so every foreign key points at a table that already exists.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Declares one foreign key on a Knex table builder (inside createTable or alterTable).
|
|
7
|
+
* @param {import('knex').Knex.TableBuilder} table
|
|
8
|
+
* @param {import('../relations/foreign-keys.js').ForeignKeySpec} fk
|
|
9
|
+
*/
|
|
10
|
+
export declare function addForeignKey(table: import('knex').Knex.TableBuilder, fk: import('../relations/foreign-keys.js').ForeignKeySpec): void;
|
|
11
|
+
/**
|
|
12
|
+
* Orders `models` for creation and decides which foreign keys go inline in each CREATE TABLE.
|
|
13
|
+
*
|
|
14
|
+
* A model is created once every table its keys point at (among `models`) already exists, so
|
|
15
|
+
* the key can sit inside the CREATE TABLE. A key to the table itself (a tree: `parent_id`) is
|
|
16
|
+
* always inline. A genuine cycle (a -> b -> a) has no such order: one table is created first
|
|
17
|
+
* with the keys that can't be satisfied yet split off into `deferred`, to be added with
|
|
18
|
+
* ALTER TABLE once everything exists.
|
|
19
|
+
*
|
|
20
|
+
* Models whose keys point at tables outside `models` (already in the database) are never held up.
|
|
21
|
+
*
|
|
22
|
+
* @param {object[]} models - descriptors to create, in the order to prefer when nothing constrains it
|
|
23
|
+
* @param {(model: object) => import('../relations/foreign-keys.js').ForeignKeySpec[]} foreignKeysFor
|
|
24
|
+
* @returns {{ order: object[], inline: Map<string, object[]>, deferred: Array<{ model: object, fk: object }> }}
|
|
25
|
+
*/
|
|
26
|
+
export declare function planCreation(models: object[], foreignKeysFor: (model: object) => import('../relations/foreign-keys.js').ForeignKeySpec[]): {
|
|
27
|
+
order: object[];
|
|
28
|
+
inline: Map<string, object[]>;
|
|
29
|
+
deferred: Array<{
|
|
30
|
+
model: object;
|
|
31
|
+
fk: object;
|
|
32
|
+
}>;
|
|
33
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { sync } from "./sync.js";
|
|
2
|
+
export { buildColumn } from "./build-column.js";
|
|
3
|
+
export { ColumnBuilderRegistry } from "./column-builder-registry.js";
|
|
4
|
+
export { defaultColumnBuilderRegistry, createDefaultColumnBuilderRegistry, } from "./default-column-builders.js";
|
|
5
|
+
export { SchemaSyncError } from "./errors.js";
|
|
6
|
+
export { listForeignKeys } from "./introspect-foreign-keys.js";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Which dialect a Knex instance talks to, from its client name. */
|
|
2
|
+
export declare function dialectOf(db: any): "other" | "postgres" | "sqlite";
|
|
3
|
+
/**
|
|
4
|
+
* The foreign keys that actually exist on a table, as `{ column, refTable }` pairs. SQLite and
|
|
5
|
+
* Postgres are supported; any other dialect returns `null` ("can't tell"), which callers treat
|
|
6
|
+
* as "don't second-guess the database".
|
|
7
|
+
*
|
|
8
|
+
* @param {import('knex').Knex} db
|
|
9
|
+
* @param {string} tableName
|
|
10
|
+
* @returns {Promise<Array<{ column: string, refTable: string }>|null>}
|
|
11
|
+
*/
|
|
12
|
+
export declare function listForeignKeys(db: import('knex').Knex, tableName: string): Promise<Array<{
|
|
13
|
+
column: string;
|
|
14
|
+
refTable: string;
|
|
15
|
+
}> | null>;
|
|
16
|
+
/**
|
|
17
|
+
* SQLite only enforces foreign keys on connections that have turned `PRAGMA foreign_keys` on,
|
|
18
|
+
* and it is off by default. Connections made by createConnection() turn it on themselves; for
|
|
19
|
+
* one you built yourself this tries, and reports whether it ended up on.
|
|
20
|
+
*
|
|
21
|
+
* @returns {Promise<boolean|null>} true/false for SQLite, null for other dialects
|
|
22
|
+
*/
|
|
23
|
+
export declare function ensureSqliteForeignKeys(db: any): Promise<boolean | null>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export type SyncResult = {
|
|
2
|
+
tablesCreated: string[];
|
|
3
|
+
/**
|
|
4
|
+
* - tableName -> column names added
|
|
5
|
+
*/
|
|
6
|
+
columnsAdded: Record<string, string[]>;
|
|
7
|
+
/**
|
|
8
|
+
* - e.g. "post.author_id -> user.id"
|
|
9
|
+
*/
|
|
10
|
+
foreignKeysAdded: string[];
|
|
11
|
+
/**
|
|
12
|
+
* - things sync() didn't change but you should know about
|
|
13
|
+
*/
|
|
14
|
+
warnings: string[];
|
|
15
|
+
meta: import('../meta/sync-meta.js').MetaSyncResult;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {Object} SyncResult
|
|
19
|
+
* @property {string[]} tablesCreated
|
|
20
|
+
* @property {Record<string, string[]>} columnsAdded - tableName -> column names added
|
|
21
|
+
* @property {string[]} foreignKeysAdded - e.g. "post.author_id -> user.id"
|
|
22
|
+
* @property {string[]} warnings - things sync() didn't change but you should know about
|
|
23
|
+
* @property {import('../meta/sync-meta.js').MetaSyncResult} meta
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Syncs every model registered on `modelRegistry` to real tables in
|
|
27
|
+
* `db`. Additive-only: creates tables/columns that don't exist yet,
|
|
28
|
+
* never drops or alters existing ones. Safe to call repeatedly -
|
|
29
|
+
* running it twice in a row with no model changes is a no-op on the
|
|
30
|
+
* second call (idempotent).
|
|
31
|
+
*
|
|
32
|
+
* This is deliberately simple for Phase 3. Real migration files with
|
|
33
|
+
* diffing, renames, and reversibility come in Phase 6, once the
|
|
34
|
+
* DB-persisted metamodel from Phase 4 exists to diff against - trying
|
|
35
|
+
* to detect renames vs drop+add from live schema introspection alone
|
|
36
|
+
* is exactly the kind of guess that goes wrong silently, so it's not
|
|
37
|
+
* attempted here.
|
|
38
|
+
*
|
|
39
|
+
* As of Phase 4, sync() also ensures the `_meta_models`/`_meta_fields`
|
|
40
|
+
* tables exist and upserts them to reflect the current registry state
|
|
41
|
+
* (see the `meta` module), so the schema stays queryable as data.
|
|
42
|
+
*
|
|
43
|
+
* As of Phase 7, sync() also ensures the pivot table for every
|
|
44
|
+
* `belongsToMany` relation exists (see the `relations` module).
|
|
45
|
+
*
|
|
46
|
+
* Every `belongsTo` relation becomes a real FOREIGN KEY with its `onDelete` action, so the
|
|
47
|
+
* database - not the ORM - enforces referential integrity. New tables are created in
|
|
48
|
+
* dependency order so each key points at a table that exists. A table that already exists
|
|
49
|
+
* is not altered, except for the columns it's missing (which bring their keys with them);
|
|
50
|
+
* existing foreign key columns that lack their constraint are reported in `warnings`, and
|
|
51
|
+
* added when `addMissingForeignKeys` is set (this can fail if rows already violate it).
|
|
52
|
+
*
|
|
53
|
+
* @param {import('knex').Knex} db
|
|
54
|
+
* @param {import('../models/registry.js').ModelRegistry} modelRegistry
|
|
55
|
+
* @param {Object} [options]
|
|
56
|
+
* @param {import('./column-builder-registry.js').ColumnBuilderRegistry} [options.columnBuilderRegistry]
|
|
57
|
+
* @param {boolean} [options.addMissingForeignKeys] - add constraints that existing tables lack
|
|
58
|
+
* @returns {Promise<SyncResult>}
|
|
59
|
+
*/
|
|
60
|
+
export declare function sync(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, options?: {
|
|
61
|
+
columnBuilderRegistry?: import('./column-builder-registry.js').ColumnBuilderRegistry;
|
|
62
|
+
addMissingForeignKeys?: boolean;
|
|
63
|
+
}): Promise<SyncResult>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Symbol-keyed so entity metadata never shows up in Object.keys(),
|
|
3
|
+
* for...in, JSON.stringify(), or spread - the entity looks and
|
|
4
|
+
* behaves exactly like the plain record Repository already returns,
|
|
5
|
+
* with tracking bolted on invisibly rather than requiring a different
|
|
6
|
+
* shape to work with.
|
|
7
|
+
*/
|
|
8
|
+
export declare const ENTITY_META: unique symbol;
|
|
9
|
+
/**
|
|
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.
|
|
15
|
+
*
|
|
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
|
+
*
|
|
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.
|
|
36
|
+
*
|
|
37
|
+
* @param {Record<string, unknown>} record
|
|
38
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
39
|
+
* @param {string} modelName
|
|
40
|
+
* @param {{ save: (entity: object, options?: object) => Promise<unknown>, delete: (entity: object, options?: object) => Promise<unknown> }} handlers
|
|
41
|
+
*/
|
|
42
|
+
export declare function createEntity(record: Record<string, unknown>, model: import('../models/define-model.js').ModelDescriptor, modelName: string, handlers: {
|
|
43
|
+
save: (entity: object, options?: object) => Promise<unknown>;
|
|
44
|
+
delete: (entity: object, options?: object) => Promise<unknown>;
|
|
45
|
+
}): {
|
|
46
|
+
readonly save: (options: any) => Promise<unknown>;
|
|
47
|
+
readonly delete: (options: any) => Promise<unknown>;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Computes the set of fields whose current value differs from the
|
|
51
|
+
* entity's original (as-loaded) snapshot. Only fields in `model.fields`
|
|
52
|
+
* are considered - relation values attached by eager loading are
|
|
53
|
+
* never part of this, since they aren't persisted columns.
|
|
54
|
+
*
|
|
55
|
+
* @param {Record<string, unknown>} entity
|
|
56
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
57
|
+
* @returns {Record<string, unknown>}
|
|
58
|
+
*/
|
|
59
|
+
export declare function diffEntity(entity: Record<string, unknown>, model: import('../models/define-model.js').ModelDescriptor): Record<string, unknown>;
|
|
60
|
+
/**
|
|
61
|
+
* Folds a freshly read `record` into an entity that is already tracked (identity-map hit)
|
|
62
|
+
* and returns that entity.
|
|
63
|
+
*
|
|
64
|
+
* The rule the identity map has always had still holds: the in-memory instance wins for any
|
|
65
|
+
* field it already has, because it may carry unsaved edits. What changed with `select` is
|
|
66
|
+
* that the two sides can hold DIFFERENT fields - the entity may have been read partially, or the
|
|
67
|
+
* new read may be - so:
|
|
68
|
+
*
|
|
69
|
+
* - fields the entity doesn't have yet are filled in from the record, in both the live
|
|
70
|
+
* value and the `original` snapshot, so they start out clean (not dirty);
|
|
71
|
+
* - computed fields the record defines that the entity lacks are defined on it, but only
|
|
72
|
+
* once everything they depend on is loaded on the entity;
|
|
73
|
+
* - eager-loaded relations are view data, never edited, so they are always refreshed.
|
|
74
|
+
*
|
|
75
|
+
* @param {Record<string, unknown>} entity
|
|
76
|
+
* @param {Record<string, unknown>} record
|
|
77
|
+
* @param {import('../models/define-model.js').ModelDescriptor} model
|
|
78
|
+
* @returns {Record<string, unknown>} the same entity
|
|
79
|
+
*/
|
|
80
|
+
export declare function mergeRecordIntoEntity(entity: Record<string, unknown>, record: Record<string, unknown>, model: import('../models/define-model.js').ModelDescriptor): Record<string, unknown>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by HookRegistry#on() when registering a hook under a name
|
|
3
|
+
* that isn't one of the known lifecycle hooks - catches a typo'd hook
|
|
4
|
+
* name at registration time rather than it silently never firing.
|
|
5
|
+
*/
|
|
6
|
+
export declare class InvalidHookNameError extends Error {
|
|
7
|
+
constructor(message: any);
|
|
8
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The complete set of lifecycle hooks a model can register for.
|
|
3
|
+
* `beforeSave`/`afterSave` fire around BOTH create and update (in
|
|
4
|
+
* addition to the more specific `*Create`/`*Update` hooks), for
|
|
5
|
+
* cross-cutting concerns (e.g. normalization) that don't care which
|
|
6
|
+
* path a write took.
|
|
7
|
+
*/
|
|
8
|
+
export declare const HOOK_NAMES: string[];
|
|
9
|
+
/**
|
|
10
|
+
* Holds lifecycle hooks registered per model and runs them in
|
|
11
|
+
* registration order. If a hook throws (or its returned promise
|
|
12
|
+
* rejects), remaining hooks for that phase are never run and the
|
|
13
|
+
* error propagates straight to the caller - a `before*` hook throwing
|
|
14
|
+
* means the underlying create/update/delete never happens at all,
|
|
15
|
+
* since UnitOfWork always awaits the relevant `before*` hooks before
|
|
16
|
+
* issuing the write.
|
|
17
|
+
*/
|
|
18
|
+
export declare class HookRegistry {
|
|
19
|
+
#private;
|
|
20
|
+
/**
|
|
21
|
+
* @param {string} modelName
|
|
22
|
+
* @param {typeof HOOK_NAMES[number]} hookName
|
|
23
|
+
* @param {(...args: unknown[]) => unknown} fn
|
|
24
|
+
*/
|
|
25
|
+
on(modelName: string, hookName: typeof HOOK_NAMES[number], fn: (...args: unknown[]) => unknown): this;
|
|
26
|
+
/**
|
|
27
|
+
* Runs every hook registered for `modelName`/`hookName`, in
|
|
28
|
+
* registration order, awaiting each before starting the next.
|
|
29
|
+
*
|
|
30
|
+
* @param {string} modelName
|
|
31
|
+
* @param {typeof HOOK_NAMES[number]} hookName
|
|
32
|
+
* @param {unknown[]} args
|
|
33
|
+
*/
|
|
34
|
+
run(modelName: string, hookName: typeof HOOK_NAMES[number], ...args: unknown[]): Promise<void>;
|
|
35
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { UnitOfWork } from "./unit-of-work.js";
|
|
2
|
+
export { withUnitOfWork } from "./with-unit-of-work.js";
|
|
3
|
+
export { HookRegistry, HOOK_NAMES } from "./hooks.js";
|
|
4
|
+
export { ENTITY_META, diffEntity } from "./entity.js";
|
|
5
|
+
export { InvalidHookNameError } from "./errors.js";
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { HookRegistry } from "./hooks.js";
|
|
2
|
+
/**
|
|
3
|
+
* Ties together identity-mapped loading, dirty-tracked saving, and
|
|
4
|
+
* lifecycle hooks for one logical unit of work - a single request, a
|
|
5
|
+
* single transaction, or any other scope the caller chooses by
|
|
6
|
+
* however long they keep the instance alive. There's no implicit
|
|
7
|
+
* global scope: creating a `new UnitOfWork(...)` per request (or per
|
|
8
|
+
* transaction, via `withUnitOfWork()`) IS what scopes its identity
|
|
9
|
+
* map, deliberately - baking in a framework-specific request
|
|
10
|
+
* lifecycle here would overreach what a core ORM library should own.
|
|
11
|
+
*
|
|
12
|
+
* `find`/`findOne` return tracked entities (see entity.js) rather
|
|
13
|
+
* than the plain objects `Repository` returns directly - loading the
|
|
14
|
+
* same row twice within one `UnitOfWork` returns the exact same
|
|
15
|
+
* object reference both times (the identity map), and each entity
|
|
16
|
+
* gets a `.save()` that only sends the fields that actually changed
|
|
17
|
+
* since it was loaded (dirty tracking, see diffEntity()).
|
|
18
|
+
*/
|
|
19
|
+
export declare class UnitOfWork {
|
|
20
|
+
#private;
|
|
21
|
+
db: import("knex").Knex<any, any[]>;
|
|
22
|
+
modelRegistry: import("../models/registry.js").ModelRegistry;
|
|
23
|
+
fieldTypeRegistry: import("../fields/registry.js").FieldTypeRegistry;
|
|
24
|
+
hooks: HookRegistry;
|
|
25
|
+
trx: import("knex").Knex.Transaction<any, any[]> | undefined;
|
|
26
|
+
identityMap: Map<any, any>;
|
|
27
|
+
/**
|
|
28
|
+
* @param {import('knex').Knex} db
|
|
29
|
+
* @param {import('../models/registry.js').ModelRegistry} modelRegistry
|
|
30
|
+
* @param {Object} [options]
|
|
31
|
+
* @param {import('../fields/registry.js').FieldTypeRegistry} [options.fieldTypeRegistry]
|
|
32
|
+
* @param {HookRegistry} [options.hooks]
|
|
33
|
+
* @param {import('knex').Knex.Transaction} [options.trx]
|
|
34
|
+
*/
|
|
35
|
+
constructor(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, options?: {
|
|
36
|
+
fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry;
|
|
37
|
+
hooks?: HookRegistry;
|
|
38
|
+
trx?: import('knex').Knex.Transaction;
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} modelName
|
|
42
|
+
* @param {Record<string, unknown>|unknown[]} [filter]
|
|
43
|
+
* @param {{ limit?: number, with?: string[] }} [options]
|
|
44
|
+
* @returns {Promise<Record<string, unknown>[]>}
|
|
45
|
+
*/
|
|
46
|
+
find(modelName: string, filter?: Record<string, unknown> | unknown[], options?: {
|
|
47
|
+
limit?: number;
|
|
48
|
+
with?: string[];
|
|
49
|
+
}): Promise<Record<string, unknown>[]>;
|
|
50
|
+
/**
|
|
51
|
+
* @param {string} modelName
|
|
52
|
+
* @param {Record<string, unknown>|unknown[]} [filter]
|
|
53
|
+
* @param {{ with?: string[] }} [options]
|
|
54
|
+
* @returns {Promise<Record<string, unknown>|null>}
|
|
55
|
+
*/
|
|
56
|
+
findOne(modelName: string, filter?: Record<string, unknown> | unknown[], options?: {
|
|
57
|
+
with?: string[];
|
|
58
|
+
}): Promise<Record<string, unknown> | null>;
|
|
59
|
+
/**
|
|
60
|
+
* Creates a record and returns it as a tracked entity. Runs
|
|
61
|
+
* `beforeCreate`/`beforeSave` (which may mutate `data` before the
|
|
62
|
+
* insert happens) then `afterCreate`/`afterSave` (with the final
|
|
63
|
+
* entity) around the write.
|
|
64
|
+
*
|
|
65
|
+
* `data` may include `hasMany` / `belongsToMany` relation values as
|
|
66
|
+
* `Command.*()` entries or ids; related records created that way go
|
|
67
|
+
* through their own model's hooks too. See createMany().
|
|
68
|
+
*
|
|
69
|
+
* @param {string} modelName
|
|
70
|
+
* @param {Record<string, unknown>} data
|
|
71
|
+
* @param {{ trx?: import('knex').Knex.Transaction }} [options]
|
|
72
|
+
* @returns {Promise<Record<string, unknown>>}
|
|
73
|
+
*/
|
|
74
|
+
create(modelName: string, data: Record<string, unknown>, options?: {
|
|
75
|
+
trx?: import('knex').Knex.Transaction;
|
|
76
|
+
}): Promise<Record<string, unknown>>;
|
|
77
|
+
/**
|
|
78
|
+
* Creates many records as tracked entities with a query count that
|
|
79
|
+
* does not grow with the number of records, including any
|
|
80
|
+
* `hasMany` / `belongsToMany` relations named in their payloads.
|
|
81
|
+
* See `createRecords()` (crud/create-many.js) for the mechanics.
|
|
82
|
+
*
|
|
83
|
+
* Per-row hooks still run for every row, in order:
|
|
84
|
+
* `beforeCreate`/`beforeSave` for all rows before anything is
|
|
85
|
+
* written, `afterCreate`/`afterSave` after the whole batch commits
|
|
86
|
+
* (parents first, then any nested children). All-or-nothing.
|
|
87
|
+
*
|
|
88
|
+
* @param {string} modelName
|
|
89
|
+
* @param {Record<string, unknown>[]} dataList
|
|
90
|
+
* @param {{ trx?: import('knex').Knex.Transaction, chunkSize?: number }} [options]
|
|
91
|
+
* @returns {Promise<Record<string, unknown>[]>} entities, in input order
|
|
92
|
+
*/
|
|
93
|
+
createMany(modelName: string, dataList: Record<string, unknown>[], options?: {
|
|
94
|
+
trx?: import('knex').Knex.Transaction;
|
|
95
|
+
chunkSize?: number;
|
|
96
|
+
}): Promise<Record<string, unknown>[]>;
|
|
97
|
+
/**
|
|
98
|
+
* Called by a tracked entity's `.save()`. Computes the dirty fields
|
|
99
|
+
* (see diffEntity()) and, if there are none, issues no SQL at all -
|
|
100
|
+
* an unmodified entity's save() is a true no-op. Otherwise runs
|
|
101
|
+
* `beforeUpdate`/`beforeSave` (which may add to `dirty`), issues an
|
|
102
|
+
* UPDATE containing only the dirty columns, refreshes the entity's
|
|
103
|
+
* original snapshot to the new baseline, then runs
|
|
104
|
+
* `afterUpdate`/`afterSave`.
|
|
105
|
+
*
|
|
106
|
+
* If the save fails - a `before*` hook throws, or the DB write
|
|
107
|
+
* itself fails - the entity's live field values are reverted back
|
|
108
|
+
* to `original` before the error propagates. Without this, a
|
|
109
|
+
* rejected save leaves the entity showing whatever the caller had
|
|
110
|
+
* just assigned (never actually persisted) indefinitely, silently
|
|
111
|
+
* diverging from the database until something else happens to
|
|
112
|
+
* overwrite it - found while testing a transition-guard hook that
|
|
113
|
+
* correctly rejected an update, then noticing the in-memory entity
|
|
114
|
+
* kept reporting the rejected value as if it had taken effect.
|
|
115
|
+
*
|
|
116
|
+
* Hooks receive a third argument, `original`: a snapshot of the
|
|
117
|
+
* entity's field values as they were BEFORE this save (captured
|
|
118
|
+
* before `entity`/`original` are mutated with the new values, so
|
|
119
|
+
* before* and after* hooks both see the same pre-edit snapshot
|
|
120
|
+
* consistently). This matters because `entity` itself holds LIVE
|
|
121
|
+
* values - by the time a `beforeUpdate` hook runs, the caller has
|
|
122
|
+
* already mutated `entity` to the new value, so a hook checking
|
|
123
|
+
* `entity.status === "shipped"` to guard against cancelling an
|
|
124
|
+
* already-shipped order would actually see `"cancelled"` (the new
|
|
125
|
+
* value), not `"shipped"` (what it was) - exactly the bug this
|
|
126
|
+
* `original` parameter exists to prevent, found while writing a
|
|
127
|
+
* transition-guard hook for a multi-module example app.
|
|
128
|
+
*
|
|
129
|
+
* @param {Record<string, unknown>} entity
|
|
130
|
+
* @param {{}} [options]
|
|
131
|
+
*/
|
|
132
|
+
saveEntity(entity: Record<string, unknown>, options?: {}): Promise<Record<string, unknown>>;
|
|
133
|
+
/**
|
|
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`.
|
|
137
|
+
*
|
|
138
|
+
* @param {Record<string, unknown>} entity
|
|
139
|
+
* @param {{}} [options]
|
|
140
|
+
*/
|
|
141
|
+
deleteEntity(entity: Record<string, unknown>, options?: {}): Promise<boolean>;
|
|
142
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { UnitOfWork } from "./unit-of-work.js";
|
|
2
|
+
/**
|
|
3
|
+
* Runs `fn` with a `UnitOfWork` bound to a fresh Knex transaction -
|
|
4
|
+
* every load/save/delete performed through it is part of that one
|
|
5
|
+
* transaction, and if `fn` throws, the transaction rolls back
|
|
6
|
+
* (Knex's own behavior, same as `runInTransaction` in the crud
|
|
7
|
+
* module). The identity map's scope is exactly this call: a fresh
|
|
8
|
+
* `UnitOfWork` (and thus a fresh, empty identity map) is created for
|
|
9
|
+
* every invocation.
|
|
10
|
+
*
|
|
11
|
+
* @template T
|
|
12
|
+
* @param {import('knex').Knex} db
|
|
13
|
+
* @param {import('../models/registry.js').ModelRegistry} modelRegistry
|
|
14
|
+
* @param {(uow: UnitOfWork) => Promise<T>} fn
|
|
15
|
+
* @param {Object} [options]
|
|
16
|
+
* @param {import('../fields/registry.js').FieldTypeRegistry} [options.fieldTypeRegistry]
|
|
17
|
+
* @param {import('./hooks.js').HookRegistry} [options.hooks]
|
|
18
|
+
* @returns {Promise<T>}
|
|
19
|
+
*/
|
|
20
|
+
export declare function withUnitOfWork<T>(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, fn: (uow: UnitOfWork) => Promise<T>, options?: {
|
|
21
|
+
fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry;
|
|
22
|
+
hooks?: import('./hooks.js').HookRegistry;
|
|
23
|
+
}): Promise<T>;
|
package/package.json
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kiri-orm/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./src/index.js",
|
|
6
|
+
"types": "./dist/types/index.d.ts",
|
|
6
7
|
"exports": {
|
|
7
|
-
".":
|
|
8
|
+
".": {
|
|
9
|
+
"import": "./src/index.js",
|
|
10
|
+
"types": "./dist/types/index.d.ts"
|
|
11
|
+
}
|
|
8
12
|
},
|
|
9
13
|
"dependencies": {
|
|
10
14
|
"knex": "^3.1.0"
|
|
@@ -24,13 +28,15 @@
|
|
|
24
28
|
"devDependencies": {
|
|
25
29
|
"better-sqlite3": "^11.5.0",
|
|
26
30
|
"pg": "^8.13.1",
|
|
31
|
+
"typescript": "^7.0.2",
|
|
27
32
|
"vitest": "^2.1.4"
|
|
28
33
|
},
|
|
29
34
|
"files": [
|
|
30
35
|
"src",
|
|
31
36
|
"README.md",
|
|
32
37
|
"LICENSE",
|
|
33
|
-
"package.json"
|
|
38
|
+
"package.json",
|
|
39
|
+
"dist"
|
|
34
40
|
],
|
|
35
41
|
"license": "MIT",
|
|
36
42
|
"publishConfig": {
|