@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.
Files changed (126) hide show
  1. package/dist/types/client/create-client.d.ts +32 -0
  2. package/dist/types/client/index.d.ts +4 -0
  3. package/dist/types/client/model-handle.d.ts +148 -0
  4. package/dist/types/client/module.d.ts +54 -0
  5. package/dist/types/client/orm-client.d.ts +107 -0
  6. package/dist/types/connection.d.ts +40 -0
  7. package/dist/types/crud/aggregate-filter.d.ts +36 -0
  8. package/dist/types/crud/aggregate-paths.d.ts +74 -0
  9. package/dist/types/crud/aggregate-spec.d.ts +36 -0
  10. package/dist/types/crud/aggregate.d.ts +59 -0
  11. package/dist/types/crud/create-many.d.ts +42 -0
  12. package/dist/types/crud/errors.d.ts +16 -0
  13. package/dist/types/crud/index.d.ts +12 -0
  14. package/dist/types/crud/insert-many.d.ts +63 -0
  15. package/dist/types/crud/map-filter.d.ts +18 -0
  16. package/dist/types/crud/order.d.ts +58 -0
  17. package/dist/types/crud/paginate.d.ts +55 -0
  18. package/dist/types/crud/prepare-write.d.ts +55 -0
  19. package/dist/types/crud/repository-factory.d.ts +27 -0
  20. package/dist/types/crud/repository.d.ts +297 -0
  21. package/dist/types/crud/resolve-where.d.ts +24 -0
  22. package/dist/types/crud/row-mapping.d.ts +45 -0
  23. package/dist/types/crud/select.d.ts +74 -0
  24. package/dist/types/crud/sequence.d.ts +56 -0
  25. package/dist/types/crud/transaction.d.ts +19 -0
  26. package/dist/types/diagnostics/index.d.ts +1 -0
  27. package/dist/types/diagnostics/n-plus-one.d.ts +108 -0
  28. package/dist/types/dialect/date-bucket.d.ts +46 -0
  29. package/dist/types/dialect/index.d.ts +1 -0
  30. package/dist/types/domain/compile.d.ts +30 -0
  31. package/dist/types/domain/errors.d.ts +20 -0
  32. package/dist/types/domain/index.d.ts +4 -0
  33. package/dist/types/domain/parse.d.ts +30 -0
  34. package/dist/types/dto/field-schema.d.ts +12 -0
  35. package/dist/types/dto/index.d.ts +3 -0
  36. package/dist/types/dto/jsdoc-generator.d.ts +29 -0
  37. package/dist/types/dto/schema-generator.d.ts +59 -0
  38. package/dist/types/fields/auto-id.d.ts +27 -0
  39. package/dist/types/fields/cast-value.d.ts +19 -0
  40. package/dist/types/fields/computed-access.d.ts +22 -0
  41. package/dist/types/fields/default-for.d.ts +11 -0
  42. package/dist/types/fields/default-registry.d.ts +9 -0
  43. package/dist/types/fields/define-computed-field.d.ts +57 -0
  44. package/dist/types/fields/define-field.d.ts +35 -0
  45. package/dist/types/fields/errors.d.ts +30 -0
  46. package/dist/types/fields/index.d.ts +7 -0
  47. package/dist/types/fields/registry.d.ts +55 -0
  48. package/dist/types/fields/types/boolean.d.ts +5 -0
  49. package/dist/types/fields/types/char.d.ts +12 -0
  50. package/dist/types/fields/types/date.d.ts +10 -0
  51. package/dist/types/fields/types/datetime.d.ts +11 -0
  52. package/dist/types/fields/types/enum.d.ts +11 -0
  53. package/dist/types/fields/types/float.d.ts +11 -0
  54. package/dist/types/fields/types/integer.d.ts +11 -0
  55. package/dist/types/fields/types/json.d.ts +9 -0
  56. package/dist/types/fields/types/text.d.ts +10 -0
  57. package/dist/types/fields/types/uuid.d.ts +14 -0
  58. package/dist/types/fields/validate-value.d.ts +14 -0
  59. package/dist/types/global/connect.d.ts +29 -0
  60. package/dist/types/global/create-model.d.ts +189 -0
  61. package/dist/types/global/create-report.d.ts +32 -0
  62. package/dist/types/global/dto.d.ts +31 -0
  63. package/dist/types/global/glob.d.ts +12 -0
  64. package/dist/types/global/identity-scope.d.ts +18 -0
  65. package/dist/types/global/index.d.ts +12 -0
  66. package/dist/types/global/load-models.d.ts +31 -0
  67. package/dist/types/global/migrate.d.ts +68 -0
  68. package/dist/types/global/n-plus-one.d.ts +42 -0
  69. package/dist/types/global/sequences.d.ts +19 -0
  70. package/dist/types/global/state.d.ts +38 -0
  71. package/dist/types/global/sync-models.d.ts +11 -0
  72. package/dist/types/global/transaction.d.ts +22 -0
  73. package/dist/types/index.d.ts +16 -0
  74. package/dist/types/meta/index.d.ts +5 -0
  75. package/dist/types/meta/query.d.ts +34 -0
  76. package/dist/types/meta/reserved-tables.d.ts +10 -0
  77. package/dist/types/meta/schema.d.ts +18 -0
  78. package/dist/types/meta/snapshot.d.ts +35 -0
  79. package/dist/types/meta/sync-meta.d.ts +42 -0
  80. package/dist/types/meta/upsert.d.ts +81 -0
  81. package/dist/types/migrations/apply.d.ts +18 -0
  82. package/dist/types/migrations/describe.d.ts +11 -0
  83. package/dist/types/migrations/diff.d.ts +141 -0
  84. package/dist/types/migrations/errors.d.ts +23 -0
  85. package/dist/types/migrations/foreign-keys-plan.d.ts +27 -0
  86. package/dist/types/migrations/generate.d.ts +51 -0
  87. package/dist/types/migrations/index.d.ts +7 -0
  88. package/dist/types/migrations/render.d.ts +45 -0
  89. package/dist/types/migrations/runner.d.ts +118 -0
  90. package/dist/types/models/define-model.d.ts +52 -0
  91. package/dist/types/models/errors.d.ts +23 -0
  92. package/dist/types/models/index.d.ts +4 -0
  93. package/dist/types/models/inheritance.d.ts +73 -0
  94. package/dist/types/models/naming.d.ts +44 -0
  95. package/dist/types/models/primary-key.d.ts +39 -0
  96. package/dist/types/models/registry.d.ts +112 -0
  97. package/dist/types/relations/attach-detach.d.ts +76 -0
  98. package/dist/types/relations/cascade-delete.d.ts +29 -0
  99. package/dist/types/relations/commands.d.ts +84 -0
  100. package/dist/types/relations/define-relation.d.ts +106 -0
  101. package/dist/types/relations/eager-load.d.ts +28 -0
  102. package/dist/types/relations/errors.d.ts +21 -0
  103. package/dist/types/relations/foreign-keys.d.ts +76 -0
  104. package/dist/types/relations/index.d.ts +7 -0
  105. package/dist/types/relations/keys.d.ts +14 -0
  106. package/dist/types/relations/pivot-schema.d.ts +24 -0
  107. package/dist/types/relations/with-spec.d.ts +33 -0
  108. package/dist/types/reports/define-report.d.ts +37 -0
  109. package/dist/types/reports/errors.d.ts +9 -0
  110. package/dist/types/reports/index.d.ts +3 -0
  111. package/dist/types/reports/report-handle.d.ts +58 -0
  112. package/dist/types/schema/build-column.d.ts +18 -0
  113. package/dist/types/schema/column-builder-registry.d.ts +30 -0
  114. package/dist/types/schema/default-column-builders.d.ts +9 -0
  115. package/dist/types/schema/errors.d.ts +9 -0
  116. package/dist/types/schema/foreign-keys.d.ts +33 -0
  117. package/dist/types/schema/index.d.ts +6 -0
  118. package/dist/types/schema/introspect-foreign-keys.d.ts +23 -0
  119. package/dist/types/schema/sync.d.ts +63 -0
  120. package/dist/types/uow/entity.d.ts +80 -0
  121. package/dist/types/uow/errors.d.ts +8 -0
  122. package/dist/types/uow/hooks.d.ts +35 -0
  123. package/dist/types/uow/index.d.ts +5 -0
  124. package/dist/types/uow/unit-of-work.d.ts +142 -0
  125. package/dist/types/uow/with-unit-of-work.d.ts +23 -0
  126. package/package.json +9 -3
