@warlock.js/cascade 5.23.1 → 5.24.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 +345 -329
- package/cjs/index.cjs +9 -0
- package/cjs/index.cjs.map +1 -1
- package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-driver.mjs +8 -0
- package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
- package/esm/drivers/postgres/types.d.mts +5 -0
- package/esm/drivers/postgres/types.d.mts.map +1 -1
- package/esm/writer/database-writer.d.mts.map +1 -1
- package/esm/writer/database-writer.mjs +1 -0
- package/esm/writer/database-writer.mjs.map +1 -1
- package/llms-full.txt +18 -3
- package/package.json +5 -5
- package/skills/manage-transactions/SKILL.md +18 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database-writer.mjs","names":[],"sources":["../../../../../../../cascade/src/writer/database-writer.ts"],"sourcesContent":["import { 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 { mergeDriverFields } from \"../model/methods/accessor-methods\";\nimport type { ChildModel, Model } from \"../model/model\";\nimport { enqueueSyncFanout } from \"../sync/sync-fanout\";\nimport { triggerModelEvent } from \"../sync/model-events\";\nimport type { StrictMode } from \"../types\";\nimport { DatabaseWriterValidationError } from \"../validation\";\nimport { afterCommit } from \"../transactions/after-commit\";\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 /** Dirty columns an update validation dropped (strip mode); never written. */\n private readonly unvalidatedColumns = new Set<string>();\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-4. Execute insert or update (validation happens inside each path)\n let result: InsertResult | UpdateResult;\n\n if (isInsert) {\n result = await this.performInsert(options);\n } else {\n await this.validateAndCast(false, options);\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 after COMMIT (inside a transaction they are\n // queued, so a rolled-back write never fans out). Failures are logged.\n if (!options.skipSync && !isInsert) {\n afterCommit(() => 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 // 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 //\n // The whitelist must apply to BOTH insert and update: on insert a caller may\n // supply a backdated createdAt (e.g. data migrations / imports), and without\n // the whitelist strictMode \"strip\" silently drops it before it reaches the\n // writer, while \"fail\" rejects the whole insert.\n const systemColumns = {\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 // Clone full schema for insert, partial (dirty keys only) for updates.\n //\n // An update validates ONLY the dirty columns and merges back only those\n // keys: columns the schema does not list (migration-added, withCount, ...)\n // are never touched, so they can no longer be turned into `$unset`.\n const dataToValidate: Record<string, unknown> = isInsert\n ? this.model.data\n : Object.fromEntries(\n this.model\n .getDirtyColumns()\n .filter(column => column in this.model.data)\n .map(column => [column, this.model.data[column]]),\n );\n\n const validationSchema = isInsert\n ? this.schema.clone().extend(systemColumns)\n : this.schema.clone(Object.keys(dataToValidate)).extend(systemColumns);\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, dataToValidate, {\n context: {\n model: this.model,\n },\n ...getSealConfig(),\n });\n\n if (!result.isValid) {\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 if (isInsert) {\n this.model.replaceData(result.data);\n } else {\n const validated = result.data as Record<string, unknown>;\n\n for (const column of Object.keys(dataToValidate)) {\n if (column in validated) {\n this.model.set(column, validated[column]);\n } else {\n // Dropped by strictMode \"strip\": never write an unvalidated column.\n this.unvalidatedColumns.add(column);\n }\n }\n }\n\n // Emit validated event\n if (!options.skipEvents) {\n await this.model.emitEvent(\"validated\", { result });\n }\n }\n\n /**\n * Validate, cast and id-generate a not-yet-persisted model for `upsert()`.\n *\n * Runs the insert-mode pipeline (schema, casts, strictMode, Mongo `id`) but\n * does not write; the caller sends the resulting data through the driver.\n */\n public async prepareForUpsert(): Promise<void> {\n await this.validateAndCast(true, {});\n await this.generateNextId();\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 const dataToInsert = await this.prepareForInsert(options);\n\n // INSERT: use full validated data\n let result: InsertResult;\n\n try {\n result = await this.driver.insert(this.table, dataToInsert);\n } catch (error) {\n throw this.mapUniqueViolation(error, true);\n }\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 mergeDriverFields(this.model, 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 * Run the insert pipeline (validation, casting, id generation, timestamps,\n * `validating`/`validated`/`creating` hooks) WITHOUT writing.\n *\n * `save()` uses this for its insert path, so bulk inserts and single inserts\n * cannot drift. The caller is responsible for sending the returned document\n * to the driver.\n *\n * @param options - Save options (e.g. `skipEvents`, `skipValidation`)\n * @returns The prepared document to insert\n */\n public async prepareForInsert(options: WriterOptions = {}): Promise<Record<string, unknown>> {\n // Validate and cast data\n await this.validateAndCast(true, options);\n\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 //\n // Only stamp createdAt when the caller did NOT supply one, so a backdated\n // value (e.g. data migrations / imports) is honored instead of overwritten.\n // This mirrors the upsert path's guard. updatedAt is always stamped to\n // reflect the moment the record is persisted.\n const createdAtColumn = this.ctor.createdAtColumn;\n\n if (createdAtColumn && dataToInsert[createdAtColumn] == null) {\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 return dataToInsert;\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 this.buildPrimaryKeyFilter(),\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 // Nothing left to write once identity columns are excluded — don't hand the\n // driver an empty update document (MongoDB rejects one).\n if (Object.keys(operations).length === 0) {\n return { modifiedCount: 0 };\n }\n\n // Execute update with operations\n try {\n return await this.driver.update(\n this.table,\n this.buildPrimaryKeyFilter(),\n operations,\n );\n } catch (error) {\n throw this.mapUniqueViolation(error, false);\n }\n }\n\n /**\n * Map a driver unique-constraint violation (Postgres 23505, MongoDB 11000)\n * to a field validation error, so a lost `unique` race never surfaces as a\n * 500. Any other error is returned untouched.\n */\n private mapUniqueViolation(error: unknown, isInsert: boolean): unknown {\n const err = error as\n | {\n code?: string | number;\n detail?: string;\n keyPattern?: Record<string, unknown>;\n message?: string;\n }\n | undefined;\n\n if (err?.code !== \"23505\" && err?.code !== 11000 && err?.code !== \"11000\") {\n return error;\n }\n\n let field: string | undefined;\n\n if (err.keyPattern) {\n field = Object.keys(err.keyPattern)[0];\n } else {\n // Postgres: \"Key (email)=(x) already exists.\"\n field = /Key \\(([^)]+)\\)=/.exec(err.detail ?? \"\")?.[1]?.split(\",\")[0]?.trim();\n }\n\n if (!field) {\n // Mongo: \"index: email_1 dup key\"\n field = /index: (\\S+?)_-?1\\b/.exec(err.message ?? \"\")?.[1];\n }\n\n return new DatabaseWriterValidationError(\n `[${this.model.constructor.name} Model] ${isInsert ? \"Insert\" : \"Update\"} Validation failed`,\n [\n {\n type: \"unique\",\n error: `The ${field ?? \"value\"} must be unique`,\n input: field ?? \"id\",\n },\n ],\n );\n }\n\n /**\n * Build the filter that pins a write to the row this model was loaded from.\n *\n * It reads `model.trustedPrimaryKey` — the value captured when the instance\n * became persisted — NOT the current value in `model.data`. The current value\n * is reachable by mass assignment (`model.merge(req.body)`), so deriving the\n * filter from it let a request body redirect the UPDATE to another document.\n *\n * @returns Filter matching the originally loaded record\n * @private\n */\n private buildPrimaryKeyFilter(): Record<string, unknown> {\n return { [this.primaryKey]: this.model.trustedPrimaryKey };\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 // Identity columns are never written by an update. The filter pins the row\n // by its captured primary key, so a dirty `id`/`_id` can only come from\n // mass assignment or an explicit set() — either way, rewriting the key of\n // an existing row corrupts identity (and `_id` is immutable in MongoDB).\n // Changing a primary key is a deliberate operation: use the atomic/raw APIs.\n const identityColumns = new Set([this.primaryKey, \"id\", \"_id\"]);\n\n // Get dirty columns (modified fields)\n const dirtyColumns = this.model\n .getDirtyColumns()\n .filter(column => !identityColumns.has(column) && !this.unvalidatedColumns.has(column));\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\n .getRemovedColumns()\n .filter(column => !identityColumns.has(column));\n\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.randomIncrement) {\n return typeof this.ctor.randomIncrement === \"function\"\n ? this.ctor.randomIncrement()\n : this.randomInt(1, 10);\n }\n\n if (this.ctor.incrementIdBy) {\n return this.ctor.incrementIdBy;\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 triggerSync(changedFields: string[]): void {\n enqueueSyncFanout({\n sourceModel: this.ctor.name,\n operation: \"update\",\n execute: () => triggerModelEvent(this.ctor, \"updated\", this.model, changedFields),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,iBAAb,MAAsD;;CAEpD,AAAiB;;CAGjB,AAAiB,qCAAqB,IAAI,IAAY;;CAGtD,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,GAA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GAAG,EAAE;EAG1B,IAAI,KAAK,KAAK,eACZ,OAAO,KAAK,KAAK;EAGnB,OAAO;CACT;;;;;;;;;CAUA,AAAQ,UAAU,KAAa,KAAqB;EAClD,OAAO,KAAK,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,EAAE,IAAI;CACvD;;;;;;;;;;CAWA,AAAQ,YAAY,eAA+B;EACjD,kBAAkB;GAChB,aAAa,KAAK,KAAK;GACvB,WAAW;GACX,eAAe,kBAAkB,KAAK,MAAM,WAAW,KAAK,OAAO,aAAa;EAClF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"database-writer.mjs","names":[],"sources":["../../../../../../../cascade/src/writer/database-writer.ts"],"sourcesContent":["import { 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 { mergeDriverFields } from \"../model/methods/accessor-methods\";\nimport type { ChildModel, Model } from \"../model/model\";\nimport { enqueueSyncFanout } from \"../sync/sync-fanout\";\nimport { triggerModelEvent } from \"../sync/model-events\";\nimport type { StrictMode } from \"../types\";\nimport { DatabaseWriterValidationError } from \"../validation\";\nimport { afterCommit } from \"../transactions/after-commit\";\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 /** Dirty columns an update validation dropped (strip mode); never written. */\n private readonly unvalidatedColumns = new Set<string>();\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-4. Execute insert or update (validation happens inside each path)\n let result: InsertResult | UpdateResult;\n\n if (isInsert) {\n result = await this.performInsert(options);\n } else {\n await this.validateAndCast(false, options);\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 after COMMIT (inside a transaction they are\n // queued, so a rolled-back write never fans out). Failures are logged.\n if (!options.skipSync && !isInsert) {\n afterCommit(() => 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 // 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 //\n // The whitelist must apply to BOTH insert and update: on insert a caller may\n // supply a backdated createdAt (e.g. data migrations / imports), and without\n // the whitelist strictMode \"strip\" silently drops it before it reaches the\n // writer, while \"fail\" rejects the whole insert.\n const systemColumns = {\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 // Clone full schema for insert, partial (dirty keys only) for updates.\n //\n // An update validates ONLY the dirty columns and merges back only those\n // keys: columns the schema does not list (migration-added, withCount, ...)\n // are never touched, so they can no longer be turned into `$unset`.\n const dataToValidate: Record<string, unknown> = isInsert\n ? this.model.data\n : Object.fromEntries(\n this.model\n .getDirtyColumns()\n .filter(column => column in this.model.data)\n .map(column => [column, this.model.data[column]]),\n );\n\n const validationSchema = isInsert\n ? this.schema.clone().extend(systemColumns)\n : this.schema.clone(Object.keys(dataToValidate)).extend(systemColumns);\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, dataToValidate, {\n context: {\n model: this.model,\n },\n ...getSealConfig(),\n });\n\n if (!result.isValid) {\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 if (isInsert) {\n this.model.replaceData(result.data);\n } else {\n const validated = result.data as Record<string, unknown>;\n\n for (const column of Object.keys(dataToValidate)) {\n if (column in validated) {\n this.model.set(column, validated[column]);\n } else if (dataToValidate[column] === null && column in validationSchema.schema) {\n // An explicit null on a KNOWN column that passed validation: an\n // optional, non-nullable leaf coalesces null to \"absent\" in seal, so\n // it is missing from the result. It is a deliberate \"clear this\n // column\", not an unknown one to strip (Real-Estate #18). A required\n // column never gets here: its rule rejects the null and validation throws.\n this.model.set(column, null);\n } else {\n // Dropped by strictMode \"strip\": never write an unvalidated column.\n this.unvalidatedColumns.add(column);\n }\n }\n }\n\n // Emit validated event\n if (!options.skipEvents) {\n await this.model.emitEvent(\"validated\", { result });\n }\n }\n\n /**\n * Validate, cast and id-generate a not-yet-persisted model for `upsert()`.\n *\n * Runs the insert-mode pipeline (schema, casts, strictMode, Mongo `id`) but\n * does not write; the caller sends the resulting data through the driver.\n */\n public async prepareForUpsert(): Promise<void> {\n await this.validateAndCast(true, {});\n await this.generateNextId();\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 const dataToInsert = await this.prepareForInsert(options);\n\n // INSERT: use full validated data\n let result: InsertResult;\n\n try {\n result = await this.driver.insert(this.table, dataToInsert);\n } catch (error) {\n throw this.mapUniqueViolation(error, true);\n }\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 mergeDriverFields(this.model, 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 * Run the insert pipeline (validation, casting, id generation, timestamps,\n * `validating`/`validated`/`creating` hooks) WITHOUT writing.\n *\n * `save()` uses this for its insert path, so bulk inserts and single inserts\n * cannot drift. The caller is responsible for sending the returned document\n * to the driver.\n *\n * @param options - Save options (e.g. `skipEvents`, `skipValidation`)\n * @returns The prepared document to insert\n */\n public async prepareForInsert(options: WriterOptions = {}): Promise<Record<string, unknown>> {\n // Validate and cast data\n await this.validateAndCast(true, options);\n\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 //\n // Only stamp createdAt when the caller did NOT supply one, so a backdated\n // value (e.g. data migrations / imports) is honored instead of overwritten.\n // This mirrors the upsert path's guard. updatedAt is always stamped to\n // reflect the moment the record is persisted.\n const createdAtColumn = this.ctor.createdAtColumn;\n\n if (createdAtColumn && dataToInsert[createdAtColumn] == null) {\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 return dataToInsert;\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 this.buildPrimaryKeyFilter(),\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 // Nothing left to write once identity columns are excluded — don't hand the\n // driver an empty update document (MongoDB rejects one).\n if (Object.keys(operations).length === 0) {\n return { modifiedCount: 0 };\n }\n\n // Execute update with operations\n try {\n return await this.driver.update(\n this.table,\n this.buildPrimaryKeyFilter(),\n operations,\n );\n } catch (error) {\n throw this.mapUniqueViolation(error, false);\n }\n }\n\n /**\n * Map a driver unique-constraint violation (Postgres 23505, MongoDB 11000)\n * to a field validation error, so a lost `unique` race never surfaces as a\n * 500. Any other error is returned untouched.\n */\n private mapUniqueViolation(error: unknown, isInsert: boolean): unknown {\n const err = error as\n | {\n code?: string | number;\n detail?: string;\n keyPattern?: Record<string, unknown>;\n message?: string;\n }\n | undefined;\n\n if (err?.code !== \"23505\" && err?.code !== 11000 && err?.code !== \"11000\") {\n return error;\n }\n\n let field: string | undefined;\n\n if (err.keyPattern) {\n field = Object.keys(err.keyPattern)[0];\n } else {\n // Postgres: \"Key (email)=(x) already exists.\"\n field = /Key \\(([^)]+)\\)=/.exec(err.detail ?? \"\")?.[1]?.split(\",\")[0]?.trim();\n }\n\n if (!field) {\n // Mongo: \"index: email_1 dup key\"\n field = /index: (\\S+?)_-?1\\b/.exec(err.message ?? \"\")?.[1];\n }\n\n return new DatabaseWriterValidationError(\n `[${this.model.constructor.name} Model] ${isInsert ? \"Insert\" : \"Update\"} Validation failed`,\n [\n {\n type: \"unique\",\n error: `The ${field ?? \"value\"} must be unique`,\n input: field ?? \"id\",\n },\n ],\n );\n }\n\n /**\n * Build the filter that pins a write to the row this model was loaded from.\n *\n * It reads `model.trustedPrimaryKey` — the value captured when the instance\n * became persisted — NOT the current value in `model.data`. The current value\n * is reachable by mass assignment (`model.merge(req.body)`), so deriving the\n * filter from it let a request body redirect the UPDATE to another document.\n *\n * @returns Filter matching the originally loaded record\n * @private\n */\n private buildPrimaryKeyFilter(): Record<string, unknown> {\n return { [this.primaryKey]: this.model.trustedPrimaryKey };\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 // Identity columns are never written by an update. The filter pins the row\n // by its captured primary key, so a dirty `id`/`_id` can only come from\n // mass assignment or an explicit set() — either way, rewriting the key of\n // an existing row corrupts identity (and `_id` is immutable in MongoDB).\n // Changing a primary key is a deliberate operation: use the atomic/raw APIs.\n const identityColumns = new Set([this.primaryKey, \"id\", \"_id\"]);\n\n // Get dirty columns (modified fields)\n const dirtyColumns = this.model\n .getDirtyColumns()\n .filter(column => !identityColumns.has(column) && !this.unvalidatedColumns.has(column));\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\n .getRemovedColumns()\n .filter(column => !identityColumns.has(column));\n\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.randomIncrement) {\n return typeof this.ctor.randomIncrement === \"function\"\n ? this.ctor.randomIncrement()\n : this.randomInt(1, 10);\n }\n\n if (this.ctor.incrementIdBy) {\n return this.ctor.incrementIdBy;\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 triggerSync(changedFields: string[]): void {\n enqueueSyncFanout({\n sourceModel: this.ctor.name,\n operation: \"update\",\n execute: () => triggerModelEvent(this.ctor, \"updated\", this.model, changedFields),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,iBAAb,MAAsD;;CAEpD,AAAiB;;CAGjB,AAAiB,qCAAqB,IAAI,IAAY;;CAGtD,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;;;;;;;;C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BAA6B;EACnC,IAAI,KAAK,KAAK,iBACZ,OAAO,OAAO,KAAK,KAAK,oBAAoB,aACxC,KAAK,KAAK,gBAAgB,IAC1B,KAAK,UAAU,GAAG,EAAE;EAG1B,IAAI,KAAK,KAAK,eACZ,OAAO,KAAK,KAAK;EAGnB,OAAO;CACT;;;;;;;;;CAUA,AAAQ,UAAU,KAAa,KAAqB;EAClD,OAAO,KAAK,MAAM,KAAK,OAAO,KAAK,MAAM,MAAM,EAAE,IAAI;CACvD;;;;;;;;;;CAWA,AAAQ,YAAY,eAA+B;EACjD,kBAAkB;GAChB,aAAa,KAAK,KAAK;GACvB,WAAW;GACX,eAAe,kBAAkB,KAAK,MAAM,WAAW,KAAK,OAAO,aAAa;EAClF,CAAC;CACH;AACF"}
|
package/llms-full.txt
CHANGED
|
@@ -1572,9 +1572,24 @@ await transaction(async () => {
|
|
|
1572
1572
|
}, { isolationLevel: "SERIALIZABLE" });
|
|
1573
1573
|
```
|
|
1574
1574
|
|
|
1575
|
-
On `SERIALIZABLE`, Postgres may abort with a serialization failure when concurrent transactions conflict — wrap in retry logic at the caller.
|
|
1576
|
-
|
|
1577
|
-
##
|
|
1575
|
+
On `SERIALIZABLE`, Postgres may abort with a serialization failure when concurrent transactions conflict — wrap in retry logic at the caller.
|
|
1576
|
+
|
|
1577
|
+
## Transaction-local settings (Postgres)
|
|
1578
|
+
|
|
1579
|
+
Pass `settings` to configure PostgreSQL values only for the current transaction. This is useful for row-level security context, timeouts, and schema selection; Cascade applies each value with parameterized `set_config(..., true)`, so it cannot leak back into the pool:
|
|
1580
|
+
|
|
1581
|
+
```ts
|
|
1582
|
+
await transaction(async () => {
|
|
1583
|
+
await Invoice.query().get();
|
|
1584
|
+
}, {
|
|
1585
|
+
settings: {
|
|
1586
|
+
"app.tenant_id": tenantId,
|
|
1587
|
+
statement_timeout: 5_000,
|
|
1588
|
+
},
|
|
1589
|
+
});
|
|
1590
|
+
```
|
|
1591
|
+
|
|
1592
|
+
## Row locking — `lockForUpdate({ skipLocked })` (Postgres)
|
|
1578
1593
|
|
|
1579
1594
|
Chain `lockForUpdate()` on any query to emit `SELECT ... FOR UPDATE`: the matched rows are locked until the transaction ends, so no other transaction can modify or lock them. Only meaningful **inside** a transaction — outside one the lock releases immediately.
|
|
1580
1595
|
|
package/package.json
CHANGED
|
@@ -13,10 +13,10 @@
|
|
|
13
13
|
"@mongez/events": "^2.2.8",
|
|
14
14
|
"@mongez/reinforcements": "^4.0.2",
|
|
15
15
|
"@mongez/supportive-is": "^2.1.5",
|
|
16
|
-
"@warlock.js/context": "5.
|
|
17
|
-
"@warlock.js/logger": "5.
|
|
18
|
-
"@warlock.js/scheduler": "5.
|
|
19
|
-
"@warlock.js/seal": "5.
|
|
16
|
+
"@warlock.js/context": "5.24.0",
|
|
17
|
+
"@warlock.js/logger": "5.24.0",
|
|
18
|
+
"@warlock.js/scheduler": "5.24.0",
|
|
19
|
+
"@warlock.js/seal": "5.24.0",
|
|
20
20
|
"citty": "^0.2.2",
|
|
21
21
|
"fast-glob": "^3.3.3"
|
|
22
22
|
},
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
],
|
|
53
53
|
"author": "hassanzohdy",
|
|
54
54
|
"license": "MIT",
|
|
55
|
-
"version": "5.
|
|
55
|
+
"version": "5.24.0",
|
|
56
56
|
"main": "./cjs/index.cjs",
|
|
57
57
|
"module": "./esm/index.mjs",
|
|
58
58
|
"types": "./esm/index.d.mts",
|
|
@@ -97,9 +97,24 @@ await transaction(async () => {
|
|
|
97
97
|
}, { isolationLevel: "SERIALIZABLE" });
|
|
98
98
|
```
|
|
99
99
|
|
|
100
|
-
On `SERIALIZABLE`, Postgres may abort with a serialization failure when concurrent transactions conflict — wrap in retry logic at the caller.
|
|
101
|
-
|
|
102
|
-
##
|
|
100
|
+
On `SERIALIZABLE`, Postgres may abort with a serialization failure when concurrent transactions conflict — wrap in retry logic at the caller.
|
|
101
|
+
|
|
102
|
+
## Transaction-local settings (Postgres)
|
|
103
|
+
|
|
104
|
+
Pass `settings` to configure PostgreSQL values only for the current transaction. This is useful for row-level security context, timeouts, and schema selection; Cascade applies each value with parameterized `set_config(..., true)`, so it cannot leak back into the pool:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
await transaction(async () => {
|
|
108
|
+
await Invoice.query().get();
|
|
109
|
+
}, {
|
|
110
|
+
settings: {
|
|
111
|
+
"app.tenant_id": tenantId,
|
|
112
|
+
statement_timeout: 5_000,
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Row locking — `lockForUpdate({ skipLocked })` (Postgres)
|
|
103
118
|
|
|
104
119
|
Chain `lockForUpdate()` on any query to emit `SELECT ... FOR UPDATE`: the matched rows are locked until the transaction ends, so no other transaction can modify or lock them. Only meaningful **inside** a transaction — outside one the lock releases immediately.
|
|
105
120
|
|