@kiri-orm/core 0.1.0 → 0.1.2

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 (130) hide show
  1. package/README.md +48 -3
  2. package/dist/types/client/create-client.d.ts +32 -0
  3. package/dist/types/client/index.d.ts +4 -0
  4. package/dist/types/client/model-handle.d.ts +148 -0
  5. package/dist/types/client/module.d.ts +54 -0
  6. package/dist/types/client/orm-client.d.ts +107 -0
  7. package/dist/types/connection.d.ts +40 -0
  8. package/dist/types/crud/aggregate-filter.d.ts +36 -0
  9. package/dist/types/crud/aggregate-paths.d.ts +74 -0
  10. package/dist/types/crud/aggregate-spec.d.ts +36 -0
  11. package/dist/types/crud/aggregate.d.ts +59 -0
  12. package/dist/types/crud/create-many.d.ts +42 -0
  13. package/dist/types/crud/errors.d.ts +16 -0
  14. package/dist/types/crud/index.d.ts +12 -0
  15. package/dist/types/crud/insert-many.d.ts +63 -0
  16. package/dist/types/crud/map-filter.d.ts +18 -0
  17. package/dist/types/crud/order.d.ts +58 -0
  18. package/dist/types/crud/paginate.d.ts +55 -0
  19. package/dist/types/crud/prepare-write.d.ts +55 -0
  20. package/dist/types/crud/repository-factory.d.ts +27 -0
  21. package/dist/types/crud/repository.d.ts +297 -0
  22. package/dist/types/crud/resolve-where.d.ts +24 -0
  23. package/dist/types/crud/row-mapping.d.ts +45 -0
  24. package/dist/types/crud/select.d.ts +74 -0
  25. package/dist/types/crud/sequence.d.ts +56 -0
  26. package/dist/types/crud/transaction.d.ts +19 -0
  27. package/dist/types/diagnostics/index.d.ts +1 -0
  28. package/dist/types/diagnostics/n-plus-one.d.ts +108 -0
  29. package/dist/types/dialect/date-bucket.d.ts +46 -0
  30. package/dist/types/dialect/index.d.ts +1 -0
  31. package/dist/types/domain/compile.d.ts +30 -0
  32. package/dist/types/domain/errors.d.ts +20 -0
  33. package/dist/types/domain/index.d.ts +4 -0
  34. package/dist/types/domain/parse.d.ts +30 -0
  35. package/dist/types/dto/field-schema.d.ts +12 -0
  36. package/dist/types/dto/index.d.ts +3 -0
  37. package/dist/types/dto/jsdoc-generator.d.ts +29 -0
  38. package/dist/types/dto/schema-generator.d.ts +59 -0
  39. package/dist/types/fields/auto-id.d.ts +27 -0
  40. package/dist/types/fields/cast-value.d.ts +19 -0
  41. package/dist/types/fields/computed-access.d.ts +22 -0
  42. package/dist/types/fields/default-for.d.ts +11 -0
  43. package/dist/types/fields/default-registry.d.ts +9 -0
  44. package/dist/types/fields/define-computed-field.d.ts +57 -0
  45. package/dist/types/fields/define-field.d.ts +35 -0
  46. package/dist/types/fields/errors.d.ts +30 -0
  47. package/dist/types/fields/index.d.ts +7 -0
  48. package/dist/types/fields/registry.d.ts +55 -0
  49. package/dist/types/fields/types/boolean.d.ts +5 -0
  50. package/dist/types/fields/types/char.d.ts +12 -0
  51. package/dist/types/fields/types/date.d.ts +10 -0
  52. package/dist/types/fields/types/datetime.d.ts +11 -0
  53. package/dist/types/fields/types/enum.d.ts +11 -0
  54. package/dist/types/fields/types/float.d.ts +11 -0
  55. package/dist/types/fields/types/integer.d.ts +11 -0
  56. package/dist/types/fields/types/json.d.ts +9 -0
  57. package/dist/types/fields/types/text.d.ts +10 -0
  58. package/dist/types/fields/types/uuid.d.ts +14 -0
  59. package/dist/types/fields/validate-value.d.ts +14 -0
  60. package/dist/types/global/connect.d.ts +29 -0
  61. package/dist/types/global/create-model.d.ts +189 -0
  62. package/dist/types/global/create-report.d.ts +32 -0
  63. package/dist/types/global/dto.d.ts +31 -0
  64. package/dist/types/global/glob.d.ts +12 -0
  65. package/dist/types/global/identity-scope.d.ts +18 -0
  66. package/dist/types/global/index.d.ts +12 -0
  67. package/dist/types/global/load-models.d.ts +31 -0
  68. package/dist/types/global/migrate.d.ts +68 -0
  69. package/dist/types/global/n-plus-one.d.ts +42 -0
  70. package/dist/types/global/sequences.d.ts +19 -0
  71. package/dist/types/global/state.d.ts +38 -0
  72. package/dist/types/global/sync-models.d.ts +11 -0
  73. package/dist/types/global/transaction.d.ts +22 -0
  74. package/dist/types/index.d.ts +16 -0
  75. package/dist/types/meta/index.d.ts +5 -0
  76. package/dist/types/meta/query.d.ts +34 -0
  77. package/dist/types/meta/reserved-tables.d.ts +10 -0
  78. package/dist/types/meta/schema.d.ts +18 -0
  79. package/dist/types/meta/snapshot.d.ts +35 -0
  80. package/dist/types/meta/sync-meta.d.ts +42 -0
  81. package/dist/types/meta/upsert.d.ts +81 -0
  82. package/dist/types/migrations/apply.d.ts +18 -0
  83. package/dist/types/migrations/describe.d.ts +11 -0
  84. package/dist/types/migrations/diff.d.ts +141 -0
  85. package/dist/types/migrations/errors.d.ts +23 -0
  86. package/dist/types/migrations/foreign-keys-plan.d.ts +27 -0
  87. package/dist/types/migrations/generate.d.ts +51 -0
  88. package/dist/types/migrations/index.d.ts +7 -0
  89. package/dist/types/migrations/render.d.ts +45 -0
  90. package/dist/types/migrations/runner.d.ts +118 -0
  91. package/dist/types/models/define-model.d.ts +52 -0
  92. package/dist/types/models/errors.d.ts +23 -0
  93. package/dist/types/models/index.d.ts +4 -0
  94. package/dist/types/models/inheritance.d.ts +73 -0
  95. package/dist/types/models/naming.d.ts +44 -0
  96. package/dist/types/models/primary-key.d.ts +39 -0
  97. package/dist/types/models/registry.d.ts +112 -0
  98. package/dist/types/relations/attach-detach.d.ts +76 -0
  99. package/dist/types/relations/cascade-delete.d.ts +29 -0
  100. package/dist/types/relations/commands.d.ts +84 -0
  101. package/dist/types/relations/define-relation.d.ts +106 -0
  102. package/dist/types/relations/eager-load.d.ts +28 -0
  103. package/dist/types/relations/errors.d.ts +21 -0
  104. package/dist/types/relations/foreign-keys.d.ts +76 -0
  105. package/dist/types/relations/index.d.ts +7 -0
  106. package/dist/types/relations/keys.d.ts +14 -0
  107. package/dist/types/relations/pivot-schema.d.ts +24 -0
  108. package/dist/types/relations/with-spec.d.ts +33 -0
  109. package/dist/types/reports/define-report.d.ts +37 -0
  110. package/dist/types/reports/errors.d.ts +9 -0
  111. package/dist/types/reports/index.d.ts +3 -0
  112. package/dist/types/reports/report-handle.d.ts +58 -0
  113. package/dist/types/schema/build-column.d.ts +18 -0
  114. package/dist/types/schema/column-builder-registry.d.ts +30 -0
  115. package/dist/types/schema/default-column-builders.d.ts +9 -0
  116. package/dist/types/schema/errors.d.ts +9 -0
  117. package/dist/types/schema/foreign-keys.d.ts +33 -0
  118. package/dist/types/schema/index.d.ts +6 -0
  119. package/dist/types/schema/introspect-foreign-keys.d.ts +23 -0
  120. package/dist/types/schema/sync.d.ts +63 -0
  121. package/dist/types/uow/entity.d.ts +80 -0
  122. package/dist/types/uow/errors.d.ts +8 -0
  123. package/dist/types/uow/hooks.d.ts +35 -0
  124. package/dist/types/uow/index.d.ts +5 -0
  125. package/dist/types/uow/unit-of-work.d.ts +142 -0
  126. package/dist/types/uow/with-unit-of-work.d.ts +23 -0
  127. package/package.json +20 -3
  128. package/src/connection.js +1 -1
  129. package/src/crud/insert-many.js +1 -1
  130. package/src/crud/repository.js +9 -1