@@ -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
+ }>;
@@ -0,0 +1,106 @@
1
+ declare const RELATION_TYPES: string[];
2
+ declare const ON_DELETE_ACTIONS: string[];
3
+ export type RelationDescriptor = {
4
+ type: "hasOne" | "hasMany" | "belongsTo" | "belongsToMany";
5
+ /**
6
+ * - the related model's name
7
+ */
8
+ model: string;
9
+ /**
10
+ * - see per-type notes below
11
+ */
12
+ foreignKey: string;
13
+ /**
14
+ * - belongsToMany only: the pivot table name
15
+ */
16
+ through?: string;
17
+ /**
18
+ * - belongsToMany only: the pivot column referencing the related model
19
+ */
20
+ otherKey?: string;
21
+ /**
22
+ * - defaults to the referenced model's primary key (see resolveLocalKey()); see per-type notes below
23
+ */
24
+ localKey: string;
25
+ /**
26
+ * - belongsTo only; see define-relation.js's docstring
27
+ */
28
+ onDelete?: "restrict" | "cascade" | "setNull";
29
+ /**
30
+ * - belongsTo only; `false` = no database foreign key (default: true)
31
+ */
32
+ constraint?: boolean;
33
+ };
34
+ /**
35
+ * @typedef {Object} RelationDescriptor
36
+ * @property {"hasOne"|"hasMany"|"belongsTo"|"belongsToMany"} type
37
+ * @property {string} model - the related model's name
38
+ * @property {string} foreignKey - see per-type notes below
39
+ * @property {string} [through] - belongsToMany only: the pivot table name
40
+ * @property {string} [otherKey] - belongsToMany only: the pivot column referencing the related model
41
+ * @property {string} localKey - defaults to the referenced model's primary key (see resolveLocalKey()); see per-type notes below
42
+ * @property {"restrict"|"cascade"|"setNull"} [onDelete] - belongsTo only; see define-relation.js's docstring
43
+ * @property {boolean} [constraint] - belongsTo only; `false` = no database foreign key (default: true)
44
+ */
45
+ /**
46
+ * Defines one relation. Direction matters and is easy to get backwards,
47
+ * so it's spelled out explicitly here:
48
+ *
49
+ * - **belongsTo**: the foreign key lives on THIS model.
50
+ * `foreignKey` = a field name on this model (e.g. "invoiceId").
51
+ * `localKey` = the field on the RELATED model it points to (default "id").
52
+ * `onDelete` says what happens to THIS model's rows when the row they
53
+ * point at is deleted - see "Deleting through a relation" below.
54
+ *
55
+ * - **hasOne** / **hasMany**: the foreign key lives on the RELATED model.
56
+ * `foreignKey` = a field name on the related model (e.g. "invoiceId").
57
+ * `localKey` = the field on THIS model it points to (default "id").
58
+ *
59
+ * - **belongsToMany**: a pivot table holds both sides.
60
+ * `through` = the pivot table name (auto-created by schema sync if missing).
61
+ * `foreignKey` = the pivot column referencing THIS model's `localKey` (default "id").
62
+ * `otherKey` = the pivot column referencing the related model's `id`.
63
+ *
64
+ * Relation *targets* are intentionally not validated here (see
65
+ * RelationError's docstring) - only the descriptor's own shape is
66
+ * checked at definition time.
67
+ *
68
+ * ## Deleting through a relation
69
+ *
70
+ * Only `belongsTo` carries `onDelete` - the side that holds the foreign
71
+ * key is the side that has something to say about losing what it points
72
+ * to, the same reasoning Odoo's Many2one `ondelete` uses (a One2many is
73
+ * just the inverse view of the same column and carries no setting of its
74
+ * own). Declare the `belongsTo` side of a relationship - even one you'd
75
+ * otherwise only query from the `hasMany` side - if you want deleting the
76
+ * parent to be handled rather than leaving an orphaned foreign key behind.
77
+ *
78
+ * Three actions, matching Odoo's own three:
79
+ * - `"restrict"` (default when the foreign key field is `required`):
80
+ * refuses the delete if any referencing row exists.
81
+ * - `"setNull"` (default when the foreign key field is NOT required):
82
+ * the referencing rows' foreign key is set to `null`.
83
+ * - `"cascade"`: the referencing rows are deleted too - recursively,
84
+ * through their own `belongsTo` relations in turn.
85
+ *
86
+ * Setting `onDelete: "setNull"` explicitly on a `required` foreign key is
87
+ * rejected (a `required` column can never legally hold `null`) - not here,
88
+ * where the related model isn't known yet, but the first time the relation
89
+ * is actually used for a delete (see relations/cascade-delete.js).
90
+ *
91
+ * These are enforced by the DATABASE: `sync()` (and generated migrations) create a real
92
+ * `FOREIGN KEY ... ON DELETE RESTRICT | SET NULL | CASCADE` constraint for every `belongsTo`,
93
+ * so a delete is one statement and the rules hold for every writer, not just this ORM.
94
+ * Set `constraint: false` on a `belongsTo` to opt out (a legacy table, a key into another
95
+ * database, ...): no constraint is created, and the ORM applies `onDelete` itself in
96
+ * JavaScript instead - several statements per delete, for that relation only.
97
+ *
98
+ * A `belongsToMany` relation's pivot rows are always cleaned up when
99
+ * either side is deleted (the pivot table's foreign keys cascade) - there's no `onDelete` to set for it, because an
100
+ * orphaned pivot row is never something you'd want kept.
101
+ *
102
+ * @param {Object} options
103
+ * @returns {Readonly<RelationDescriptor>}
104
+ */
105
+ export declare function defineRelation(options: Object): Readonly<RelationDescriptor>;
106
+ export { RELATION_TYPES, ON_DELETE_ACTIONS };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Loads every relation named in `withSpec` for `records`, mutating each record in place and
3
+ * returning the same array. A no-op for an empty `records` array (no queries issued at all).
4
+ *
5
+ * `withSpec` is anything `find({ with })` accepts (see with-spec.js): relation names,
6
+ * dotted paths, and/or `{ relation: { select, with } }` objects. It is validated up front,
7
+ * before any query runs.
8
+ *
9
+ * Supports dot-path nesting - `"items.product"` loads `items` on
10
+ * `model` first (one batched query), then recurses onto every loaded
11
+ * item to load `product` on THEM (another batched query, deduplicated
12
+ * by object reference first so records that share the same related
13
+ * row - e.g. many order items pointing at the same product - aren't
14
+ * redundantly re-queried). Arbitrary depth works the same way,
15
+ * recursively: `"items.product.tags"` loads three levels, each still
16
+ * one query per level regardless of how many records are at that
17
+ * level - the N+1 guarantee holds at every depth, not just the first.
18
+ * Field selection changes which columns each of those queries reads, never how many run.
19
+ *
20
+ * @param {import('knex').Knex} db
21
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
22
+ * @param {import('../models/define-model.js').ModelDescriptor} model
23
+ * @param {Record<string, unknown>[]} records
24
+ * @param {unknown} withSpec - relation names / paths / `{ relation: { select, with } }`
25
+ * @param {import('../fields/registry.js').FieldTypeRegistry} fieldTypeRegistry
26
+ * @returns {Promise<Record<string, unknown>[]>}
27
+ */
28
+ export declare function eagerLoad(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, model: import('../models/define-model.js').ModelDescriptor, records: Record<string, unknown>[], withSpec: unknown, fieldTypeRegistry: import('../fields/registry.js').FieldTypeRegistry): Promise<Record<string, unknown>[]>;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Thrown by defineRelation() when a relation descriptor is malformed:
3
+ * unknown type, missing `model`, or missing the type-specific keys
4
+ * (`foreignKey` for hasOne/hasMany/belongsTo; `through`/`foreignKey`/
5
+ * `otherKey` for belongsToMany). A developer-time error about the
6
+ * schema, same spirit as InvalidFieldDefinitionError.
7
+ */
8
+ export declare class InvalidRelationDefinitionError extends Error {
9
+ constructor(message: any);
10
+ }
11
+ /**
12
+ * Thrown at query time (eager or lazy load) when a relation name
13
+ * isn't defined on the model, or when its target model isn't
14
+ * registered. Relation *targets* can't be validated at definition
15
+ * time - two models can legitimately reference each other, so
16
+ * whichever is defined first would otherwise fail validation against
17
+ * a model that doesn't exist yet.
18
+ */
19
+ export declare class RelationError extends Error {
20
+ constructor(message: any, options: any);
21
+ }
@@ -0,0 +1,76 @@
1
+ export type ForeignKeySpec = {
2
+ /**
3
+ * - the column holding the key, in the table that owns it
4
+ */
5
+ column: string;
6
+ /**
7
+ * - the table it points at
8
+ */
9
+ refTable: string;
10
+ /**
11
+ * - the column it points at (primary or unique)
12
+ */
13
+ refColumn: string;
14
+ onDelete: "RESTRICT" | "CASCADE" | "SET NULL";
15
+ /**
16
+ * - the `belongsTo` relation it comes from (absent for pivot tables)
17
+ */
18
+ relation?: string;
19
+ /**
20
+ * - the model it points at (absent for pivot tables)
21
+ */
22
+ refModel?: string;
23
+ };
24
+ /**
25
+ * @typedef {Object} ForeignKeySpec
26
+ * @property {string} column - the column holding the key, in the table that owns it
27
+ * @property {string} refTable - the table it points at
28
+ * @property {string} refColumn - the column it points at (primary or unique)
29
+ * @property {"RESTRICT"|"CASCADE"|"SET NULL"} onDelete
30
+ * @property {string} [relation] - the `belongsTo` relation it comes from (absent for pivot tables)
31
+ * @property {string} [refModel] - the model it points at (absent for pivot tables)
32
+ */
33
+ /**
34
+ * The effective on-delete action for one `belongsTo` relation: whatever it declared
35
+ * explicitly, or a default from whether its foreign key field can hold `null`
36
+ * (required -> "restrict", otherwise "setNull").
37
+ *
38
+ * @param {object} childModel - the model that owns the foreign key
39
+ * @param {import('./define-relation.js').RelationDescriptor} relation
40
+ * @returns {"restrict"|"cascade"|"setNull"}
41
+ * @throws {RelationError} `onDelete: "setNull"` was set explicitly on a `required` foreign key field
42
+ */
43
+ export declare function resolveOnDelete(childModel: object, relation: import('./define-relation.js').RelationDescriptor): "restrict" | "cascade" | "setNull";
44
+ /** A `belongsTo` is backed by a real database constraint unless it opted out with `constraint: false`. */
45
+ export declare const hasDatabaseConstraint: (relation: any) => boolean;
46
+ /**
47
+ * The foreign keys a model's table should carry: one per `belongsTo` relation (that hasn't
48
+ * opted out with `constraint: false`) whose target is registered and whose referenced field is
49
+ * a primary key or `unique` - the only things a database lets a foreign key point at.
50
+ *
51
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
52
+ * @param {object} model
53
+ * @returns {ForeignKeySpec[]}
54
+ * @throws {RelationError} an explicit `onDelete: "setNull"` on a `required` foreign key field
55
+ */
56
+ export declare function foreignKeysOf(modelRegistry: import('../models/registry.js').ModelRegistry, model: object): ForeignKeySpec[];
57
+ /**
58
+ * The two foreign keys of a `belongsToMany` pivot table. Both cascade: an orphaned pivot row
59
+ * is never something to keep, so deleting either side removes its associations.
60
+ *
61
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
62
+ * @param {object} ownerModel - the model the relation is declared on
63
+ * @param {import('./define-relation.js').RelationDescriptor} relation
64
+ * @returns {ForeignKeySpec[]}
65
+ */
66
+ export declare function pivotForeignKeysOf(modelRegistry: import('../models/registry.js').ModelRegistry, ownerModel: object, relation: import('./define-relation.js').RelationDescriptor): ForeignKeySpec[];
67
+ /**
68
+ * Whether a driver error is a foreign key violation: Postgres code 23503, or SQLite's
69
+ * SQLITE_CONSTRAINT_FOREIGNKEY (older drivers only say so in the message).
70
+ */
71
+ export declare function isForeignKeyViolation(error: any): boolean;
72
+ /**
73
+ * Turns the database's refusal to delete a still-referenced row into the ORM's own
74
+ * `RelationError`, keeping the driver error as `cause`. Anything else passes through.
75
+ */
76
+ export declare function translateDeleteError(error: any, modelName: any): any;
@@ -0,0 +1,7 @@
1
+ export { defineRelation, RELATION_TYPES } from "./define-relation.js";
2
+ export { eagerLoad } from "./eager-load.js";
3
+ export { ensurePivotTables } from "./pivot-schema.js";
4
+ export { attachRelation, attachManyRelation, detachRelation } from "./attach-detach.js";
5
+ export { Command, isCommand } from "./commands.js";
6
+ export { InvalidRelationDefinitionError, RelationError } from "./errors.js";
7
+ export { hasIncomingRelations, deleteRowsWithCascade, ON_DELETE_ACTIONS } from "./cascade-delete.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Which field a relation's `localKey` means, once defaults are resolved.
3
+ *
4
+ * `localKey` defaults to "the primary key of the model it refers to":
5
+ * - hasOne / hasMany / belongsToMany: the field on THIS (owner) model
6
+ * - belongsTo: the field on the RELATED model
7
+ * A `localKey` the relation set explicitly is always used as written.
8
+ *
9
+ * @param {import('./define-relation.js').RelationDescriptor} relation
10
+ * @param {object} ownerModel - the model the relation is defined on
11
+ * @param {object} [relatedModel] - required for belongsTo when localKey is defaulted
12
+ * @returns {string}
13
+ */
14
+ export declare function resolveLocalKey(relation: import('./define-relation.js').RelationDescriptor, ownerModel: object, relatedModel?: object): string;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Creates the pivot table for every `belongsToMany` relation across
3
+ * every registered model, if it doesn't already exist. Same spirit as
4
+ * Phase 3's additive sync(): create-if-missing, never alter or drop,
5
+ * safe to call on every sync().
6
+ *
7
+ * The pivot table is intentionally minimal - just the two foreign-key
8
+ * columns plus a composite unique constraint preventing the same pair
9
+ * from being associated twice. No surrogate `id` column, since
10
+ * nothing needs to reference a pivot row individually for Phase 7's
11
+ * scope (association metadata like "when was this tag added" is a
12
+ * reasonable future extension, not attempted here).
13
+ *
14
+ * If two different relations (possibly on different models) declare
15
+ * the same `through` table name, the table is only created once - its
16
+ * columns are whatever the first relation to be processed specifies.
17
+ * Declaring the same pivot table with different column names across
18
+ * relations is a modeling error the caller needs to avoid; this
19
+ * function doesn't attempt to detect or reconcile that mismatch.
20
+ *
21
+ * @param {import('knex').Knex} db
22
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
23
+ */
24
+ export declare function ensurePivotTables(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry): Promise<void>;
@@ -0,0 +1,33 @@
1
+ export type WithNode = {
2
+ select: string[] | null;
3
+ with: Map<string, WithNode>;
4
+ where: unknown;
5
+ orderBy: unknown;
6
+ limit: number | undefined;
7
+ offset: number | undefined;
8
+ whereFn: Function | null;
9
+ order: Array<{
10
+ field: string;
11
+ direction: "asc" | "desc";
12
+ }>;
13
+ };
14
+ /**
15
+ * @param {import('../models/define-model.js').ModelDescriptor} model
16
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
17
+ * @param {unknown} input - any accepted shape of `with`
18
+ * @param {import('../fields/registry.js').FieldTypeRegistry} [fieldTypeRegistry] - for compiling `where`
19
+ * @returns {Map<string, WithNode>} empty when nothing is to be loaded
20
+ * @throws {RelationError} unknown relation or option, malformed entry
21
+ * @throws {import('../crud/errors.js').ValidationError} a `select` naming a field that doesn't exist
22
+ */
23
+ export declare function normalizeWith(model: import('../models/define-model.js').ModelDescriptor, modelRegistry: import('../models/registry.js').ModelRegistry, input: unknown, fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry): Map<string, WithNode>;
24
+ /**
25
+ * The fields of `model` that must be read for the relations in `tree` to be matched to it:
26
+ * a belongsTo reads the foreign key, everything else reads the local key.
27
+ *
28
+ * @param {import('../models/define-model.js').ModelDescriptor} model
29
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
30
+ * @param {Map<string, WithNode>} tree
31
+ * @returns {string[]}
32
+ */
33
+ export declare function parentKeysNeeded(model: import('../models/define-model.js').ModelDescriptor, modelRegistry: import('../models/registry.js').ModelRegistry, tree: Map<string, WithNode>): string[];
@@ -0,0 +1,37 @@
1
+ export type ReportField = {
2
+ kind: "key";
3
+ from: string;
4
+ bucket?: string;
5
+ } | {
6
+ kind: "aggregate";
7
+ agg: string;
8
+ of: string | null;
9
+ } | {
10
+ kind: "computed";
11
+ compute: Function;
12
+ depends: string[];
13
+ };
14
+ export type ReportDescriptor = {
15
+ name: string;
16
+ from: string;
17
+ where: unknown;
18
+ orderBy: unknown;
19
+ fields: Readonly<Record<string, ReportField>>;
20
+ };
21
+ /**
22
+ * @param {string} name
23
+ * @param {object} definition
24
+ * @returns {Readonly<ReportDescriptor>}
25
+ * @throws {ReportDefinitionError}
26
+ */
27
+ export declare function defineReport(name: string, definition: object): Readonly<ReportDescriptor>;
28
+ /**
29
+ * The options aggregate() needs to run a report's fields: keys become `groupBy` entries named after
30
+ * the report field, aggregates become `aggregates`.
31
+ * @param {ReportDescriptor} descriptor
32
+ * @returns {{ groupBy: object[], aggregates: Record<string, unknown> }}
33
+ */
34
+ export declare function toAggregateOptions(descriptor: ReportDescriptor): {
35
+ groupBy: object[];
36
+ aggregates: Record<string, unknown>;
37
+ };