@payloadcms/drizzle 4.0.0-internal.b6f3b9a → 4.0.0-internal.b8a92d2
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/exports/postgres.d.ts +2 -0
- package/dist/exports/postgres.d.ts.map +1 -1
- package/dist/exports/postgres.js +2 -0
- package/dist/exports/postgres.js.map +1 -1
- package/dist/find/buildPolymorphicJoinQuery.d.ts +38 -0
- package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -0
- package/dist/find/buildPolymorphicJoinQuery.js +135 -0
- package/dist/find/buildPolymorphicJoinQuery.js.map +1 -0
- package/dist/find/buildPolymorphicJoinWhere.d.ts +20 -0
- package/dist/find/buildPolymorphicJoinWhere.d.ts.map +1 -0
- package/dist/find/buildPolymorphicJoinWhere.js +301 -0
- package/dist/find/buildPolymorphicJoinWhere.js.map +1 -0
- package/dist/find/createPolymorphicJoinWherePlan.d.ts +37 -0
- package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -0
- package/dist/find/createPolymorphicJoinWherePlan.js +191 -0
- package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -0
- package/dist/find/traverseFields.d.ts.map +1 -1
- package/dist/find/traverseFields.js +19 -191
- package/dist/find/traverseFields.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- 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/createJSONQuery/index.js +3 -3
- package/dist/postgres/createJSONQuery/index.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/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/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/getTableColumnFromPath.d.ts +12 -3
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +59 -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 +262 -10
- 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/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +4 -5
- package/dist/schema/build.js.map +1 -1
- package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js +3 -2
- package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js.map +1 -1
- package/dist/sqlite/createJSONQuery/index.d.ts.map +1 -1
- package/dist/sqlite/createJSONQuery/index.js +6 -5
- package/dist/sqlite/createJSONQuery/index.js.map +1 -1
- package/dist/transform/write/traverseFields.d.ts.map +1 -1
- package/dist/transform/write/traverseFields.js +8 -14
- package/dist/transform/write/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/updateOne.d.ts.map +1 -1
- package/dist/updateOne.js +41 -1
- package/dist/updateOne.js.map +1 -1
- package/dist/upsertRow/index.d.ts +1 -1
- package/dist/upsertRow/index.d.ts.map +1 -1
- package/dist/upsertRow/index.js +25 -5
- package/dist/upsertRow/index.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/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +3 -0
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/parseJSONPathSegment.d.ts +9 -0
- package/dist/utilities/parseJSONPathSegment.d.ts.map +1 -0
- package/dist/utilities/parseJSONPathSegment.js +17 -0
- package/dist/utilities/parseJSONPathSegment.js.map +1 -0
- package/dist/utilities/validateIdentifierLength.d.ts +5 -0
- package/dist/utilities/validateIdentifierLength.d.ts.map +1 -1
- package/dist/utilities/validateIdentifierLength.js +4 -0
- package/dist/utilities/validateIdentifierLength.js.map +1 -1
- package/package.json +3 -3
- package/dist/schema/buildRawSchema.spec.js +0 -230
- package/dist/schema/buildRawSchema.spec.js.map +0 -1
- package/dist/upsertRow/handleUpsertError.spec.js +0 -42
- package/dist/upsertRow/handleUpsertError.spec.js.map +0 -1
- package/dist/utilities/isValidStringID.spec.js +0 -15
- package/dist/utilities/isValidStringID.spec.js.map +0 -1
- package/dist/utilities/validateIdentifierLength.spec.js +0 -19
- package/dist/utilities/validateIdentifierLength.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,SAAiBJ;IACvC,MAAMK,YAAY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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,SAAiBJ;IACvC,MAAMK,YAA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,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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parseJSONPathSegment.d.ts","sourceRoot":"","sources":["../../src/utilities/parseJSONPathSegment.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,eAAe,GACvB;IACE,IAAI,EAAE,YAAY,CAAA;IAClB,KAAK,EAAE,MAAM,CAAA;CACd,GACD;IACE,IAAI,EAAE,WAAW,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAIL,eAAO,MAAM,oBAAoB,YAAa,MAAM,KAAG,eActD,CAAA"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { sanitizePathSegment } from './sanitizePathSegment.js';
|
|
2
|
+
const ARRAY_INDEX_REGEX = /^\d+$/;
|
|
3
|
+
export const parseJSONPathSegment = (segment)=>{
|
|
4
|
+
const sanitizedSegment = sanitizePathSegment(segment);
|
|
5
|
+
if (ARRAY_INDEX_REGEX.test(sanitizedSegment)) {
|
|
6
|
+
return {
|
|
7
|
+
type: 'arrayIndex',
|
|
8
|
+
value: sanitizedSegment
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
return {
|
|
12
|
+
type: 'objectKey',
|
|
13
|
+
value: sanitizedSegment
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=parseJSONPathSegment.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/parseJSONPathSegment.ts"],"sourcesContent":["import { sanitizePathSegment } from './sanitizePathSegment.js'\n\nexport type JSONPathSegment =\n | {\n type: 'arrayIndex'\n value: string\n }\n | {\n type: 'objectKey'\n value: string\n }\n\nconst ARRAY_INDEX_REGEX = /^\\d+$/\n\nexport const parseJSONPathSegment = (segment: string): JSONPathSegment => {\n const sanitizedSegment = sanitizePathSegment(segment)\n\n if (ARRAY_INDEX_REGEX.test(sanitizedSegment)) {\n return {\n type: 'arrayIndex',\n value: sanitizedSegment,\n }\n }\n\n return {\n type: 'objectKey',\n value: sanitizedSegment,\n }\n}\n"],"names":["sanitizePathSegment","ARRAY_INDEX_REGEX","parseJSONPathSegment","segment","sanitizedSegment","test","type","value"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,2BAA0B;AAY9D,MAAMC,oBAAoB;AAE1B,OAAO,MAAMC,uBAAuB,CAACC;IACnC,MAAMC,mBAAmBJ,oBAAoBG;IAE7C,IAAIF,kBAAkBI,IAAI,CAACD,mBAAmB;QAC5C,OAAO;YACLE,MAAM;YACNC,OAAOH;QACT;IACF;IAEA,OAAO;QACLE,MAAM;QACNC,OAAOH;IACT;AACF,EAAC"}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
/** Postgres max identifier length (NAMEDATALEN - 1). */
|
|
2
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;
|
|
3
8
|
/**
|
|
4
9
|
* Throws if a table or enum identifier exceeds the Postgres 63-char limit.
|
|
5
10
|
*/
|
|
@@ -1 +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;;GAEG;AACH,eAAO,MAAM,wBAAwB,SAAU,MAAM,KAAG,MAUvD,CAAA"}
|
|
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"}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { APIError } from 'payload';
|
|
2
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;
|
|
3
7
|
/**
|
|
4
8
|
* Throws if a table or enum identifier exceeds the Postgres 63-char limit.
|
|
5
9
|
*/ export const validateIdentifierLength = (name)=>{
|
|
@@ -1 +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 * 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","validateIdentifierLength","name","length"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,UAAS;AAElC,sDAAsD,GACtD,OAAO,MAAMC,sBAAsB,GAAE;AAErC;;CAEC,GACD,OAAO,
|
|
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"}
|
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.b8a92d2",
|
|
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.b8a92d2"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"payload": "4.0.0-internal.
|
|
61
|
+
"payload": "4.0.0-internal.b8a92d2"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "pnpm build:swc && pnpm build:types",
|
|
@@ -1,230 +0,0 @@
|
|
|
1
|
-
import { sanitizeConfig } from 'payload';
|
|
2
|
-
import { describe, expect, it } from 'vitest';
|
|
3
|
-
import { setColumnID } from '../postgres/schema/setColumnID.js';
|
|
4
|
-
import { buildRawSchema } from './buildRawSchema.js';
|
|
5
|
-
const headlineBlock = {
|
|
6
|
-
slug: 'headline',
|
|
7
|
-
fields: [
|
|
8
|
-
{
|
|
9
|
-
name: 'title',
|
|
10
|
-
type: 'text'
|
|
11
|
-
}
|
|
12
|
-
]
|
|
13
|
-
};
|
|
14
|
-
const createContainerBlock = (slug)=>({
|
|
15
|
-
slug,
|
|
16
|
-
fields: [
|
|
17
|
-
{
|
|
18
|
-
name: 'content',
|
|
19
|
-
type: 'blocks',
|
|
20
|
-
blocks: [
|
|
21
|
-
'headline'
|
|
22
|
-
]
|
|
23
|
-
}
|
|
24
|
-
]
|
|
25
|
-
});
|
|
26
|
-
const createAdapter = (config)=>({
|
|
27
|
-
blocksAsJSON: false,
|
|
28
|
-
fieldConstraints: {},
|
|
29
|
-
idType: 'serial',
|
|
30
|
-
localesSuffix: '_locales',
|
|
31
|
-
payload: {
|
|
32
|
-
blocks: Object.fromEntries(config.blocks.map((block)=>[
|
|
33
|
-
block.slug,
|
|
34
|
-
block
|
|
35
|
-
])),
|
|
36
|
-
collections: Object.fromEntries(config.collections.map((collection)=>[
|
|
37
|
-
collection.slug,
|
|
38
|
-
{
|
|
39
|
-
config: collection,
|
|
40
|
-
customIDType: undefined
|
|
41
|
-
}
|
|
42
|
-
])),
|
|
43
|
-
config
|
|
44
|
-
},
|
|
45
|
-
rawRelations: {},
|
|
46
|
-
rawTables: {},
|
|
47
|
-
tableNameMap: new Map(),
|
|
48
|
-
versionsSuffix: '_versions'
|
|
49
|
-
});
|
|
50
|
-
describe('buildRawSchema', ()=>{
|
|
51
|
-
it('should create suffixed block tables for different schemas with the same slug', async ()=>{
|
|
52
|
-
const config = await sanitizeConfig({
|
|
53
|
-
collections: [
|
|
54
|
-
{
|
|
55
|
-
slug: 'pages',
|
|
56
|
-
fields: [
|
|
57
|
-
{
|
|
58
|
-
name: 'primaryContent',
|
|
59
|
-
type: 'blocks',
|
|
60
|
-
localized: true,
|
|
61
|
-
blocks: [
|
|
62
|
-
{
|
|
63
|
-
slug: 'content',
|
|
64
|
-
fields: [
|
|
65
|
-
{
|
|
66
|
-
name: 'title',
|
|
67
|
-
type: 'text'
|
|
68
|
-
}
|
|
69
|
-
]
|
|
70
|
-
}
|
|
71
|
-
]
|
|
72
|
-
},
|
|
73
|
-
{
|
|
74
|
-
name: 'secondaryContent',
|
|
75
|
-
type: 'blocks',
|
|
76
|
-
localized: true,
|
|
77
|
-
blocks: [
|
|
78
|
-
{
|
|
79
|
-
slug: 'content',
|
|
80
|
-
fields: [
|
|
81
|
-
{
|
|
82
|
-
name: 'description',
|
|
83
|
-
type: 'textarea'
|
|
84
|
-
}
|
|
85
|
-
]
|
|
86
|
-
}
|
|
87
|
-
]
|
|
88
|
-
}
|
|
89
|
-
]
|
|
90
|
-
}
|
|
91
|
-
],
|
|
92
|
-
localization: {
|
|
93
|
-
defaultLocale: 'en',
|
|
94
|
-
locales: [
|
|
95
|
-
'en',
|
|
96
|
-
'de'
|
|
97
|
-
]
|
|
98
|
-
}
|
|
99
|
-
});
|
|
100
|
-
const adapter = createAdapter(config);
|
|
101
|
-
buildRawSchema({
|
|
102
|
-
adapter,
|
|
103
|
-
setColumnID
|
|
104
|
-
});
|
|
105
|
-
expect(adapter.rawTables.pages_blocks_content.columns.title).toBeDefined();
|
|
106
|
-
expect(adapter.rawTables.pages_blocks_content.columns._locale).toBeDefined();
|
|
107
|
-
expect(adapter.rawTables.pages_blocks_content_2.columns.description).toBeDefined();
|
|
108
|
-
expect(adapter.rawTables.pages_blocks_content_2.columns._locale).toBeDefined();
|
|
109
|
-
});
|
|
110
|
-
it('should not create duplicate suffixed block tables for identical reused blocks under localized ancestors', async ()=>{
|
|
111
|
-
const layoutBlocks = [
|
|
112
|
-
createContainerBlock('container'),
|
|
113
|
-
createContainerBlock('container50')
|
|
114
|
-
];
|
|
115
|
-
const config = await sanitizeConfig({
|
|
116
|
-
blocks: [
|
|
117
|
-
headlineBlock
|
|
118
|
-
],
|
|
119
|
-
collections: [
|
|
120
|
-
{
|
|
121
|
-
slug: 'pages',
|
|
122
|
-
fields: [
|
|
123
|
-
{
|
|
124
|
-
name: 'layout',
|
|
125
|
-
type: 'blocks',
|
|
126
|
-
localized: true,
|
|
127
|
-
blocks: layoutBlocks
|
|
128
|
-
}
|
|
129
|
-
]
|
|
130
|
-
},
|
|
131
|
-
{
|
|
132
|
-
slug: 'posts',
|
|
133
|
-
fields: [
|
|
134
|
-
{
|
|
135
|
-
name: 'layout',
|
|
136
|
-
type: 'blocks',
|
|
137
|
-
localized: true,
|
|
138
|
-
blocks: layoutBlocks
|
|
139
|
-
}
|
|
140
|
-
]
|
|
141
|
-
}
|
|
142
|
-
],
|
|
143
|
-
localization: {
|
|
144
|
-
defaultLocale: 'en',
|
|
145
|
-
locales: [
|
|
146
|
-
'en',
|
|
147
|
-
'de'
|
|
148
|
-
]
|
|
149
|
-
}
|
|
150
|
-
});
|
|
151
|
-
const adapter = createAdapter(config);
|
|
152
|
-
buildRawSchema({
|
|
153
|
-
adapter,
|
|
154
|
-
setColumnID
|
|
155
|
-
});
|
|
156
|
-
expect(adapter.rawTables.pages_blocks_headline).toBeDefined();
|
|
157
|
-
expect(adapter.rawTables.pages_blocks_headline.columns._locale).toBeDefined();
|
|
158
|
-
expect(adapter.rawTables.pages_blocks_headline_2).toBeUndefined();
|
|
159
|
-
expect(adapter.rawTables.pages_blocks_headline_2_locales).toBeUndefined();
|
|
160
|
-
expect(adapter.rawTables.posts_blocks_headline).toBeDefined();
|
|
161
|
-
expect(adapter.rawTables.posts_blocks_headline.columns._locale).toBeDefined();
|
|
162
|
-
expect(adapter.rawTables.posts_blocks_headline_2).toBeUndefined();
|
|
163
|
-
expect(adapter.rawTables.posts_blocks_headline_2_locales).toBeUndefined();
|
|
164
|
-
});
|
|
165
|
-
it('should throw when a localized field pushes the _locales companion table past 63 chars', async ()=>{
|
|
166
|
-
// Base table name (61 chars) is under the limit, but `${base}_locales` (69) overflows it.
|
|
167
|
-
const longSlug = `localized_collection_${'x'.repeat(40)}`;
|
|
168
|
-
const config = await sanitizeConfig({
|
|
169
|
-
collections: [
|
|
170
|
-
{
|
|
171
|
-
slug: longSlug,
|
|
172
|
-
fields: [
|
|
173
|
-
{
|
|
174
|
-
name: 'title',
|
|
175
|
-
type: 'text',
|
|
176
|
-
localized: true
|
|
177
|
-
}
|
|
178
|
-
],
|
|
179
|
-
timestamps: false,
|
|
180
|
-
versions: false
|
|
181
|
-
}
|
|
182
|
-
],
|
|
183
|
-
localization: {
|
|
184
|
-
defaultLocale: 'en',
|
|
185
|
-
locales: [
|
|
186
|
-
'en',
|
|
187
|
-
'de'
|
|
188
|
-
]
|
|
189
|
-
}
|
|
190
|
-
});
|
|
191
|
-
const adapter = createAdapter(config);
|
|
192
|
-
expect(()=>buildRawSchema({
|
|
193
|
-
adapter,
|
|
194
|
-
setColumnID
|
|
195
|
-
})).toThrow('Exceeded max identifier length');
|
|
196
|
-
});
|
|
197
|
-
it('should not throw for a localized field whose _locales companion table fits within 63 chars', async ()=>{
|
|
198
|
-
const config = await sanitizeConfig({
|
|
199
|
-
collections: [
|
|
200
|
-
{
|
|
201
|
-
slug: 'short_localized',
|
|
202
|
-
fields: [
|
|
203
|
-
{
|
|
204
|
-
name: 'title',
|
|
205
|
-
type: 'text',
|
|
206
|
-
localized: true
|
|
207
|
-
}
|
|
208
|
-
],
|
|
209
|
-
timestamps: false,
|
|
210
|
-
versions: false
|
|
211
|
-
}
|
|
212
|
-
],
|
|
213
|
-
localization: {
|
|
214
|
-
defaultLocale: 'en',
|
|
215
|
-
locales: [
|
|
216
|
-
'en',
|
|
217
|
-
'de'
|
|
218
|
-
]
|
|
219
|
-
}
|
|
220
|
-
});
|
|
221
|
-
const adapter = createAdapter(config);
|
|
222
|
-
buildRawSchema({
|
|
223
|
-
adapter,
|
|
224
|
-
setColumnID
|
|
225
|
-
});
|
|
226
|
-
expect(adapter.rawTables.short_localized_locales).toBeDefined();
|
|
227
|
-
});
|
|
228
|
-
});
|
|
229
|
-
|
|
230
|
-
//# sourceMappingURL=buildRawSchema.spec.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/schema/buildRawSchema.spec.ts"],"sourcesContent":["import type { Block, Config, SanitizedConfig } from 'payload'\nimport { sanitizeConfig } from 'payload'\nimport { describe, expect, it } from 'vitest'\n\nimport { setColumnID } from '../postgres/schema/setColumnID.js'\nimport type { DrizzleAdapter } from '../types.js'\nimport { buildRawSchema } from './buildRawSchema.js'\n\nconst headlineBlock: Block = {\n slug: 'headline',\n fields: [\n {\n name: 'title',\n type: 'text',\n },\n ],\n}\n\nconst createContainerBlock = (slug: string): Block => ({\n slug,\n fields: [\n {\n name: 'content',\n type: 'blocks',\n blocks: ['headline'],\n },\n ],\n})\n\nconst createAdapter = (config: SanitizedConfig): DrizzleAdapter =>\n ({\n blocksAsJSON: false,\n fieldConstraints: {},\n idType: 'serial',\n localesSuffix: '_locales',\n payload: {\n blocks: Object.fromEntries(config.blocks.map((block) => [block.slug, block])),\n collections: Object.fromEntries(\n config.collections.map((collection) => [\n collection.slug,\n {\n config: collection,\n customIDType: undefined,\n },\n ]),\n ),\n config,\n },\n rawRelations: {},\n rawTables: {},\n tableNameMap: new Map(),\n versionsSuffix: '_versions',\n }) as unknown as DrizzleAdapter\n\ndescribe('buildRawSchema', () => {\n it('should create suffixed block tables for different schemas with the same slug', async () => {\n const config = await sanitizeConfig({\n collections: [\n {\n slug: 'pages',\n fields: [\n {\n name: 'primaryContent',\n type: 'blocks',\n localized: true,\n blocks: [\n {\n slug: 'content',\n fields: [\n {\n name: 'title',\n type: 'text',\n },\n ],\n },\n ],\n },\n {\n name: 'secondaryContent',\n type: 'blocks',\n localized: true,\n blocks: [\n {\n slug: 'content',\n fields: [\n {\n name: 'description',\n type: 'textarea',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n localization: {\n defaultLocale: 'en',\n locales: ['en', 'de'],\n },\n } as Config)\n\n const adapter = createAdapter(config)\n\n buildRawSchema({\n adapter,\n setColumnID,\n })\n\n expect(adapter.rawTables.pages_blocks_content.columns.title).toBeDefined()\n expect(adapter.rawTables.pages_blocks_content.columns._locale).toBeDefined()\n expect(adapter.rawTables.pages_blocks_content_2.columns.description).toBeDefined()\n expect(adapter.rawTables.pages_blocks_content_2.columns._locale).toBeDefined()\n })\n\n it('should not create duplicate suffixed block tables for identical reused blocks under localized ancestors', async () => {\n const layoutBlocks = [createContainerBlock('container'), createContainerBlock('container50')]\n\n const config = await sanitizeConfig({\n blocks: [headlineBlock],\n collections: [\n {\n slug: 'pages',\n fields: [\n {\n name: 'layout',\n type: 'blocks',\n localized: true,\n blocks: layoutBlocks,\n },\n ],\n },\n {\n slug: 'posts',\n fields: [\n {\n name: 'layout',\n type: 'blocks',\n localized: true,\n blocks: layoutBlocks,\n },\n ],\n },\n ],\n localization: {\n defaultLocale: 'en',\n locales: ['en', 'de'],\n },\n } as Config)\n\n const adapter = createAdapter(config)\n\n buildRawSchema({\n adapter,\n setColumnID,\n })\n\n expect(adapter.rawTables.pages_blocks_headline).toBeDefined()\n expect(adapter.rawTables.pages_blocks_headline.columns._locale).toBeDefined()\n expect(adapter.rawTables.pages_blocks_headline_2).toBeUndefined()\n expect(adapter.rawTables.pages_blocks_headline_2_locales).toBeUndefined()\n expect(adapter.rawTables.posts_blocks_headline).toBeDefined()\n expect(adapter.rawTables.posts_blocks_headline.columns._locale).toBeDefined()\n expect(adapter.rawTables.posts_blocks_headline_2).toBeUndefined()\n expect(adapter.rawTables.posts_blocks_headline_2_locales).toBeUndefined()\n })\n\n it('should throw when a localized field pushes the _locales companion table past 63 chars', async () => {\n // Base table name (61 chars) is under the limit, but `${base}_locales` (69) overflows it.\n const longSlug = `localized_collection_${'x'.repeat(40)}`\n\n const config = await sanitizeConfig({\n collections: [\n {\n slug: longSlug,\n fields: [\n {\n name: 'title',\n type: 'text',\n localized: true,\n },\n ],\n timestamps: false,\n versions: false,\n },\n ],\n localization: {\n defaultLocale: 'en',\n locales: ['en', 'de'],\n },\n } as Config)\n\n const adapter = createAdapter(config)\n\n expect(() =>\n buildRawSchema({\n adapter,\n setColumnID,\n }),\n ).toThrow('Exceeded max identifier length')\n })\n\n it('should not throw for a localized field whose _locales companion table fits within 63 chars', async () => {\n const config = await sanitizeConfig({\n collections: [\n {\n slug: 'short_localized',\n fields: [\n {\n name: 'title',\n type: 'text',\n localized: true,\n },\n ],\n timestamps: false,\n versions: false,\n },\n ],\n localization: {\n defaultLocale: 'en',\n locales: ['en', 'de'],\n },\n } as Config)\n\n const adapter = createAdapter(config)\n\n buildRawSchema({\n adapter,\n setColumnID,\n })\n\n expect(adapter.rawTables.short_localized_locales).toBeDefined()\n })\n})\n"],"names":["sanitizeConfig","describe","expect","it","setColumnID","buildRawSchema","headlineBlock","slug","fields","name","type","createContainerBlock","blocks","createAdapter","config","blocksAsJSON","fieldConstraints","idType","localesSuffix","payload","Object","fromEntries","map","block","collections","collection","customIDType","undefined","rawRelations","rawTables","tableNameMap","Map","versionsSuffix","localized","localization","defaultLocale","locales","adapter","pages_blocks_content","columns","title","toBeDefined","_locale","pages_blocks_content_2","description","layoutBlocks","pages_blocks_headline","pages_blocks_headline_2","toBeUndefined","pages_blocks_headline_2_locales","posts_blocks_headline","posts_blocks_headline_2","posts_blocks_headline_2_locales","longSlug","repeat","timestamps","versions","toThrow","short_localized_locales"],"mappings":"AACA,SAASA,cAAc,QAAQ,UAAS;AACxC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAE7C,SAASC,WAAW,QAAQ,oCAAmC;AAE/D,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,MAAMC,gBAAuB;IAC3BC,MAAM;IACNC,QAAQ;QACN;YACEC,MAAM;YACNC,MAAM;QACR;KACD;AACH;AAEA,MAAMC,uBAAuB,CAACJ,OAAyB,CAAA;QACrDA;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;gBAC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,SAAS,CAACuB,+BAA+B,EAAEJ,aAAa;IACzE;IAEA7C,GAAG,yFAAyF;QAC1F,0FAA0F;QAC1F,MAAMkD,WAAW,CAAC,qBAAqB,EAAE,IAAIC,MAAM,CAAC,KAAK;QAEzD,MAAMxC,SAAS,MAAMd,eAAe;YAClCwB,aAAa;gBACX;oBACEjB,MAAM8C;oBACN7C,QAAQ;wBACN;4BACEC,MAAM;4BACNC,MAAM;4BACNuB,WAAW;wBACb;qBACD;oBACDsB,YAAY;oBACZC,UAAU;gBACZ;aACD;YACDtB,cAAc;gBACZC,eAAe;gBACfC,SAAS;oBAAC;oBAAM;iBAAK;YACvB;QACF;QAEA,MAAMC,UAAUxB,cAAcC;QAE9BZ,OAAO,IACLG,eAAe;gBACbgC;gBACAjC;YACF,IACAqD,OAAO,CAAC;IACZ;IAEAtD,GAAG,8FAA8F;QAC/F,MAAMW,SAAS,MAAMd,eAAe;YAClCwB,aAAa;gBACX;oBACEjB,MAAM;oBACNC,QAAQ;wBACN;4BACEC,MAAM;4BACNC,MAAM;4BACNuB,WAAW;wBACb;qBACD;oBACDsB,YAAY;oBACZC,UAAU;gBACZ;aACD;YACDtB,cAAc;gBACZC,eAAe;gBACfC,SAAS;oBAAC;oBAAM;iBAAK;YACvB;QACF;QAEA,MAAMC,UAAUxB,cAAcC;QAE9BT,eAAe;YACbgC;YACAjC;QACF;QAEAF,OAAOmC,QAAQR,SAAS,CAAC6B,uBAAuB,EAAEjB,WAAW;IAC/D;AACF"}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { ValidationError } from 'payload';
|
|
2
|
-
import { describe, expect, it } from 'vitest';
|
|
3
|
-
import { handleUpsertError } from './handleUpsertError.js';
|
|
4
|
-
const adapter = {
|
|
5
|
-
fieldConstraints: {}
|
|
6
|
-
};
|
|
7
|
-
describe('handleUpsertError', ()=>{
|
|
8
|
-
it('preserves the failing sub-table name on the ValidationError', ()=>{
|
|
9
|
-
const pgError = {
|
|
10
|
-
code: '23505',
|
|
11
|
-
constraint: 'ultrasonic_avail_country_pkey',
|
|
12
|
-
detail: 'Key (id)=(6a27e2a63f4b64567370f595) already exists.'
|
|
13
|
-
};
|
|
14
|
-
let thrown;
|
|
15
|
-
try {
|
|
16
|
-
handleUpsertError({
|
|
17
|
-
adapter,
|
|
18
|
-
collectionSlug: 'ultrasonic',
|
|
19
|
-
error: pgError,
|
|
20
|
-
tableName: 'ultrasonic_avail_country'
|
|
21
|
-
});
|
|
22
|
-
} catch (error) {
|
|
23
|
-
thrown = error;
|
|
24
|
-
}
|
|
25
|
-
expect(thrown).toBeInstanceOf(ValidationError);
|
|
26
|
-
const validationError = thrown;
|
|
27
|
-
const fieldError = validationError.data.errors[0];
|
|
28
|
-
expect(fieldError.path).toBe('id');
|
|
29
|
-
expect(fieldError.tableName).toBe('ultrasonic_avail_country');
|
|
30
|
-
});
|
|
31
|
-
it('re-throws non unique-constraint errors unchanged', ()=>{
|
|
32
|
-
const otherError = new Error('some other db error');
|
|
33
|
-
expect(()=>handleUpsertError({
|
|
34
|
-
adapter,
|
|
35
|
-
collectionSlug: 'ultrasonic',
|
|
36
|
-
error: otherError,
|
|
37
|
-
tableName: 'ultrasonic_avail_country'
|
|
38
|
-
})).toThrow(otherError);
|
|
39
|
-
});
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
//# sourceMappingURL=handleUpsertError.spec.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/upsertRow/handleUpsertError.spec.ts"],"sourcesContent":["import { ValidationError } from 'payload'\nimport { describe, expect, it } from 'vitest'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { handleUpsertError } from './handleUpsertError.js'\n\nconst adapter = { fieldConstraints: {} } as unknown as DrizzleAdapter\n\ndescribe('handleUpsertError', () => {\n it('preserves the failing sub-table name on the ValidationError', () => {\n const pgError = {\n code: '23505',\n constraint: 'ultrasonic_avail_country_pkey',\n detail: 'Key (id)=(6a27e2a63f4b64567370f595) already exists.',\n }\n\n let thrown: unknown\n try {\n handleUpsertError({\n adapter,\n collectionSlug: 'ultrasonic',\n error: pgError,\n tableName: 'ultrasonic_avail_country',\n })\n } catch (error) {\n thrown = error\n }\n\n expect(thrown).toBeInstanceOf(ValidationError)\n const validationError = thrown as ValidationError\n const fieldError = validationError.data.errors[0]!\n expect(fieldError.path).toBe('id')\n expect(fieldError.tableName).toBe('ultrasonic_avail_country')\n })\n\n it('re-throws non unique-constraint errors unchanged', () => {\n const otherError = new Error('some other db error')\n\n expect(() =>\n handleUpsertError({\n adapter,\n collectionSlug: 'ultrasonic',\n error: otherError,\n tableName: 'ultrasonic_avail_country',\n }),\n ).toThrow(otherError)\n })\n})\n"],"names":["ValidationError","describe","expect","it","handleUpsertError","adapter","fieldConstraints","pgError","code","constraint","detail","thrown","collectionSlug","error","tableName","toBeInstanceOf","validationError","fieldError","data","errors","path","toBe","otherError","Error","toThrow"],"mappings":"AAAA,SAASA,eAAe,QAAQ,UAAS;AACzC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,MAAMC,UAAU;IAAEC,kBAAkB,CAAC;AAAE;AAEvCL,SAAS,qBAAqB;IAC5BE,GAAG,+DAA+D;QAChE,MAAMI,UAAU;YACdC,MAAM;YACNC,YAAY;YACZC,QAAQ;QACV;QAEA,IAAIC;QACJ,IAAI;YACFP,kBAAkB;gBAChBC;gBACAO,gBAAgB;gBAChBC,OAAON;gBACPO,WAAW;YACb;QACF,EAAE,OAAOD,OAAO;YACdF,SAASE;QACX;QAEAX,OAAOS,QAAQI,cAAc,CAACf;QAC9B,MAAMgB,kBAAkBL;QACxB,MAAMM,aAAaD,gBAAgBE,IAAI,CAACC,MAAM,CAAC,EAAE;QACjDjB,OAAOe,WAAWG,IAAI,EAAEC,IAAI,CAAC;QAC7BnB,OAAOe,WAAWH,SAAS,EAAEO,IAAI,CAAC;IACpC;IAEAlB,GAAG,oDAAoD;QACrD,MAAMmB,aAAa,IAAIC,MAAM;QAE7BrB,OAAO,IACLE,kBAAkB;gBAChBC;gBACAO,gBAAgB;gBAChBC,OAAOS;gBACPR,WAAW;YACb,IACAU,OAAO,CAACF;IACZ;AACF"}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect } from 'vitest';
|
|
2
|
-
import { isValidStringID } from './isValidStringID.js';
|
|
3
|
-
describe('isValidStringID', ()=>{
|
|
4
|
-
it('should pass', ()=>{
|
|
5
|
-
expect(isValidStringID('1')).toBe(true);
|
|
6
|
-
expect(isValidStringID('a_b_c')).toBe(true);
|
|
7
|
-
expect(isValidStringID('8cc2df6d-6e07-4da4-be48-5fa747c3b92b')).toBe(true);
|
|
8
|
-
});
|
|
9
|
-
it('should not pass', ()=>{
|
|
10
|
-
expect(isValidStringID('1 2 3')).toBe(false);
|
|
11
|
-
expect(isValidStringID('1@')).toBe(false);
|
|
12
|
-
});
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
//# sourceMappingURL=isValidStringID.spec.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/isValidStringID.spec.ts"],"sourcesContent":["import { describe, it, expect } from 'vitest'\nimport { isValidStringID } from './isValidStringID.js'\n\ndescribe('isValidStringID', () => {\n it('should pass', () => {\n expect(isValidStringID('1')).toBe(true)\n expect(isValidStringID('a_b_c')).toBe(true)\n expect(isValidStringID('8cc2df6d-6e07-4da4-be48-5fa747c3b92b')).toBe(true)\n })\n\n it('should not pass', () => {\n expect(isValidStringID('1 2 3')).toBe(false)\n expect(isValidStringID('1@')).toBe(false)\n })\n})\n"],"names":["describe","it","expect","isValidStringID","toBe"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,EAAE,EAAEC,MAAM,QAAQ,SAAQ;AAC7C,SAASC,eAAe,QAAQ,uBAAsB;AAEtDH,SAAS,mBAAmB;IAC1BC,GAAG,eAAe;QAChBC,OAAOC,gBAAgB,MAAMC,IAAI,CAAC;QAClCF,OAAOC,gBAAgB,UAAUC,IAAI,CAAC;QACtCF,OAAOC,gBAAgB,yCAAyCC,IAAI,CAAC;IACvE;IAEAH,GAAG,mBAAmB;QACpBC,OAAOC,gBAAgB,UAAUC,IAAI,CAAC;QACtCF,OAAOC,gBAAgB,OAAOC,IAAI,CAAC;IACrC;AACF"}
|
|
@@ -1,19 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|