@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,34 @@
1
+ /**
2
+ * Returns the `_meta_models` row for a model, or undefined if it's
3
+ * never been synced. Excludes models flagged as removed unless
4
+ * `includeRemoved` is set.
5
+ *
6
+ * @param {import('knex').Knex} db
7
+ * @param {string} modelName
8
+ * @param {{ includeRemoved?: boolean }} [options]
9
+ */
10
+ export declare function getModelMeta(db: import('knex').Knex, modelName: string, options?: {
11
+ includeRemoved?: boolean;
12
+ }): Promise<any>;
13
+ /**
14
+ * Returns the `_meta_fields` rows for a model, ordered by field name.
15
+ * This is the plain-SQL-queryable answer to "what fields does model X
16
+ * have, and what are their types" that Phase 4 exists to provide.
17
+ *
18
+ * @param {import('knex').Knex} db
19
+ * @param {string} modelName
20
+ * @param {{ includeRemoved?: boolean }} [options]
21
+ */
22
+ export declare function getFieldsMeta(db: import('knex').Knex, modelName: string, options?: {
23
+ includeRemoved?: boolean;
24
+ }): Promise<any[]>;
25
+ /**
26
+ * Returns all `_meta_models` rows, ordered by name. Excludes models
27
+ * flagged as removed unless `includeRemoved` is set.
28
+ *
29
+ * @param {import('knex').Knex} db
30
+ * @param {{ includeRemoved?: boolean }} [options]
31
+ */
32
+ export declare function listModelsMeta(db: import('knex').Knex, options?: {
33
+ includeRemoved?: boolean;
34
+ }): Promise<any[]>;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Table names starting with this prefix are reserved for internal
3
+ * metadata tables and cannot be used by user-defined models (enforced
4
+ * in ModelRegistry#register). Exported from here rather than defined
5
+ * inline in the registry so the meta module stays the single source
6
+ * of truth for what it owns.
7
+ */
8
+ export declare const META_TABLE_PREFIX = "_meta_";
9
+ export declare const META_MODELS_TABLE = "_meta_models";
10
+ export declare const META_FIELDS_TABLE = "_meta_fields";
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Creates the two internal metadata tables if they don't already
3
+ * exist. Idempotent, same spirit as Phase 3's additive sync() - safe
4
+ * to call on every sync().
5
+ *
6
+ * `_meta_models` - one row per registered model (name, resolved table
7
+ * name, lifecycle timestamps).
8
+ *
9
+ * `_meta_fields` - one row per field on a model (name, resolved
10
+ * column name, type, constraints, and the full field descriptor as
11
+ * JSON for fidelity). Denormalizes the model name onto each row
12
+ * (alongside the `model_id` FK) specifically so a flat query like
13
+ * `SELECT * FROM _meta_fields WHERE model = 'invoice'` works without
14
+ * a join - that ergonomic is the whole point of this phase.
15
+ *
16
+ * @param {import('knex').Knex} db
17
+ */
18
+ export declare function ensureMetaTables(db: import('knex').Knex): Promise<void>;
@@ -0,0 +1,35 @@
1
+ export type ModelMetaSnapshot = {
2
+ table_name: string;
3
+ removed: boolean;
4
+ /**
5
+ * - ordered by name
6
+ */
7
+ fields: Array<{
8
+ name: string;
9
+ column: string;
10
+ type: string;
11
+ required: boolean;
12
+ is_unique: boolean;
13
+ is_indexed: boolean;
14
+ options: unknown;
15
+ removed: boolean;
16
+ }>;
17
+ };
18
+ /**
19
+ * @param {import('knex').Knex} db
20
+ * @param {string} modelName
21
+ * @returns {Promise<ModelMetaSnapshot|null>} null if the model has no metadata row at all
22
+ */
23
+ export declare function snapshotModelMeta(db: import('knex').Knex, modelName: string): Promise<ModelMetaSnapshot | null>;
24
+ /**
25
+ * Makes a model's metadata rows match `snapshot` exactly: rows are
26
+ * created or updated to the snapshot's values, rows the snapshot
27
+ * doesn't have are deleted, and `null` deletes the model's metadata
28
+ * entirely (it did not exist in that state). Run it inside the same
29
+ * transaction as the schema change it accompanies.
30
+ *
31
+ * @param {import('knex').Knex} db - ideally a transaction
32
+ * @param {string} modelName
33
+ * @param {ModelMetaSnapshot|null} snapshot
34
+ */
35
+ export declare function restoreModelMeta(db: import('knex').Knex, modelName: string, snapshot: ModelMetaSnapshot | null): Promise<void>;
@@ -0,0 +1,42 @@
1
+ export type MetaSyncResult = {
2
+ modelsUpserted: string[];
3
+ /**
4
+ * - "modelName.fieldName"
5
+ */
6
+ fieldsUpserted: string[];
7
+ /**
8
+ * - flagged, not deleted
9
+ */
10
+ modelsRemoved: string[];
11
+ /**
12
+ * - "modelName.fieldName", flagged not deleted
13
+ */
14
+ fieldsRemoved: string[];
15
+ };
16
+ /**
17
+ * @typedef {Object} MetaSyncResult
18
+ * @property {string[]} modelsUpserted
19
+ * @property {string[]} fieldsUpserted - "modelName.fieldName"
20
+ * @property {string[]} modelsRemoved - flagged, not deleted
21
+ * @property {string[]} fieldsRemoved - "modelName.fieldName", flagged not deleted
22
+ */
23
+ /**
24
+ * Upserts `_meta_models`/`_meta_fields` rows to reflect the current
25
+ * state of `modelRegistry`. Called by schema.sync() after the real
26
+ * data tables have been created/altered, so the metadata always
27
+ * describes what's actually in the database.
28
+ *
29
+ * Assumes ensureMetaTables() has already been run - deliberately not
30
+ * called from here, since that's a DDL operation kept outside the
31
+ * DML transaction this function runs in.
32
+ *
33
+ * A model or field that existed in a previous sync but is no longer
34
+ * in the registry is flagged via `removed_at`, never deleted - so
35
+ * `_meta_fields` remains a durable record answerable by a plain SQL
36
+ * query even for things that used to exist.
37
+ *
38
+ * @param {import('knex').Knex} db
39
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
40
+ * @returns {Promise<MetaSyncResult>}
41
+ */
42
+ export declare function syncMeta(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry): Promise<MetaSyncResult>;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Inserts or updates a `_meta_models` row for the given model
3
+ * descriptor, and returns its id. Clears `removed_at` if the model
4
+ * was previously flagged as removed and has now reappeared.
5
+ *
6
+ * Uses select-then-insert-or-update rather than an upsert/onConflict
7
+ * clause: `.onConflict().merge()` support varies enough across Knex's
8
+ * sqlite and postgres dialects that the extra round trip here is a
9
+ * worthwhile trade for staying dialect-portable without surprises.
10
+ *
11
+ * @param {import('knex').Knex} trx
12
+ * @param {import('../models/define-model.js').ModelDescriptor} model
13
+ * @param {Date} now
14
+ * @returns {Promise<number>}
15
+ */
16
+ export declare function ensureMetaModel(trx: import('knex').Knex, model: import('../models/define-model.js').ModelDescriptor, now: Date): Promise<number>;
17
+ /**
18
+ * Inserts or updates a `_meta_fields` row for one field on a model.
19
+ * The full field descriptor is stored as JSON in `options` for
20
+ * fidelity (factory-function defaults are silently dropped by
21
+ * JSON.stringify, consistent with Phase 3's schema-sync treatment of
22
+ * them as a JS-side, not a persisted, concern).
23
+ *
24
+ * @param {import('knex').Knex} trx
25
+ * @param {number} modelId
26
+ * @param {string} modelName
27
+ * @param {string} fieldName
28
+ * @param {import('../fields/define-field.js').FieldDescriptor} field
29
+ * @param {string} columnName
30
+ * @param {Date} now
31
+ */
32
+ export declare function ensureMetaField(trx: import('knex').Knex, modelId: number, modelName: string, fieldName: string, field: import('../fields/define-field.js').FieldDescriptor, columnName: string, now: Date): Promise<void>;
33
+ /**
34
+ * Inserts or updates a `_meta_fields` row for one relation on a model
35
+ * (Phase 7). Relations share the `_meta_fields` table with scalar
36
+ * fields rather than getting a table of their own - the roadmap calls
37
+ * for exactly this ("Relation fields stored in _meta_fields too"),
38
+ * and it's a natural fit since `options` already exists as a flexible
39
+ * JSON column for full-fidelity storage regardless of shape.
40
+ *
41
+ * `column` is set to the underlying foreign-key column when this
42
+ * model owns it (belongsTo), or left as an empty string for
43
+ * hasOne/hasMany/belongsToMany, which don't have a column of their
44
+ * own on this model. `required`/`is_unique`/`is_indexed` don't apply
45
+ * to relations and are always stored as false; the full descriptor
46
+ * (type, model, foreignKey, through, otherKey, localKey) lives in
47
+ * `options` for introspection.
48
+ *
49
+ * @param {import('knex').Knex} trx
50
+ * @param {number} modelId
51
+ * @param {string} modelName
52
+ * @param {string} relationName
53
+ * @param {import('../relations/define-relation.js').RelationDescriptor} relation
54
+ * @param {import('../models/define-model.js').ModelDescriptor} model
55
+ * @param {Date} now
56
+ */
57
+ export declare function ensureMetaRelation(trx: import('knex').Knex, modelId: number, modelName: string, relationName: string, relation: import('../relations/define-relation.js').RelationDescriptor, model: import('../models/define-model.js').ModelDescriptor, now: Date): Promise<void>;
58
+ /**
59
+ * Flags `_meta_models` rows as removed (sets `removed_at`) when their
60
+ * name is no longer present in the current registry. Never deletes -
61
+ * metadata history is preserved so a later phase (migrations) can
62
+ * still see what used to exist.
63
+ *
64
+ * @param {import('knex').Knex} trx
65
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
66
+ * @param {Date} now
67
+ * @returns {Promise<string[]>} names of models newly flagged as removed
68
+ */
69
+ export declare function flagRemovedModels(trx: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, now: Date): Promise<string[]>;
70
+ /**
71
+ * Flags `_meta_fields` rows as removed for one model when their field
72
+ * name is no longer present on that model's current field set. Never
73
+ * deletes, same rationale as flagRemovedModels().
74
+ *
75
+ * @param {import('knex').Knex} trx
76
+ * @param {number} modelId
77
+ * @param {Set<string>} currentFieldNames
78
+ * @param {Date} now
79
+ * @returns {Promise<string[]>} field names newly flagged as removed
80
+ */
81
+ export declare function flagRemovedFields(trx: import('knex').Knex, modelId: number, currentFieldNames: Set<string>, now: Date): Promise<string[]>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Runs a migration's `up`. Thin pass-through kept mainly so
3
+ * applying/rolling back reads symmetrically and is discoverable from
4
+ * `@kiri-orm/core`'s exports.
5
+ *
6
+ * @param {import('knex').Knex} db
7
+ * @param {import('./generate.js').Migration} migration
8
+ */
9
+ export declare function applyMigration(db: import('knex').Knex, migration: import('./generate.js').Migration): Promise<void>;
10
+ /**
11
+ * Runs a migration's `down`. See generateMigration() for exactly what
12
+ * "reversible" does and doesn't mean here (schema-level, not
13
+ * data-level, for destructive operations).
14
+ *
15
+ * @param {import('knex').Knex} db
16
+ * @param {import('./generate.js').Migration} migration
17
+ */
18
+ export declare function rollbackMigration(db: import('knex').Knex, migration: import('./generate.js').Migration): Promise<void>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Renders a `DiffPlan` (from diffSchema) into human-readable lines,
3
+ * prefixed so destructive/ambiguous items are impossible to miss when
4
+ * reviewing before applying. This is the "dry-run" preview the
5
+ * roadmap calls for - the plan itself is already inert data, this
6
+ * just formats it for a human (or a future CLI) to review.
7
+ *
8
+ * @param {import('./diff.js').DiffPlan} plan
9
+ * @returns {string[]}
10
+ */
11
+ export declare function describePlan(plan: import('./diff.js').DiffPlan): string[];
@@ -0,0 +1,141 @@
1
+ export type DiffPlan = {
2
+ /**
3
+ * - model names that are entirely new
4
+ */
5
+ createModels: string[];
6
+ /**
7
+ * - previously-active models no longer
8
+ * in the registry: { modelName, tableName, fields, columns } where
9
+ * `fields`/`columns` are reconstructed from the stored meta rows'
10
+ * `options` JSON, so a rollback can recreate the table's schema
11
+ * even though the model no longer exists in code.
12
+ */
13
+ dropModels: Object[];
14
+ /**
15
+ * - { modelName, fromTable, toTable } -
16
+ * detected with certainty (not a heuristic): the model's `name` is
17
+ * its stable identity in `_meta_models`, so if that same name's
18
+ * resolved table name changed, it's unambiguously a rename.
19
+ */
20
+ renameModels: Object[];
21
+ /**
22
+ * -
23
+ * advisory only: models present in the old snapshot but absent from
24
+ * the registry, alongside newly-registered models, when neither list
25
+ * is empty and no explicit `modelRenames` resolved them. There's no
26
+ * way to know if these are genuinely related without the caller
27
+ * telling us - this exists purely to prompt "did you mean to rename
28
+ * one of these?" rather than to guess.
29
+ */
30
+ possibleModelRenames: {
31
+ removed: string[];
32
+ added: string[];
33
+ } | null;
34
+ /**
35
+ * - per model
36
+ */
37
+ fieldChanges: Record<string, FieldChangePlan>;
38
+ };
39
+ export type FieldChangePlan = {
40
+ /**
41
+ * - new field names on an existing model
42
+ */
43
+ addFields: string[];
44
+ /**
45
+ * - { fieldName, columnName, field } for
46
+ * fields removed from the model; `field` is reconstructed from the
47
+ * stored meta row's `options` JSON for rollback purposes.
48
+ */
49
+ dropFields: Object[];
50
+ /**
51
+ * - { from, to } - resolved via the
52
+ * caller's explicit `fieldRenames` option. Fully reversible: a
53
+ * RENAME COLUMN loses no data.
54
+ */
55
+ renameFields: Object[];
56
+ /**
57
+ * - { fieldName, fromColumn, toColumn } -
58
+ * detected with certainty: same field `name` (the stable identity
59
+ * key in `_meta_fields`), only its resolved column name changed
60
+ * (e.g. an explicit `column` option was added/changed). Not a
61
+ * heuristic guess, same reasoning as renameModels above.
62
+ */
63
+ columnRenames: Object[];
64
+ /**
65
+ * - { fieldName, from, to } - flagged
66
+ * but never auto-migrated (see generateMigration).
67
+ */
68
+ typeChanges: Object[];
69
+ /**
70
+ * -
71
+ * advisory only, same rationale as possibleModelRenames but at the
72
+ * field level (e.g. `customerId` renamed to `clientId` in code).
73
+ */
74
+ possibleFieldRenames: {
75
+ removed: string[];
76
+ added: string[];
77
+ } | null;
78
+ };
79
+ /**
80
+ * @typedef {Object} DiffPlan
81
+ * @property {string[]} createModels - model names that are entirely new
82
+ * @property {Object[]} dropModels - previously-active models no longer
83
+ * in the registry: { modelName, tableName, fields, columns } where
84
+ * `fields`/`columns` are reconstructed from the stored meta rows'
85
+ * `options` JSON, so a rollback can recreate the table's schema
86
+ * even though the model no longer exists in code.
87
+ * @property {Object[]} renameModels - { modelName, fromTable, toTable } -
88
+ * detected with certainty (not a heuristic): the model's `name` is
89
+ * its stable identity in `_meta_models`, so if that same name's
90
+ * resolved table name changed, it's unambiguously a rename.
91
+ * @property {{removed: string[], added: string[]}|null} possibleModelRenames -
92
+ * advisory only: models present in the old snapshot but absent from
93
+ * the registry, alongside newly-registered models, when neither list
94
+ * is empty and no explicit `modelRenames` resolved them. There's no
95
+ * way to know if these are genuinely related without the caller
96
+ * telling us - this exists purely to prompt "did you mean to rename
97
+ * one of these?" rather than to guess.
98
+ * @property {Record<string, FieldChangePlan>} fieldChanges - per model
99
+ */
100
+ /**
101
+ * @typedef {Object} FieldChangePlan
102
+ * @property {string[]} addFields - new field names on an existing model
103
+ * @property {Object[]} dropFields - { fieldName, columnName, field } for
104
+ * fields removed from the model; `field` is reconstructed from the
105
+ * stored meta row's `options` JSON for rollback purposes.
106
+ * @property {Object[]} renameFields - { from, to } - resolved via the
107
+ * caller's explicit `fieldRenames` option. Fully reversible: a
108
+ * RENAME COLUMN loses no data.
109
+ * @property {Object[]} columnRenames - { fieldName, fromColumn, toColumn } -
110
+ * detected with certainty: same field `name` (the stable identity
111
+ * key in `_meta_fields`), only its resolved column name changed
112
+ * (e.g. an explicit `column` option was added/changed). Not a
113
+ * heuristic guess, same reasoning as renameModels above.
114
+ * @property {Object[]} typeChanges - { fieldName, from, to } - flagged
115
+ * but never auto-migrated (see generateMigration).
116
+ * @property {{removed: string[], added: string[]}|null} possibleFieldRenames -
117
+ * advisory only, same rationale as possibleModelRenames but at the
118
+ * field level (e.g. `customerId` renamed to `clientId` in code).
119
+ */
120
+ /**
121
+ * Compares `modelRegistry`'s current state against what's recorded in
122
+ * `_meta_models`/`_meta_fields` (Phase 4) - NOT live schema
123
+ * introspection. This is precisely the reason Phase 4 exists: model
124
+ * and field *identity* (their `name`) is stable in the metadata even
125
+ * when their resolved table/column name changes, so a table or column
126
+ * rename is detected with certainty rather than guessed. A field or
127
+ * model being renamed *in code* (a genuinely new identity) can't be
128
+ * known for certain and is only ever surfaced as an advisory
129
+ * `possible...Renames` hint unless the caller explicitly resolves it.
130
+ *
131
+ * @param {import('knex').Knex} db
132
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
133
+ * @param {Object} [options]
134
+ * @param {Record<string, string>} [options.modelRenames] - { oldModelName: newModelName }
135
+ * @param {Record<string, Record<string, string>>} [options.fieldRenames] - { modelName: { oldFieldName: newFieldName } }
136
+ * @returns {Promise<DiffPlan>}
137
+ */
138
+ export declare function diffSchema(db: import('knex').Knex, modelRegistry: import('../models/registry.js').ModelRegistry, options?: {
139
+ modelRenames?: Record<string, string>;
140
+ fieldRenames?: Record<string, Record<string, string>>;
141
+ }): Promise<DiffPlan>;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Thrown by generateMigration() when a plan contains destructive
3
+ * operations (dropping a model, dropping a field) that weren't
4
+ * explicitly allowed via `{ allowDestructive: true }`, or unresolved
5
+ * field-type changes that Phase 6 refuses to auto-generate ALTER
6
+ * statements for. This is the central safety gate for this phase:
7
+ * nothing destructive is ever silently applied.
8
+ */
9
+ export declare class MigrationSafetyError extends Error {
10
+ constructor(message: any);
11
+ }
12
+ /**
13
+ * Thrown by the migration runner when the migrations on disk and the
14
+ * migrations recorded as applied in the database can't be reconciled
15
+ * safely - pending migrations blocking a generate, an applied
16
+ * migration whose file is gone, a new file that sorts before one
17
+ * already applied. Every one of these means the recorded "before"
18
+ * state a migration was generated against may no longer be true, so
19
+ * the runner stops rather than guess.
20
+ */
21
+ export declare class MigrationStateError extends Error {
22
+ constructor(message: any);
23
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The foreign keys a migration plan has to create, worked out once so the in-memory
3
+ * migration (generate.js) and the rendered file (render.js) agree:
4
+ *
5
+ * creation new models in dependency order, with the keys that go inside each CREATE TABLE
6
+ * (`inline`) and the few that can't (a cycle) added afterwards (`deferred`)
7
+ * added per existing model, the keys belonging to columns this migration adds
8
+ *
9
+ * Keys on columns that already exist are not part of a plan: the diff only sees fields.
10
+ * (`sync({ addMissingForeignKeys: true })` is the way to add those.)
11
+ *
12
+ * @param {import('./diff.js').DiffPlan} plan
13
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
14
+ */
15
+ export declare function planMigrationForeignKeys(plan: import('./diff.js').DiffPlan, modelRegistry: import('../models/registry.js').ModelRegistry): {
16
+ creation: {
17
+ order: object[];
18
+ inline: Map<string, object[]>;
19
+ deferred: Array<{
20
+ model: object;
21
+ fk: object;
22
+ }>;
23
+ };
24
+ added: {};
25
+ };
26
+ /** The source line for one foreign key, as written into a rendered migration file. */
27
+ export declare const renderForeignKey: (fk: any) => string;
@@ -0,0 +1,51 @@
1
+ export type Migration = {
2
+ up: (db: import('knex').Knex) => Promise<void>;
3
+ down: (db: import('knex').Knex) => Promise<void>;
4
+ /**
5
+ * - describePlan() output, for logging/review
6
+ */
7
+ summary: string[];
8
+ };
9
+ /**
10
+ * @typedef {Object} Migration
11
+ * @property {(db: import('knex').Knex) => Promise<void>} up
12
+ * @property {(db: import('knex').Knex) => Promise<void>} down
13
+ * @property {string[]} summary - describePlan() output, for logging/review
14
+ */
15
+ /**
16
+ * Turns a `DiffPlan` (from diffSchema) into a reversible migration:
17
+ * plain `up`/`down` async functions built from Knex's schema builder -
18
+ * generated as code you can inspect before running, not a black box.
19
+ *
20
+ * The central safety rule for this phase: **destructive operations are
21
+ * never included unless explicitly allowed**. If the plan drops a
22
+ * model or a field, this throws `MigrationSafetyError` describing
23
+ * exactly what's destructive, unless the caller passes
24
+ * `{ allowDestructive: true }` - a conscious, one-time
25
+ * acknowledgment, never a silent default.
26
+ *
27
+ * Field type changes are never auto-migrated at all, regardless of
28
+ * `allowDestructive` - they differ too much across dialects and risk
29
+ * silent truncation, so this always refuses until the caller resolves
30
+ * them by hand.
31
+ *
32
+ * Reversibility is schema-level, not data-level: a dropped model or
33
+ * field's `down` recreates the table/column shape (using the
34
+ * descriptor Phase 4 stored in `_meta_fields.options`), but rows that
35
+ * existed before the drop are gone - no migration tool can undo data
36
+ * a DROP already committed. Renames (table, column, or field) are the
37
+ * one case that's fully reversible with no data loss at all, since a
38
+ * RENAME never touches the underlying values.
39
+ *
40
+ * @param {import('./diff.js').DiffPlan} plan
41
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
42
+ * @param {Object} [options]
43
+ * @param {boolean} [options.allowDestructive]
44
+ * @param {import('../schema/column-builder-registry.js').ColumnBuilderRegistry} [options.columnBuilderRegistry]
45
+ * @returns {Migration}
46
+ * @throws {MigrationSafetyError}
47
+ */
48
+ export declare function generateMigration(plan: import('./diff.js').DiffPlan, modelRegistry: import('../models/registry.js').ModelRegistry, options?: {
49
+ allowDestructive?: boolean;
50
+ columnBuilderRegistry?: import('../schema/column-builder-registry.js').ColumnBuilderRegistry;
51
+ }): Migration;
@@ -0,0 +1,7 @@
1
+ export { diffSchema } from "./diff.js";
2
+ export { generateMigration } from "./generate.js";
3
+ export { describePlan } from "./describe.js";
4
+ export { applyMigration, rollbackMigration } from "./apply.js";
5
+ export { MigrationSafetyError, MigrationStateError } from "./errors.js";
6
+ export { renderMigrationSource } from "./render.js";
7
+ export { MIGRATIONS_TABLE, ensureMigrationsTable, listMigrationFiles, getMigrationStatus, migrateUp, migrateDown, generateMigrationFile, } from "./runner.js";
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Renders a `DiffPlan` as the source of a standalone ESM migration
3
+ * file - the on-disk counterpart of generateMigration()'s in-memory
4
+ * `up`/`down`, for a migration workflow that has to survive between
5
+ * runs.
6
+ *
7
+ * The file is meant to be read, reviewed and, if needed, edited:
8
+ *
9
+ * export const summary - the describePlan() lines, for logs and review
10
+ * export async function up(db, helpers)
11
+ * export async function down(db, helpers)
12
+ * export const meta - per touched model, the `_meta_*` snapshot
13
+ * before and after (see meta/snapshot.js);
14
+ * applied/rolled back with the schema change
15
+ *
16
+ * It is self-contained on purpose. Every field descriptor a change
17
+ * needs is embedded, so the file keeps meaning the same thing after
18
+ * the models it was generated from have changed again. It imports
19
+ * nothing: the column-building helpers arrive as `up`/`down`'s second
20
+ * argument, so the file runs wherever it is loaded from (the runner
21
+ * in ./runner.js supplies them) without needing `@kiri-orm/core` to
22
+ * resolve from the migrations directory.
23
+ *
24
+ * The safety rules are exactly generateMigration()'s, because this
25
+ * calls it first: a plan with destructive operations throws
26
+ * `MigrationSafetyError` unless `allowDestructive` is set, and field
27
+ * type changes always throw.
28
+ *
29
+ * @param {import('./diff.js').DiffPlan} plan
30
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
31
+ * @param {Object} [options]
32
+ * @param {boolean} [options.allowDestructive]
33
+ * @param {Record<string, { before: object|null, after: object|null }>} [options.meta]
34
+ * @param {string} [options.header] - text for the leading comment
35
+ * @returns {string}
36
+ * @throws {import('./errors.js').MigrationSafetyError}
37
+ */
38
+ export declare function renderMigrationSource(plan: import('./diff.js').DiffPlan, modelRegistry: import('../models/registry.js').ModelRegistry, options?: {
39
+ allowDestructive?: boolean;
40
+ meta?: Record<string, {
41
+ before: object | null;
42
+ after: object | null;
43
+ }>;
44
+ header?: string;
45
+ }): string;