{"version":3,"file":"rename-helpers.mjs","sources":["../../src/schema/rename-helpers.ts"],"sourcesContent":["import type { Knex } from 'knex';\n\nimport { getOperationComment } from '../migrations/file-builder';\n\nimport type { Database } from '..';\nimport type {\n  AttributeRenamesOperation,\n  RenameColumnOperation,\n  RenameTableOperation,\n  UpdateRowsOperation,\n} from '../migrations/file-builder';\n\n/**\n * Runtime helpers used by generated rename migrations (see\n * `migrations/file-builder.ts`). Keeping the guards, logging and dialect\n * specifics here instead of in the generated file means a fix in the database\n * package applies to migrations users already generated.\n *\n * Every helper:\n * - runs on the transaction it is given (never on `db.connection`, which may\n *   be exhausted by that very transaction on single-connection pools);\n * - checks the source exists and the target does not before doing anything,\n *   so it is a safe no-op on a fresh database (schema sync creates the tables\n *   afterwards) or on one that already moved on. For `updateRows` the source\n *   is the rows matching `where`: with none, nothing is deleted or updated, so\n *   re-running a partly applied migration (MySQL commits DDL implicitly)\n *   cannot mistake the rows it already renamed for orphans;\n * - logs when it skips: `info` when the source is missing (expected on a fresh\n *   database), `warn` when the target already exists (the environment drifted\n *   and the rename could not be applied — schema sync will then drop the old\n *   artifact, so this is worth a look);\n * - renames the indexes/constraints whose names embed the renamed identifier\n *   where the dialect supports it (Postgres), so schema sync sees no diff\n *   afterwards. On other dialects it drops them instead and schema sync\n *   re-creates them under the new name. Leaving them under the old name is not\n *   an option: sync only drops indexes it tracked on a table of the same name,\n *   so re-adding the old table/column later would collide with them.\n */\n\nexport type RenameSkipReason = 'source-missing' | 'target-exists';\n\n/**\n * Attribute renames of one save, composed per model: `uid -> { origin: final }`.\n */\nexport interface AttributeRenames {\n  renames: Record<string, Record<string, string>>;\n  comment?: string;\n}\n\n/**\n * Updates a store keyed by attribute name (e.g. admin field permissions) for\n * the given renames. Runs inside the migration transaction `trx`.\n */\nexport type AttributeRenameHandler = (\n  trx: Knex,\n  renames: AttributeRenames['renames']\n) => Promise<void>;\n\ninterface RenameHelpersDeps {\n  db: Database;\n}\n\nexport const createRenameHelpers = ({ db }: RenameHelpersDeps) => {\n  const { identifiers } = db.metadata;\n\n  const logSkip = (comment: string, detail: string, reason: RenameSkipReason): void => {\n    const message = `[rename migration] skipped: ${comment} (${detail})`;\n    if (reason === 'target-exists') {\n      db.logger.warn(message);\n    } else {\n      db.logger.info(message);\n    }\n  };\n\n  const logApplied = (comment: string): void => {\n    db.logger.info(`[rename migration] applied: ${comment}`);\n  };\n\n  // A knex SchemaBuilder accumulates statements, so build a fresh one per call.\n  const schemaOf = (trx: Knex) => db.getSchemaConnection(trx);\n  const hasTable = (trx: Knex, table: string) => schemaOf(trx).hasTable(table);\n  const hasColumn = (trx: Knex, table: string, column: string) =>\n    schemaOf(trx).hasColumn(table, column);\n  const tableOf = (trx: Knex, table: string) => {\n    const schemaName = db.getSchemaName();\n    return schemaName ? trx(table).withSchema(schemaName) : trx(table);\n  };\n\n  /**\n   * Brings every index / constraint from the `pairs` list that exists on\n   * `table` in line with a rename: renamed in place when the dialect can do so,\n   * dropped otherwise (schema sync then re-creates it under the new name).\n   */\n  const syncSchemaObjectNames = async (\n    trx: Knex,\n    table: string,\n    pairs: Array<{ from: string; to: string }>\n  ): Promise<void> => {\n    const canRename = db.dialect.canRenameSchemaObjects();\n\n    for (const { from, to } of pairs) {\n      if (from === to) {\n        continue;\n      }\n\n      if (canRename) {\n        await db.dialect.renameSchemaObject(trx, { table, from, to });\n      } else {\n        await db.dialect.dropSchemaObject(trx, { table, name: from });\n      }\n    }\n  };\n\n  const attributeRenameHandlers = new Set<AttributeRenameHandler>();\n\n  return {\n    /**\n     * Renames a column, then the index / unique / foreign-key constraints named\n     * after it (`<table>_<column>_index|unique|fk`) where supported.\n     */\n    async renameColumn(trx: Knex, op: RenameColumnOperation): Promise<boolean> {\n      const comment = getOperationComment({ kind: 'renameColumn', ...op });\n\n      if (!(await hasTable(trx, op.table))) {\n        logSkip(comment, `table \"${op.table}\" does not exist`, 'source-missing');\n        return false;\n      }\n\n      if (!(await hasColumn(trx, op.table, op.from))) {\n        logSkip(comment, `column \"${op.table}.${op.from}\" does not exist`, 'source-missing');\n        return false;\n      }\n\n      if (await hasColumn(trx, op.table, op.to)) {\n        logSkip(comment, `column \"${op.table}.${op.to}\" already exists`, 'target-exists');\n        return false;\n      }\n\n      await schemaOf(trx).alterTable(op.table, (table) => {\n        table.renameColumn(op.from, op.to);\n      });\n\n      await syncSchemaObjectNames(trx, op.table, [\n        {\n          from: identifiers.getIndexName([op.table, op.from]),\n          to: identifiers.getIndexName([op.table, op.to]),\n        },\n        {\n          from: identifiers.getUniqueIndexName([op.table, op.from]),\n          to: identifiers.getUniqueIndexName([op.table, op.to]),\n        },\n        {\n          from: identifiers.getFkIndexName([op.table, op.from]),\n          to: identifiers.getFkIndexName([op.table, op.to]),\n        },\n      ]);\n\n      logApplied(comment);\n      return true;\n    },\n\n    /**\n     * Renames a table (typically a relation join table), then the indexes and\n     * constraints named after it where supported.\n     */\n    async renameTable(trx: Knex, op: RenameTableOperation): Promise<boolean> {\n      const comment = getOperationComment({ kind: 'renameTable', ...op });\n\n      if (!(await hasTable(trx, op.from))) {\n        logSkip(comment, `table \"${op.from}\" does not exist`, 'source-missing');\n        return false;\n      }\n\n      if (await hasTable(trx, op.to)) {\n        logSkip(comment, `table \"${op.to}\" already exists`, 'target-exists');\n        return false;\n      }\n\n      await schemaOf(trx).renameTable(op.from, op.to);\n\n      // Every name a join table's metadata derives from the table name (see\n      // `createJoinTable` in metadata/relations.ts and the component link\n      // tables in core's transform-content-types-to-models).\n      const derived: Array<(name: string) => string> = [\n        (name) => identifiers.getFkIndexName(name),\n        (name) => identifiers.getInverseFkIndexName(name),\n        (name) => identifiers.getUniqueIndexName(name),\n        (name) => identifiers.getOrderFkIndexName(name),\n        (name) => identifiers.getOrderInverseFkIndexName(name),\n        (name) => identifiers.getOrderIndexName(name),\n        (name) => identifiers.getIdColumnIndexName(name),\n      ];\n\n      await syncSchemaObjectNames(\n        trx,\n        op.to,\n        derived.map((derive) => ({ from: derive(op.from), to: derive(op.to) }))\n      );\n\n      logApplied(comment);\n      return true;\n    },\n\n    /**\n     * Rewrites a stored value (e.g. the `field` or `component_type` column of a\n     * component link table). Guarded on the table and `guardColumn` (defaults\n     * to the first updated column) existing, and on rows matching `where`.\n     */\n    async updateRows(trx: Knex, op: UpdateRowsOperation): Promise<boolean> {\n      const comment = getOperationComment({ kind: 'updateRows', ...op });\n      const [firstSetColumn] = Object.keys(op.set);\n      const guardColumn = op.guardColumn ?? firstSetColumn;\n\n      if (!(await hasTable(trx, op.table))) {\n        logSkip(comment, `table \"${op.table}\" does not exist`, 'source-missing');\n        return false;\n      }\n\n      if (!(await hasColumn(trx, op.table, guardColumn))) {\n        logSkip(comment, `column \"${op.table}.${guardColumn}\" does not exist`, 'source-missing');\n        return false;\n      }\n\n      // Scope: every `where` key except the renamed column(s).\n      const scope = Object.fromEntries(\n        Object.entries(op.where).filter(([key]) => !(key in op.set))\n      );\n      const countRows = async (where: Record<string, unknown>): Promise<number> => {\n        const [row] = await tableOf(trx, op.table).where(where).count({ count: '*' });\n        return Number(row?.count ?? 0);\n      };\n\n      // Without source rows there is nothing to rename. Rows carrying the\n      // target value may then be the ones a previous run already renamed, so\n      // they must not be taken for orphans.\n      if ((await countRows(op.where)) === 0) {\n        if ((await countRows({ ...scope, ...op.set })) > 0) {\n          logSkip(\n            comment,\n            `no row matches ${JSON.stringify(op.where)} in \"${op.table}\"; rows already matching ${JSON.stringify(op.set)} were left untouched, the rename may already have run`,\n            'target-exists'\n          );\n        } else {\n          logSkip(\n            comment,\n            `no row matches ${JSON.stringify(op.where)} in \"${op.table}\"`,\n            'source-missing'\n          );\n        }\n        return false;\n      }\n\n      // Rows already carrying the target value are orphans (left behind when\n      // an attribute with the target name was deleted earlier). Updating would\n      // merge them into the renamed field and resurrect deleted content, so\n      // they go first.\n      const removed = await tableOf(trx, op.table)\n        .where({ ...scope, ...op.set })\n        .delete();\n      if (removed > 0) {\n        db.logger.info(\n          `[rename migration] removed ${removed} orphan row(s) already matching ${JSON.stringify(op.set)} in \"${op.table}\" before: ${comment}`\n        );\n      }\n\n      await tableOf(trx, op.table).where(op.where).update(op.set);\n\n      logApplied(comment);\n      return true;\n    },\n\n    /**\n     * Registers a handler for `applyAttributeRenames`. Plugins that keep data\n     * keyed by attribute name register one during their register phase, before\n     * user migrations run. Returns a function that unregisters it.\n     */\n    registerAttributeRenameHandler(handler: AttributeRenameHandler): () => void {\n      attributeRenameHandlers.add(handler);\n      return () => {\n        attributeRenameHandlers.delete(handler);\n      };\n    },\n\n    /**\n     * Dispatches one save's attribute renames to every registered handler, in\n     * registration order, inside `trx`. The database package itself stores\n     * nothing keyed by attribute name, so with no handler this is a no-op.\n     */\n    async applyAttributeRenames(trx: Knex, op: AttributeRenamesOperation): Promise<boolean> {\n      const comment = getOperationComment({ kind: 'attributeRenames', ...op });\n\n      if (attributeRenameHandlers.size === 0) {\n        db.logger.debug(`[rename migration] skipped: ${comment} (no handler registered)`);\n        return false;\n      }\n\n      for (const handler of attributeRenameHandlers) {\n        await handler(trx, op.renames);\n      }\n\n      logApplied(comment);\n      return true;\n    },\n  };\n};\n\nexport type RenameHelpers = ReturnType<typeof createRenameHelpers>;\n"],"names":["createRenameHelpers","db","identifiers","metadata","logSkip","comment","detail","reason","message","logger","warn","info","logApplied","schemaOf","trx","getSchemaConnection","hasTable","table","hasColumn","column","tableOf","schemaName","getSchemaName","withSchema","syncSchemaObjectNames","pairs","canRename","dialect","canRenameSchemaObjects","from","to","renameSchemaObject","dropSchemaObject","name","attributeRenameHandlers","Set","renameColumn","op","getOperationComment","kind","alterTable","getIndexName","getUniqueIndexName","getFkIndexName","renameTable","derived","getInverseFkIndexName","getOrderFkIndexName","getOrderInverseFkIndexName","getOrderIndexName","getIdColumnIndexName","map","derive","updateRows","firstSetColumn","Object","keys","set","guardColumn","scope","fromEntries","entries","where","filter","key","countRows","row","count","Number","JSON","stringify","removed","delete","update","registerAttributeRenameHandler","handler","add","applyAttributeRenames","size","debug","renames"],"mappings":";;AA8DO,MA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