@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,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
+ };
@@ -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,3 @@
1
+ export { defineReport } from "./define-report.js";
2
+ export { ReportHandle } from "./report-handle.js";
3
+ export { ReportDefinitionError } from "./errors.js";
@@ -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>;