@payloadcms/drizzle 4.0.0-internal.9726517 → 4.0.0-internal.a1317b2
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/dist/createTableName.d.ts.map +1 -1
- package/dist/createTableName.js +2 -7
- package/dist/createTableName.js.map +1 -1
- package/dist/exports/postgres.d.ts +2 -1
- package/dist/exports/postgres.d.ts.map +1 -1
- package/dist/exports/postgres.js +2 -1
- package/dist/exports/postgres.js.map +1 -1
- package/dist/exports/sqlite.d.ts +0 -1
- package/dist/exports/sqlite.d.ts.map +1 -1
- package/dist/exports/sqlite.js +0 -1
- package/dist/exports/sqlite.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +35 -13
- package/dist/migrate.js.map +1 -1
- package/dist/migrateDown.d.ts +2 -1
- package/dist/migrateDown.d.ts.map +1 -1
- package/dist/migrateDown.js +12 -2
- package/dist/migrateDown.js.map +1 -1
- package/dist/migrateFresh.d.ts +4 -2
- package/dist/migrateFresh.d.ts.map +1 -1
- package/dist/migrateFresh.js +21 -7
- package/dist/migrateFresh.js.map +1 -1
- package/dist/migrateRefresh.d.ts +2 -1
- package/dist/migrateRefresh.d.ts.map +1 -1
- package/dist/migrateRefresh.js +14 -3
- package/dist/migrateRefresh.js.map +1 -1
- package/dist/migrateReset.d.ts +2 -1
- package/dist/migrateReset.d.ts.map +1 -1
- package/dist/migrateReset.js +12 -2
- package/dist/migrateReset.js.map +1 -1
- package/dist/migrateStatus.d.ts +2 -1
- package/dist/migrateStatus.d.ts.map +1 -1
- package/dist/migrateStatus.js +11 -6
- package/dist/migrateStatus.js.map +1 -1
- package/dist/postgres/init.d.ts.map +1 -1
- package/dist/postgres/init.js +6 -0
- package/dist/postgres/init.js.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts +15 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts.map +1 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js +25 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js.map +1 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js +91 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js.map +1 -0
- package/dist/postgres/query/postgresUnaccent.d.ts +13 -0
- package/dist/postgres/query/postgresUnaccent.d.ts.map +1 -0
- package/dist/postgres/query/postgresUnaccent.js +40 -0
- package/dist/postgres/query/postgresUnaccent.js.map +1 -0
- package/dist/postgres/query/postgresUnaccent.spec.js +71 -0
- package/dist/postgres/query/postgresUnaccent.spec.js.map +1 -0
- package/dist/postgres/types.d.ts +13 -2
- package/dist/postgres/types.d.ts.map +1 -1
- package/dist/postgres/types.js.map +1 -1
- package/dist/queries/buildOperatorConstraint.d.ts +22 -0
- package/dist/queries/buildOperatorConstraint.d.ts.map +1 -0
- package/dist/queries/buildOperatorConstraint.js +63 -0
- package/dist/queries/buildOperatorConstraint.js.map +1 -0
- package/dist/queries/buildOperatorConstraint.spec.js +348 -0
- package/dist/queries/buildOperatorConstraint.spec.js.map +1 -0
- package/dist/queries/getTableColumnFromPath.d.ts +12 -3
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +50 -27
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/operatorMap.d.ts +7 -3
- package/dist/queries/operatorMap.d.ts.map +1 -1
- package/dist/queries/operatorMap.js.map +1 -1
- package/dist/queries/parseParams.d.ts.map +1 -1
- package/dist/queries/parseParams.js +203 -8
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queries/resolveRelationshipPath.d.ts +36 -0
- package/dist/queries/resolveRelationshipPath.d.ts.map +1 -0
- package/dist/queries/resolveRelationshipPath.js +66 -0
- package/dist/queries/resolveRelationshipPath.js.map +1 -0
- package/dist/queries/validateOperatorHandlers.d.ts +8 -0
- package/dist/queries/validateOperatorHandlers.d.ts.map +1 -0
- package/dist/queries/validateOperatorHandlers.js +30 -0
- package/dist/queries/validateOperatorHandlers.js.map +1 -0
- package/dist/queries/validateOperatorHandlers.spec.js +142 -0
- package/dist/queries/validateOperatorHandlers.spec.js.map +1 -0
- package/dist/schema/buildRawSchema.spec.js +290 -0
- package/dist/schema/buildRawSchema.spec.js.map +1 -0
- package/dist/schema/traverseFields.js +5 -5
- package/dist/schema/traverseFields.js.map +1 -1
- package/dist/types.d.ts +50 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/updateJobs.d.ts.map +1 -1
- package/dist/updateJobs.js +37 -0
- package/dist/updateJobs.js.map +1 -1
- package/dist/utilities/buildCreateMigration.d.ts.map +1 -1
- package/dist/utilities/buildCreateMigration.js +12 -8
- package/dist/utilities/buildCreateMigration.js.map +1 -1
- package/dist/utilities/buildForeignKeyName.d.ts.map +1 -1
- package/dist/utilities/buildForeignKeyName.js +3 -2
- package/dist/utilities/buildForeignKeyName.js.map +1 -1
- package/dist/utilities/buildIndexName.d.ts.map +1 -1
- package/dist/utilities/buildIndexName.js +3 -2
- package/dist/utilities/buildIndexName.js.map +1 -1
- package/dist/utilities/checkTruncatedIdentifiers.d.ts +13 -0
- package/dist/utilities/checkTruncatedIdentifiers.d.ts.map +1 -0
- package/dist/utilities/checkTruncatedIdentifiers.js +56 -0
- package/dist/utilities/checkTruncatedIdentifiers.js.map +1 -0
- package/dist/utilities/checkTruncatedIdentifiers.spec.js +301 -0
- package/dist/utilities/checkTruncatedIdentifiers.spec.js.map +1 -0
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +3 -0
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts +1 -5
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.js.map +1 -1
- package/dist/utilities/validateIdentifierLength.d.ts +12 -0
- package/dist/utilities/validateIdentifierLength.d.ts.map +1 -0
- package/dist/utilities/validateIdentifierLength.js +18 -0
- package/dist/utilities/validateIdentifierLength.js.map +1 -0
- package/dist/utilities/validateIdentifierLength.spec.js +19 -0
- package/dist/utilities/validateIdentifierLength.spec.js.map +1 -0
- package/package.json +3 -3
- package/dist/postgres/predefinedMigrations/jobs-processing-lease/index.d.ts +0 -12
- package/dist/postgres/predefinedMigrations/jobs-processing-lease/index.d.ts.map +0 -1
- package/dist/postgres/predefinedMigrations/jobs-processing-lease/index.js +0 -20
- package/dist/postgres/predefinedMigrations/jobs-processing-lease/index.js.map +0 -1
- package/dist/sqlite/predefinedMigrations/jobs-processing-lease/index.d.ts +0 -12
- package/dist/sqlite/predefinedMigrations/jobs-processing-lease/index.d.ts.map +0 -1
- package/dist/sqlite/predefinedMigrations/jobs-processing-lease/index.js +0 -20
- package/dist/sqlite/predefinedMigrations/jobs-processing-lease/index.js.map +0 -1
- package/dist/utilities/jobsProcessingLeaseMigration.d.ts +0 -6
- package/dist/utilities/jobsProcessingLeaseMigration.d.ts.map +0 -1
- package/dist/utilities/jobsProcessingLeaseMigration.js +0 -64
- package/dist/utilities/jobsProcessingLeaseMigration.js.map +0 -1
- package/dist/utilities/jobsProcessingLeaseMigration.spec.js +0 -166
- package/dist/utilities/jobsProcessingLeaseMigration.spec.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,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;gBACd,EAAE,IAAI,CAAC9E,WAAW,CAAC;;;;;IAK/B,CAAC;QAED,MAAM+E,UAAU,CAAC;;;;;;;;AAQrB,CAAC;QAEG,MAAMC,cAAc,CAAC,qBAAqB,EAAE,IAAI,CAAChF,WAAW,CAAC,CAAC,CAAC;QAE/D,IAAIiF,OAAO;YACTF;YACAC;eACGV;YACHrE;eACGT;eACAD;eACAE;YACHiF;YACAI;SACD,CACEF,MAAM,CAACC,SACPjE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAM8F,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASlH,KAAKmH,OAAO,CAACH,KAAK;YAEjC,IAAIlH,WAAWoH,SAAS;gBACtBhG,aAAalB,KAAKmH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAalB,KAAKmH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAI7F,UAAU;YACZ,IAAI;gBACF,MAAMiG,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAM3E,SAAS0E,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGnE,MAAM;oBAAE8E,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM3H,UAAUmB,YAAY6F,MAAM;QAElC,IAAI9F,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACgF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE1G,YAAY;QAClD;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n\n return { outputFile }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC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C;gBACd,EAAE,IAAI,CAAC9E,WAAW,CAAC;;;;;IAK/B,CAAC;QAED,MAAM+E,UAAU,CAAC;;;;;;;;AAQrB,CAAC;QAEG,MAAMC,cAAc,CAAC,qBAAqB,EAAE,IAAI,CAAChF,WAAW,CAAC,CAAC,CAAC;QAE/D,IAAIiF,OAAO;YACTF;YACAC;eACGV;YACHrE;eACGT;eACAD;eACAE;YACHiF;YACAI;SACD,CACEF,MAAM,CAACC,SACPjE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAM8F,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASlH,KAAKmH,OAAO,CAACH,KAAK;YAEjC,IAAIlH,WAAWoH,SAAS;gBACtBhG,aAAalB,KAAKmH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAalB,KAAKmH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAI7F,UAAU;YACZ,IAAI;gBACF,MAAMiG,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAM3E,SAAS0E,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGnE,MAAM;oBAAE8E,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM3H,UAAUmB,YAAY6F,MAAM;QAElC,IAAI9F,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACgF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE1G,YAAY;QAClD;QAEA,OAAO;YAAEA;QAAW;IACtB;AACF,EAAC"}
|
|
@@ -3,11 +3,7 @@ import type { RawTable } from '../types.js';
|
|
|
3
3
|
type Args = {
|
|
4
4
|
block: Block;
|
|
5
5
|
localized: boolean;
|
|
6
|
-
|
|
7
|
-
* @todo make required in v4.0. Usually you'd wanna pass this in
|
|
8
|
-
*/
|
|
9
|
-
parentIsLocalized?: boolean;
|
|
10
|
-
rootTableName: string;
|
|
6
|
+
parentIsLocalized: boolean;
|
|
11
7
|
table: RawTable;
|
|
12
8
|
tableLocales?: RawTable;
|
|
13
9
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateExistingBlockIsIdentical.d.ts","sourceRoot":"","sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAS,cAAc,EAAE,MAAM,SAAS,CAAA;AAS3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,OAAO,CAAA;IAClB
|
|
1
|
+
{"version":3,"file":"validateExistingBlockIsIdentical.d.ts","sourceRoot":"","sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAS,cAAc,EAAE,MAAM,SAAS,CAAA;AAS3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,OAAO,CAAA;IAClB,iBAAiB,EAAE,OAAO,CAAA;IAC1B,KAAK,EAAE,QAAQ,CAAA;IACf,YAAY,CAAC,EAAE,QAAQ,CAAA;CACxB,CAAA;AA+DD;;GAEG;AACH,eAAO,MAAM,gCAAgC,kEAM1C,IAAI,KAAG,OAwBT,CAAA;AAED,eAAO,MAAM,2BAA2B,eAAwC,CAAA;AAChF,eAAO,MAAM,qBAAqB,UAAW,cAAc,SAAS,MAAM,SAEzE,CAAA;AAED,eAAO,MAAM,qBAAqB,UAAW,cAAc,qBAAqB,MAAM,WAMrF,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"sourcesContent":["import type { Block, Field, FlattenedBlock } from 'payload'\n\nimport {\n fieldAffectsData,\n fieldHasSubFields,\n fieldShouldBeLocalized,\n tabHasName,\n} from 'payload/shared'\n\nimport type { RawTable } from '../types.js'\n\ntype Args = {\n block: Block\n localized: boolean\n
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"sourcesContent":["import type { Block, Field, FlattenedBlock } from 'payload'\n\nimport {\n fieldAffectsData,\n fieldHasSubFields,\n fieldShouldBeLocalized,\n tabHasName,\n} from 'payload/shared'\n\nimport type { RawTable } from '../types.js'\n\ntype Args = {\n block: Block\n localized: boolean\n parentIsLocalized: boolean\n table: RawTable\n tableLocales?: RawTable\n}\n\nconst getFlattenedFieldNames = (args: {\n fields: Field[]\n parentIsLocalized: boolean\n prefix?: string\n}): { localized?: boolean; name: string }[] => {\n const { fields, parentIsLocalized, prefix = '' } = args\n return fields.reduce((fieldsToUse, field) => {\n let fieldPrefix = prefix\n\n if (\n ['array', 'blocks', 'relationship', 'upload'].includes(field.type) ||\n ('hasMany' in field && field.hasMany === true)\n ) {\n return fieldsToUse\n }\n\n if (fieldHasSubFields(field)) {\n fieldPrefix = 'name' in field ? `${prefix}${field.name}_` : prefix\n return [\n ...fieldsToUse,\n ...getFlattenedFieldNames({\n fields: field.fields,\n parentIsLocalized: parentIsLocalized || ('localized' in field && field.localized),\n prefix: fieldPrefix,\n }),\n ]\n }\n\n if (field.type === 'tabs') {\n return [\n ...fieldsToUse,\n ...field.tabs.reduce((tabFields, tab) => {\n fieldPrefix = 'name' in tab ? `${prefix}_${tab.name}` : prefix\n return [\n ...tabFields,\n ...(tabHasName(tab)\n ? [{ ...tab, type: 'tab' }]\n : getFlattenedFieldNames({\n fields: tab.fields,\n parentIsLocalized: parentIsLocalized || tab.localized,\n prefix: fieldPrefix,\n })),\n ]\n }, []),\n ]\n }\n\n if (fieldAffectsData(field)) {\n return [\n ...fieldsToUse,\n {\n name: `${fieldPrefix}${field.name}`,\n localized: fieldShouldBeLocalized({ field, parentIsLocalized }),\n },\n ]\n }\n\n return fieldsToUse\n }, [])\n}\n\n/**\n * returns true if all the fields in a block are identical to the existing table\n */\nexport const validateExistingBlockIsIdentical = ({\n block,\n localized,\n parentIsLocalized,\n table,\n tableLocales,\n}: Args): boolean => {\n const fieldNames = getFlattenedFieldNames({\n fields: block.fields,\n parentIsLocalized: parentIsLocalized || localized,\n })\n\n const missingField =\n // ensure every field from the config is in the matching table\n fieldNames.find(({ name, localized }) => {\n const fieldTable = localized && tableLocales ? tableLocales : table\n return Object.keys(fieldTable.columns).indexOf(name) === -1\n }) ||\n // ensure every table column is matched for every field from the config\n Object.keys(table).find((fieldName) => {\n if (!['_locale', '_order', '_parentID', '_path', '_uuid'].includes(fieldName)) {\n return fieldNames.findIndex((field) => field.name) === -1\n }\n })\n\n if (missingField) {\n return false\n }\n\n return Boolean(localized) === Boolean(table.columns._locale)\n}\n\nexport const InternalBlockTableNameIndex = Symbol('InternalBlockTableNameIndex')\nexport const setInternalBlockIndex = (block: FlattenedBlock, index: number) => {\n block[InternalBlockTableNameIndex] = index\n}\n\nexport const resolveBlockTableName = (block: FlattenedBlock, originalTableName: string) => {\n if (!block[InternalBlockTableNameIndex]) {\n return originalTableName\n }\n\n return `${originalTableName}_${block[InternalBlockTableNameIndex]}`\n}\n"],"names":["fieldAffectsData","fieldHasSubFields","fieldShouldBeLocalized","tabHasName","getFlattenedFieldNames","args","fields","parentIsLocalized","prefix","reduce","fieldsToUse","field","fieldPrefix","includes","type","hasMany","name","localized","tabs","tabFields","tab","validateExistingBlockIsIdentical","block","table","tableLocales","fieldNames","missingField","find","fieldTable","Object","keys","columns","indexOf","fieldName","findIndex","Boolean","_locale","InternalBlockTableNameIndex","Symbol","setInternalBlockIndex","index","resolveBlockTableName","originalTableName"],"mappings":"AAEA,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,sBAAsB,EACtBC,UAAU,QACL,iBAAgB;AAYvB,MAAMC,yB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AC,EAC/CC,KAAK,EACLL,SAAS,EACTV,iBAAiB,EACjBgB,KAAK,EACLC,YAAY,EACP;IACL,MAAMC,aAAarB,uBAAuB;QACxCE,QAAQgB,MAAMhB,MAAM;QACpBC,mBAAmBA,qBAAqBU;IAC1C;IAEA,MAAMS,eACJ,8DAA8D;IAC9DD,WAAWE,IAAI,CAAC,CAAC,EAAEX,IAAI,EAAEC,SAAS,EAAE;QAClC,MAAMW,aAAaX,aAAaO,eAAeA,eAAeD;QAC9D,OAAOM,OAAOC,IAAI,CAACF,WAAWG,OAAO,EAAEC,OAAO,CAAChB,UAAU,CAAC;IAC5D,MACA,uEAAuE;IACvEa,OAAOC,IAAI,CAACP,OAAOI,IAAI,CAAC,CAACM;QACvB,IAAI,CAAC;YAAC;YAAW;YAAU;YAAa;YAAS;SAAQ,CAACpB,QAAQ,CAACoB,YAAY;YAC7E,OAAOR,WAAWS,SAAS,CAAC,CAACvB,QAAUA,MAAMK,IAAI,MAAM,CAAC;QAC1D;IACF;IAEF,IAAIU,cAAc;QAChB,OAAO;IACT;IAEA,OAAOS,QAAQlB,eAAekB,QAAQZ,MAAMQ,OAAO,CAACK,OAAO;AAC7D,EAAC;AAED,OAAO,MAAMC,8BAA8BC,OAAO,+BAA8B;AAChF,OAAO,MAAMC,wBAAwB,CAACjB,OAAuBkB;IAC3DlB,KAAK,CAACe,4BAA4B,GAAGG;AACvC,EAAC;AAED,OAAO,MAAMC,wBAAwB,CAACnB,OAAuBoB;IAC3D,IAAI,CAACpB,KAAK,CAACe,4BAA4B,EAAE;QACvC,OAAOK;IACT;IAEA,OAAO,GAAGA,kBAAkB,CAAC,EAAEpB,KAAK,CAACe,4BAA4B,EAAE;AACrE,EAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Postgres max identifier length (NAMEDATALEN - 1). */
|
|
2
|
+
export declare const maxIdentifierLength = 63;
|
|
3
|
+
/**
|
|
4
|
+
* Cap for builder-generated identifiers (`buildIndexName`/`buildForeignKeyName`). Sits
|
|
5
|
+
* below `maxIdentifierLength` to leave headroom for the appended `_idx`/`_fk`/`_N` suffixes.
|
|
6
|
+
*/
|
|
7
|
+
export declare const maxGeneratedIdentifierLength: number;
|
|
8
|
+
/**
|
|
9
|
+
* Throws if a table or enum identifier exceeds the Postgres 63-char limit.
|
|
10
|
+
*/
|
|
11
|
+
export declare const validateIdentifierLength: (name: string) => string;
|
|
12
|
+
//# sourceMappingURL=validateIdentifierLength.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateIdentifierLength.d.ts","sourceRoot":"","sources":["../../src/utilities/validateIdentifierLength.ts"],"names":[],"mappings":"AAEA,wDAAwD;AACxD,eAAO,MAAM,mBAAmB,KAAK,CAAA;AAErC;;;GAGG;AACH,eAAO,MAAM,4BAA4B,QAA0B,CAAA;AAEnE;;GAEG;AACH,eAAO,MAAM,wBAAwB,SAAU,MAAM,KAAG,MAUvD,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
/** Postgres max identifier length (NAMEDATALEN - 1). */ export const maxIdentifierLength = 63;
|
|
3
|
+
/**
|
|
4
|
+
* Cap for builder-generated identifiers (`buildIndexName`/`buildForeignKeyName`). Sits
|
|
5
|
+
* below `maxIdentifierLength` to leave headroom for the appended `_idx`/`_fk`/`_N` suffixes.
|
|
6
|
+
*/ export const maxGeneratedIdentifierLength = maxIdentifierLength - 3;
|
|
7
|
+
/**
|
|
8
|
+
* Throws if a table or enum identifier exceeds the Postgres 63-char limit.
|
|
9
|
+
*/ export const validateIdentifierLength = (name)=>{
|
|
10
|
+
if (name.length > maxIdentifierLength) {
|
|
11
|
+
throw new APIError(`Exceeded max identifier length for table or enum name of ${maxIdentifierLength} characters. Invalid name: ${name}.
|
|
12
|
+
Tip: You can use the dbName property to reduce the table name length.
|
|
13
|
+
`);
|
|
14
|
+
}
|
|
15
|
+
return name;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=validateIdentifierLength.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/validateIdentifierLength.ts"],"sourcesContent":["import { APIError } from 'payload'\n\n/** Postgres max identifier length (NAMEDATALEN - 1). */\nexport const maxIdentifierLength = 63\n\n/**\n * Cap for builder-generated identifiers (`buildIndexName`/`buildForeignKeyName`). Sits\n * below `maxIdentifierLength` to leave headroom for the appended `_idx`/`_fk`/`_N` suffixes.\n */\nexport const maxGeneratedIdentifierLength = maxIdentifierLength - 3\n\n/**\n * Throws if a table or enum identifier exceeds the Postgres 63-char limit.\n */\nexport const validateIdentifierLength = (name: string): string => {\n if (name.length > maxIdentifierLength) {\n throw new APIError(\n `Exceeded max identifier length for table or enum name of ${maxIdentifierLength} characters. Invalid name: ${name}.\nTip: You can use the dbName property to reduce the table name length.\n `,\n )\n }\n\n return name\n}\n"],"names":["APIError","maxIdentifierLength","maxGeneratedIdentifierLength","validateIdentifierLength","name","length"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,UAAS;AAElC,sDAAsD,GACtD,OAAO,MAAMC,sBAAsB,GAAE;AAErC;;;CAGC,GACD,OAAO,MAAMC,+BAA+BD,sBAAsB,EAAC;AAEnE;;CAEC,GACD,OAAO,MAAME,2BAA2B,CAACC;IACvC,IAAIA,KAAKC,MAAM,GAAGJ,qBAAqB;QACrC,MAAM,IAAID,SACR,CAAC,yDAAyD,EAAEC,oBAAoB,2BAA2B,EAAEG,KAAK;;MAElH,CAAC;IAEL;IAEA,OAAOA;AACT,EAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { maxIdentifierLength, validateIdentifierLength } from './validateIdentifierLength.js';
|
|
3
|
+
describe('validateIdentifierLength', ()=>{
|
|
4
|
+
it('should return the name unchanged when at or under the 63-char limit', ()=>{
|
|
5
|
+
const name = 'a'.repeat(maxIdentifierLength);
|
|
6
|
+
expect(validateIdentifierLength(name)).toBe(name);
|
|
7
|
+
});
|
|
8
|
+
it('should throw when the name exceeds the 63-char limit', ()=>{
|
|
9
|
+
const name = 'a'.repeat(maxIdentifierLength + 1);
|
|
10
|
+
expect(()=>validateIdentifierLength(name)).toThrow('Exceeded max identifier length');
|
|
11
|
+
});
|
|
12
|
+
it('should include the invalid name and the dbName tip in the error', ()=>{
|
|
13
|
+
const name = `some_long_table_name${'x'.repeat(maxIdentifierLength)}_locales`;
|
|
14
|
+
expect(()=>validateIdentifierLength(name)).toThrow(name);
|
|
15
|
+
expect(()=>validateIdentifierLength(name)).toThrow('You can use the dbName property to reduce the table name length');
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=validateIdentifierLength.spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/validateIdentifierLength.spec.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest'\n\nimport { maxIdentifierLength, validateIdentifierLength } from './validateIdentifierLength.js'\n\ndescribe('validateIdentifierLength', () => {\n it('should return the name unchanged when at or under the 63-char limit', () => {\n const name = 'a'.repeat(maxIdentifierLength)\n\n expect(validateIdentifierLength(name)).toBe(name)\n })\n\n it('should throw when the name exceeds the 63-char limit', () => {\n const name = 'a'.repeat(maxIdentifierLength + 1)\n\n expect(() => validateIdentifierLength(name)).toThrow('Exceeded max identifier length')\n })\n\n it('should include the invalid name and the dbName tip in the error', () => {\n const name = `some_long_table_name${'x'.repeat(maxIdentifierLength)}_locales`\n\n expect(() => validateIdentifierLength(name)).toThrow(name)\n expect(() => validateIdentifierLength(name)).toThrow(\n 'You can use the dbName property to reduce the table name length',\n )\n })\n})\n"],"names":["describe","expect","it","maxIdentifierLength","validateIdentifierLength","name","repeat","toBe","toThrow"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAE7C,SAASC,mBAAmB,EAAEC,wBAAwB,QAAQ,gCAA+B;AAE7FJ,SAAS,4BAA4B;IACnCE,GAAG,uEAAuE;QACxE,MAAMG,OAAO,IAAIC,MAAM,CAACH;QAExBF,OAAOG,yBAAyBC,OAAOE,IAAI,CAACF;IAC9C;IAEAH,GAAG,wDAAwD;QACzD,MAAMG,OAAO,IAAIC,MAAM,CAACH,sBAAsB;QAE9CF,OAAO,IAAMG,yBAAyBC,OAAOG,OAAO,CAAC;IACvD;IAEAN,GAAG,mEAAmE;QACpE,MAAMG,OAAO,CAAC,oBAAoB,EAAE,IAAIC,MAAM,CAACH,qBAAqB,QAAQ,CAAC;QAE7EF,OAAO,IAAMG,yBAAyBC,OAAOG,OAAO,CAACH;QACrDJ,OAAO,IAAMG,yBAAyBC,OAAOG,OAAO,CAClD;IAEJ;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/drizzle",
|
|
3
|
-
"version": "4.0.0-internal.
|
|
3
|
+
"version": "4.0.0-internal.a1317b2",
|
|
4
4
|
"description": "A library of shared functions used by different payload database adapters",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"repository": {
|
|
@@ -55,10 +55,10 @@
|
|
|
55
55
|
"@types/pg": "8.20.0",
|
|
56
56
|
"@types/to-snake-case": "1.0.0",
|
|
57
57
|
"@payloadcms/eslint-config": "3.28.0",
|
|
58
|
-
"payload": "4.0.0-internal.
|
|
58
|
+
"payload": "4.0.0-internal.a1317b2"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"payload": "4.0.0-internal.
|
|
61
|
+
"payload": "4.0.0-internal.a1317b2"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "pnpm build:swc && pnpm build:types",
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
type Args = {
|
|
2
|
-
db: any;
|
|
3
|
-
direction: 'down' | 'up';
|
|
4
|
-
newIndexName: string;
|
|
5
|
-
oldIndexName: string;
|
|
6
|
-
schemaName?: string;
|
|
7
|
-
sql: any;
|
|
8
|
-
tableName: string;
|
|
9
|
-
};
|
|
10
|
-
export declare function migratePostgresJobsProcessingLease({ db, direction, newIndexName, oldIndexName, schemaName, sql, tableName, }: Args): Promise<void>;
|
|
11
|
-
export {};
|
|
12
|
-
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/postgres/predefinedMigrations/jobs-processing-lease/index.ts"],"names":[],"mappings":"AAAA,KAAK,IAAI,GAAG;IACV,EAAE,EAAE,GAAG,CAAA;IACP,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,YAAY,EAAE,MAAM,CAAA;IACpB,YAAY,EAAE,MAAM,CAAA;IACpB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,GAAG,EAAE,GAAG,CAAA;IACR,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAID,wBAAsB,kCAAkC,CAAC,EACvD,EAAE,EACF,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,UAAqB,EACrB,GAAG,EACH,SAAS,GACV,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CA+BtB"}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
const quoteIdentifier = (identifier)=>`"${identifier.replaceAll('"', '""')}"`;
|
|
2
|
-
export async function migratePostgresJobsProcessingLease({ db, direction, newIndexName, oldIndexName, schemaName = 'public', sql, tableName }) {
|
|
3
|
-
const qualifiedTableName = `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;
|
|
4
|
-
const run = (statement)=>db.execute(sql.raw(statement));
|
|
5
|
-
if (direction === 'up') {
|
|
6
|
-
await run(`ALTER TABLE ${qualifiedTableName} ADD COLUMN "processing_until" timestamp(3) with time zone`);
|
|
7
|
-
await run(`UPDATE ${qualifiedTableName} SET "processing_until" = '1970-01-01 00:00:00+00' WHERE "processing" = true`);
|
|
8
|
-
await run(`DROP INDEX IF EXISTS ${quoteIdentifier(schemaName)}.${quoteIdentifier(oldIndexName)}`);
|
|
9
|
-
await run(`ALTER TABLE ${qualifiedTableName} DROP COLUMN "processing"`);
|
|
10
|
-
await run(`CREATE INDEX ${quoteIdentifier(newIndexName)} ON ${qualifiedTableName} USING btree ("processing_until")`);
|
|
11
|
-
return;
|
|
12
|
-
}
|
|
13
|
-
await run(`ALTER TABLE ${qualifiedTableName} ADD COLUMN "processing" boolean DEFAULT false`);
|
|
14
|
-
await run(`UPDATE ${qualifiedTableName} SET "processing" = true WHERE "processing_until" IS NOT NULL`);
|
|
15
|
-
await run(`DROP INDEX IF EXISTS ${quoteIdentifier(schemaName)}.${quoteIdentifier(newIndexName)}`);
|
|
16
|
-
await run(`ALTER TABLE ${qualifiedTableName} DROP COLUMN "processing_until"`);
|
|
17
|
-
await run(`CREATE INDEX ${quoteIdentifier(oldIndexName)} ON ${qualifiedTableName} USING btree ("processing")`);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/postgres/predefinedMigrations/jobs-processing-lease/index.ts"],"sourcesContent":["type Args = {\n db: any\n direction: 'down' | 'up'\n newIndexName: string\n oldIndexName: string\n schemaName?: string\n sql: any\n tableName: string\n}\n\nconst quoteIdentifier = (identifier: string): string => `\"${identifier.replaceAll('\"', '\"\"')}\"`\n\nexport async function migratePostgresJobsProcessingLease({\n db,\n direction,\n newIndexName,\n oldIndexName,\n schemaName = 'public',\n sql,\n tableName,\n}: Args): Promise<void> {\n const qualifiedTableName = `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`\n const run = (statement: string) => db.execute(sql.raw(statement))\n\n if (direction === 'up') {\n await run(\n `ALTER TABLE ${qualifiedTableName} ADD COLUMN \"processing_until\" timestamp(3) with time zone`,\n )\n await run(\n `UPDATE ${qualifiedTableName} SET \"processing_until\" = '1970-01-01 00:00:00+00' WHERE \"processing\" = true`,\n )\n await run(\n `DROP INDEX IF EXISTS ${quoteIdentifier(schemaName)}.${quoteIdentifier(oldIndexName)}`,\n )\n await run(`ALTER TABLE ${qualifiedTableName} DROP COLUMN \"processing\"`)\n await run(\n `CREATE INDEX ${quoteIdentifier(newIndexName)} ON ${qualifiedTableName} USING btree (\"processing_until\")`,\n )\n\n return\n }\n\n await run(`ALTER TABLE ${qualifiedTableName} ADD COLUMN \"processing\" boolean DEFAULT false`)\n await run(\n `UPDATE ${qualifiedTableName} SET \"processing\" = true WHERE \"processing_until\" IS NOT NULL`,\n )\n await run(`DROP INDEX IF EXISTS ${quoteIdentifier(schemaName)}.${quoteIdentifier(newIndexName)}`)\n await run(`ALTER TABLE ${qualifiedTableName} DROP COLUMN \"processing_until\"`)\n await run(\n `CREATE INDEX ${quoteIdentifier(oldIndexName)} ON ${qualifiedTableName} USING btree (\"processing\")`,\n )\n}\n"],"names":["quoteIdentifier","identifier","replaceAll","migratePostgresJobsProcessingLease","db","direction","newIndexName","oldIndexName","schemaName","sql","tableName","qualifiedTableName","run","statement","execute","raw"],"mappings":"AAUA,MAAMA,kBAAkB,CAACC,aAA+B,CAAC,CAAC,EAAEA,WAAWC,UAAU,CAAC,KAAK,MAAM,CAAC,CAAC;AAE/F,OAAO,eAAeC,mCAAmC,EACvDC,EAAE,EACFC,SAAS,EACTC,YAAY,EACZC,YAAY,EACZC,aAAa,QAAQ,EACrBC,GAAG,EACHC,SAAS,EACJ;IACL,MAAMC,qBAAqB,GAAGX,gBAAgBQ,YAAY,CAAC,EAAER,gBAAgBU,YAAY;IACzF,MAAME,MAAM,CAACC,YAAsBT,GAAGU,OAAO,CAACL,IAAIM,GAAG,CAACF;IAEtD,IAAIR,cAAc,MAAM;QACtB,MAAMO,IACJ,CAAC,YAAY,EAAED,mBAAmB,0DAA0D,CAAC;QAE/F,MAAMC,IACJ,CAAC,OAAO,EAAED,mBAAmB,4EAA4E,CAAC;QAE5G,MAAMC,IACJ,CAAC,qBAAqB,EAAEZ,gBAAgBQ,YAAY,CAAC,EAAER,gBAAgBO,eAAe;QAExF,MAAMK,IAAI,CAAC,YAAY,EAAED,mBAAmB,yBAAyB,CAAC;QACtE,MAAMC,IACJ,CAAC,aAAa,EAAEZ,gBAAgBM,cAAc,IAAI,EAAEK,mBAAmB,iCAAiC,CAAC;QAG3G;IACF;IAEA,MAAMC,IAAI,CAAC,YAAY,EAAED,mBAAmB,8CAA8C,CAAC;IAC3F,MAAMC,IACJ,CAAC,OAAO,EAAED,mBAAmB,6DAA6D,CAAC;IAE7F,MAAMC,IAAI,CAAC,qBAAqB,EAAEZ,gBAAgBQ,YAAY,CAAC,EAAER,gBAAgBM,eAAe;IAChG,MAAMM,IAAI,CAAC,YAAY,EAAED,mBAAmB,+BAA+B,CAAC;IAC5E,MAAMC,IACJ,CAAC,aAAa,EAAEZ,gBAAgBO,cAAc,IAAI,EAAEI,mBAAmB,2BAA2B,CAAC;AAEvG"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
type Args = {
|
|
2
|
-
db: any;
|
|
3
|
-
direction: 'down' | 'up';
|
|
4
|
-
newIndexName: string;
|
|
5
|
-
oldIndexName: string;
|
|
6
|
-
schemaName?: string;
|
|
7
|
-
sql: any;
|
|
8
|
-
tableName: string;
|
|
9
|
-
};
|
|
10
|
-
export declare function migrateSqliteJobsProcessingLease({ db, direction, newIndexName, oldIndexName, sql, tableName, }: Args): Promise<void>;
|
|
11
|
-
export {};
|
|
12
|
-
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/sqlite/predefinedMigrations/jobs-processing-lease/index.ts"],"names":[],"mappings":"AAAA,KAAK,IAAI,GAAG;IACV,EAAE,EAAE,GAAG,CAAA;IACP,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,YAAY,EAAE,MAAM,CAAA;IACpB,YAAY,EAAE,MAAM,CAAA;IACpB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,GAAG,EAAE,GAAG,CAAA;IACR,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAID,wBAAsB,gCAAgC,CAAC,EACrD,EAAE,EACF,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,GAAG,EACH,SAAS,GACV,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAyBtB"}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
const quoteIdentifier = (identifier)=>`"${identifier.replaceAll('"', '""')}"`;
|
|
2
|
-
export async function migrateSqliteJobsProcessingLease({ db, direction, newIndexName, oldIndexName, sql, tableName }) {
|
|
3
|
-
const quotedTableName = quoteIdentifier(tableName);
|
|
4
|
-
const run = (statement)=>db.run(sql.raw(statement));
|
|
5
|
-
if (direction === 'up') {
|
|
6
|
-
await run(`ALTER TABLE ${quotedTableName} ADD COLUMN "processing_until" text`);
|
|
7
|
-
await run(`UPDATE ${quotedTableName} SET "processing_until" = '1970-01-01T00:00:00.000Z' WHERE "processing" = true`);
|
|
8
|
-
await run(`DROP INDEX IF EXISTS ${quoteIdentifier(oldIndexName)}`);
|
|
9
|
-
await run(`ALTER TABLE ${quotedTableName} DROP COLUMN "processing"`);
|
|
10
|
-
await run(`CREATE INDEX ${quoteIdentifier(newIndexName)} ON ${quotedTableName} ("processing_until")`);
|
|
11
|
-
return;
|
|
12
|
-
}
|
|
13
|
-
await run(`ALTER TABLE ${quotedTableName} ADD COLUMN "processing" integer DEFAULT false`);
|
|
14
|
-
await run(`UPDATE ${quotedTableName} SET "processing" = true WHERE "processing_until" IS NOT NULL`);
|
|
15
|
-
await run(`DROP INDEX IF EXISTS ${quoteIdentifier(newIndexName)}`);
|
|
16
|
-
await run(`ALTER TABLE ${quotedTableName} DROP COLUMN "processing_until"`);
|
|
17
|
-
await run(`CREATE INDEX ${quoteIdentifier(oldIndexName)} ON ${quotedTableName} ("processing")`);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/sqlite/predefinedMigrations/jobs-processing-lease/index.ts"],"sourcesContent":["type Args = {\n db: any\n direction: 'down' | 'up'\n newIndexName: string\n oldIndexName: string\n schemaName?: string\n sql: any\n tableName: string\n}\n\nconst quoteIdentifier = (identifier: string): string => `\"${identifier.replaceAll('\"', '\"\"')}\"`\n\nexport async function migrateSqliteJobsProcessingLease({\n db,\n direction,\n newIndexName,\n oldIndexName,\n sql,\n tableName,\n}: Args): Promise<void> {\n const quotedTableName = quoteIdentifier(tableName)\n const run = (statement: string) => db.run(sql.raw(statement))\n\n if (direction === 'up') {\n await run(`ALTER TABLE ${quotedTableName} ADD COLUMN \"processing_until\" text`)\n await run(\n `UPDATE ${quotedTableName} SET \"processing_until\" = '1970-01-01T00:00:00.000Z' WHERE \"processing\" = true`,\n )\n await run(`DROP INDEX IF EXISTS ${quoteIdentifier(oldIndexName)}`)\n await run(`ALTER TABLE ${quotedTableName} DROP COLUMN \"processing\"`)\n await run(\n `CREATE INDEX ${quoteIdentifier(newIndexName)} ON ${quotedTableName} (\"processing_until\")`,\n )\n\n return\n }\n\n await run(`ALTER TABLE ${quotedTableName} ADD COLUMN \"processing\" integer DEFAULT false`)\n await run(\n `UPDATE ${quotedTableName} SET \"processing\" = true WHERE \"processing_until\" IS NOT NULL`,\n )\n await run(`DROP INDEX IF EXISTS ${quoteIdentifier(newIndexName)}`)\n await run(`ALTER TABLE ${quotedTableName} DROP COLUMN \"processing_until\"`)\n await run(`CREATE INDEX ${quoteIdentifier(oldIndexName)} ON ${quotedTableName} (\"processing\")`)\n}\n"],"names":["quoteIdentifier","identifier","replaceAll","migrateSqliteJobsProcessingLease","db","direction","newIndexName","oldIndexName","sql","tableName","quotedTableName","run","statement","raw"],"mappings":"AAUA,MAAMA,kBAAkB,CAACC,aAA+B,CAAC,CAAC,EAAEA,WAAWC,UAAU,CAAC,KAAK,MAAM,CAAC,CAAC;AAE/F,OAAO,eAAeC,iCAAiC,EACrDC,EAAE,EACFC,SAAS,EACTC,YAAY,EACZC,YAAY,EACZC,GAAG,EACHC,SAAS,EACJ;IACL,MAAMC,kBAAkBV,gBAAgBS;IACxC,MAAME,MAAM,CAACC,YAAsBR,GAAGO,GAAG,CAACH,IAAIK,GAAG,CAACD;IAElD,IAAIP,cAAc,MAAM;QACtB,MAAMM,IAAI,CAAC,YAAY,EAAED,gBAAgB,mCAAmC,CAAC;QAC7E,MAAMC,IACJ,CAAC,OAAO,EAAED,gBAAgB,8EAA8E,CAAC;QAE3G,MAAMC,IAAI,CAAC,qBAAqB,EAAEX,gBAAgBO,eAAe;QACjE,MAAMI,IAAI,CAAC,YAAY,EAAED,gBAAgB,yBAAyB,CAAC;QACnE,MAAMC,IACJ,CAAC,aAAa,EAAEX,gBAAgBM,cAAc,IAAI,EAAEI,gBAAgB,qBAAqB,CAAC;QAG5F;IACF;IAEA,MAAMC,IAAI,CAAC,YAAY,EAAED,gBAAgB,8CAA8C,CAAC;IACxF,MAAMC,IACJ,CAAC,OAAO,EAAED,gBAAgB,6DAA6D,CAAC;IAE1F,MAAMC,IAAI,CAAC,qBAAqB,EAAEX,gBAAgBM,eAAe;IACjE,MAAMK,IAAI,CAAC,YAAY,EAAED,gBAAgB,+BAA+B,CAAC;IACzE,MAAMC,IAAI,CAAC,aAAa,EAAEX,gBAAgBO,cAAc,IAAI,EAAEG,gBAAgB,eAAe,CAAC;AAChG"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import type { DynamicMigrationTemplate } from 'payload';
|
|
2
|
-
export declare const buildDynamicPredefinedJobsProcessingLeaseMigration: ({ dialect, packageName, }: {
|
|
3
|
-
dialect: 'postgres' | 'sqlite';
|
|
4
|
-
packageName: string;
|
|
5
|
-
}) => DynamicMigrationTemplate;
|
|
6
|
-
//# sourceMappingURL=jobsProcessingLeaseMigration.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"jobsProcessingLeaseMigration.d.ts","sourceRoot":"","sources":["../../src/utilities/jobsProcessingLeaseMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAA;AAqEvD,eAAO,MAAM,kDAAkD,8BAG5D;IACD,OAAO,EAAE,UAAU,GAAG,QAAQ,CAAA;IAC9B,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,wBAwCH,CAAA"}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { readdirSync, readFileSync, writeFileSync } from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import toSnakeCase from 'to-snake-case';
|
|
4
|
-
const getDefaultIndexName = (name)=>{
|
|
5
|
-
const suffix = '_idx';
|
|
6
|
-
return `${name.slice(0, 60 - suffix.length)}${suffix}`;
|
|
7
|
-
};
|
|
8
|
-
const getIndexName = ({ fallbackFieldName, indexes, on, tableName })=>{
|
|
9
|
-
const matchingIndex = Object.values(indexes ?? {}).find((index)=>index.on === on);
|
|
10
|
-
return matchingIndex?.name ?? getDefaultIndexName(`${tableName}_${fallbackFieldName}`);
|
|
11
|
-
};
|
|
12
|
-
const getLegacyProcessingIndexName = ({ filePath, tableName })=>{
|
|
13
|
-
const latestSnapshotFile = readdirSync(path.dirname(filePath)).filter((file)=>file.endsWith('.json')).sort().reverse()[0];
|
|
14
|
-
if (latestSnapshotFile) {
|
|
15
|
-
const snapshot = JSON.parse(readFileSync(path.join(path.dirname(filePath), latestSnapshotFile), 'utf8'));
|
|
16
|
-
const table = Object.values(snapshot.tables ?? {}).find(({ name })=>name === tableName);
|
|
17
|
-
const processingIndex = Object.values(table?.indexes ?? {}).find((index)=>index.columns?.some(({ expression })=>expression === 'processing'));
|
|
18
|
-
if (processingIndex?.name) {
|
|
19
|
-
return processingIndex.name;
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
return getDefaultIndexName(`${tableName}_processing`);
|
|
23
|
-
};
|
|
24
|
-
export const buildDynamicPredefinedJobsProcessingLeaseMigration = ({ dialect, packageName })=>{
|
|
25
|
-
return async ({ filePath, payload })=>{
|
|
26
|
-
const adapter = payload.db;
|
|
27
|
-
const tableName = adapter.tableNameMap.get(toSnakeCase('payload-jobs'));
|
|
28
|
-
if (!tableName) {
|
|
29
|
-
throw new Error('Could not find the payload-jobs database table');
|
|
30
|
-
}
|
|
31
|
-
const rawTable = adapter.rawTables[tableName];
|
|
32
|
-
const newIndexName = getIndexName({
|
|
33
|
-
fallbackFieldName: 'processing_until',
|
|
34
|
-
indexes: rawTable?.indexes,
|
|
35
|
-
on: 'processingUntil',
|
|
36
|
-
tableName
|
|
37
|
-
});
|
|
38
|
-
const oldIndexName = getLegacyProcessingIndexName({
|
|
39
|
-
filePath,
|
|
40
|
-
tableName
|
|
41
|
-
});
|
|
42
|
-
const schemaName = dialect === 'postgres' ? adapter.schemaName ?? 'public' : undefined;
|
|
43
|
-
const drizzleSnapshot = await adapter.requireDrizzleKit().generateDrizzleJson(adapter.schema);
|
|
44
|
-
writeFileSync(`${filePath}.json`, JSON.stringify(drizzleSnapshot, null, 2));
|
|
45
|
-
const sharedArgs = `
|
|
46
|
-
db,
|
|
47
|
-
newIndexName: ${JSON.stringify(newIndexName)},
|
|
48
|
-
oldIndexName: ${JSON.stringify(oldIndexName)},
|
|
49
|
-
schemaName: ${JSON.stringify(schemaName)},
|
|
50
|
-
sql,
|
|
51
|
-
tableName: ${JSON.stringify(tableName)},`;
|
|
52
|
-
return {
|
|
53
|
-
downSQL: `await migrateJobsProcessingLease({${sharedArgs}
|
|
54
|
-
direction: 'down',
|
|
55
|
-
})`,
|
|
56
|
-
imports: `import { migrateJobsProcessingLease } from '${packageName}/migration-utils'`,
|
|
57
|
-
upSQL: `await migrateJobsProcessingLease({${sharedArgs}
|
|
58
|
-
direction: 'up',
|
|
59
|
-
})`
|
|
60
|
-
};
|
|
61
|
-
};
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
//# sourceMappingURL=jobsProcessingLeaseMigration.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/jobsProcessingLeaseMigration.ts"],"sourcesContent":["import type { DynamicMigrationTemplate } from 'payload'\n\nimport { readdirSync, readFileSync, writeFileSync } from 'fs'\nimport path from 'path'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, RawIndex } from '../types.js'\n\ntype SnapshotIndex = {\n columns?: { expression?: string }[]\n name?: string\n}\n\ntype SnapshotTable = {\n indexes?: Record<string, SnapshotIndex>\n name?: string\n}\n\nconst getDefaultIndexName = (name: string): string => {\n const suffix = '_idx'\n\n return `${name.slice(0, 60 - suffix.length)}${suffix}`\n}\n\nconst getIndexName = ({\n fallbackFieldName,\n indexes,\n on,\n tableName,\n}: {\n fallbackFieldName: string\n indexes?: Record<string, RawIndex>\n on: string\n tableName: string\n}): string => {\n const matchingIndex = Object.values(indexes ?? {}).find((index) => index.on === on)\n\n return matchingIndex?.name ?? getDefaultIndexName(`${tableName}_${fallbackFieldName}`)\n}\n\nconst getLegacyProcessingIndexName = ({\n filePath,\n tableName,\n}: {\n filePath: string\n tableName: string\n}): string => {\n const latestSnapshotFile = readdirSync(path.dirname(filePath))\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()[0]\n\n if (latestSnapshotFile) {\n const snapshot = JSON.parse(\n readFileSync(path.join(path.dirname(filePath), latestSnapshotFile), 'utf8'),\n ) as { tables?: Record<string, SnapshotTable> }\n const table = Object.values(snapshot.tables ?? {}).find(({ name }) => name === tableName)\n const processingIndex = Object.values(table?.indexes ?? {}).find((index) =>\n index.columns?.some(({ expression }) => expression === 'processing'),\n )\n\n if (processingIndex?.name) {\n return processingIndex.name\n }\n }\n\n return getDefaultIndexName(`${tableName}_processing`)\n}\n\nexport const buildDynamicPredefinedJobsProcessingLeaseMigration = ({\n dialect,\n packageName,\n}: {\n dialect: 'postgres' | 'sqlite'\n packageName: string\n}): DynamicMigrationTemplate => {\n return async ({ filePath, payload }) => {\n const adapter = payload.db as DrizzleAdapter\n const tableName = adapter.tableNameMap.get(toSnakeCase('payload-jobs'))\n\n if (!tableName) {\n throw new Error('Could not find the payload-jobs database table')\n }\n\n const rawTable = adapter.rawTables[tableName]\n const newIndexName = getIndexName({\n fallbackFieldName: 'processing_until',\n indexes: rawTable?.indexes,\n on: 'processingUntil',\n tableName,\n })\n const oldIndexName = getLegacyProcessingIndexName({ filePath, tableName })\n const schemaName = dialect === 'postgres' ? (adapter.schemaName ?? 'public') : undefined\n const drizzleSnapshot = await adapter.requireDrizzleKit().generateDrizzleJson(adapter.schema)\n\n writeFileSync(`${filePath}.json`, JSON.stringify(drizzleSnapshot, null, 2))\n\n const sharedArgs = `\n db,\n newIndexName: ${JSON.stringify(newIndexName)},\n oldIndexName: ${JSON.stringify(oldIndexName)},\n schemaName: ${JSON.stringify(schemaName)},\n sql,\n tableName: ${JSON.stringify(tableName)},`\n\n return {\n downSQL: `await migrateJobsProcessingLease({${sharedArgs}\n direction: 'down',\n })`,\n imports: `import { migrateJobsProcessingLease } from '${packageName}/migration-utils'`,\n upSQL: `await migrateJobsProcessingLease({${sharedArgs}\n direction: 'up',\n })`,\n }\n }\n}\n"],"names":["readdirSync","readFileSync","writeFileSync","path","toSnakeCase","getDefaultIndexName","name","suffix","slice","length","getIndexName","fallbackFieldName","indexes","on","tableName","matchingIndex","Object","values","find","index","getLegacyProcessingIndexName","filePath","latestSnapshotFile","dirname","filter","file","endsWith","sort","reverse","snapshot","JSON","parse","join","table","tables","processingIndex","columns","some","expression","buildDynamicPredefinedJobsProcessingLeaseMigration","dialect","packageName","payload","adapter","db","tableNameMap","get","Error","rawTable","rawTables","newIndexName","oldIndexName","schemaName","undefined","drizzleSnapshot","requireDrizzleKit","generateDrizzleJson","schema","stringify","sharedArgs","downSQL","imports","upSQL"],"mappings":"AAEA,SAASA,WAAW,E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ileSync } from 'fs';
|
|
3
|
-
import { tmpdir } from 'os';
|
|
4
|
-
import path from 'path';
|
|
5
|
-
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
6
|
-
import { migratePostgresJobsProcessingLease } from '../postgres/predefinedMigrations/jobs-processing-lease/index.js';
|
|
7
|
-
import { migrateSqliteJobsProcessingLease } from '../sqlite/predefinedMigrations/jobs-processing-lease/index.js';
|
|
8
|
-
import { buildDynamicPredefinedJobsProcessingLeaseMigration } from './jobsProcessingLeaseMigration.js';
|
|
9
|
-
describe('jobs processing lease predefined migration', ()=>{
|
|
10
|
-
let client;
|
|
11
|
-
const temporaryDirectories = [];
|
|
12
|
-
afterEach(()=>{
|
|
13
|
-
client?.close();
|
|
14
|
-
client = undefined;
|
|
15
|
-
for (const directory of temporaryDirectories){
|
|
16
|
-
rmSync(directory, {
|
|
17
|
-
force: true,
|
|
18
|
-
recursive: true
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
temporaryDirectories.length = 0;
|
|
22
|
-
});
|
|
23
|
-
it('should migrate SQLite job data up and down', async ()=>{
|
|
24
|
-
client = createClient({
|
|
25
|
-
url: ':memory:'
|
|
26
|
-
});
|
|
27
|
-
await client.execute('CREATE TABLE "custom_jobs" ("id" integer primary key, "processing" integer DEFAULT false)');
|
|
28
|
-
await client.execute('CREATE INDEX "custom_jobs_processing_idx" ON "custom_jobs" ("processing")');
|
|
29
|
-
await client.execute('INSERT INTO "custom_jobs" ("id", "processing") VALUES (1, true), (2, false)');
|
|
30
|
-
const db = {
|
|
31
|
-
run: (statement)=>client.execute(statement)
|
|
32
|
-
};
|
|
33
|
-
const sql = {
|
|
34
|
-
raw: (statement)=>statement
|
|
35
|
-
};
|
|
36
|
-
await migrateSqliteJobsProcessingLease({
|
|
37
|
-
db,
|
|
38
|
-
direction: 'up',
|
|
39
|
-
newIndexName: 'custom_jobs_processing_until_idx',
|
|
40
|
-
oldIndexName: 'custom_jobs_processing_idx',
|
|
41
|
-
sql,
|
|
42
|
-
tableName: 'custom_jobs'
|
|
43
|
-
});
|
|
44
|
-
const migratedJobs = await client.execute('SELECT "id", "processing_until" FROM "custom_jobs" ORDER BY "id"');
|
|
45
|
-
expect(migratedJobs.rows).toEqual([
|
|
46
|
-
{
|
|
47
|
-
id: 1,
|
|
48
|
-
processing_until: '1970-01-01T00:00:00.000Z'
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
id: 2,
|
|
52
|
-
processing_until: null
|
|
53
|
-
}
|
|
54
|
-
]);
|
|
55
|
-
await migrateSqliteJobsProcessingLease({
|
|
56
|
-
db,
|
|
57
|
-
direction: 'down',
|
|
58
|
-
newIndexName: 'custom_jobs_processing_until_idx',
|
|
59
|
-
oldIndexName: 'custom_jobs_processing_idx',
|
|
60
|
-
sql,
|
|
61
|
-
tableName: 'custom_jobs'
|
|
62
|
-
});
|
|
63
|
-
const restoredJobs = await client.execute('SELECT "id", "processing" FROM "custom_jobs" ORDER BY "id"');
|
|
64
|
-
expect(restoredJobs.rows).toEqual([
|
|
65
|
-
{
|
|
66
|
-
id: 1,
|
|
67
|
-
processing: 1
|
|
68
|
-
},
|
|
69
|
-
{
|
|
70
|
-
id: 2,
|
|
71
|
-
processing: 0
|
|
72
|
-
}
|
|
73
|
-
]);
|
|
74
|
-
});
|
|
75
|
-
it('should produce PostgreSQL statements with quoted custom names', async ()=>{
|
|
76
|
-
const execute = vi.fn().mockResolvedValue(undefined);
|
|
77
|
-
await migratePostgresJobsProcessingLease({
|
|
78
|
-
db: {
|
|
79
|
-
execute
|
|
80
|
-
},
|
|
81
|
-
direction: 'up',
|
|
82
|
-
newIndexName: 'custom_jobs_processing_until_idx',
|
|
83
|
-
oldIndexName: 'custom_jobs_processing_idx',
|
|
84
|
-
schemaName: 'custom_schema',
|
|
85
|
-
sql: {
|
|
86
|
-
raw: (statement)=>statement
|
|
87
|
-
},
|
|
88
|
-
tableName: 'custom_jobs'
|
|
89
|
-
});
|
|
90
|
-
expect(execute.mock.calls.map(([statement])=>statement)).toEqual([
|
|
91
|
-
'ALTER TABLE "custom_schema"."custom_jobs" ADD COLUMN "processing_until" timestamp(3) with time zone',
|
|
92
|
-
'UPDATE "custom_schema"."custom_jobs" SET "processing_until" = \'1970-01-01 00:00:00+00\' WHERE "processing" = true',
|
|
93
|
-
'DROP INDEX IF EXISTS "custom_schema"."custom_jobs_processing_idx"',
|
|
94
|
-
'ALTER TABLE "custom_schema"."custom_jobs" DROP COLUMN "processing"',
|
|
95
|
-
'CREATE INDEX "custom_jobs_processing_until_idx" ON "custom_schema"."custom_jobs" USING btree ("processing_until")'
|
|
96
|
-
]);
|
|
97
|
-
});
|
|
98
|
-
it('should write a Drizzle snapshot and generate adapter-specific migration code', async ()=>{
|
|
99
|
-
const temporaryDirectory = mkdtempSync(path.join(tmpdir(), 'payload-jobs-migration-'));
|
|
100
|
-
temporaryDirectories.push(temporaryDirectory);
|
|
101
|
-
const filePath = path.join(temporaryDirectory, 'migration');
|
|
102
|
-
writeFileSync(path.join(temporaryDirectory, 'previous.json'), JSON.stringify({
|
|
103
|
-
tables: {
|
|
104
|
-
jobs: {
|
|
105
|
-
indexes: {
|
|
106
|
-
legacy: {
|
|
107
|
-
columns: [
|
|
108
|
-
{
|
|
109
|
-
expression: 'processing'
|
|
110
|
-
}
|
|
111
|
-
],
|
|
112
|
-
name: 'legacy_processing_index'
|
|
113
|
-
}
|
|
114
|
-
},
|
|
115
|
-
name: 'custom_jobs'
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}));
|
|
119
|
-
const payload = {
|
|
120
|
-
db: {
|
|
121
|
-
rawTables: {
|
|
122
|
-
custom_jobs: {
|
|
123
|
-
indexes: {
|
|
124
|
-
processingUntil: {
|
|
125
|
-
name: 'custom_jobs_processing_until_idx',
|
|
126
|
-
on: 'processingUntil'
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
},
|
|
131
|
-
requireDrizzleKit: ()=>({
|
|
132
|
-
generateDrizzleJson: vi.fn().mockResolvedValue({
|
|
133
|
-
version: 'test-snapshot'
|
|
134
|
-
})
|
|
135
|
-
}),
|
|
136
|
-
schema: {},
|
|
137
|
-
schemaName: 'custom_schema',
|
|
138
|
-
tableNameMap: new Map([
|
|
139
|
-
[
|
|
140
|
-
'payload_jobs',
|
|
141
|
-
'custom_jobs'
|
|
142
|
-
]
|
|
143
|
-
])
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
const dynamic = buildDynamicPredefinedJobsProcessingLeaseMigration({
|
|
147
|
-
dialect: 'postgres',
|
|
148
|
-
packageName: '@payloadcms/db-postgres'
|
|
149
|
-
});
|
|
150
|
-
const migration = await dynamic({
|
|
151
|
-
filePath,
|
|
152
|
-
payload
|
|
153
|
-
});
|
|
154
|
-
expect(existsSync(`${filePath}.json`)).toBe(true);
|
|
155
|
-
expect(JSON.parse(readFileSync(`${filePath}.json`, 'utf8'))).toEqual({
|
|
156
|
-
version: 'test-snapshot'
|
|
157
|
-
});
|
|
158
|
-
expect(migration.imports).toContain('@payloadcms/db-postgres/migration-utils');
|
|
159
|
-
expect(migration.upSQL).toContain("direction: 'up'");
|
|
160
|
-
expect(migration.upSQL).toContain('custom_jobs_processing_until_idx');
|
|
161
|
-
expect(migration.upSQL).toContain('legacy_processing_index');
|
|
162
|
-
expect(migration.downSQL).toContain("direction: 'down'");
|
|
163
|
-
});
|
|
164
|
-
});
|
|
165
|
-
|
|
166
|
-
//# sourceMappingURL=jobsProcessingLeaseMigration.spec.js.map
|