@@ -0,0 +1,118 @@
1
+ /** Applied-migration history. `_meta_` is a reserved prefix, so no model's table can collide with it. */
2
+ export declare const MIGRATIONS_TABLE = "_meta_migrations";
3
+ /** @param {import('knex').Knex} db */
4
+ export declare function ensureMigrationsTable(db: import('knex').Knex): Promise<void>;
5
+ /**
6
+ * Migration files in `dir`, oldest first. Only names shaped
7
+ * `YYYYMMDDHHMMSS_slug.js` count, so a README or editor backup file
8
+ * in the directory is ignored rather than executed.
9
+ *
10
+ * @param {string} dir
11
+ * @returns {Promise<Array<{ name: string, file: string }>>}
12
+ */
13
+ export declare function listMigrationFiles(dir: string): Promise<Array<{
14
+ name: string;
15
+ file: string;
16
+ }>>;
17
+ /**
18
+ * Reconciles files on disk with the history table.
19
+ *
20
+ * @param {import('knex').Knex} db
21
+ * @param {string} dir
22
+ * @returns {Promise<{ applied: Array<{name: string, applied_at: unknown}>, pending: Array<{name: string, file: string}> }>}
23
+ * @throws {MigrationStateError} history and disk disagree in a way that makes the chain untrustworthy
24
+ */
25
+ export declare function getMigrationStatus(db: import('knex').Knex, dir: string): Promise<{
26
+ applied: Array<{
27
+ name: string;
28
+ applied_at: unknown;
29
+ }>;
30
+ pending: Array<{
31
+ name: string;
32
+ file: string;
33
+ }>;
34
+ }>;
35
+ /**
36
+ * Applies pending migrations, oldest first. Each one runs in its own
37
+ * transaction together with its metadata update and its history row,
38
+ * so a failure leaves the database, `_meta_*` and the history exactly
39
+ * as they were before that migration.
40
+ *
41
+ * @param {import('knex').Knex} db
42
+ * @param {Object} options
43
+ * @param {string} options.dir
44
+ * @param {number} [options.steps] - apply at most this many
45
+ * @param {import('../schema/column-builder-registry.js').ColumnBuilderRegistry} [options.columnBuilderRegistry]
46
+ * @param {import('../models/registry.js').ModelRegistry} [options.modelRegistry] - if given, pivot tables for its
47
+ * belongsToMany relations are ensured afterwards (migrations don't cover relations; see README)
48
+ * @param {(name: string, summary: string[]) => void} [options.onApply]
49
+ * @returns {Promise<{ applied: string[], pivotTablesCreated: string[] }>}
50
+ */
51
+ export declare function migrateUp(db: import('knex').Knex, options: {
52
+ dir: string;
53
+ steps?: number;
54
+ columnBuilderRegistry?: import('../schema/column-builder-registry.js').ColumnBuilderRegistry;
55
+ modelRegistry?: import('../models/registry.js').ModelRegistry;
56
+ onApply?: (name: string, summary: string[]) => void;
57
+ }): Promise<{
58
+ applied: string[];
59
+ pivotTablesCreated: string[];
60
+ }>;
61
+ /**
62
+ * Rolls back the most recently applied migrations, newest first (one,
63
+ * unless `steps` or `all` says otherwise), each in its own transaction
64
+ * with its metadata restored to the "before" snapshot.
65
+ *
66
+ * @param {import('knex').Knex} db
67
+ * @param {Object} options
68
+ * @param {string} options.dir
69
+ * @param {number} [options.steps] - default 1
70
+ * @param {boolean} [options.all]
71
+ * @param {import('../schema/column-builder-registry.js').ColumnBuilderRegistry} [options.columnBuilderRegistry]
72
+ * @param {(name: string, summary: string[]) => void} [options.onRollback]
73
+ * @returns {Promise<{ rolledBack: string[] }>}
74
+ */
75
+ export declare function migrateDown(db: import('knex').Knex, options: {
76
+ dir: string;
77
+ steps?: number;
78
+ all?: boolean;
79
+ columnBuilderRegistry?: import('../schema/column-builder-registry.js').ColumnBuilderRegistry;
80
+ onRollback?: (name: string, summary: string[]) => void;
81
+ }): Promise<{
82
+ rolledBack: string[];
83
+ }>;
84
+ /**
85
+ * Diffs the registry against the recorded schema state and, if there
86
+ * are changes, writes a migration file for them.
87
+ *
88
+ * Refuses while unapplied migrations exist: the diff is against the
89
+ * *applied* state, so generating on top of pending migrations would
90
+ * write the same changes into a second file.
91
+ *
92
+ * @param {import('knex').Knex} db
93
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
94
+ * @param {Object} options
95
+ * @param {string} options.dir
96
+ * @param {string} [options.name] - slug for the file name
97
+ * @param {boolean} [options.dryRun] - compute and return the plan, write nothing
98
+ * @param {boolean} [options.allowDestructive]
99
+ * @param {Record<string, string>} [options.modelRenames]
100
+ * @param {Record<string, Record<string, string>>} [options.fieldRenames]
101
+ * @returns {Promise<{ plan: object, summary: string[], file: string|null, name: string|null }>}
102
+ * `file` is null when there is nothing to write (no changes, or a dry run)
103
+ * @throws {MigrationStateError} pending migrations exist
104
+ * @throws {MigrationSafetyError} destructive changes not allowed / type changes; carries `planLines`
105
+ */
106
+ export declare function generateMigrationFile(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, options: {
107
+ dir: string;
108
+ name?: string;
109
+ dryRun?: boolean;
110
+ allowDestructive?: boolean;
111
+ modelRenames?: Record<string, string>;
112
+ fieldRenames?: Record<string, Record<string, string>>;
113
+ }): Promise<{
114
+ plan: object;
115
+ summary: string[];
116
+ file: string | null;
117
+ name: string | null;
118
+ }>;
@@ -0,0 +1,52 @@
1
+ export type ModelDescriptor = {
2
+ name: string;
3
+ tableName: string;
4
+ fields: Record<string, import('../fields/define-field.js').FieldDescriptor>;
5
+ /**
6
+ * - name of the primary-key field: the model's `primaryKey` option, else the
7
+ * one field marked `primaryKey: true`, else a field named `id`, else null. That field's descriptor carries
8
+ * `primary: true`. Single-field keys only.
9
+ */
10
+ primaryKey: string | null;
11
+ /**
12
+ * - fieldName -> resolved column name
13
+ */
14
+ columns: Record<string, string>;
15
+ relations: Record<string, import('../relations/define-relation.js').RelationDescriptor>;
16
+ /**
17
+ * -
18
+ * virtual fields: calculated on read, never stored. Deliberately separate from `fields`, which is
19
+ * everything that has a column; everything that persists data iterates `fields` and so can't see these.
20
+ */
21
+ computed: Record<string, import('../fields/define-computed-field.js').ComputedFieldDescriptor>;
22
+ };
23
+ /**
24
+ * Defines a model: a named collection of fields (from Phase 1), plus
25
+ * the resolved table/column names a naming strategy produces from
26
+ * them. This is still purely in-memory - no DB access happens here.
27
+ * Schema sync (Phase 3) and the DB-persisted metamodel (Phase 4) both
28
+ * build on top of the descriptor this returns.
29
+ *
30
+ * Field entries may be either raw field options (`{ type: "char" }`)
31
+ * or an already-built descriptor from defineField() - both are run
32
+ * through defineField() here so validation always happens at model
33
+ * definition time, not deferred to first use.
34
+ *
35
+ * @param {Object} options
36
+ * @param {string} options.name - model name, e.g. "invoice"
37
+ * @param {string} [options.table] - explicit table name; defaults to
38
+ * namingStrategy.modelToTable(name) if omitted
39
+ * @param {string} [options.primaryKey] - the primary-key field; defaults to the field marked
40
+ * `primaryKey: true`, else a field named `id`. An integer or uuid key is assigned automatically
41
+ * (`auto: false` on the field opts out).
42
+ * @param {Record<string, object>} options.fields
43
+ * @param {import('./naming.js').NamingStrategy} [namingStrategy]
44
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry]
45
+ * @returns {Readonly<ModelDescriptor>}
46
+ */
47
+ export declare function defineModel(options: {
48
+ name: string;
49
+ table?: string;
50
+ primaryKey?: string;
51
+ fields: Record<string, object>;
52
+ }, namingStrategy?: import('./naming.js').NamingStrategy, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry): Readonly<ModelDescriptor>;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Thrown by defineModel() when a model descriptor itself is malformed:
3
+ * missing name, no fields, an invalid field definition, or a naming
4
+ * collision between two fields' resolved column names within the same
5
+ * model. A developer-time error about the schema, not runtime data.
6
+ */
7
+ export declare class InvalidModelDefinitionError extends Error {
8
+ constructor(message: any);
9
+ }
10
+ /**
11
+ * Thrown by ModelRegistry#register() when a model name or resolved
12
+ * table name is already taken by a previously registered model.
13
+ */
14
+ export declare class ModelConflictError extends Error {
15
+ constructor(message: any);
16
+ }
17
+ /**
18
+ * Thrown by ModelRegistry#getModel()/#getFields() when the requested
19
+ * model name isn't registered.
20
+ */
21
+ export declare class UnknownModelError extends Error {
22
+ constructor(message: any);
23
+ }
@@ -0,0 +1,4 @@
1
+ export { defineModel } from "./define-model.js";
2
+ export { ModelRegistry } from "./registry.js";
3
+ export { toSnakeCase, toCamelCase, defaultNamingStrategy, identityNamingStrategy, } from "./naming.js";
4
+ export { InvalidModelDefinitionError, ModelConflictError, UnknownModelError, } from "./errors.js";
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Checks the shape of a raw definition and says what kind of layer it is.
3
+ *
4
+ * @param {unknown} def
5
+ * @returns {{ kind: "primary"|"abstract"|"extension", name: string }} `name` is the model the layer belongs to
6
+ */
7
+ export declare function classifyDefinition(def: unknown): {
8
+ kind: "primary" | "abstract" | "extension";
9
+ name: string;
10
+ };
11
+ /** How a layer is named in error messages and in `origins`. */
12
+ export declare function layerLabel(layer: any): string;
13
+ /** Names that must already be defined before this layer can be applied. */
14
+ export declare function requirementsOf(layer: any): any[];
15
+ /**
16
+ * Folds a model's layers (mixins expanded, in order) into the single
17
+ * definition defineModel() will validate. Reads everything fresh from
18
+ * `specs` every time - nothing is cached - so a change to a mixin is
19
+ * always seen by the models that use it.
20
+ *
21
+ * @param {string} name
22
+ * @param {Map<string, { abstract: boolean, layers: Array<{ kind: string, def: object, origin?: string|null }> }>} specs
23
+ * @param {string[]} [stack] - models currently being folded, to catch mixin cycles
24
+ * @returns {{ table: string|undefined, primaryKey: string|undefined, fields: Record<string, object>, relations: Record<string, object>, origins: Record<string, string> }}
25
+ */
26
+ export declare function foldModel(name: string, specs: Map<string, {
27
+ abstract: boolean;
28
+ layers: Array<{
29
+ kind: string;
30
+ def: object;
31
+ origin?: string | null;
32
+ }>;
33
+ }>, stack?: string[]): {
34
+ table: string | undefined;
35
+ primaryKey: string | undefined;
36
+ fields: Record<string, object>;
37
+ relations: Record<string, object>;
38
+ origins: Record<string, string>;
39
+ };
40
+ /**
41
+ * Every mixin used by `name`'s layers, transitively (a mixin using
42
+ * another mixin counts too). Used to decide which mixins' hooks a
43
+ * concrete model should pick up when it's created - see
44
+ * `global/create-model.js`'s `createModel()`.
45
+ *
46
+ * @param {string} name
47
+ * @param {Map<string, { abstract: boolean, layers: Array<{ kind: string, def: object }> }>} specs
48
+ * @returns {string[]} deepest mixins first - a mixin's own mixins resolve
49
+ * before the mixin that includes them, matching how `foldModel()` folds
50
+ * their fields (so the same ordering intuition applies to both)
51
+ */
52
+ export declare function collectMixinNames(name: string, specs: Map<string, {
53
+ abstract: boolean;
54
+ layers: Array<{
55
+ kind: string;
56
+ def: object;
57
+ }>;
58
+ }>, seen?: Set<any>): string[];
59
+ /**
60
+ * Names of every model that mixes in `name`, directly or through
61
+ * another mixin, according to `specs`.
62
+ *
63
+ * @param {string} name
64
+ * @param {Map<string, { abstract: boolean, layers: Array<{ kind: string, def: object }> }>} specs
65
+ * @returns {string[]}
66
+ */
67
+ export declare function dependentsOf(name: string, specs: Map<string, {
68
+ abstract: boolean;
69
+ layers: Array<{
70
+ kind: string;
71
+ def: object;
72
+ }>;
73
+ }>): string[];
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Converts camelCase/PascalCase to snake_case.
3
+ * "customerId" -> "customer_id", "OrderLine" -> "order_line",
4
+ * "userID" -> "user_id" (acronym-aware).
5
+ *
6
+ * @param {string} str
7
+ * @returns {string}
8
+ */
9
+ export declare function toSnakeCase(str: string): string;
10
+ /**
11
+ * Converts snake_case to camelCase.
12
+ * "customer_id" -> "customerId"
13
+ *
14
+ * @param {string} str
15
+ * @returns {string}
16
+ */
17
+ export declare function toCamelCase(str: string): string;
18
+ export type NamingStrategy = {
19
+ modelToTable: (modelName: string) => string;
20
+ fieldToColumn: (fieldName: string) => string;
21
+ };
22
+ /**
23
+ * @typedef {Object} NamingStrategy
24
+ * @property {(modelName: string) => string} modelToTable
25
+ * @property {(fieldName: string) => string} fieldToColumn
26
+ */
27
+ /**
28
+ * The default naming strategy: model and field names (assumed
29
+ * camelCase, JS-idiomatic) map to snake_case table/column names
30
+ * (SQL-idiomatic). Table names are NOT pluralized automatically -
31
+ * pluralization rules are inconsistent enough across languages/plurals
32
+ * that guessing wrong silently is worse than requiring an explicit
33
+ * `table` option when the default isn't wanted.
34
+ *
35
+ * @type {NamingStrategy}
36
+ */
37
+ export declare const defaultNamingStrategy: NamingStrategy;
38
+ /**
39
+ * A pass-through strategy for callers who want model/field names used
40
+ * verbatim as table/column names, with no transformation.
41
+ *
42
+ * @type {NamingStrategy}
43
+ */
44
+ export declare const identityNamingStrategy: NamingStrategy;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The name of a model's primary-key FIELD, or null if it has none.
3
+ *
4
+ * A model built by defineModel() carries `primaryKey` explicitly. The
5
+ * fallback (a field literally named `id`) only serves descriptors that
6
+ * predate declared primary keys, e.g. ones a test builds by hand.
7
+ *
8
+ * @param {{ primaryKey?: string|null, fields: Record<string, unknown> }} model
9
+ * @returns {string|null}
10
+ */
11
+ export declare function primaryKeyOf(model: {
12
+ primaryKey?: string | null;
13
+ fields: Record<string, unknown>;
14
+ }): string | null;
15
+ /** The primary key's column name, or null. */
16
+ export declare function primaryKeyColumnOf(model: any): any;
17
+ /**
18
+ * Like primaryKeyOf(), but throws `ErrorClass` when the model has no
19
+ * primary key. `needing` finishes the sentence "... needs a primary key".
20
+ *
21
+ * @param {object} model
22
+ * @param {string} needing - what needs it, for the message
23
+ * @param {new (message: string) => Error} ErrorClass
24
+ * @returns {string}
25
+ */
26
+ export declare function requirePrimaryKey(model: object, needing: string, ErrorClass?: new (message: string) => Error): string;
27
+ /**
28
+ * Decides which field is the primary key while a model is being defined.
29
+ *
30
+ * Precedence: the model's `primaryKey` option, else the one field marked
31
+ * `primaryKey: true`, else a field named `id`, else none.
32
+ *
33
+ * @param {string} modelName
34
+ * @param {Record<string, object>} storedFields - the model's stored (non-computed) fields, raw
35
+ * @param {unknown} declared - the model-level `primaryKey` option
36
+ * @param {new (message: string) => Error} ErrorClass
37
+ * @returns {string|null}
38
+ */
39
+ export declare function resolvePrimaryKey(modelName: string, storedFields: Record<string, object>, declared: unknown, ErrorClass: new (message: string) => Error): string | null;
@@ -0,0 +1,112 @@
1
+ import { defineModel } from "./define-model.js";
2
+ /**
3
+ * Holds registered model descriptors, keyed by model name. This is the
4
+ * in-memory metamodel: the source of truth Phase 3 (schema sync) and
5
+ * Phase 4 (persisting the registry itself into `_meta_models`/
6
+ * `_meta_fields`) will read from.
7
+ *
8
+ * A class rather than a bare object/singleton so multiple independent
9
+ * registries can exist - useful for tests, and later for multi-tenant
10
+ * setups where different tenants might register different model sets.
11
+ *
12
+ * ## Inheritance and definition order
13
+ *
14
+ * A model is really a stack of layers (see models/inheritance.js): its
15
+ * own definition plus any extensions from other packages, with mixins
16
+ * expanded. `getModel()` returns the folded, validated result.
17
+ *
18
+ * Definitions may arrive in ANY order. One that depends on something
19
+ * not defined yet - an extension whose base hasn't been registered, a
20
+ * model whose mixin hasn't - waits, and is applied the moment its
21
+ * dependencies exist. That matters because the packages contributing
22
+ * to a model are usually imported in an order nobody controls. Call
23
+ * assertResolved() once everything has been registered (createClient,
24
+ * sync() and the CLI do) to turn "still waiting on X" into an error.
25
+ *
26
+ * Every change is atomic: the new layer is applied, and the model plus
27
+ * everything that mixes it in is rebuilt, and only if ALL of that
28
+ * validates does the registry change. An extension that would break a
29
+ * model that inherits from the one it extends is rejected whole.
30
+ */
31
+ export declare class ModelRegistry {
32
+ #private;
33
+ /**
34
+ * @param {Object} [options]
35
+ * @param {import('./naming.js').NamingStrategy} [options.namingStrategy]
36
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [options.fieldTypeRegistry]
37
+ */
38
+ constructor(options?: {
39
+ namingStrategy?: import('./naming.js').NamingStrategy;
40
+ fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry;
41
+ });
42
+ /**
43
+ * Defines a model - or extends one, or defines an abstract mixin - in
44
+ * one step, using this registry's naming strategy and field types.
45
+ *
46
+ * @param {Parameters<typeof defineModel>[0] & { extend?: string, mixins?: string[], abstract?: boolean }} options
47
+ * @param {{ origin?: string }} [meta] - who is contributing this (a module/package name),
48
+ * used in error messages and recorded in the descriptor's `origins`
49
+ * @returns {import('./define-model.js').ModelDescriptor|null} the model's descriptor, or
50
+ * null when the definition is abstract or is waiting on a definition that doesn't exist yet
51
+ */
52
+ define(options: Parameters<typeof defineModel>[0] & {
53
+ extend?: string;
54
+ mixins?: string[];
55
+ abstract?: boolean;
56
+ }, meta?: {
57
+ origin?: string;
58
+ }): import('./define-model.js').ModelDescriptor | null;
59
+ /**
60
+ * Registers an already-built model descriptor (e.g. from
61
+ * defineModel() called directly). Throws if the model name or its
62
+ * resolved table name is already taken. The descriptor is kept as
63
+ * given; it can still be extended or mixed in by later definitions.
64
+ *
65
+ * @param {import('./define-model.js').ModelDescriptor} model
66
+ */
67
+ register(model: import('./define-model.js').ModelDescriptor): this;
68
+ /**
69
+ * @param {string} name
70
+ * @returns {import('./define-model.js').ModelDescriptor}
71
+ */
72
+ getModel(name: string): import('./define-model.js').ModelDescriptor;
73
+ /**
74
+ * @param {string} name
75
+ * @returns {Record<string, import('../fields/define-field.js').FieldDescriptor>}
76
+ */
77
+ getFields(name: string): Record<string, import('../fields/define-field.js').FieldDescriptor>;
78
+ /** True for a concrete (table-backed) model; abstract mixins are not "models" in this sense. */
79
+ hasModel(name: any): boolean;
80
+ /** Concrete models only: this is what schema sync, migrations, DTO generation and the meta tables iterate. */
81
+ listModels(): any[];
82
+ /** @param {string} name */
83
+ isAbstract(name: string): boolean;
84
+ listAbstract(): any[];
85
+ /**
86
+ * Every mixin `name` uses, transitively (a mixin that itself uses
87
+ * mixins counts too), deepest mixin first. Used by `createModel()`'s
88
+ * hook-pulling: hooks a mixin carries (see `defineMixin()`) are
89
+ * applied to a model in this order, before the model's own hooks.
90
+ *
91
+ * @param {string} name
92
+ * @returns {string[]}
93
+ */
94
+ mixinsOf(name: string): string[];
95
+ /**
96
+ * Every CONCRETE model currently using `name` as a mixin, directly or
97
+ * through another mixin. (Compare `mixinsOf()`, which goes the other
98
+ * direction: what a model uses, not who uses it.)
99
+ *
100
+ * @param {string} name
101
+ * @returns {string[]}
102
+ */
103
+ modelsUsingMixin(name: string): string[];
104
+ /**
105
+ * Throws if any definition is still waiting on something that was
106
+ * never defined (or that is part of a mixin cycle). Call once every
107
+ * package has registered its models.
108
+ *
109
+ * @throws {InvalidModelDefinitionError}
110
+ */
111
+ assertResolved(): void;
112
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The batched core behind attach(), attachMany(), and relation
3
+ * payloads on create. Associates any number of (source, target) pairs
4
+ * through a `belongsToMany` relation's pivot table using a constant
5
+ * number of statements: at most one existence check per few hundred
6
+ * sources, plus one INSERT per chunk of rows - never one per pair.
7
+ *
8
+ * Duplicate pairs within `pairs`, and pairs that already exist, are
9
+ * skipped rather than erroring.
10
+ *
11
+ * @param {import('knex').Knex} db - connection or transaction
12
+ * @param {import('./define-relation.js').RelationDescriptor} relation - a belongsToMany relation
13
+ * @param {Array<[number|string, number|string]>} pairs - `[sourceId, targetId]`
14
+ * @param {Object} [options]
15
+ * @param {boolean} [options.checkExisting] - default true. Pass false only when the
16
+ * sources were created in this same operation (so no association can exist yet),
17
+ * which skips the existence check entirely; a genuine duplicate then surfaces as
18
+ * the pivot table's own unique-constraint error instead of being silently skipped.
19
+ * @param {number} [options.chunkSize]
20
+ * @returns {Promise<number>} count of associations actually inserted
21
+ */
22
+ export declare function attachPairs(db: import('knex').Knex, relation: import('./define-relation.js').RelationDescriptor, pairs: Array<[number | string, number | string]>, options?: {
23
+ checkExisting?: boolean;
24
+ chunkSize?: number;
25
+ }): Promise<number>;
26
+ /**
27
+ * Associates one or more related records via a `belongsToMany`
28
+ * relation's pivot table. Existing associations are left alone (not
29
+ * duplicated) rather than erroring on a repeat attach() of the same
30
+ * pair.
31
+ *
32
+ * For many sources at once use attachManyRelation() - calling this in
33
+ * a loop costs a couple of queries per source.
34
+ *
35
+ * @param {import('knex').Knex} db
36
+ * @param {import('../models/define-model.js').ModelDescriptor} model
37
+ * @param {string} modelName
38
+ * @param {Record<string, unknown>|number|string} source - an entity or a raw id
39
+ * @param {string} relationName
40
+ * @param {number|string|Array<number|string>} targetIds
41
+ * @returns {Promise<number>} count of new associations actually inserted
42
+ */
43
+ export declare function attachRelation(db: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, modelName: string, source: Record<string, unknown> | number | string, relationName: string, targetIds: number | string | Array<number | string>): Promise<number>;
44
+ /**
45
+ * Bulk version of attachRelation(): associates many sources with
46
+ * their targets in one go. Cost is independent of how many sources
47
+ * there are - a handful of statements for thousands of associations
48
+ * - which is what makes it the right tool for importing pivot data.
49
+ *
50
+ * @param {import('knex').Knex} db
51
+ * @param {import('../models/define-model.js').ModelDescriptor} model
52
+ * @param {string} modelName
53
+ * @param {string} relationName
54
+ * @param {Array<{ source: Record<string, unknown>|number|string, targets: number|string|Array<number|string> }>} links
55
+ * @param {{ chunkSize?: number }} [options]
56
+ * @returns {Promise<number>} count of new associations actually inserted
57
+ */
58
+ export declare function attachManyRelation(db: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, modelName: string, relationName: string, links: Array<{
59
+ source: Record<string, unknown> | number | string;
60
+ targets: number | string | Array<number | string>;
61
+ }>, options?: {
62
+ chunkSize?: number;
63
+ }): Promise<number>;
64
+ /**
65
+ * Removes one or more associations via a `belongsToMany` relation's
66
+ * pivot table.
67
+ *
68
+ * @param {import('knex').Knex} db
69
+ * @param {import('../models/define-model.js').ModelDescriptor} model
70
+ * @param {string} modelName
71
+ * @param {Record<string, unknown>|number|string} source
72
+ * @param {string} relationName
73
+ * @param {number|string|Array<number|string>} targetIds
74
+ * @returns {Promise<number>} count of associations removed
75
+ */
76
+ export declare function detachRelation(db: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, modelName: string, source: Record<string, unknown> | number | string, relationName: string, targetIds: number | string | Array<number | string>): Promise<number>;
@@ -0,0 +1,29 @@
1
+ import { ON_DELETE_ACTIONS } from "./define-relation.js";
2
+ /**
3
+ * Whether deleting a row of `modelName` needs anything beyond a plain `DELETE ... WHERE ...`
4
+ * - i.e. whether a `constraint: false` relation points at it. Anything else is handled by the
5
+ * database's own foreign keys. Pure registry inspection, no query.
6
+ *
7
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
8
+ * @param {string} modelName
9
+ * @returns {boolean}
10
+ */
11
+ export declare function hasIncomingRelations(modelRegistry: import('../models/registry.js').ModelRegistry, modelName: string): boolean;
12
+ /**
13
+ * Entry point used by Repository#delete(): resolves `where` to actual
14
+ * ids, then deletes them with full cascade/restrict/setNull handling,
15
+ * in one transaction (joining `options.trx` if given, opening one
16
+ * otherwise) so a `"restrict"` refusal or a mid-cascade failure leaves
17
+ * nothing changed.
18
+ *
19
+ * @param {import('knex').Knex} db
20
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
21
+ * @param {import('../models/define-model.js').ModelDescriptor} model
22
+ * @param {(qb: import('knex').Knex.QueryBuilder) => void} where - as built by resolveWhere()
23
+ * @param {{ trx?: import('knex').Knex.Transaction }} [options]
24
+ * @returns {Promise<number>} rows of `model` deleted
25
+ */
26
+ export declare function deleteRowsWithCascade(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, model: import('../models/define-model.js').ModelDescriptor, where: (qb: import('knex').Knex.QueryBuilder) => void, options?: {
27
+ trx?: import('knex').Knex.Transaction;
28
+ }): Promise<number>;
29
+ export { ON_DELETE_ACTIONS };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Odoo-style commands for writing a `hasMany` / `belongsToMany`
3
+ * relation as part of a `create()` / `createMany()` payload:
4
+ *
5
+ * await Post.createMany([
6
+ * {
7
+ * id: 1, title: "Hello",
8
+ * tags: [Command.link(3), Command.link(4)], // or simply [3, 4]
9
+ * comments: [Command.create({ id: 1, body: "First!" })],
10
+ * },
11
+ * ]);
12
+ *
13
+ * Commands are deliberately explicit (rather than "an array of plain
14
+ * objects means create"): the same payload shape could otherwise mean
15
+ * "create these" or "link to these existing records", and guessing
16
+ * wrong silently duplicates data.
17
+ *
18
+ * Only the commands that are meaningful on a record that has just
19
+ * been created exist here (`create`, `link`, `set`). Odoo's
20
+ * update/delete/unlink/clear operate on records that already have
21
+ * relations, so they belong with a future write()-with-commands
22
+ * feature rather than create.
23
+ */
24
+ export declare const Command: Readonly<{
25
+ /**
26
+ * Create a new related record and associate it with the parent.
27
+ * For `hasMany` the parent's key is written into the child's
28
+ * foreign key for you; for `belongsToMany` a pivot row is added.
29
+ *
30
+ * @param {Record<string, unknown>} values
31
+ */
32
+ create(values: Record<string, unknown>): any;
33
+ /**
34
+ * Associate an already-existing related record, by id.
35
+ * For `hasMany` this points the child's foreign key at the parent
36
+ * (moving it if it belonged to another parent); for `belongsToMany`
37
+ * it adds a pivot row.
38
+ *
39
+ * @param {number|string} id
40
+ */
41
+ link(id: number | string): any;
42
+ /**
43
+ * Shorthand for linking several existing records. On a freshly
44
+ * created parent this is identical to one `link` per id.
45
+ *
46
+ * @param {Array<number|string>} ids
47
+ */
48
+ set(ids: Array<number | string>): any;
49
+ }>;
50
+ /**
51
+ * @param {unknown} value
52
+ * @returns {boolean}
53
+ */
54
+ export declare function isCommand(value: unknown): boolean;
55
+ /** Relation types that can be written through a create payload. */
56
+ export declare const WRITABLE_RELATION_TYPES: Set<string>;
57
+ /**
58
+ * Validates one relation's value from a create payload and flattens
59
+ * it into a list of primitive operations - `{ type: "create", values }`
60
+ * or `{ type: "link", id }` - each tagged with `index`, its position
61
+ * in the caller's array, so later errors can point at the exact entry
62
+ * (`items[2].quantity`) even after `set([...])` expands to many links.
63
+ *
64
+ * Accepts `Command.*()` results and bare ids (shorthand for link).
65
+ * Anything else - notably a plain object - is rejected with a message
66
+ * that says how to fix it, for the reason given on `Command`.
67
+ *
68
+ * Structural problems throw `RelationError` here, before any SQL runs.
69
+ *
70
+ * @param {string} modelName
71
+ * @param {string} relationName
72
+ * @param {import('./define-relation.js').RelationDescriptor} relation
73
+ * @param {unknown} value
74
+ * @returns {Array<{ type: "create", values: Record<string, unknown>, index: number } | { type: "link", id: number|string, index: number }>}
75
+ */
76
+ export declare function normalizeRelationValue(modelName: string, relationName: string, relation: import('./define-relation.js').RelationDescriptor, value: unknown): Array<{
77
+ type: "create";
78
+ values: Record<string, unknown>;
79
+ index: number;
80
+ } | {
81
+ type: "link";
82
+ id: number | string;
83
+ index: number;
84
+ }>;