@warlock.js/cascade 4.2.10 → 4.2.11
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 +15 -0
- package/cjs/index.cjs +40 -3
- package/cjs/index.cjs.map +1 -1
- package/esm/migration/migration.d.mts +20 -0
- package/esm/migration/migration.d.mts.map +1 -1
- package/esm/migration/migration.mjs +34 -0
- package/esm/migration/migration.mjs.map +1 -1
- package/esm/remover/database-remover.d.mts.map +1 -1
- package/esm/remover/database-remover.mjs +3 -1
- package/esm/remover/database-remover.mjs.map +1 -1
- package/esm/writer/database-writer.d.mts.map +1 -1
- package/esm/writer/database-writer.mjs +4 -2
- package/esm/writer/database-writer.mjs.map +1 -1
- package/llms-full.txt +24 -1
- package/package.json +5 -5
- package/skills/configure-delete-strategy/SKILL.md +4 -0
- package/skills/write-migration/SKILL.md +20 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database-remover.d.mts","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/remover/database-remover.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"database-remover.d.mts","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/remover/database-remover.ts"],"mappings":";;;;;;AAmCA;;;;;;;;;;;;;;;;;;cAAa,eAAA,YAA2B,eAAA;EA+BnB;EAAA,iBA7BF,KAAA;EA6Ca;EAAA,iBA1Cb,IAAA;EA0CmC;EAAA,iBAvCnC,UAAA;EAmMT;EAAA,iBAhMS,MAAA;EA0OH;EAAA,iBAvOG,KAAA;EAuOQ;EAAA,iBApOR,UAAA;;;;;;;;;;;;;cAcE,KAAA,EAAO,KAAA;;;;;;;;EAgBb,OAAA,CAAQ,OAAA,GAAS,cAAA,GAAsB,OAAA,CAAQ,aAAA;;;;;;;;;;;;;;;;;;;;;UA4JpD,kBAAA;;;;;;;;;;;;UAsBA,iBAAA;;;;;;;;;UAoBM,WAAA;AAAA"}
|
|
@@ -96,8 +96,10 @@ var DatabaseRemover = class {
|
|
|
96
96
|
case "soft": {
|
|
97
97
|
const deletedAtColumn = this.ctor.deletedAtColumn;
|
|
98
98
|
if (deletedAtColumn === false || deletedAtColumn === void 0) throw new Error(`Cannot perform soft delete on ${this.ctor.name}: deletedAtColumn is not configured. Set a column name or use a different delete strategy.`);
|
|
99
|
-
const
|
|
99
|
+
const deletedAt = /* @__PURE__ */ new Date();
|
|
100
|
+
const updateOperations = { $set: { [deletedAtColumn]: deletedAt } };
|
|
100
101
|
deletedCount = (await this.driver.update(this.table, filter, updateOperations)).modifiedCount > 0 ? 1 : 0;
|
|
102
|
+
if (deletedCount > 0) this.model.set(deletedAtColumn, deletedAt);
|
|
101
103
|
break;
|
|
102
104
|
}
|
|
103
105
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database-remover.mjs","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/remover/database-remover.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport type { DriverContract, UpdateOperations } from \"../contracts/database-driver.contract\";\nimport type {\n RemoverContract,\n RemoverOptions,\n RemoverResult,\n} from \"../contracts/database-remover.contract\";\nimport type { OnDeletedEventContext } from \"../events/model-events\";\nimport type { ChildModel, Model } from \"../model/model\";\nimport { getModelDeletedEvent } from \"../sync/model-events\";\nimport type { DataSource } from \"./../data-source/data-source\";\n\n/**\n * Database remover service that orchestrates model deletion.\n *\n * Handles the complete deletion pipeline:\n * 1. Strategy resolution (options → model static → data source default)\n * 2. Validation (check if model is new, has primary key)\n * 3. Event emission (deleting, deleted)\n * 4. Driver execution (based on strategy: trash, permanent, or soft)\n * 5. Post-deletion cleanup (mark as new, reset state)\n *\n * @example\n * ```typescript\n * const user = await User.find(1);\n * const remover = new DatabaseRemover(user);\n * const result = await remover.destroy();\n *\n * console.log(result.success); // true\n * console.log(result.strategy); // \"trash\" | \"permanent\" | \"soft\"\n * ```\n */\nexport class DatabaseRemover implements RemoverContract {\n /** The model instance being deleted */\n private readonly model: Model;\n\n /** Model constructor reference */\n private readonly ctor: ChildModel<Model>;\n\n /** Data source containing driver */\n private readonly dataSource: DataSource;\n\n /** Database driver for executing queries */\n private readonly driver: DriverContract;\n\n /** Table/collection name */\n private readonly table: string;\n\n /** Primary key field name */\n private readonly primaryKey: string;\n\n /**\n * Create a new remover instance for a model.\n *\n * @param model - The model instance to delete\n *\n * @example\n * ```typescript\n * const user = await User.find(1);\n * const remover = new DatabaseRemover(user);\n * await remover.destroy();\n * ```\n */\n public constructor(model: Model) {\n this.model = model;\n this.ctor = model.constructor as ChildModel<Model>;\n this.dataSource = this.ctor.getDataSource();\n this.driver = this.dataSource.driver;\n this.table = this.ctor.table;\n this.primaryKey = this.ctor.primaryKey;\n }\n\n /**\n * Destroy (delete) the model instance from the database.\n *\n * @param options - Remover options\n * @returns Result containing success status, strategy used, and metadata\n * @throws {Error} If model is new (not saved) or if deletion fails\n */\n public async destroy(options: RemoverOptions = {}): Promise<RemoverResult> {\n // 1. Resolve strategy (options → model static → data source default → permanent)\n const strategy =\n options.strategy ??\n this.ctor.deleteStrategy ??\n this.dataSource.defaultDeleteStrategy ??\n \"permanent\";\n\n // 2. Validate model is not new and has primary key\n if (this.model.isNew) {\n throw new Error(\n `Cannot destroy ${this.ctor.name} instance that hasn't been saved to the database.`,\n );\n }\n\n const primaryKeyValue = this.model.get(this.primaryKey);\n if (!primaryKeyValue) {\n throw new Error(\n `Cannot destroy ${this.ctor.name} instance: primary key (${this.primaryKey}) is missing.`,\n );\n }\n\n // 3. Emit deleting event (unless skipEvents)\n if (!options.skipEvents) {\n await this.model.emitEvent(\"deleting\", {\n strategy,\n primaryKeyValue,\n primaryKey: this.primaryKey,\n });\n }\n\n // 4. Execute deletion based on strategy\n let deletedCount = 0;\n let trashRecord: Record<string, unknown> | undefined;\n\n const filter = { [this.primaryKey]: primaryKeyValue };\n\n const context: Partial<OnDeletedEventContext> = {\n strategy,\n primaryKeyValue,\n primaryKey: this.primaryKey,\n };\n\n switch (strategy) {\n case \"trash\": {\n // Move to trash table, then delete\n const trashTable = this.resolveTrashTable();\n const documentData = { ...this.model.data };\n\n // Prepare trash record with metadata and handle ID conflicts\n const trashData = this.prepareTrashRecord(documentData);\n\n // Insert into trash table\n const insertResult = await this.driver.insert(trashTable, trashData);\n trashRecord = insertResult.document as Record<string, unknown>;\n\n context.trashRecord = trashRecord;\n\n // Delete original\n const result = await this.driver.delete(this.table, filter);\n deletedCount = result > 0 ? 1 : 0;\n break;\n }\n\n case \"permanent\": {\n // Direct deletion\n const result = await this.driver.delete(this.table, filter);\n deletedCount = result > 0 ? 1 : 0;\n break;\n }\n\n case \"soft\": {\n // Set deletedAt timestamp (using resolved column name)\n const deletedAtColumn = this.ctor.deletedAtColumn;\n \n // Only proceed if deletedAtColumn is configured (not false or undefined)\n if (deletedAtColumn === false || deletedAtColumn === undefined) {\n throw new Error(\n `Cannot perform soft delete on ${this.ctor.name}: deletedAtColumn is not configured. ` +\n `Set a column name or use a different delete strategy.`,\n );\n }\n \n const updateOperations: UpdateOperations = {\n $set: { [deletedAtColumn]: new Date() },\n };\n const updateResult = await this.driver.update(this.table, filter, updateOperations);\n deletedCount = updateResult.modifiedCount > 0 ? 1 : 0;\n break;\n }\n }\n\n if (deletedCount === 0) {\n throw new Error(`Failed to destroy ${this.ctor.name} instance: record not found.`);\n }\n\n context.deletedCount = deletedCount;\n\n // 5. Post-deletion cleanup\n // Only mark as new for permanent and trash (soft delete keeps the record)\n if (strategy !== \"soft\") {\n this.model.isNew = true;\n }\n\n // 6. Emit deleted event (unless skipEvents)\n if (!options.skipEvents) {\n await this.model.emitEvent(\"deleted\", context);\n }\n\n // 7. Trigger sync operations (fire-and-forget, non-blocking)\n if (!options.skipSync) {\n void this.triggerSync();\n }\n\n return {\n success: true,\n deletedCount,\n strategy,\n trashRecord,\n };\n }\n\n /**\n * Prepare the trash record by preserving all original fields and adding deletion metadata.\n *\n * Keeps all original fields intact for easy restoration and adds:\n * - `deletedAt`: Timestamp when the record was deleted\n * - `originalTable`: The table/collection the record came from (for filtering in restoreAll)\n *\n * **ID Handling:**\n * - MongoDB with `_id`: Keeps `_id` as-is (unique across database)\n * - MongoDB with auto-increment `id`: Keeps `id` as a regular field (not primary key)\n * - SQL: Keeps original `id` as a regular field (trash table uses its own auto-increment primary key)\n *\n * The trash table should use its own primary key structure:\n * - MongoDB: Uses `_id` (ObjectId) as primary key, original `id` is just a field\n * - SQL: Uses auto-increment `trashId` as primary key, original `id` is just a field\n *\n * @param documentData - The original document data\n * @returns Prepared trash record data with all original fields + deletedAt + originalTable\n * @private\n */\n private prepareTrashRecord(documentData: Record<string, unknown>): Record<string, unknown> {\n // Preserve all original fields and add deletion metadata\n return {\n ...documentData,\n deletedAt: new Date(),\n originalTable: this.table,\n };\n }\n\n /**\n * Resolve the trash table/collection name.\n *\n * Priority:\n * 1. Model.trashTable (if set)\n * 2. Data source defaultTrashTable (e.g., \"RecycleBin\" for MongoDB)\n * 3. Default pattern: `{table}Trash`\n *\n * @returns The trash table/collection name\n * @private\n */\n private resolveTrashTable(): string {\n if (this.ctor.trashTable) {\n return this.ctor.trashTable;\n }\n\n if (this.dataSource.defaultTrashTable) {\n return this.dataSource.defaultTrashTable;\n }\n\n return `${this.table}Trash`;\n }\n\n /**\n * Trigger sync operations after successful deletion.\n *\n * Emits a model.deleted event that ModelSyncOperation listens to.\n * The sync is handled by registered sync operations, not directly here.\n *\n * @private\n */\n private async triggerSync(): Promise<void> {\n // Emit model.deleted event - ModelSyncOperation listens to these\n await events.triggerAll(getModelDeletedEvent(this.ctor), this.model);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAa,kBAAb,MAAwD;;CAEtD,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;;;;;;;;;;;;CAcjB,AAAO,YAAY,OAAc;EAC/B,KAAK,QAAQ;EACb,KAAK,OAAO,MAAM;EAClB,KAA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,KAAK,KAAK,2FAElD;IAGF,MAAM,mBAAqC,EACzC,MAAM,GAAG,kCAAkB,IAAI,KAAK,EAAE,EACxC;IAEA,gBAAe,MADY,KAAK,OAAO,OAAO,KAAK,OAAO,QAAQ,gBAAgB,EACvD,CAAC,gBAAgB,IAAI,IAAI;IACpD;GACF;EACF;EAEA,IAAI,iBAAiB,GACnB,MAAM,IAAI,MAAM,qBAAqB,KAAK,KAAK,KAAK,6BAA6B;EAGnF,QAAQ,eAAe;EAIvB,IAAI,aAAa,QACf,KAAK,MAAM,QAAQ;EAIrB,IAAI,CAAC,QAAQ,YACX,MAAM,KAAK,MAAM,UAAU,WAAW,OAAO;EAI/C,IAAI,CAAC,QAAQ,UACX,AAAK,KAAK,YAAY;EAGxB,OAAO;GACL,SAAS;GACT;GACA;GACA;EACF;CACF;;;;;;;;;;;;;;;;;;;;;CAsBA,AAAQ,mBAAmB,cAAgE;EAEzF,OAAO;GACL,GAAG;GACH,2BAAW,IAAI,KAAK;GACpB,eAAe,KAAK;EACtB;CACF;;;;;;;;;;;;CAaA,AAAQ,oBAA4B;EAClC,IAAI,KAAK,KAAK,YACZ,OAAO,KAAK,KAAK;EAGnB,IAAI,KAAK,WAAW,mBAClB,OAAO,KAAK,WAAW;EAGzB,OAAO,GAAG,KAAK,MAAM;CACvB;;;;;;;;;CAUA,MAAc,cAA6B;EAEzC,MAAM,OAAO,WAAW,qBAAqB,KAAK,IAAI,GAAG,KAAK,KAAK;CACrE;AACF"}
|
|
1
|
+
{"version":3,"file":"database-remover.mjs","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/remover/database-remover.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport type {\n DriverContract,\n UpdateOperations,\n} from \"../contracts/database-driver.contract\";\nimport type {\n RemoverContract,\n RemoverOptions,\n RemoverResult,\n} from \"../contracts/database-remover.contract\";\nimport type { OnDeletedEventContext } from \"../events/model-events\";\nimport type { ChildModel, Model } from \"../model/model\";\nimport { getModelDeletedEvent } from \"../sync/model-events\";\nimport type { DataSource } from \"./../data-source/data-source\";\n\n/**\n * Database remover service that orchestrates model deletion.\n *\n * Handles the complete deletion pipeline:\n * 1. Strategy resolution (options → model static → data source default)\n * 2. Validation (check if model is new, has primary key)\n * 3. Event emission (deleting, deleted)\n * 4. Driver execution (based on strategy: trash, permanent, or soft)\n * 5. Post-deletion cleanup (mark as new, reset state)\n *\n * @example\n * ```typescript\n * const user = await User.find(1);\n * const remover = new DatabaseRemover(user);\n * const result = await remover.destroy();\n *\n * console.log(result.success); // true\n * console.log(result.strategy); // \"trash\" | \"permanent\" | \"soft\"\n * ```\n */\nexport class DatabaseRemover implements RemoverContract {\n /** The model instance being deleted */\n private readonly model: Model;\n\n /** Model constructor reference */\n private readonly ctor: ChildModel<Model>;\n\n /** Data source containing driver */\n private readonly dataSource: DataSource;\n\n /** Database driver for executing queries */\n private readonly driver: DriverContract;\n\n /** Table/collection name */\n private readonly table: string;\n\n /** Primary key field name */\n private readonly primaryKey: string;\n\n /**\n * Create a new remover instance for a model.\n *\n * @param model - The model instance to delete\n *\n * @example\n * ```typescript\n * const user = await User.find(1);\n * const remover = new DatabaseRemover(user);\n * await remover.destroy();\n * ```\n */\n public constructor(model: Model) {\n this.model = model;\n this.ctor = model.constructor as ChildModel<Model>;\n this.dataSource = this.ctor.getDataSource();\n this.driver = this.dataSource.driver;\n this.table = this.ctor.table;\n this.primaryKey = this.ctor.primaryKey;\n }\n\n /**\n * Destroy (delete) the model instance from the database.\n *\n * @param options - Remover options\n * @returns Result containing success status, strategy used, and metadata\n * @throws {Error} If model is new (not saved) or if deletion fails\n */\n public async destroy(options: RemoverOptions = {}): Promise<RemoverResult> {\n // 1. Resolve strategy (options → model static → data source default → permanent)\n const strategy =\n options.strategy ??\n this.ctor.deleteStrategy ??\n this.dataSource.defaultDeleteStrategy ??\n \"permanent\";\n\n // 2. Validate model is not new and has primary key\n if (this.model.isNew) {\n throw new Error(\n `Cannot destroy ${this.ctor.name} instance that hasn't been saved to the database.`,\n );\n }\n\n const primaryKeyValue = this.model.get(this.primaryKey);\n if (!primaryKeyValue) {\n throw new Error(\n `Cannot destroy ${this.ctor.name} instance: primary key (${this.primaryKey}) is missing.`,\n );\n }\n\n // 3. Emit deleting event (unless skipEvents)\n if (!options.skipEvents) {\n await this.model.emitEvent(\"deleting\", {\n strategy,\n primaryKeyValue,\n primaryKey: this.primaryKey,\n });\n }\n\n // 4. Execute deletion based on strategy\n let deletedCount = 0;\n let trashRecord: Record<string, unknown> | undefined;\n\n const filter = { [this.primaryKey]: primaryKeyValue };\n\n const context: Partial<OnDeletedEventContext> = {\n strategy,\n primaryKeyValue,\n primaryKey: this.primaryKey,\n };\n\n switch (strategy) {\n case \"trash\": {\n // Move to trash table, then delete\n const trashTable = this.resolveTrashTable();\n const documentData = { ...this.model.data };\n\n // Prepare trash record with metadata and handle ID conflicts\n const trashData = this.prepareTrashRecord(documentData);\n\n // Insert into trash table\n const insertResult = await this.driver.insert(trashTable, trashData);\n trashRecord = insertResult.document as Record<string, unknown>;\n\n context.trashRecord = trashRecord;\n\n // Delete original\n const result = await this.driver.delete(this.table, filter);\n deletedCount = result > 0 ? 1 : 0;\n break;\n }\n\n case \"permanent\": {\n // Direct deletion\n const result = await this.driver.delete(this.table, filter);\n deletedCount = result > 0 ? 1 : 0;\n break;\n }\n\n case \"soft\": {\n // Set deletedAt timestamp (using resolved column name)\n const deletedAtColumn = this.ctor.deletedAtColumn;\n\n // Only proceed if deletedAtColumn is configured (not false or undefined)\n if (deletedAtColumn === false || deletedAtColumn === undefined) {\n throw new Error(\n `Cannot perform soft delete on ${this.ctor.name}: deletedAtColumn is not configured. ` +\n `Set a column name or use a different delete strategy.`,\n );\n }\n\n const deletedAt = new Date();\n const updateOperations: UpdateOperations = {\n $set: { [deletedAtColumn]: deletedAt },\n };\n const updateResult = await this.driver.update(\n this.table,\n filter,\n updateOperations,\n );\n deletedCount = updateResult.modifiedCount > 0 ? 1 : 0;\n\n // The row stays (unlike trash/permanent), so reflect the persisted\n // timestamp on the in-memory model — otherwise the instance is stale\n // and `model.get(deletedAtColumn)` stays undefined after destroy().\n if (deletedCount > 0) {\n this.model.set(deletedAtColumn, deletedAt);\n }\n break;\n }\n }\n\n if (deletedCount === 0) {\n throw new Error(\n `Failed to destroy ${this.ctor.name} instance: record not found.`,\n );\n }\n\n context.deletedCount = deletedCount;\n\n // 5. Post-deletion cleanup\n // Only mark as new for permanent and trash (soft delete keeps the record)\n if (strategy !== \"soft\") {\n this.model.isNew = true;\n }\n\n // 6. Emit deleted event (unless skipEvents)\n if (!options.skipEvents) {\n await this.model.emitEvent(\"deleted\", context);\n }\n\n // 7. Trigger sync operations (fire-and-forget, non-blocking)\n if (!options.skipSync) {\n void this.triggerSync();\n }\n\n return {\n success: true,\n deletedCount,\n strategy,\n trashRecord,\n };\n }\n\n /**\n * Prepare the trash record by preserving all original fields and adding deletion metadata.\n *\n * Keeps all original fields intact for easy restoration and adds:\n * - `deletedAt`: Timestamp when the record was deleted\n * - `originalTable`: The table/collection the record came from (for filtering in restoreAll)\n *\n * **ID Handling:**\n * - MongoDB with `_id`: Keeps `_id` as-is (unique across database)\n * - MongoDB with auto-increment `id`: Keeps `id` as a regular field (not primary key)\n * - SQL: Keeps original `id` as a regular field (trash table uses its own auto-increment primary key)\n *\n * The trash table should use its own primary key structure:\n * - MongoDB: Uses `_id` (ObjectId) as primary key, original `id` is just a field\n * - SQL: Uses auto-increment `trashId` as primary key, original `id` is just a field\n *\n * @param documentData - The original document data\n * @returns Prepared trash record data with all original fields + deletedAt + originalTable\n * @private\n */\n private prepareTrashRecord(\n documentData: Record<string, unknown>,\n ): Record<string, unknown> {\n // Preserve all original fields and add deletion metadata\n return {\n ...documentData,\n deletedAt: new Date(),\n originalTable: this.table,\n };\n }\n\n /**\n * Resolve the trash table/collection name.\n *\n * Priority:\n * 1. Model.trashTable (if set)\n * 2. Data source defaultTrashTable (e.g., \"RecycleBin\" for MongoDB)\n * 3. Default pattern: `{table}Trash`\n *\n * @returns The trash table/collection name\n * @private\n */\n private resolveTrashTable(): string {\n if (this.ctor.trashTable) {\n return this.ctor.trashTable;\n }\n\n if (this.dataSource.defaultTrashTable) {\n return this.dataSource.defaultTrashTable;\n }\n\n return `${this.table}Trash`;\n }\n\n /**\n * Trigger sync operations after successful deletion.\n *\n * Emits a model.deleted event that ModelSyncOperation listens to.\n * The sync is handled by registered sync operations, not directly here.\n *\n * @private\n */\n private async triggerSync(): Promise<void> {\n // Emit model.deleted event - ModelSyncOperation listens to these\n await events.triggerAll(getModelDeletedEvent(this.ctor), this.model);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,kBAAb,MAAwD;;CAEtD,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;;;;;;;;;;;;CAcjB,AAAO,YAAY,OAAc;EAC/B,KAAK,QAAQ;EACb,KAAK,OAAO,MAAM;EAClB,KAAK,aAAa,KAAK,KAAK,cAAc;EAC1C,KAAK,SAAS,KAAK,WAAW;EAC9B,KAAK,QAAQ,KAAK,KAAK;EACvB,KAAK,aAAa,KAAK,KAAK;CAC9B;;;;;;;;CASA,MAAa,QAAQ,UAA0B,CAAC,GAA2B;EAEzE,MAAM,WACJ,QAAQ,YACR,KAAK,KAAK,kBACV,KAAK,WAAW,yBAChB;EAGF,IAAI,KAAK,MAAM,OACb,MAAM,IAAI,MACR,kBAAkB,KAAK,KAAK,KAAK,kDACnC;EAGF,MAAM,kBAAkB,KAAK,MAAM,IAAI,KAAK,UAAU;EACtD,IAAI,CAAC,iBACH,MAAM,IAAI,MACR,kBAAkB,KAAK,KAAK,KAAK,0BAA0B,KAAK,WAAW,cAC7E;EAIF,IAAI,CAAC,QAAQ,YACX,MAAM,KAAK,MAAM,UAAU,YAAY;GACrC;GACA;GACA,YAAY,KAAK;EACnB,CAAC;EAIH,IAAI,eAAe;EACnB,IAAI;EAEJ,MAAM,SA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AAAQ,mBACN,cACyB;EAEzB,OAAO;GACL,GAAG;GACH,2BAAW,IAAI,KAAK;GACpB,eAAe,KAAK;EACtB;CACF;;;;;;;;;;;;CAaA,AAAQ,oBAA4B;EAClC,IAAI,KAAK,KAAK,YACZ,OAAO,KAAK,KAAK;EAGnB,IAAI,KAAK,WAAW,mBAClB,OAAO,KAAK,WAAW;EAGzB,OAAO,GAAG,KAAK,MAAM;CACvB;;;;;;;;;CAUA,MAAc,cAA6B;EAEzC,MAAM,OAAO,WAAW,qBAAqB,KAAK,IAAI,GAAG,KAAK,KAAK;CACrE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database-writer.d.mts","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/writer/database-writer.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"database-writer.d.mts","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/writer/database-writer.ts"],"mappings":";;;;;;AAsDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,cAAA,YAA0B,cAAA;EA4V7B;EAAA,iBA1VS,KAAA;EA0ZT;EAAA,iBAvZS,IAAA;EA0bH;EAAA,iBAvbG,UAAA;EAubQ;EAAA,iBApbR,MAAA;;mBAGA,KAAA;;mBAGA,UAAA;;mBAGA,MAAA;;mBAGA,UAAA;;;;;;;;;;;;;cAcE,KAAA,EAAO,KAAA;;;;;;;;EAkBb,IAAA,CAAK,OAAA,GAAS,aAAA,GAAqB,OAAA,CAAQ,YAAA;;;;;;;;;;;UAsE1C,eAAA;;;;;;;;UAuFA,aAAA;;;;;;;;UAgDA,aAAA;;;;;;EA2CD,cAAA,IAAkB,OAAA;;;;;;;;;;;;;;;;;;;;;;UA6CvB,qBAAA;;;;;;;;;;;;UAuCA,gBAAA;;;;;;;;;;;;UAyBA,kBAAA;;;;;;;;;UAsBA,SAAA;;;;;;;;;;UAaM,WAAA;AAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getModelUpdatedEvent } from "../sync/model-events.mjs";
|
|
2
2
|
import { DatabaseWriterValidationError } from "../validation/database-writer-validation-error.mjs";
|
|
3
3
|
import "../validation/index.mjs";
|
|
4
|
+
import { when } from "@mongez/reinforcements";
|
|
4
5
|
import events from "@mongez/events";
|
|
5
6
|
import { getSealConfig, v } from "@warlock.js/seal";
|
|
6
7
|
|
|
@@ -137,8 +138,9 @@ var DatabaseWriter = class {
|
|
|
137
138
|
const validationSchema = isInsert ? this.schema.clone() : this.schema.clone(Object.keys(this.model.data)).extend({
|
|
138
139
|
id: v.scalar().optional(),
|
|
139
140
|
_id: v.any().optional(),
|
|
140
|
-
[this.ctor.createdAtColumn]: v.date().optional(),
|
|
141
|
-
[this.ctor.updatedAtColumn]: v.date().optional()
|
|
141
|
+
...when(this.ctor.createdAtColumn, () => ({ [this.ctor.createdAtColumn]: v.date().optional() })),
|
|
142
|
+
...when(this.ctor.updatedAtColumn, () => ({ [this.ctor.updatedAtColumn]: v.date().optional() })),
|
|
143
|
+
...when(this.ctor.deletedAtColumn, () => ({ [this.ctor.deletedAtColumn]: v.date().optional() }))
|
|
142
144
|
});
|
|
143
145
|
if (this.strictMode === "strip") validationSchema.stripUnknown();
|
|
144
146
|
else if (this.strictMode === "fail") validationSchema.allowUnknown(false);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database-writer.mjs","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/writer/database-writer.ts"],"sourcesContent":["import events from \"@mongez/events\";\r\nimport { getSealConfig, v, type ObjectValidator } from \"@warlock.js/seal\";\r\nimport type {\r\n DriverContract,\r\n InsertResult,\r\n UpdateOperations,\r\n UpdateResult,\r\n} from \"../contracts/database-driver.contract\";\r\nimport type {\r\n WriterContract,\r\n WriterOptions,\r\n WriterResult,\r\n} from \"../contracts/database-writer.contract\";\r\nimport type { ChildModel, Model } from \"../model/model\";\r\nimport { getModelUpdatedEvent } from \"../sync/model-events\";\r\nimport type { StrictMode } from \"../types\";\r\nimport { DatabaseWriterValidationError } from \"../validation\";\r\nimport type { DataSource } from \"./../data-source/data-source\";\r\n\r\n/**\r\n * Database writer service that orchestrates model persistence.\r\n *\r\n * Handles the complete save pipeline:\r\n * 1. Check for changes (skip if no changes and not new)\r\n * 2. Emit `saving` event (for data enrichment)\r\n * 3. Emit `validating` event\r\n * 4. Validate and cast data via @warlock.js/seal schema\r\n * 5. Emit `validated` event\r\n * 6. Generate ID (for new NoSQL records)\r\n * 7. Emit `creating`/`updating` events\r\n * 8. Execute insert or update via driver\r\n * 9. Merge returned data into model\r\n * 10. Reset dirty tracker and update `isNew` flag\r\n * 11. Emit `saved` and `created`/`updated` events\r\n *\r\n * @example\r\n * ```typescript\r\n * const user = new User({ name: \"Alice\", email: \"alice@example.com\" });\r\n * const writer = new DatabaseWriter(user);\r\n * await writer.save();\r\n *\r\n * console.log(user.get(\"id\")); // 1 (auto-generated)\r\n * console.log(user.get(\"_id\")); // ObjectId(\"...\")\r\n *\r\n * // Update existing record\r\n * user.set(\"name\", \"Alice Smith\");\r\n * await writer.save();\r\n * // Only updates the \"name\" field (partial update)\r\n *\r\n * // Silent save (no events)\r\n * await writer.save({ skipEvents: true });\r\n * ```\r\n */\r\nexport class DatabaseWriter implements WriterContract {\r\n /** The model instance being persisted */\r\n private readonly model: Model;\r\n\r\n /** Model constructor reference */\r\n private readonly ctor: ChildModel<Model>;\r\n\r\n /** Data source containing driver and ID generator */\r\n private readonly dataSource: DataSource;\r\n\r\n /** Database driver for executing queries */\r\n private readonly driver: DriverContract;\r\n\r\n /** Table/collection name */\r\n private readonly table: string;\r\n\r\n /** Primary key field name */\r\n private readonly primaryKey: string;\r\n\r\n /** Validation schema (if defined) */\r\n private readonly schema?: ObjectValidator;\r\n\r\n /** Strict mode configuration */\r\n private readonly strictMode: StrictMode;\r\n\r\n /**\r\n * Create a new writer instance for a model.\r\n *\r\n * @param model - The model instance to persist\r\n *\r\n * @example\r\n * ```typescript\r\n * const user = new User({ name: \"Alice\" });\r\n * const writer = new DatabaseWriter(user);\r\n * await writer.save();\r\n * ```\r\n */\r\n public constructor(model: Model) {\r\n this.model = model;\r\n this.ctor = model.constructor as ChildModel<Model>;\r\n this.dataSource = this.ctor.getDataSource();\r\n this.driver = this.dataSource.driver;\r\n this.table = this.ctor.table;\r\n this.primaryKey = this.ctor.primaryKey;\r\n this.schema = this.ctor.schema;\r\n this.strictMode = this.ctor.strictMode;\r\n }\r\n\r\n /**\r\n * Save the model instance to the database.\r\n *\r\n * @param options - Save options\r\n * @returns Result with success status, document, and metadata\r\n * @throws {ValidationError} If validation fails\r\n */\r\n public async save(options: WriterOptions = {}): Promise<WriterResult> {\r\n const isInsert = this.model.isNew;\r\n\r\n // 1. Check if model has changes (skip if no changes and not new)\r\n if (!isInsert && !this.model.hasChanges()) {\r\n return {\r\n success: true,\r\n document: this.model.data,\r\n isNew: false,\r\n modifiedCount: 0,\r\n };\r\n }\r\n\r\n // 2. Emit saving event (before validation for data enrichment)\r\n if (!options.skipEvents) {\r\n await this.model.emitEvent(\"saving\", {\r\n isInsert,\r\n options,\r\n mode: isInsert ? \"insert\" : \"update\",\r\n });\r\n }\r\n\r\n // 3. Validate and cast data\r\n await this.validateAndCast(isInsert, options);\r\n\r\n // 4. Execute insert or update\r\n let result: InsertResult | UpdateResult;\r\n\r\n if (isInsert) {\r\n result = await this.performInsert(options);\r\n } else {\r\n result = await this.performUpdate(options);\r\n }\r\n\r\n // 5. Reset dirty tracker and update isNew flag\r\n const changedFields = isInsert ? [] : this.model.getDirtyColumns();\r\n this.model.dirtyTracker.reset();\r\n this.model.isNew = false;\r\n\r\n // 6. Emit post-save events\r\n if (!options.skipEvents) {\r\n await this.model.emitEvent(\"saved\");\r\n await this.model.emitEvent(isInsert ? \"created\" : \"updated\");\r\n }\r\n\r\n // 7. Trigger sync operations (fire-and-forget, non-blocking)\r\n if (!options.skipSync && !isInsert) {\r\n void this.triggerSync(changedFields);\r\n }\r\n\r\n return {\r\n success: true,\r\n document: this.model.data,\r\n isNew: isInsert,\r\n modifiedCount: isInsert ? undefined : (result as UpdateResult).modifiedCount,\r\n };\r\n }\r\n\r\n /**\r\n * Validate and cast model data using the schema.\r\n *\r\n * Updates the model's data in-place with validated/casted values.\r\n *\r\n * @param isInsert - Whether this is an insert operation\r\n * @param options - Save options\r\n * @throws {ValidationError} If validation fails\r\n * @private\r\n */\r\n private async validateAndCast(isInsert: boolean, options: WriterOptions): Promise<void> {\r\n // Emit validating event\r\n if (!options.skipEvents) {\r\n await this.model.emitEvent(\"validating\", {\r\n isInsert,\r\n options,\r\n mode: isInsert ? \"insert\" : \"update\",\r\n });\r\n }\r\n\r\n // Skip validation if requested or no schema defined\r\n if (options.skipValidation || !this.schema) {\r\n return;\r\n }\r\n\r\n // Clone schema for partial data (updates only)\r\n const validationSchema = isInsert\r\n ? this.schema.clone()\r\n : this.schema.clone(Object.keys(this.model.data)).extend({\r\n id: v.scalar().optional(),\r\n _id: v.any().optional(),\r\n [this.ctor.createdAtColumn as string]: v.date().optional(),\r\n [this.ctor.updatedAtColumn as string]: v.date().optional(),\r\n });\r\n\r\n // Apply strict mode\r\n if (this.strictMode === \"strip\") {\r\n validationSchema.stripUnknown();\r\n } else if (this.strictMode === \"fail\") {\r\n validationSchema.allowUnknown(false);\r\n } else if (this.strictMode === \"allow\") {\r\n validationSchema.allowUnknown(true);\r\n }\r\n\r\n // Run validation\r\n const result = await v.validate(validationSchema, this.model.data, {\r\n context: {\r\n model: this.model,\r\n },\r\n ...getSealConfig(),\r\n });\r\n\r\n if (!result.isValid) {\r\n console.trace(result.errors);\r\n\r\n const error = new DatabaseWriterValidationError(\r\n `[${this.model.constructor.name} Model] ${isInsert ? \"Insert\" : \"Update\"} Validation failed`,\r\n result.errors,\r\n );\r\n if (!options.skipEvents) {\r\n await this.model.emitEvent(\"validated\", { result, error });\r\n }\r\n throw error;\r\n }\r\n\r\n // Update model data with validated/casted data\r\n this.model.replaceData(result.data);\r\n\r\n // Emit validated event\r\n if (!options.skipEvents) {\r\n await this.model.emitEvent(\"validated\", { result });\r\n }\r\n }\r\n\r\n /**\r\n * Perform an insert operation.\r\n *\r\n * @param options - Save options\r\n * @returns Insert result\r\n * @private\r\n */\r\n private async performInsert(options: WriterOptions): Promise<InsertResult> {\r\n // Generate ID if needed (NoSQL only)\r\n await this.generateNextId();\r\n\r\n // Get data to insert (already validated and casted)\r\n const dataToInsert = this.model.data;\r\n\r\n // Add createdAt and updatedAt to the data (using resolved column names)\r\n // The column names are already resolved through the hierarchy:\r\n // Model static property > Database config > Driver defaults > undefined\r\n const createdAtColumn = this.ctor.createdAtColumn;\r\n\r\n if (createdAtColumn) {\r\n dataToInsert[createdAtColumn] = new Date();\r\n }\r\n\r\n const updatedAtColumn = this.ctor.updatedAtColumn;\r\n if (updatedAtColumn) {\r\n dataToInsert[updatedAtColumn] = new Date();\r\n }\r\n\r\n // Emit creating event\r\n if (!options.skipEvents) {\r\n await this.model.emitEvent(\"creating\");\r\n }\r\n\r\n // INSERT: use full validated data\r\n const result = await this.driver.insert(this.table, dataToInsert);\r\n\r\n // Merge returned data (e.g., generated _id, timestamps)\r\n // Note: We use merge here because the result might not include all fields\r\n // (e.g., our generated 'id' field), and we don't want to lose them\r\n this.model.merge(result.document as Record<string, unknown>);\r\n\r\n // Reset dirty tracker immediately after merge to prevent\r\n // database-generated fields (like _id) from being marked as dirty\r\n this.model.dirtyTracker.reset();\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Perform an update operation.\r\n *\r\n * @param options - Save options\r\n * @returns Update result\r\n * @private\r\n */\r\n private async performUpdate(options: WriterOptions): Promise<UpdateResult> {\r\n // Emit updating event\r\n if (!options.skipEvents) {\r\n await this.model.emitEvent(\"updating\");\r\n }\r\n\r\n // Update the updatedAt timestamp (using resolved column name)\r\n const updatedAtColumn = this.ctor.updatedAtColumn;\r\n if (updatedAtColumn) {\r\n this.model.set(updatedAtColumn, new Date());\r\n }\r\n\r\n if (options.replace) {\r\n const document = await this.driver.replace(\r\n this.table,\r\n {\r\n [this.primaryKey]: this.model.get(this.primaryKey),\r\n },\r\n this.model.data,\r\n );\r\n\r\n if (document) {\r\n this.model.replaceData(document as Record<string, unknown>);\r\n }\r\n\r\n return { modifiedCount: document ? 1 : 0 };\r\n }\r\n\r\n // Build operations from dirty tracker\r\n const operations = this.buildUpdateOperations();\r\n\r\n // Build filter using primary key\r\n const filter = { [this.primaryKey]: this.model.get(this.primaryKey) };\r\n\r\n // Execute update with operations\r\n return await this.driver.update(this.table, filter, operations);\r\n }\r\n\r\n /**\r\n * Generate ID for the model if auto-generation is enabled.\r\n *\r\n * @private\r\n */\r\n public async generateNextId(): Promise<void> {\r\n if (!this.ctor.autoGenerateId || this.model.get(\"id\")) {\r\n return;\r\n }\r\n\r\n const idGenerator = this.dataSource.idGenerator;\r\n if (!idGenerator) {\r\n return;\r\n }\r\n\r\n // Resolve ID generation options from model configuration\r\n const initialId = this.resolveInitialId();\r\n\r\n const incrementIdBy = this.resolveIncrementBy();\r\n\r\n const id = await idGenerator.generateNextId({\r\n table: this.table,\r\n initialId,\r\n incrementIdBy,\r\n });\r\n\r\n this.model.set(\"id\", id);\r\n }\r\n\r\n /**\r\n * Build update operations from the model's dirty tracker.\r\n *\r\n * Handles both modified fields ($set) and removed fields ($unset).\r\n *\r\n * @returns Update operations for the driver\r\n * @private\r\n *\r\n * @example\r\n * ```typescript\r\n * // Model with changes\r\n * user.set(\"name\", \"Alice\");\r\n * user.unset(\"tempField\");\r\n *\r\n * const operations = this.buildUpdateOperations();\r\n * // {\r\n * // $set: { name: \"Alice\" },\r\n * // $unset: { tempField: 1 }\r\n * // }\r\n * ```\r\n */\r\n private buildUpdateOperations(): UpdateOperations {\r\n const operations: UpdateOperations = {};\r\n\r\n // Get dirty columns (modified fields)\r\n const dirtyColumns = this.model.getDirtyColumns();\r\n\r\n if (dirtyColumns.length > 0) {\r\n operations.$set = {};\r\n for (const column of dirtyColumns) {\r\n const value = this.model.get(column);\r\n if (value === undefined) continue;\r\n\r\n operations.$set[column] = this.model.get(column);\r\n }\r\n }\r\n\r\n // Get removed columns\r\n const removedColumns = this.model.getRemovedColumns();\r\n if (removedColumns.length > 0) {\r\n operations.$unset = {};\r\n for (const column of removedColumns) {\r\n operations.$unset[column] = 1;\r\n }\r\n }\r\n\r\n return operations;\r\n }\r\n\r\n /**\r\n * Resolve the initial ID from model configuration.\r\n *\r\n * Priority:\r\n * 1. Model.initialId (explicit value)\r\n * 2. Model.randomInitialId (random or function)\r\n * 3. Default: 1\r\n *\r\n * @returns The initial ID value\r\n * @private\r\n */\r\n private resolveInitialId(): number {\r\n if (this.ctor.initialId) {\r\n return this.ctor.initialId;\r\n }\r\n\r\n if (this.ctor.randomInitialId) {\r\n return typeof this.ctor.randomInitialId === \"function\"\r\n ? this.ctor.randomInitialId()\r\n : this.randomInt(10000, 499999);\r\n }\r\n\r\n return 1; // Default initial ID\r\n }\r\n\r\n /**\r\n * Resolve the increment value from model configuration.\r\n *\r\n * Priority:\r\n * 1. Model.incrementIdBy (explicit value)\r\n * 2. Model.randomIncrement (random or function)\r\n * 3. Default: 1\r\n *\r\n * @returns The increment value\r\n * @private\r\n */\r\n private resolveIncrementBy(): number {\r\n if (this.ctor.incrementIdBy) {\r\n return this.ctor.incrementIdBy;\r\n }\r\n\r\n if (this.ctor.randomIncrement) {\r\n return typeof this.ctor.randomIncrement === \"function\"\r\n ? this.ctor.randomIncrement()\r\n : this.randomInt(1, 10);\r\n }\r\n\r\n return 1; // Default increment\r\n }\r\n\r\n /**\r\n * Generate a random integer between min and max (inclusive).\r\n *\r\n * @param min - Minimum value\r\n * @param max - Maximum value\r\n * @returns Random integer\r\n * @private\r\n */\r\n private randomInt(min: number, max: number): number {\r\n return Math.floor(Math.random() * (max - min + 1)) + min;\r\n }\r\n\r\n /**\r\n * Trigger sync operations after successful save.\r\n *\r\n * Emits a model.updated event that ModelSyncOperation listens to.\r\n * The sync is handled by registered sync operations, not directly here.\r\n *\r\n * @param changedFields - Fields that were changed (for filtering)\r\n * @private\r\n */\r\n private async triggerSync(changedFields: string[]): Promise<void> {\r\n // Emit model.updated event - ModelSyncOperation listens to these\r\n await events.triggerAll(getModelUpdatedEvent(this.ctor), this.model, changedFields);\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAa,iBAAb,MAAsD;;CAEpD,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;;;;;;;;;;;;CAcjB,AAAO,YAAY,OAAc;EAC/B,KAAK,QAAQ;EACb,KAAK,OAAO,MAAM;EAClB,KAAK,aAAa,KAAK,KAAK,cAAc;EAC1C,KAAK,SAAS,KAAK,WAAW;EAC9B,KAAK,QAAQ,KAAK,KAAK;EACvB,KAAK,aAAa,KAAK,KAAK;EAC5B,KAAK,SAAS,KAAK,KAAK;EACxB,KAAK,aAAa,KAAK,KAAK;CAC9B;;;;;;;;CASA,MAAa,KAAK,UAAyB,CAAC,GAA0B;EACpE,MAAM,WAAW,KAAK,MAAM;EAG5B,IAAI,CAAC,YAAY,CAAC,KAAK,MAAM,WAAW,GACtC,OAAO;GACL,SAAS;GACT,UAAU,KAAK,MAAM;GACrB,OAAO;GACP,eAAe;EACjB;EAIF,IAAI,CAAC,QAAQ,YACX,MAAM,KAAK,MAAM,UAAU,UAAU;GACnC;GACA;GACA,MAAM,WAAW,WAAW;EAC9B,CAAC;EAIH,MAAM,KAAK,gBAAgB,UAAU,OAAO;EAG5C,IAAI;EAEJ,IAAI,UACF,SAAS,MAAM,KAAK,cAAc,OAAO;OAEzC,SAAS,MAAM,KAAK,cAAc,OAAO;EAI3C,MAAM,gBAAgB,WAAW,CAAC,IAAI,KAAK,MAAM,gBAAgB;EACjE,KAAK,MAAM,aAAa,MAAM;EAC9B,KAAK,MAAM,QAAQ;EAGnB,IAAI,CAAC,QAAQ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O,KAAK,KAAK,oBAAoB,aACxC,KAAK,KAAK,gBAAgB,IAC1B,KAAK,UAAU,GAAG,EAAE;EAG1B,OAAO;CACT;;;;;;;;;CAUA,AAAQ,UAAU,KAAa,KAAqB;EAClD,OAAO,KAAK,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,EAAE,IAAI;CACvD;;;;;;;;;;CAWA,MAAc,YAAY,eAAwC;EAEhE,MAAM,OAAO,WAAW,qBAAqB,KAAK,IAAI,GAAG,KAAK,OAAO,aAAa;CACpF;AACF"}
|
|
1
|
+
{"version":3,"file":"database-writer.mjs","names":[],"sources":["../../../../../../../@warlock.js/cascade/src/writer/database-writer.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport { when } from \"@mongez/reinforcements\";\nimport { getSealConfig, v, type ObjectValidator } from \"@warlock.js/seal\";\nimport type {\n DriverContract,\n InsertResult,\n UpdateOperations,\n UpdateResult,\n} from \"../contracts/database-driver.contract\";\nimport type {\n WriterContract,\n WriterOptions,\n WriterResult,\n} from \"../contracts/database-writer.contract\";\nimport type { ChildModel, Model } from \"../model/model\";\nimport { getModelUpdatedEvent } from \"../sync/model-events\";\nimport type { StrictMode } from \"../types\";\nimport { DatabaseWriterValidationError } from \"../validation\";\nimport type { DataSource } from \"./../data-source/data-source\";\n\n/**\n * Database writer service that orchestrates model persistence.\n *\n * Handles the complete save pipeline:\n * 1. Check for changes (skip if no changes and not new)\n * 2. Emit `saving` event (for data enrichment)\n * 3. Emit `validating` event\n * 4. Validate and cast data via @warlock.js/seal schema\n * 5. Emit `validated` event\n * 6. Generate ID (for new NoSQL records)\n * 7. Emit `creating`/`updating` events\n * 8. Execute insert or update via driver\n * 9. Merge returned data into model\n * 10. Reset dirty tracker and update `isNew` flag\n * 11. Emit `saved` and `created`/`updated` events\n *\n * @example\n * ```typescript\n * const user = new User({ name: \"Alice\", email: \"alice@example.com\" });\n * const writer = new DatabaseWriter(user);\n * await writer.save();\n *\n * console.log(user.get(\"id\")); // 1 (auto-generated)\n * console.log(user.get(\"_id\")); // ObjectId(\"...\")\n *\n * // Update existing record\n * user.set(\"name\", \"Alice Smith\");\n * await writer.save();\n * // Only updates the \"name\" field (partial update)\n *\n * // Silent save (no events)\n * await writer.save({ skipEvents: true });\n * ```\n */\nexport class DatabaseWriter implements WriterContract {\n /** The model instance being persisted */\n private readonly model: Model;\n\n /** Model constructor reference */\n private readonly ctor: ChildModel<Model>;\n\n /** Data source containing driver and ID generator */\n private readonly dataSource: DataSource;\n\n /** Database driver for executing queries */\n private readonly driver: DriverContract;\n\n /** Table/collection name */\n private readonly table: string;\n\n /** Primary key field name */\n private readonly primaryKey: string;\n\n /** Validation schema (if defined) */\n private readonly schema?: ObjectValidator;\n\n /** Strict mode configuration */\n private readonly strictMode: StrictMode;\n\n /**\n * Create a new writer instance for a model.\n *\n * @param model - The model instance to persist\n *\n * @example\n * ```typescript\n * const user = new User({ name: \"Alice\" });\n * const writer = new DatabaseWriter(user);\n * await writer.save();\n * ```\n */\n public constructor(model: Model) {\n this.model = model;\n this.ctor = model.constructor as ChildModel<Model>;\n this.dataSource = this.ctor.getDataSource();\n this.driver = this.dataSource.driver;\n this.table = this.ctor.table;\n this.primaryKey = this.ctor.primaryKey;\n this.schema = this.ctor.schema;\n this.strictMode = this.ctor.strictMode;\n }\n\n /**\n * Save the model instance to the database.\n *\n * @param options - Save options\n * @returns Result with success status, document, and metadata\n * @throws {ValidationError} If validation fails\n */\n public async save(options: WriterOptions = {}): Promise<WriterResult> {\n const isInsert = this.model.isNew;\n\n // 1. Check if model has changes (skip if no changes and not new)\n if (!isInsert && !this.model.hasChanges()) {\n return {\n success: true,\n document: this.model.data,\n isNew: false,\n modifiedCount: 0,\n };\n }\n\n // 2. Emit saving event (before validation for data enrichment)\n if (!options.skipEvents) {\n await this.model.emitEvent(\"saving\", {\n isInsert,\n options,\n mode: isInsert ? \"insert\" : \"update\",\n });\n }\n\n // 3. Validate and cast data\n await this.validateAndCast(isInsert, options);\n\n // 4. Execute insert or update\n let result: InsertResult | UpdateResult;\n\n if (isInsert) {\n result = await this.performInsert(options);\n } else {\n result = await this.performUpdate(options);\n }\n\n // 5. Reset dirty tracker and update isNew flag\n const changedFields = isInsert ? [] : this.model.getDirtyColumns();\n this.model.dirtyTracker.reset();\n this.model.isNew = false;\n\n // 6. Emit post-save events\n if (!options.skipEvents) {\n await this.model.emitEvent(\"saved\");\n await this.model.emitEvent(isInsert ? \"created\" : \"updated\");\n }\n\n // 7. Trigger sync operations (fire-and-forget, non-blocking)\n if (!options.skipSync && !isInsert) {\n void this.triggerSync(changedFields);\n }\n\n return {\n success: true,\n document: this.model.data,\n isNew: isInsert,\n modifiedCount: isInsert\n ? undefined\n : (result as UpdateResult).modifiedCount,\n };\n }\n\n /**\n * Validate and cast model data using the schema.\n *\n * Updates the model's data in-place with validated/casted values.\n *\n * @param isInsert - Whether this is an insert operation\n * @param options - Save options\n * @throws {ValidationError} If validation fails\n * @private\n */\n private async validateAndCast(\n isInsert: boolean,\n options: WriterOptions,\n ): Promise<void> {\n // Emit validating event\n if (!options.skipEvents) {\n await this.model.emitEvent(\"validating\", {\n isInsert,\n options,\n mode: isInsert ? \"insert\" : \"update\",\n });\n }\n\n // Skip validation if requested or no schema defined\n if (options.skipValidation || !this.schema) {\n return;\n }\n\n // Clone schema for partial data (updates only).\n // Whitelist the framework-managed system columns so a model carrying them\n // (id / _id / timestamps / soft-delete deletedAt) validates cleanly instead\n // of being stripped (strictMode \"strip\") or rejected (strictMode \"fail\").\n // `when(...)` adds each timestamp/soft-delete column only when configured\n // (truthy) — the lazy factory means a disabled column (`false`) never even\n // builds a bogus schema key.\n const validationSchema = isInsert\n ? this.schema.clone()\n : this.schema.clone(Object.keys(this.model.data)).extend({\n id: v.scalar().optional(),\n _id: v.any().optional(),\n ...when(this.ctor.createdAtColumn, () => ({\n [this.ctor.createdAtColumn as string]: v.date().optional(),\n })),\n ...when(this.ctor.updatedAtColumn, () => ({\n [this.ctor.updatedAtColumn as string]: v.date().optional(),\n })),\n ...when(this.ctor.deletedAtColumn, () => ({\n [this.ctor.deletedAtColumn as string]: v.date().optional(),\n })),\n });\n\n // Apply strict mode\n if (this.strictMode === \"strip\") {\n validationSchema.stripUnknown();\n } else if (this.strictMode === \"fail\") {\n validationSchema.allowUnknown(false);\n } else if (this.strictMode === \"allow\") {\n validationSchema.allowUnknown(true);\n }\n\n // Run validation\n const result = await v.validate(validationSchema, this.model.data, {\n context: {\n model: this.model,\n },\n ...getSealConfig(),\n });\n\n if (!result.isValid) {\n console.trace(result.errors);\n\n const error = new DatabaseWriterValidationError(\n `[${this.model.constructor.name} Model] ${isInsert ? \"Insert\" : \"Update\"} Validation failed`,\n result.errors,\n );\n if (!options.skipEvents) {\n await this.model.emitEvent(\"validated\", { result, error });\n }\n throw error;\n }\n\n // Update model data with validated/casted data\n this.model.replaceData(result.data);\n\n // Emit validated event\n if (!options.skipEvents) {\n await this.model.emitEvent(\"validated\", { result });\n }\n }\n\n /**\n * Perform an insert operation.\n *\n * @param options - Save options\n * @returns Insert result\n * @private\n */\n private async performInsert(options: WriterOptions): Promise<InsertResult> {\n // Generate ID if needed (NoSQL only)\n await this.generateNextId();\n\n // Get data to insert (already validated and casted)\n const dataToInsert = this.model.data;\n\n // Add createdAt and updatedAt to the data (using resolved column names)\n // The column names are already resolved through the hierarchy:\n // Model static property > Database config > Driver defaults > undefined\n const createdAtColumn = this.ctor.createdAtColumn;\n\n if (createdAtColumn) {\n dataToInsert[createdAtColumn] = new Date();\n }\n\n const updatedAtColumn = this.ctor.updatedAtColumn;\n if (updatedAtColumn) {\n dataToInsert[updatedAtColumn] = new Date();\n }\n\n // Emit creating event\n if (!options.skipEvents) {\n await this.model.emitEvent(\"creating\");\n }\n\n // INSERT: use full validated data\n const result = await this.driver.insert(this.table, dataToInsert);\n\n // Merge returned data (e.g., generated _id, timestamps)\n // Note: We use merge here because the result might not include all fields\n // (e.g., our generated 'id' field), and we don't want to lose them\n this.model.merge(result.document as Record<string, unknown>);\n\n // Reset dirty tracker immediately after merge to prevent\n // database-generated fields (like _id) from being marked as dirty\n this.model.dirtyTracker.reset();\n\n return result;\n }\n\n /**\n * Perform an update operation.\n *\n * @param options - Save options\n * @returns Update result\n * @private\n */\n private async performUpdate(options: WriterOptions): Promise<UpdateResult> {\n // Emit updating event\n if (!options.skipEvents) {\n await this.model.emitEvent(\"updating\");\n }\n\n // Update the updatedAt timestamp (using resolved column name)\n const updatedAtColumn = this.ctor.updatedAtColumn;\n if (updatedAtColumn) {\n this.model.set(updatedAtColumn, new Date());\n }\n\n if (options.replace) {\n const document = await this.driver.replace(\n this.table,\n {\n [this.primaryKey]: this.model.get(this.primaryKey),\n },\n this.model.data,\n );\n\n if (document) {\n this.model.replaceData(document as Record<string, unknown>);\n }\n\n return { modifiedCount: document ? 1 : 0 };\n }\n\n // Build operations from dirty tracker\n const operations = this.buildUpdateOperations();\n\n // Build filter using primary key\n const filter = { [this.primaryKey]: this.model.get(this.primaryKey) };\n\n // Execute update with operations\n return await this.driver.update(this.table, filter, operations);\n }\n\n /**\n * Generate ID for the model if auto-generation is enabled.\n *\n * @private\n */\n public async generateNextId(): Promise<void> {\n if (!this.ctor.autoGenerateId || this.model.get(\"id\")) {\n return;\n }\n\n const idGenerator = this.dataSource.idGenerator;\n if (!idGenerator) {\n return;\n }\n\n // Resolve ID generation options from model configuration\n const initialId = this.resolveInitialId();\n\n const incrementIdBy = this.resolveIncrementBy();\n\n const id = await idGenerator.generateNextId({\n table: this.table,\n initialId,\n incrementIdBy,\n });\n\n this.model.set(\"id\", id);\n }\n\n /**\n * Build update operations from the model's dirty tracker.\n *\n * Handles both modified fields ($set) and removed fields ($unset).\n *\n * @returns Update operations for the driver\n * @private\n *\n * @example\n * ```typescript\n * // Model with changes\n * user.set(\"name\", \"Alice\");\n * user.unset(\"tempField\");\n *\n * const operations = this.buildUpdateOperations();\n * // {\n * // $set: { name: \"Alice\" },\n * // $unset: { tempField: 1 }\n * // }\n * ```\n */\n private buildUpdateOperations(): UpdateOperations {\n const operations: UpdateOperations = {};\n\n // Get dirty columns (modified fields)\n const dirtyColumns = this.model.getDirtyColumns();\n\n if (dirtyColumns.length > 0) {\n operations.$set = {};\n for (const column of dirtyColumns) {\n const value = this.model.get(column);\n if (value === undefined) continue;\n\n operations.$set[column] = this.model.get(column);\n }\n }\n\n // Get removed columns\n const removedColumns = this.model.getRemovedColumns();\n if (removedColumns.length > 0) {\n operations.$unset = {};\n for (const column of removedColumns) {\n operations.$unset[column] = 1;\n }\n }\n\n return operations;\n }\n\n /**\n * Resolve the initial ID from model configuration.\n *\n * Priority:\n * 1. Model.initialId (explicit value)\n * 2. Model.randomInitialId (random or function)\n * 3. Default: 1\n *\n * @returns The initial ID value\n * @private\n */\n private resolveInitialId(): number {\n if (this.ctor.initialId) {\n return this.ctor.initialId;\n }\n\n if (this.ctor.randomInitialId) {\n return typeof this.ctor.randomInitialId === \"function\"\n ? this.ctor.randomInitialId()\n : this.randomInt(10000, 499999);\n }\n\n return 1; // Default initial ID\n }\n\n /**\n * Resolve the increment value from model configuration.\n *\n * Priority:\n * 1. Model.incrementIdBy (explicit value)\n * 2. Model.randomIncrement (random or function)\n * 3. Default: 1\n *\n * @returns The increment value\n * @private\n */\n private resolveIncrementBy(): number {\n if (this.ctor.incrementIdBy) {\n return this.ctor.incrementIdBy;\n }\n\n if (this.ctor.randomIncrement) {\n return typeof this.ctor.randomIncrement === \"function\"\n ? this.ctor.randomIncrement()\n : this.randomInt(1, 10);\n }\n\n return 1; // Default increment\n }\n\n /**\n * Generate a random integer between min and max (inclusive).\n *\n * @param min - Minimum value\n * @param max - Maximum value\n * @returns Random integer\n * @private\n */\n private randomInt(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n\n /**\n * Trigger sync operations after successful save.\n *\n * Emits a model.updated event that ModelSyncOperation listens to.\n * The sync is handled by registered sync operations, not directly here.\n *\n * @param changedFields - Fields that were changed (for filtering)\n * @private\n */\n private async triggerSync(changedFields: string[]): Promise<void> {\n // Emit model.updated event - ModelSyncOperation listens to these\n await events.triggerAll(\n getModelUpdatedEvent(this.ctor),\n this.model,\n changedFields,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,iBAAb,MAAsD;;CAEpD,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;;;;;;;;;;;;CAcjB,AAAO,YAAY,OAAc;EAC/B,KAAK,QAAQ;EACb,KAAK,OAAO,MAAM;EAClB,KAAK,aAAa,KAAK,KAAK,cAAc;EAC1C,KAAK,SAAS,KAAK,WAAW;EAC9B,KAAK,QAAQ,KAAK,KAAK;EACvB,KAAK,aAAa,KAAK,KAAK;EAC5B,KAAK,SAAS,KAAK,KAAK;EACxB,KAAK,aAAa,KAAK,KAAK;CAC9B;;;;;;;;CASA,MAAa,KAAK,UAAyB,CAAC,GAA0B;EACpE,MAAM,WAAW,KAAK,MAAM;EAG5B,IAAI,CAAC,YAAY,CAAC,KAAK,MAAM,WAAW,GACtC,OAAO;GACL,SAAS;GACT,UAAU,KAAK,MAAM;GACrB,OAAO;GACP,eAAe;EACjB;EAIF,IAAI,CAAC,QAAQ,YACX,MAAM,KAAK,MAAM,UAAU,UAAU;GACnC;GACA;GACA,MAAM,WAAW,WAAW;EAC9B,CAAC;EAIH,MAAM,KAAK,gBAAgB,UAAU,OAAO;EAG5C,IAAI;EAEJ,IAAI,UACF,SAAS,MAAM,KAAK,cAAc,OAAO;OAEzC,SAAS,MAAM,KAAK,cAAc,OAAO;EAI3C,MAAM,gBAAgB,WAAW,CAAC,IAAI,KAAK,MAAM,gBAAgB;EACjE,KAAK,MAAM,aAAa,MAAM;EAC9B,KAAK,MAAM,QAAQ;EAGnB,IAAI,CAAC,QAAQ,YAAY;GACvB,MAAM,KAAK,MAAM,UAAU,OAAO;GAClC,M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MAAM;EAGlC,OAAO;CACT;;;;;;;;;;;;CAaA,AAAQ,qBAA6B;EACnC,IAAI,KAAK,KAAK,eACZ,OAAO,KAAK,KAAK;EAGnB,IAAI,KAAK,KAAK,iBACZ,OAAO,OAAO,KAAK,KAAK,oBAAoB,aACxC,KAAK,KAAK,gBAAgB,IAC1B,KAAK,UAAU,GAAG,EAAE;EAG1B,OAAO;CACT;;;;;;;;;CAUA,AAAQ,UAAU,KAAa,KAAqB;EAClD,OAAO,KAAK,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,EAAE,IAAI;CACvD;;;;;;;;;;CAWA,MAAc,YAAY,eAAwC;EAEhE,MAAM,OAAO,WACX,qBAAqB,KAAK,IAAI,GAC9B,KAAK,OACL,aACF;CACF;AACF"}
|
package/llms-full.txt
CHANGED
|
@@ -777,6 +777,8 @@ export class User extends Model<UserSchema> {
|
|
|
777
777
|
}
|
|
778
778
|
```
|
|
779
779
|
|
|
780
|
+
When the strategy resolves to `"soft"`, `Migration.create(Model, { … })` adds the `deletedAt` column for you (using `deletedAtColumn`), so the schema matches what `destroy()` writes — no need to declare it in the migration. Opt out per table with `{ softDeletes: false }`. See [`@warlock.js/cascade/write-migration/SKILL.md`](@warlock.js/cascade/write-migration/SKILL.md).
|
|
781
|
+
|
|
780
782
|
## Override per-call
|
|
781
783
|
|
|
782
784
|
```ts
|
|
@@ -787,6 +789,8 @@ await user.destroy({ strategy: "trash" }); // move to the trash table
|
|
|
787
789
|
|
|
788
790
|
Resolution order: `destroy({ strategy })` → `static deleteStrategy` → data source `defaultDeleteStrategy` → `"permanent"`.
|
|
789
791
|
|
|
792
|
+
After a `"soft"` destroy the in-memory instance reflects the change — `model.get(deletedAtColumn)` returns the persisted timestamp (the row stays, so the instance stays usable).
|
|
793
|
+
|
|
790
794
|
## Restoring — static, by id
|
|
791
795
|
|
|
792
796
|
Restore is a **static** operation keyed by the record's id. It auto-detects whether the record was soft-deleted or trashed:
|
|
@@ -2443,10 +2447,28 @@ What happens:
|
|
|
2443
2447
|
- `Migration.create(Model, columns)` reads `User.table` for the table name and builds the DDL from the column map; it infers the rollback for you.
|
|
2444
2448
|
- Column helpers (`text`, `uuid`, `string`, `integer`, …) are imported from `@warlock.js/cascade`. Each returns a builder you chain modifiers onto (`.notNullable()`, `.unique()`, `.nullable()`, `.default(...)`, `.references(table)`).
|
|
2445
2449
|
- The `id` primary key and `createdAt` / `updatedAt` timestamps are added **automatically** — don't declare them. Naming follows the data source convention (snake_case on Postgres, camelCase on MongoDB).
|
|
2450
|
+
- The soft-delete column is added **automatically when the model's delete strategy resolves to `"soft"`** — don't declare it. See below.
|
|
2446
2451
|
- `export default` is required — the runner imports each file's default export.
|
|
2447
2452
|
|
|
2448
2453
|
Evolve an existing table with `Migration.alter(Model, { ... })` (add / drop / rename / modify columns and indexes); it's declarative the same way.
|
|
2449
2454
|
|
|
2455
|
+
## Soft-delete column is auto-wired
|
|
2456
|
+
|
|
2457
|
+
If the model uses soft deletes, `Migration.create` adds the `deletedAt` column for you — you don't declare it, the same way you don't declare `createdAt` / `updatedAt`. The strategy is resolved exactly as `destroy()` resolves it: model static `deleteStrategy` → data source `defaultDeleteStrategy` → `"permanent"`. Since soft delete is usually an app-wide policy set on the data source, every `Migration.create` then gets the column with zero extra config.
|
|
2458
|
+
|
|
2459
|
+
```ts
|
|
2460
|
+
// User (or the data source) has deleteStrategy "soft" → deletedAt is added.
|
|
2461
|
+
export default Migration.create(User, {
|
|
2462
|
+
name: text().notNullable(),
|
|
2463
|
+
});
|
|
2464
|
+
```
|
|
2465
|
+
|
|
2466
|
+
- The column name comes from the model's `deletedAtColumn` (default `"deletedAt"`), so it matches what `destroy()` writes at runtime.
|
|
2467
|
+
- It only fires for the `"soft"` strategy — `"permanent"` and `"trash"` add nothing. No driver defaults to `"soft"`, so this never fires unless soft delete is opted into.
|
|
2468
|
+
- Opt out for one table with `{ softDeletes: false }`; force it on with `{ softDeletes: true }`. A model with `deletedAtColumn = false` is never wired. An already-declared `deletedAt` in the map is not duplicated.
|
|
2469
|
+
|
|
2470
|
+
See [`@warlock.js/cascade/configure-delete-strategy/SKILL.md`](@warlock.js/cascade/configure-delete-strategy/SKILL.md) for the strategies themselves.
|
|
2471
|
+
|
|
2450
2472
|
## Running migrations
|
|
2451
2473
|
|
|
2452
2474
|
```bash
|
|
@@ -2549,7 +2571,7 @@ For a class-form migration not bound to a model, set `public readonly dataSource
|
|
|
2549
2571
|
## Things NOT to do
|
|
2550
2572
|
|
|
2551
2573
|
- Don't reach for a `migration({ up(driver) {...} })` factory or `driver.createTable(name, (table) => {...})` — that API doesn't exist. Use `Migration.create(Model, { columns })`, or `extends Migration` with `this.createTable()` for the imperative case.
|
|
2552
|
-
- Don't declare `id` / `createdAt` / `updatedAt` — they're added for you.
|
|
2574
|
+
- Don't declare `id` / `createdAt` / `updatedAt` — they're added for you. Same for `deletedAt` when the model's strategy is `"soft"` — it's auto-wired (opt out with `{ softDeletes: false }`).
|
|
2553
2575
|
- Don't auto-run migrations from app code in production. Run them as a deploy step.
|
|
2554
2576
|
- Don't put irreversible data backfills in the same file as a schema change — split them so rollback only undoes the schema.
|
|
2555
2577
|
- Don't change a committed migration. Add a new one. Editing a migration that already ran in production puts environments out of sync.
|
|
@@ -2558,5 +2580,6 @@ For a class-form migration not bound to a model, set `public readonly dataSource
|
|
|
2558
2580
|
|
|
2559
2581
|
- [`@warlock.js/cascade/run-cascade-cli/SKILL.md`](@warlock.js/cascade/run-cascade-cli/SKILL.md) — CLI flags + Operations API for programmatic runs
|
|
2560
2582
|
- [`@warlock.js/cascade/manage-data-sources/SKILL.md`](@warlock.js/cascade/manage-data-sources/SKILL.md) — multi-DB migrations
|
|
2583
|
+
- [`@warlock.js/cascade/configure-delete-strategy/SKILL.md`](@warlock.js/cascade/configure-delete-strategy/SKILL.md) — soft / trash / permanent deletes and the `deletedAt` column
|
|
2561
2584
|
|
|
2562
2585
|
|
package/package.json
CHANGED
|
@@ -25,11 +25,11 @@
|
|
|
25
25
|
"@mongez/copper": "^2.1.2",
|
|
26
26
|
"@mongez/dotenv": "^1.2.4",
|
|
27
27
|
"@mongez/events": "^2.2.6",
|
|
28
|
-
"@mongez/reinforcements": "^3.
|
|
28
|
+
"@mongez/reinforcements": "^3.3.0",
|
|
29
29
|
"@mongez/supportive-is": "^2.1.3",
|
|
30
|
-
"@warlock.js/context": "4.2.
|
|
31
|
-
"@warlock.js/logger": "4.2.
|
|
32
|
-
"@warlock.js/seal": "4.2.
|
|
30
|
+
"@warlock.js/context": "4.2.11",
|
|
31
|
+
"@warlock.js/logger": "4.2.11",
|
|
32
|
+
"@warlock.js/seal": "4.2.11",
|
|
33
33
|
"citty": "^0.2.2",
|
|
34
34
|
"fast-glob": "^3.3.3"
|
|
35
35
|
},
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"bin": {
|
|
41
41
|
"cascade": "bin/cascade.js"
|
|
42
42
|
},
|
|
43
|
-
"version": "4.2.
|
|
43
|
+
"version": "4.2.11",
|
|
44
44
|
"main": "./cjs/index.cjs",
|
|
45
45
|
"module": "./esm/index.mjs",
|
|
46
46
|
"types": "./esm/index.d.mts",
|
|
@@ -31,6 +31,8 @@ export class User extends Model<UserSchema> {
|
|
|
31
31
|
}
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
+
When the strategy resolves to `"soft"`, `Migration.create(Model, { … })` adds the `deletedAt` column for you (using `deletedAtColumn`), so the schema matches what `destroy()` writes — no need to declare it in the migration. Opt out per table with `{ softDeletes: false }`. See [`@warlock.js/cascade/write-migration/SKILL.md`](@warlock.js/cascade/write-migration/SKILL.md).
|
|
35
|
+
|
|
34
36
|
## Override per-call
|
|
35
37
|
|
|
36
38
|
```ts
|
|
@@ -41,6 +43,8 @@ await user.destroy({ strategy: "trash" }); // move to the trash table
|
|
|
41
43
|
|
|
42
44
|
Resolution order: `destroy({ strategy })` → `static deleteStrategy` → data source `defaultDeleteStrategy` → `"permanent"`.
|
|
43
45
|
|
|
46
|
+
After a `"soft"` destroy the in-memory instance reflects the change — `model.get(deletedAtColumn)` returns the persisted timestamp (the row stays, so the instance stays usable).
|
|
47
|
+
|
|
44
48
|
## Restoring — static, by id
|
|
45
49
|
|
|
46
50
|
Restore is a **static** operation keyed by the record's id. It auto-detects whether the record was soft-deleted or trashed:
|
|
@@ -27,10 +27,28 @@ What happens:
|
|
|
27
27
|
- `Migration.create(Model, columns)` reads `User.table` for the table name and builds the DDL from the column map; it infers the rollback for you.
|
|
28
28
|
- Column helpers (`text`, `uuid`, `string`, `integer`, …) are imported from `@warlock.js/cascade`. Each returns a builder you chain modifiers onto (`.notNullable()`, `.unique()`, `.nullable()`, `.default(...)`, `.references(table)`).
|
|
29
29
|
- The `id` primary key and `createdAt` / `updatedAt` timestamps are added **automatically** — don't declare them. Naming follows the data source convention (snake_case on Postgres, camelCase on MongoDB).
|
|
30
|
+
- The soft-delete column is added **automatically when the model's delete strategy resolves to `"soft"`** — don't declare it. See below.
|
|
30
31
|
- `export default` is required — the runner imports each file's default export.
|
|
31
32
|
|
|
32
33
|
Evolve an existing table with `Migration.alter(Model, { ... })` (add / drop / rename / modify columns and indexes); it's declarative the same way.
|
|
33
34
|
|
|
35
|
+
## Soft-delete column is auto-wired
|
|
36
|
+
|
|
37
|
+
If the model uses soft deletes, `Migration.create` adds the `deletedAt` column for you — you don't declare it, the same way you don't declare `createdAt` / `updatedAt`. The strategy is resolved exactly as `destroy()` resolves it: model static `deleteStrategy` → data source `defaultDeleteStrategy` → `"permanent"`. Since soft delete is usually an app-wide policy set on the data source, every `Migration.create` then gets the column with zero extra config.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
// User (or the data source) has deleteStrategy "soft" → deletedAt is added.
|
|
41
|
+
export default Migration.create(User, {
|
|
42
|
+
name: text().notNullable(),
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
- The column name comes from the model's `deletedAtColumn` (default `"deletedAt"`), so it matches what `destroy()` writes at runtime.
|
|
47
|
+
- It only fires for the `"soft"` strategy — `"permanent"` and `"trash"` add nothing. No driver defaults to `"soft"`, so this never fires unless soft delete is opted into.
|
|
48
|
+
- Opt out for one table with `{ softDeletes: false }`; force it on with `{ softDeletes: true }`. A model with `deletedAtColumn = false` is never wired. An already-declared `deletedAt` in the map is not duplicated.
|
|
49
|
+
|
|
50
|
+
See [`@warlock.js/cascade/configure-delete-strategy/SKILL.md`](@warlock.js/cascade/configure-delete-strategy/SKILL.md) for the strategies themselves.
|
|
51
|
+
|
|
34
52
|
## Running migrations
|
|
35
53
|
|
|
36
54
|
```bash
|
|
@@ -133,7 +151,7 @@ For a class-form migration not bound to a model, set `public readonly dataSource
|
|
|
133
151
|
## Things NOT to do
|
|
134
152
|
|
|
135
153
|
- Don't reach for a `migration({ up(driver) {...} })` factory or `driver.createTable(name, (table) => {...})` — that API doesn't exist. Use `Migration.create(Model, { columns })`, or `extends Migration` with `this.createTable()` for the imperative case.
|
|
136
|
-
- Don't declare `id` / `createdAt` / `updatedAt` — they're added for you.
|
|
154
|
+
- Don't declare `id` / `createdAt` / `updatedAt` — they're added for you. Same for `deletedAt` when the model's strategy is `"soft"` — it's auto-wired (opt out with `{ softDeletes: false }`).
|
|
137
155
|
- Don't auto-run migrations from app code in production. Run them as a deploy step.
|
|
138
156
|
- Don't put irreversible data backfills in the same file as a schema change — split them so rollback only undoes the schema.
|
|
139
157
|
- Don't change a committed migration. Add a new one. Editing a migration that already ran in production puts environments out of sync.
|
|
@@ -142,3 +160,4 @@ For a class-form migration not bound to a model, set `public readonly dataSource
|
|
|
142
160
|
|
|
143
161
|
- [`@warlock.js/cascade/run-cascade-cli/SKILL.md`](@warlock.js/cascade/run-cascade-cli/SKILL.md) — CLI flags + Operations API for programmatic runs
|
|
144
162
|
- [`@warlock.js/cascade/manage-data-sources/SKILL.md`](@warlock.js/cascade/manage-data-sources/SKILL.md) — multi-DB migrations
|
|
163
|
+
- [`@warlock.js/cascade/configure-delete-strategy/SKILL.md`](@warlock.js/cascade/configure-delete-strategy/SKILL.md) — soft / trash / permanent deletes and the `deletedAt` column
|