@duraxis/migrations 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/LICENSE +15 -0
- package/README.md +192 -2
- package/dist/context.d.ts +30 -0
- package/dist/diff.d.ts +20 -0
- package/dist/index.cjs +470 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +456 -0
- package/dist/index.js.map +1 -0
- package/dist/runner.d.ts +49 -0
- package/dist/schema.d.ts +15 -0
- package/package.json +59 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# @duraxis/migrations
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- eb56e40: Add transactional collection alteration/removal, final-schema validation, schema-aware index rebuilding, and protected subsystem metadata. Add standalone ORM schema export and opt-in strict managed validation. Introduce the migration runtime and CLI with snapshots, schema comparison, atomic history, conservative rollback, baseline adoption, and recovery-aware publication. Document deployment sequencing and transaction memory limits.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [eb56e40]
|
|
12
|
+
- @duraxis/core@0.3.0
|
|
13
|
+
|
|
14
|
+
## 0.1.0
|
|
15
|
+
|
|
16
|
+
Initial migration tooling.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 João Paulo Dias
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
10
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
11
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
12
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
13
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
14
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
15
|
+
PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,193 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @duraxis/migrations
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Transactional schema evolution for Duraxis. Requires Node.js 24.15.0 or later.
|
|
4
|
+
The engine depends only on `@duraxis/core`; it does not load files, ORM entities,
|
|
5
|
+
NestJS, or concrete storage drivers. Use `@duraxis/cli` for project tooling.
|
|
6
|
+
|
|
7
|
+
## Installation and programmatic execution
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @duraxis/core @duraxis/migrations
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { MigrationRunner, defineMigration, createSnapshot, checksum } from "@duraxis/migrations";
|
|
15
|
+
|
|
16
|
+
const definition = {
|
|
17
|
+
name: "users",
|
|
18
|
+
fields: { name: { type: "string" as const, required: true } },
|
|
19
|
+
allowAdditionalFields: false,
|
|
20
|
+
indexes: [],
|
|
21
|
+
};
|
|
22
|
+
const migration = defineMigration({
|
|
23
|
+
id: "20261127110000000_create_users",
|
|
24
|
+
up(context) {
|
|
25
|
+
context.schema.createCollection(definition);
|
|
26
|
+
},
|
|
27
|
+
// This manual rollback deliberately removes records. Review backups first.
|
|
28
|
+
down(context) {
|
|
29
|
+
context.schema.dropCollection("users");
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
const runner = new MigrationRunner(database, [
|
|
33
|
+
{
|
|
34
|
+
migration,
|
|
35
|
+
// Your loader must hash the immutable executable artifact, not its ID alone.
|
|
36
|
+
checksum: checksum(immutableArtifactText),
|
|
37
|
+
snapshot: createSnapshot(migration.id, null, [definition]),
|
|
38
|
+
},
|
|
39
|
+
]);
|
|
40
|
+
await runner.up();
|
|
41
|
+
console.log(await runner.status());
|
|
42
|
+
console.log(await runner.drift());
|
|
43
|
+
await runner.down({ allowDestructive: true });
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The caller owns `database` and its storage. The runner never closes them. All
|
|
47
|
+
artifacts and their expected snapshots must be supplied in ascending ID order,
|
|
48
|
+
including every applied version. IDs have 17 UTC timestamp digits (milliseconds),
|
|
49
|
+
an underscore, and a lowercase underscore-separated name. Duplicate IDs,
|
|
50
|
+
missing parents, invalid snapshots, and modified applied artifacts are errors.
|
|
51
|
+
|
|
52
|
+
`up({ steps, to, allowDestructive })` applies one transaction per version.
|
|
53
|
+
`to` includes the target for `up`. `down()` reverts one version by default;
|
|
54
|
+
`down({ to })` **retains** that version and reverts later versions. `steps` and
|
|
55
|
+
`to` are mutually exclusive. Rollback requires `allowDestructive: true`, and all
|
|
56
|
+
selected versions must have `down` implementations before rollback begins.
|
|
57
|
+
|
|
58
|
+
## Context and schema editing
|
|
59
|
+
|
|
60
|
+
Migration callbacks receive schema inspection, generic collection replacement,
|
|
61
|
+
field/index/foreign-key editing, and document methods. They receive no transaction
|
|
62
|
+
commit, abort, close, raw-key access, or metadata access.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
async up(context) {
|
|
66
|
+
context.schema.addField("users", "status", {
|
|
67
|
+
type: "string", required: true, nullable: false,
|
|
68
|
+
});
|
|
69
|
+
await context.transform("users", document => ({
|
|
70
|
+
...document, status: "active",
|
|
71
|
+
}));
|
|
72
|
+
await context.schema.renameField("users", "name", "fullName");
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`get(collection, id)`, `scan(collection)`, `put(collection, id, document)`, and
|
|
77
|
+
`delete(collection, id)` operate on the same transaction. `transform` awaits
|
|
78
|
+
one callback per document. Scans include staged writes and capture their view
|
|
79
|
+
when iteration starts. Transformations must satisfy the schema currently staged
|
|
80
|
+
for each `put`; stage compatible field definitions before rewriting values.
|
|
81
|
+
Commit validates the final schema, including records written before alteration.
|
|
82
|
+
|
|
83
|
+
`schema.inspect()` returns detached definitions. `definition(name)` returns one.
|
|
84
|
+
`createCollection`, `createCollections`, `alterCollection`, `dropCollection`,
|
|
85
|
+
`addField`, `alterField`, `addIndex`, `removeIndex`, `addForeignKey`, and
|
|
86
|
+
`removeForeignKey` stage changes. Cross-collection references are checked against
|
|
87
|
+
the final catalog at commit, allowing cyclic definitions to be staged atomically.
|
|
88
|
+
Foreign key removal retains its supporting index unless explicitly removed.
|
|
89
|
+
|
|
90
|
+
`renameField` is asynchronous, preserves values, updates indexes and foreign keys,
|
|
91
|
+
and rejects destination collisions. `removeField` is asynchronous and requires
|
|
92
|
+
`{ strategy: "reject-if-populated" }` or `{ strategy: "delete-values" }`.
|
|
93
|
+
Dependent indexes and foreign keys must be removed first. `delete-values` is an
|
|
94
|
+
explicit irreversible data transformation. Dropping a collection removes its
|
|
95
|
+
logical records and index roots; no physical storage objects are directly deleted.
|
|
96
|
+
Old snapshots retain their roots, and ordinary garbage collection reclaims
|
|
97
|
+
unreachable objects under existing maintenance rules.
|
|
98
|
+
|
|
99
|
+
## Transactions, history, concurrency, and recovery
|
|
100
|
+
|
|
101
|
+
The runner reads history, verifies its expected predecessor, checks managed schema
|
|
102
|
+
drift, runs the callback, checks the expected result, and writes history within
|
|
103
|
+
one Core transaction. Final document, foreign key, and unique-index validation
|
|
104
|
+
runs before conditional manifest publication. An exception discards staged data,
|
|
105
|
+
catalog changes, and history together. Earlier successful migrations remain
|
|
106
|
+
committed when a later migration fails.
|
|
107
|
+
|
|
108
|
+
History is versioned JSON in the protected primary-tree logical key
|
|
109
|
+
`__duraxis/metadata/migrations`, scoped by the database's storage namespace. Each
|
|
110
|
+
entry includes ID, artifact checksum, applied time, sequence, resulting schema
|
|
111
|
+
hash, and an operation receipt. History follows normal object integrity checks,
|
|
112
|
+
snapshot publication, recovery, and GC. Ordinary transaction `put`/`delete`
|
|
113
|
+
cannot address reserved metadata. Core's explicit subsystem metadata API is a
|
|
114
|
+
trusted extension API, not an authorization boundary against hostile application
|
|
115
|
+
code with direct storage access.
|
|
116
|
+
|
|
117
|
+
Independent runners race on the existing storage manifest CAS. A conflicting
|
|
118
|
+
runner reloads and verifies history. It accepts an identical committed version
|
|
119
|
+
and otherwise stops; it never automatically replays a migration callback. A lost
|
|
120
|
+
commit acknowledgement is reconciled using persisted history receipts, then Core
|
|
121
|
+
commit-history recovery when necessary. Receipts remain usable after commit
|
|
122
|
+
history checkpointing. If success cannot be established, the original unknown
|
|
123
|
+
outcome is surfaced. Inspect persisted history and storage health before another
|
|
124
|
+
attempt. Migration callbacks must avoid nontransactional external side effects.
|
|
125
|
+
|
|
126
|
+
This mechanism also conflicts with ordinary concurrent application commits; it
|
|
127
|
+
does not lock out application writes or provide online schema-change coordination.
|
|
128
|
+
Quiesce incompatible writers during deployment. Disk retains exclusive directory
|
|
129
|
+
ownership. S3 uses the driver's existing conditional publication contract.
|
|
130
|
+
|
|
131
|
+
## Snapshots, comparison, and artifact identity
|
|
132
|
+
|
|
133
|
+
`canonicalSchema`, `canonicalJSON`, `schemaHash`, `createSnapshot`, and
|
|
134
|
+
`validateSnapshot` provide format-version-1 JSON snapshots with migration ID,
|
|
135
|
+
parent ID, canonical managed collections, and a SHA-256 schema hash. Collection,
|
|
136
|
+
field, index, and foreign-key names are deterministic; composite index component
|
|
137
|
+
order is preserved. Snapshots contain no timestamps or machine paths.
|
|
138
|
+
|
|
139
|
+
`diffSchemas(before, after)` returns a typed `SchemaPlan` with before/after
|
|
140
|
+
schemas and collection, field, index, foreign-key, and additional-field-policy
|
|
141
|
+
operations. Risks are `safe`, `requires-validation`,
|
|
142
|
+
`requires-data-transformation`, or `destructive`. Renames are never inferred.
|
|
143
|
+
`applySchemaPlan(context, plan)` verifies the predecessor and stages the final
|
|
144
|
+
catalog graph. This defers relationship validation until the graph is complete
|
|
145
|
+
instead of imposing an impossible topological order on cyclic relationships.
|
|
146
|
+
Required-field backfills and field-type conversions require manual migrations;
|
|
147
|
+
automatic plans refuse to invent values. Field removal rejects populated values.
|
|
148
|
+
|
|
149
|
+
The engine accepts SHA-256 artifact digests from its loader. The CLI defines an
|
|
150
|
+
identity using pinned TypeScript 5.9.3: two transpilation/printing passes targeting
|
|
151
|
+
ES2022 ESM, with comments removed and legacy decorators enabled. It verifies the
|
|
152
|
+
same digest for TypeScript and JavaScript emitted using those options. Ship ESM
|
|
153
|
+
migration files, preserve ESM imports, and do not bundle/minify or downlevel them.
|
|
154
|
+
Formatting, comments, and type-only edits are excluded from executable identity.
|
|
155
|
+
Changing executable code changes the checksum. Imported helper contents are not
|
|
156
|
+
transitively hashed: historical migrations must be self-contained, and any
|
|
157
|
+
external dependencies must be immutable and pinned. Upgrading the identity
|
|
158
|
+
compiler requires an explicit compatibility review, not rewriting history.
|
|
159
|
+
|
|
160
|
+
## Managed scope, baseline, and compatibility
|
|
161
|
+
|
|
162
|
+
Snapshots contain the complete schema managed by this migration chain. Drift is
|
|
163
|
+
checked over the union of names in all supplied snapshots; unrelated collections
|
|
164
|
+
are permitted and migration callbacks may not change them. `baseline()` requires
|
|
165
|
+
exactly one initial artifact and a matching persisted managed schema, then records
|
|
166
|
+
it without executing `up`. That artifact must also create the same schema on an
|
|
167
|
+
empty database. The CLI verifies its generated initial-schema artifact for this
|
|
168
|
+
workflow. Never use baseline to conceal drift.
|
|
169
|
+
|
|
170
|
+
Existing databases and manifest format 1 remain readable with the updated Core;
|
|
171
|
+
no metadata is created until migrations are adopted. Databases containing the
|
|
172
|
+
new reserved metadata entries require the updated Core for full-tree operations.
|
|
173
|
+
Do not downgrade Core on a migration-enabled database. Existing applications
|
|
174
|
+
without migration configuration retain their normal initialization behavior.
|
|
175
|
+
|
|
176
|
+
## Operational limits
|
|
177
|
+
|
|
178
|
+
Each migration is one transaction. Streaming reads do **not** make write staging
|
|
179
|
+
bounded: transformed writes, schema-validation writes, cascades, and deletes are
|
|
180
|
+
held in memory. Queries against a changed index use a transaction-local scan and
|
|
181
|
+
sort. Size migrations for available memory and test on representative data.
|
|
182
|
+
There is no implicit partial commit, resumable batching, online DDL, distributed
|
|
183
|
+
maintenance lock, or backup restoration. Retain backups before destructive
|
|
184
|
+
production operations. A structural inverse cannot reconstruct discarded values.
|
|
185
|
+
|
|
186
|
+
Use `duraxis migrate:up` before starting NestJS with `schema: { mode: "validate" }`
|
|
187
|
+
(or opt-in `validate-managed` for strict index validation on owned collections).
|
|
188
|
+
Named connections, async configuration, and auto-loaded entities remain under
|
|
189
|
+
NestJS's existing ownership model. A runner can reuse an already-owned Core
|
|
190
|
+
connection programmatically, but application startup does not run migrations.
|
|
191
|
+
For incompatible changes, stop older replicas, migrate once, then start compatible
|
|
192
|
+
replicas. Use staged backward-compatible application/schema releases when downtime
|
|
193
|
+
is unsuitable.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type CollectionDefinition, type DocumentRecord, type FieldDefinition, type ForeignKeyDefinition, type SecondaryIndexDefinition, type Transaction } from "@duraxis/core";
|
|
2
|
+
export declare class SchemaEditor {
|
|
3
|
+
#private;
|
|
4
|
+
constructor(tx: Transaction);
|
|
5
|
+
inspect(): readonly CollectionDefinition[];
|
|
6
|
+
definition(name: string): CollectionDefinition;
|
|
7
|
+
createCollection(definition: CollectionDefinition): void;
|
|
8
|
+
createCollections(definitions: readonly CollectionDefinition[]): void;
|
|
9
|
+
alterCollection(name: string, definition: CollectionDefinition): void;
|
|
10
|
+
dropCollection(name: string): void;
|
|
11
|
+
addField(collection: string, name: string, definition: FieldDefinition): void;
|
|
12
|
+
alterField(collection: string, name: string, definition: FieldDefinition): void;
|
|
13
|
+
removeField(collection: string, name: string, options: {
|
|
14
|
+
strategy: "reject-if-populated" | "delete-values";
|
|
15
|
+
}): Promise<void>;
|
|
16
|
+
renameField(collection: string, from: string, to: string): Promise<void>;
|
|
17
|
+
addIndex(collection: string, index: SecondaryIndexDefinition): void;
|
|
18
|
+
removeIndex(collection: string, name: string): void;
|
|
19
|
+
addForeignKey(collection: string, definition: ForeignKeyDefinition): void;
|
|
20
|
+
removeForeignKey(collection: string, name: string): void;
|
|
21
|
+
}
|
|
22
|
+
export interface MigrationContext {
|
|
23
|
+
readonly schema: SchemaEditor;
|
|
24
|
+
readonly get: Transaction["getDocument"];
|
|
25
|
+
readonly scan: Transaction["scanCollection"];
|
|
26
|
+
readonly put: Transaction["putDocument"];
|
|
27
|
+
readonly delete: Transaction["deleteDocument"];
|
|
28
|
+
transform(collection: string, transform: (document: DocumentRecord, id: string) => DocumentRecord | Promise<DocumentRecord>): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare function createMigrationContext(tx: Transaction): MigrationContext;
|
package/dist/diff.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { CollectionDefinition, FieldDefinition, ForeignKeyDefinition, SecondaryIndexDefinition } from "@duraxis/core";
|
|
2
|
+
import type { MigrationContext } from "./context.js";
|
|
3
|
+
export type MigrationRisk = "safe" | "requires-validation" | "requires-data-transformation" | "destructive";
|
|
4
|
+
interface Change<K extends string, T> {
|
|
5
|
+
readonly kind: K;
|
|
6
|
+
readonly collection: string;
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly before: T | null;
|
|
9
|
+
readonly after: T | null;
|
|
10
|
+
readonly risk: MigrationRisk;
|
|
11
|
+
}
|
|
12
|
+
export type MigrationOperation = Change<"collection", CollectionDefinition> | Change<"field", FieldDefinition> | Change<"index", SecondaryIndexDefinition> | Change<"foreign-key", ForeignKeyDefinition> | Change<"additional-fields", boolean>;
|
|
13
|
+
export interface SchemaPlan {
|
|
14
|
+
readonly before: readonly CollectionDefinition[];
|
|
15
|
+
readonly after: readonly CollectionDefinition[];
|
|
16
|
+
readonly operations: readonly MigrationOperation[];
|
|
17
|
+
}
|
|
18
|
+
export declare function diffSchemas(before: readonly CollectionDefinition[], after: readonly CollectionDefinition[]): SchemaPlan;
|
|
19
|
+
export declare function applySchemaPlan(context: MigrationContext, plan: SchemaPlan): Promise<void>;
|
|
20
|
+
export {};
|