@payloadcms/drizzle 3.7.0 → 3.7.1-canary.2ce70a3
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/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/postgres/columnToCodeConverter.d.ts +3 -0
- package/dist/postgres/columnToCodeConverter.d.ts.map +1 -0
- package/dist/postgres/columnToCodeConverter.js +64 -0
- package/dist/postgres/columnToCodeConverter.js.map +1 -0
- package/dist/postgres/init.d.ts.map +1 -1
- package/dist/postgres/init.js +16 -85
- package/dist/postgres/init.js.map +1 -1
- package/dist/postgres/schema/buildDrizzleTable.d.ts +7 -0
- package/dist/postgres/schema/buildDrizzleTable.d.ts.map +1 -0
- package/dist/postgres/schema/buildDrizzleTable.js +114 -0
- package/dist/postgres/schema/buildDrizzleTable.js.map +1 -0
- package/dist/postgres/schema/setColumnID.d.ts +2 -10
- package/dist/postgres/schema/setColumnID.d.ts.map +1 -1
- package/dist/postgres/schema/setColumnID.js +21 -5
- package/dist/postgres/schema/setColumnID.js.map +1 -1
- package/dist/{postgres/schema → schema}/build.d.ts +12 -7
- package/dist/schema/build.d.ts.map +1 -0
- package/dist/schema/build.js +603 -0
- package/dist/schema/build.js.map +1 -0
- package/dist/schema/buildDrizzleRelations.d.ts +5 -0
- package/dist/schema/buildDrizzleRelations.d.ts.map +1 -0
- package/dist/schema/buildDrizzleRelations.js +26 -0
- package/dist/schema/buildDrizzleRelations.js.map +1 -0
- package/dist/schema/buildRawSchema.d.ts +9 -0
- package/dist/schema/buildRawSchema.d.ts.map +1 -0
- package/dist/schema/buildRawSchema.js +97 -0
- package/dist/schema/buildRawSchema.js.map +1 -0
- package/dist/schema/idToUUID.d.ts.map +1 -0
- package/dist/schema/idToUUID.js.map +1 -0
- package/dist/{postgres/schema → schema}/traverseFields.d.ts +9 -9
- package/dist/schema/traverseFields.d.ts.map +1 -0
- package/dist/{postgres/schema → schema}/traverseFields.js +343 -174
- package/dist/schema/traverseFields.js.map +1 -0
- package/dist/schema/withDefault.d.ts +4 -0
- package/dist/schema/withDefault.d.ts.map +1 -0
- package/dist/{postgres/schema → schema}/withDefault.js +8 -5
- package/dist/schema/withDefault.js.map +1 -0
- package/dist/transform/read/traverseFields.d.ts.map +1 -1
- package/dist/transform/read/traverseFields.js +7 -0
- package/dist/transform/read/traverseFields.js.map +1 -1
- package/dist/types.d.ts +124 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utilities/createSchemaGenerator.d.ts +11 -0
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -0
- package/dist/utilities/createSchemaGenerator.js +216 -0
- package/dist/utilities/createSchemaGenerator.js.map +1 -0
- package/dist/utilities/executeSchemaHooks.js +1 -1
- package/dist/utilities/executeSchemaHooks.js.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts +3 -2
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.js +2 -2
- package/dist/utilities/validateExistingBlockIsIdentical.js.map +1 -1
- package/package.json +3 -3
- package/dist/postgres/createMigration.d.ts +0 -3
- package/dist/postgres/createMigration.d.ts.map +0 -1
- package/dist/postgres/createMigration.js +0 -91
- package/dist/postgres/createMigration.js.map +0 -1
- package/dist/postgres/getMigrationTemplate.d.ts +0 -4
- package/dist/postgres/getMigrationTemplate.d.ts.map +0 -1
- package/dist/postgres/getMigrationTemplate.js +0 -13
- package/dist/postgres/getMigrationTemplate.js.map +0 -1
- package/dist/postgres/schema/build.d.ts.map +0 -1
- package/dist/postgres/schema/build.js +0 -404
- package/dist/postgres/schema/build.js.map +0 -1
- package/dist/postgres/schema/createIndex.d.ts +0 -11
- package/dist/postgres/schema/createIndex.d.ts.map +0 -1
- package/dist/postgres/schema/createIndex.js +0 -20
- package/dist/postgres/schema/createIndex.js.map +0 -1
- package/dist/postgres/schema/idToUUID.d.ts.map +0 -1
- package/dist/postgres/schema/idToUUID.js.map +0 -1
- package/dist/postgres/schema/parentIDColumnMap.d.ts +0 -4
- package/dist/postgres/schema/parentIDColumnMap.d.ts.map +0 -1
- package/dist/postgres/schema/parentIDColumnMap.js +0 -9
- package/dist/postgres/schema/parentIDColumnMap.js.map +0 -1
- package/dist/postgres/schema/traverseFields.d.ts.map +0 -1
- package/dist/postgres/schema/traverseFields.js.map +0 -1
- package/dist/postgres/schema/withDefault.d.ts +0 -4
- package/dist/postgres/schema/withDefault.d.ts.map +0 -1
- package/dist/postgres/schema/withDefault.js.map +0 -1
- /package/dist/{postgres/schema → schema}/idToUUID.d.ts +0 -0
- /package/dist/{postgres/schema → schema}/idToUUID.js +0 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { exec } from 'child_process';
|
|
2
|
+
import { existsSync } from 'fs';
|
|
3
|
+
import { writeFile } from 'fs/promises';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { promisify } from 'util';
|
|
6
|
+
const execAsync = promisify(exec);
|
|
7
|
+
/**
|
|
8
|
+
* @example
|
|
9
|
+
* console.log(sanitizeObjectKey("oneTwo")); // oneTwo
|
|
10
|
+
* console.log(sanitizeObjectKey("one-two")); // 'one-two'
|
|
11
|
+
* console.log(sanitizeObjectKey("_one$Two3")); // _one$Two3
|
|
12
|
+
* console.log(sanitizeObjectKey("3invalid")); // '3invalid'
|
|
13
|
+
*/ const sanitizeObjectKey = (key)=>{
|
|
14
|
+
// Regular expression for a valid identifier
|
|
15
|
+
const identifierRegex = /^[a-z_$][\w$]*$/i;
|
|
16
|
+
if (identifierRegex.test(key)) {
|
|
17
|
+
return key;
|
|
18
|
+
}
|
|
19
|
+
return `'${key}'`;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* @example
|
|
23
|
+
* (columns default-valuesID) -> columns['default-valuesID']
|
|
24
|
+
* (columns defaultValues) -> columns.defaultValues
|
|
25
|
+
*/ const accessProperty = (objName, key)=>{
|
|
26
|
+
const sanitized = sanitizeObjectKey(key);
|
|
27
|
+
if (sanitized.startsWith("'")) {
|
|
28
|
+
return `${objName}[${sanitized}]`;
|
|
29
|
+
}
|
|
30
|
+
return `${objName}.${key}`;
|
|
31
|
+
};
|
|
32
|
+
export const createSchemaGenerator = ({ columnToCodeConverter, corePackageSuffix, defaultOutputFile, enumImport, schemaImport, tableImport })=>{
|
|
33
|
+
return async function generateSchema({ log = true, outputFile = defaultOutputFile, prettify = true } = {}) {
|
|
34
|
+
const importDeclarations = {};
|
|
35
|
+
const tableDeclarations = [];
|
|
36
|
+
const enumDeclarations = [];
|
|
37
|
+
const relationsDeclarations = [];
|
|
38
|
+
const addImport = (from, name)=>{
|
|
39
|
+
if (!importDeclarations[from]) {
|
|
40
|
+
importDeclarations[from] = new Set();
|
|
41
|
+
}
|
|
42
|
+
importDeclarations[from].add(name);
|
|
43
|
+
};
|
|
44
|
+
const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`;
|
|
45
|
+
let schemaDeclaration = null;
|
|
46
|
+
if (this.schemaName) {
|
|
47
|
+
addImport(corePackage, schemaImport);
|
|
48
|
+
schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`;
|
|
49
|
+
}
|
|
50
|
+
const enumFn = this.schemaName ? `db_schema.enum` : enumImport;
|
|
51
|
+
const enumsList = [];
|
|
52
|
+
const addEnum = (name, options)=>{
|
|
53
|
+
if (enumsList.some((each)=>each === name)) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
enumsList.push(name);
|
|
57
|
+
enumDeclarations.push(`export const ${name} = ${enumFn}('${name}', [${options.map((option)=>`'${option}'`).join(', ')}])`);
|
|
58
|
+
};
|
|
59
|
+
if (this.payload.config.localization && enumImport) {
|
|
60
|
+
addEnum('enum__locales', this.payload.config.localization.localeCodes);
|
|
61
|
+
}
|
|
62
|
+
const tableFn = this.schemaName ? `db_schema.table` : tableImport;
|
|
63
|
+
if (!this.schemaName) {
|
|
64
|
+
addImport(corePackage, tableImport);
|
|
65
|
+
}
|
|
66
|
+
addImport(corePackage, 'index');
|
|
67
|
+
addImport(corePackage, 'uniqueIndex');
|
|
68
|
+
addImport(corePackage, 'foreignKey');
|
|
69
|
+
addImport(`${this.packageName}/drizzle`, 'sql');
|
|
70
|
+
addImport(`${this.packageName}/drizzle`, 'relations');
|
|
71
|
+
for(const tableName in this.rawTables){
|
|
72
|
+
const table = this.rawTables[tableName];
|
|
73
|
+
const extrasDeclarations = [];
|
|
74
|
+
if (table.indexes) {
|
|
75
|
+
for(const key in table.indexes){
|
|
76
|
+
const index = table.indexes[key];
|
|
77
|
+
let indexDeclaration = `${sanitizeObjectKey(key)}: ${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`;
|
|
78
|
+
indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on)=>`${accessProperty('columns', on)}`).join(', ')}`}),`;
|
|
79
|
+
extrasDeclarations.push(indexDeclaration);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (table.foreignKeys) {
|
|
83
|
+
for(const key in table.foreignKeys){
|
|
84
|
+
const foreignKey = table.foreignKeys[key];
|
|
85
|
+
let foreignKeyDeclaration = `${sanitizeObjectKey(key)}: foreignKey({
|
|
86
|
+
columns: [${foreignKey.columns.map((col)=>`columns['${col}']`).join(', ')}],
|
|
87
|
+
foreignColumns: [${foreignKey.foreignColumns.map((col)=>`${accessProperty(col.table, col.name)}`).join(', ')}],
|
|
88
|
+
name: '${foreignKey.name}'
|
|
89
|
+
})`;
|
|
90
|
+
if (foreignKey.onDelete) {
|
|
91
|
+
foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`;
|
|
92
|
+
}
|
|
93
|
+
if (foreignKey.onUpdate) {
|
|
94
|
+
foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`;
|
|
95
|
+
}
|
|
96
|
+
foreignKeyDeclaration += ',';
|
|
97
|
+
extrasDeclarations.push(foreignKeyDeclaration);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const tableCode = `
|
|
101
|
+
export const ${tableName} = ${tableFn}('${tableName}', {
|
|
102
|
+
${Object.entries(table.columns).map(([key, column])=>` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({
|
|
103
|
+
adapter: this,
|
|
104
|
+
addEnum,
|
|
105
|
+
addImport,
|
|
106
|
+
column,
|
|
107
|
+
locales: this.payload.config.localization ? this.payload.config.localization.localeCodes : undefined
|
|
108
|
+
})},`).join('\n')}
|
|
109
|
+
}${extrasDeclarations.length ? `, (columns) => ({
|
|
110
|
+
${extrasDeclarations.join('\n ')}
|
|
111
|
+
})` : ''}
|
|
112
|
+
)
|
|
113
|
+
`;
|
|
114
|
+
tableDeclarations.push(tableCode);
|
|
115
|
+
}
|
|
116
|
+
for(const tableName in this.rawRelations){
|
|
117
|
+
const relations = this.rawRelations[tableName];
|
|
118
|
+
const properties = [];
|
|
119
|
+
for(const key in relations){
|
|
120
|
+
const relation = relations[key];
|
|
121
|
+
let declaration;
|
|
122
|
+
if (relation.type === 'one') {
|
|
123
|
+
declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {
|
|
124
|
+
${relation.fields.some((field)=>field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}
|
|
125
|
+
fields: [${relation.fields.map((field)=>`${accessProperty(field.table, field.name)}`).join(', ')}],
|
|
126
|
+
references: [${relation.references.map((col)=>`${accessProperty(relation.to, col)}`).join(', ')}],
|
|
127
|
+
${relation.relationName ? `relationName: '${relation.relationName}',` : ''}
|
|
128
|
+
}),`;
|
|
129
|
+
} else {
|
|
130
|
+
declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {
|
|
131
|
+
${relation.relationName ? `relationName: '${relation.relationName}',` : ''}
|
|
132
|
+
}),`;
|
|
133
|
+
}
|
|
134
|
+
properties.push(declaration);
|
|
135
|
+
}
|
|
136
|
+
// beautify / lintify relations callback output, when no many for example, don't add it
|
|
137
|
+
const args = [];
|
|
138
|
+
if (Object.values(relations).some((rel)=>rel.type === 'one')) {
|
|
139
|
+
args.push('one');
|
|
140
|
+
}
|
|
141
|
+
if (Object.values(relations).some((rel)=>rel.type === 'many')) {
|
|
142
|
+
args.push('many');
|
|
143
|
+
}
|
|
144
|
+
const arg = args.length ? `{ ${args.join(', ')} }` : '';
|
|
145
|
+
const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({
|
|
146
|
+
${properties.join('\n ')}
|
|
147
|
+
}))`;
|
|
148
|
+
relationsDeclarations.push(declaration);
|
|
149
|
+
}
|
|
150
|
+
if (enumDeclarations.length && !this.schemaName) {
|
|
151
|
+
addImport(corePackage, enumImport);
|
|
152
|
+
}
|
|
153
|
+
const importDeclarationsSanitized = [];
|
|
154
|
+
for(const moduleName in importDeclarations){
|
|
155
|
+
const moduleImports = importDeclarations[moduleName];
|
|
156
|
+
importDeclarationsSanitized.push(`import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`);
|
|
157
|
+
}
|
|
158
|
+
const schemaType = `
|
|
159
|
+
type DatabaseSchema = {
|
|
160
|
+
${[
|
|
161
|
+
this.schemaName ? 'db_schema' : null,
|
|
162
|
+
...enumsList,
|
|
163
|
+
...Object.keys(this.rawTables),
|
|
164
|
+
...Object.keys(this.rawRelations).map((table)=>`relations_${table}`)
|
|
165
|
+
].filter(Boolean).map((name)=>`${name}: typeof ${name}`).join('\n ')}
|
|
166
|
+
}
|
|
167
|
+
`;
|
|
168
|
+
const finalDeclaration = `
|
|
169
|
+
declare module '${this.packageName}/types' {
|
|
170
|
+
export interface GeneratedDatabaseSchema {
|
|
171
|
+
schema: DatabaseSchema
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
`;
|
|
175
|
+
const warning = `
|
|
176
|
+
/* tslint:disable */
|
|
177
|
+
/* eslint-disable */
|
|
178
|
+
/**
|
|
179
|
+
* This file was automatically generated by Payload.
|
|
180
|
+
* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,
|
|
181
|
+
* and re-run \`payload generate:db-schema\` to regenerate this file.
|
|
182
|
+
*/
|
|
183
|
+
`;
|
|
184
|
+
const code = [
|
|
185
|
+
warning,
|
|
186
|
+
...importDeclarationsSanitized,
|
|
187
|
+
schemaDeclaration,
|
|
188
|
+
...enumDeclarations,
|
|
189
|
+
...tableDeclarations,
|
|
190
|
+
...relationsDeclarations,
|
|
191
|
+
schemaType,
|
|
192
|
+
finalDeclaration
|
|
193
|
+
].filter(Boolean).join('\n');
|
|
194
|
+
if (!outputFile) {
|
|
195
|
+
const cwd = process.cwd();
|
|
196
|
+
const srcDir = path.resolve(cwd, 'src');
|
|
197
|
+
if (existsSync(srcDir)) {
|
|
198
|
+
outputFile = path.resolve(srcDir, 'payload-generated-schema.ts');
|
|
199
|
+
} else {
|
|
200
|
+
outputFile = path.resolve(cwd, 'payload-generated-schema.ts');
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
await writeFile(outputFile, code, 'utf-8');
|
|
204
|
+
if (prettify) {
|
|
205
|
+
try {
|
|
206
|
+
await execAsync(`npx prettier ${outputFile} --write`);
|
|
207
|
+
// eslint-disable-next-line no-empty
|
|
208
|
+
} catch {}
|
|
209
|
+
}
|
|
210
|
+
if (log) {
|
|
211
|
+
this.payload.logger.info(`Written ${outputFile}`);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
//# sourceMappingURL=createSchemaGenerator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { exec } from 'child_process'\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\nimport { promisify } from 'util'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\nconst execAsync = promisify(exec)\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 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 = `${sanitizeObjectKey(key)}: ${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 = `${sanitizeObjectKey(key)}: 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 column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => ({\n ${extrasDeclarations.join('\\n ')} \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}/types' {\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 code = [\n warning,\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 await writeFile(outputFile, code, 'utf-8')\n\n if (prettify) {\n try {\n await execAsync(`npx prettier ${outputFile} --write`)\n // eslint-disable-next-line no-empty\n } catch {}\n }\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n }\n}\n"],"names":["exec","existsSync","writeFile","path","promisify","execAsync","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","tableName","rawTables","table","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","columns","col","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","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","code","cwd","process","srcDir","resolve","logger","info"],"mappings":"AAEA,SAASA,IAAI,QAAQ,gBAAe;AACpC,SAASC,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AACvB,SAASC,SAAS,QAAQ,OAAM;AAIhC,MAAMC,YAAYD,UAAUJ;AAE5B;;;;;;CAMC,GACD,MAAMM,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,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ,KAAK;AAC5B;AAEA,OAAO,MAAMO,wBAAwB,CAAC,EACpCC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,WAAW,EAQZ;IACC,OAAO,eAAeC,eAEpB,EAAEC,MAAM,IAAI,EAAEC,aAAaN,iBAAiB,EAAEO,WAAW,IAAI,EAAE,GAAG,CAAC,CAAC;QAEpE,MAAMC,qBAAkD,CAAC;QAEzD,MAAMC,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,YAAY;YACf,MAAMiF,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASvG,KAAKwG,OAAO,CAACH,KAAK;YAEjC,IAAIvG,WAAWyG,SAAS;gBACtBnF,aAAapB,KAAKwG,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLnF,aAAapB,KAAKwG,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,MAAMtG,UAAUqB,YAAYgF,MAAM;QAElC,IAAI/E,UAAU;YACZ,IAAI;gBACF,MAAMnB,UAAU,CAAC,aAAa,EAAEkB,WAAW,QAAQ,CAAC;YACpD,oCAAoC;YACtC,EAAE,OAAM,CAAC;QACX;QAEA,IAAID,KAAK;YACP,IAAI,CAAC0B,OAAO,CAAC4D,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAEtF,YAAY;QAClD;IACF;AACF,EAAC"}
|
|
@@ -2,7 +2,7 @@ import { extendDrizzleTable } from './extendDrizzleTable.js';
|
|
|
2
2
|
export const executeSchemaHooks = async ({ type, adapter })=>{
|
|
3
3
|
for (const hook of adapter[type]){
|
|
4
4
|
const result = await hook({
|
|
5
|
-
adapter,
|
|
5
|
+
adapter: adapter,
|
|
6
6
|
extendTable: extendDrizzleTable,
|
|
7
7
|
schema: {
|
|
8
8
|
enums: adapter.enums,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of adapter[type]) {\n const result = await hook({\n adapter,\n extendTable: extendDrizzleTable,\n schema: {\n enums: adapter.enums,\n relations: adapter.relations,\n tables: adapter.tables,\n },\n })\n if (result.enums) {\n adapter.enums = result.enums\n }\n\n adapter.tables = result.tables\n adapter.relations = result.relations\n }\n}\n"],"names":["extendDrizzleTable","executeSchemaHooks","type","adapter","hook","result","extendTable","schema","enums","relations","tables"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,0BAAyB;AA0B5D,OAAO,MAAMC,qBAAqB,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAQ;IAC9D,KAAK,MAAMC,
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of (adapter as unknown as Adapter)[type]) {\n const result = await hook({\n adapter: adapter as unknown as Adapter,\n extendTable: extendDrizzleTable,\n schema: {\n enums: adapter.enums,\n relations: adapter.relations,\n tables: adapter.tables,\n },\n })\n if (result.enums) {\n adapter.enums = result.enums\n }\n\n adapter.tables = result.tables\n adapter.relations = result.relations\n }\n}\n"],"names":["extendDrizzleTable","executeSchemaHooks","type","adapter","hook","result","extendTable","schema","enums","relations","tables"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,0BAAyB;AA0B5D,OAAO,MAAMC,qBAAqB,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAQ;IAC9D,KAAK,MAAMC,QAAQ,AAACD,OAA8B,CAACD,KAAK,CAAE;QACxD,MAAMG,SAAS,MAAMD,KAAK;YACxBD,SAASA;YACTG,aAAaN;YACbO,QAAQ;gBACNC,OAAOL,QAAQK,KAAK;gBACpBC,WAAWN,QAAQM,SAAS;gBAC5BC,QAAQP,QAAQO,MAAM;YACxB;QACF;QACA,IAAIL,OAAOG,KAAK,EAAE;YAChBL,QAAQK,KAAK,GAAGH,OAAOG,KAAK;QAC9B;QAEAL,QAAQO,MAAM,GAAGL,OAAOK,MAAM;QAC9BP,QAAQM,SAAS,GAAGJ,OAAOI,SAAS;IACtC;AACF,EAAC"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { Block } from 'payload';
|
|
2
|
+
import type { RawTable } from '../types.js';
|
|
2
3
|
type Args = {
|
|
3
4
|
block: Block;
|
|
4
5
|
localized: boolean;
|
|
5
6
|
rootTableName: string;
|
|
6
|
-
table:
|
|
7
|
-
tableLocales?:
|
|
7
|
+
table: RawTable;
|
|
8
|
+
tableLocales?: RawTable;
|
|
8
9
|
};
|
|
9
10
|
export declare const validateExistingBlockIsIdentical: ({ block, localized, rootTableName, table, tableLocales, }: Args) => void;
|
|
10
11
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateExistingBlockIsIdentical.d.ts","sourceRoot":"","sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAS,MAAM,SAAS,CAAA;AAK3C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,OAAO,CAAA;IAClB,aAAa,EAAE,MAAM,CAAA;IACrB,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"validateExistingBlockIsIdentical.d.ts","sourceRoot":"","sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAS,MAAM,SAAS,CAAA;AAK3C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,OAAO,CAAA;IAClB,aAAa,EAAE,MAAM,CAAA;IACrB,KAAK,EAAE,QAAQ,CAAA;IACf,YAAY,CAAC,EAAE,QAAQ,CAAA;CACxB,CAAA;AAkDD,eAAO,MAAM,gCAAgC,8DAM1C,IAAI,KAAG,IA+BT,CAAA"}
|
|
@@ -52,7 +52,7 @@ export const validateExistingBlockIsIdentical = ({ block, localized, rootTableNa
|
|
|
52
52
|
const missingField = // ensure every field from the config is in the matching table
|
|
53
53
|
fieldNames.find(({ name, localized })=>{
|
|
54
54
|
const fieldTable = localized && tableLocales ? tableLocales : table;
|
|
55
|
-
return Object.keys(fieldTable).indexOf(name) === -1;
|
|
55
|
+
return Object.keys(fieldTable.columns).indexOf(name) === -1;
|
|
56
56
|
}) || // ensure every table column is matched for every field from the config
|
|
57
57
|
Object.keys(table).find((fieldName)=>{
|
|
58
58
|
if (![
|
|
@@ -68,7 +68,7 @@ export const validateExistingBlockIsIdentical = ({ block, localized, rootTableNa
|
|
|
68
68
|
if (missingField) {
|
|
69
69
|
throw new InvalidConfiguration(`The table ${rootTableName} has multiple blocks with slug ${block.slug}, but the schemas do not match. One block includes the field ${typeof missingField === 'string' ? missingField : missingField.name}, while the other block does not.`);
|
|
70
70
|
}
|
|
71
|
-
if (Boolean(localized) !== Boolean(table._locale)) {
|
|
71
|
+
if (Boolean(localized) !== Boolean(table.columns._locale)) {
|
|
72
72
|
throw new InvalidConfiguration(`The table ${rootTableName} has multiple blocks with slug ${block.slug}, but the schemas do not match. One is localized, but another is not. Block schemas of the same name must match exactly.`);
|
|
73
73
|
}
|
|
74
74
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"sourcesContent":["import type { Block, Field } from 'payload'\n\nimport { InvalidConfiguration } from 'payload'\nimport { fieldAffectsData, fieldHasSubFields, tabHasName } from 'payload/shared'\n\ntype Args = {\n block: Block\n localized: boolean\n rootTableName: string\n table:
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"sourcesContent":["import type { Block, Field } from 'payload'\n\nimport { InvalidConfiguration } from 'payload'\nimport { fieldAffectsData, fieldHasSubFields, tabHasName } from 'payload/shared'\n\nimport type { RawTable } from '../types.js'\n\ntype Args = {\n block: Block\n localized: boolean\n rootTableName: string\n table: RawTable\n tableLocales?: RawTable\n}\n\nconst getFlattenedFieldNames = (\n fields: Field[],\n prefix: string = '',\n): { localized?: boolean; name: string }[] => {\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 [...fieldsToUse, ...getFlattenedFieldNames(field.fields, fieldPrefix)]\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(tab.fields, fieldPrefix)),\n ]\n }, []),\n ]\n }\n\n if (fieldAffectsData(field)) {\n return [\n ...fieldsToUse,\n {\n name: `${fieldPrefix}${field.name}`,\n localized: field.localized,\n },\n ]\n }\n\n return fieldsToUse\n }, [])\n}\n\nexport const validateExistingBlockIsIdentical = ({\n block,\n localized,\n rootTableName,\n table,\n tableLocales,\n}: Args): void => {\n const fieldNames = getFlattenedFieldNames(block.fields)\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 throw new InvalidConfiguration(\n `The table ${rootTableName} has multiple blocks with slug ${\n block.slug\n }, but the schemas do not match. One block includes the field ${\n typeof missingField === 'string' ? missingField : missingField.name\n }, while the other block does not.`,\n )\n }\n\n if (Boolean(localized) !== Boolean(table.columns._locale)) {\n throw new InvalidConfiguration(\n `The table ${rootTableName} has multiple blocks with slug ${block.slug}, but the schemas do not match. One is localized, but another is not. Block schemas of the same name must match exactly.`,\n )\n }\n}\n"],"names":["InvalidConfiguration","fieldAffectsData","fieldHasSubFields","tabHasName","getFlattenedFieldNames","fields","prefix","reduce","fieldsToUse","field","fieldPrefix","includes","type","hasMany","name","tabs","tabFields","tab","localized","validateExistingBlockIsIdentical","block","rootTableName","table","tableLocales","fieldNames","missingField","find","fieldTable","Object","keys","columns","indexOf","fieldName","findIndex","slug","Boolean","_locale"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,UAAS;AAC9C,SAASC,gBAAgB,EAAEC,iBAAiB,EAAEC,UAAU,QAAQ,iBAAgB;AAYhF,MAAMC,yBAAyB,CAC7BC,QACAC,SAAiB,EAAE;IAEnB,OAAOD,OAAOE,MAAM,CAAC,CAACC,aAAaC;QACjC,IAAIC,cAAcJ;QAElB,IACE;YAAC;YA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AAuE;IACvEc,OAAOC,IAAI,CAACP,OAAOI,IAAI,CAAC,CAACM;QACvB,IAAI,CAAC;YAAC;YAAW;YAAU;YAAa;YAAS;SAAQ,CAACrB,QAAQ,CAACqB,YAAY;YAC7E,OAAOR,WAAWS,SAAS,CAAC,CAACxB,QAAUA,MAAMK,IAAI,MAAM,CAAC;QAC1D;IACF;IAEF,IAAIW,cAAc;QAChB,MAAM,IAAIzB,qBACR,CAAC,UAAU,EAAEqB,cAAc,+BAA+B,EACxDD,MAAMc,IAAI,CACX,6DAA6D,EAC5D,OAAOT,iBAAiB,WAAWA,eAAeA,aAAaX,IAAI,CACpE,iCAAiC,CAAC;IAEvC;IAEA,IAAIqB,QAAQjB,eAAeiB,QAAQb,MAAMQ,OAAO,CAACM,OAAO,GAAG;QACzD,MAAM,IAAIpC,qBACR,CAAC,UAAU,EAAEqB,cAAc,+BAA+B,EAAED,MAAMc,IAAI,CAAC,wHAAwH,CAAC;IAEpM;AACF,EAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/drizzle",
|
|
3
|
-
"version": "3.7.
|
|
3
|
+
"version": "3.7.1-canary.2ce70a3",
|
|
4
4
|
"description": "A library of shared functions used by different payload database adapters",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"repository": {
|
|
@@ -53,10 +53,10 @@
|
|
|
53
53
|
"@types/pg": "8.10.2",
|
|
54
54
|
"@types/to-snake-case": "1.0.0",
|
|
55
55
|
"@payloadcms/eslint-config": "3.0.0",
|
|
56
|
-
"payload": "3.7.
|
|
56
|
+
"payload": "3.7.1-canary.2ce70a3"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
|
-
"payload": "3.7.
|
|
59
|
+
"payload": "3.7.1-canary.2ce70a3"
|
|
60
60
|
},
|
|
61
61
|
"scripts": {
|
|
62
62
|
"build": "pnpm build:swc && pnpm build:types",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../../src/postgres/createMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAc9C,eAAO,MAAM,eAAe,EAAE,eA2G7B,CAAA"}
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import { createRequire } from 'module';
|
|
3
|
-
import { getPredefinedMigration, writeMigrationIndex } from 'payload';
|
|
4
|
-
import prompts from 'prompts';
|
|
5
|
-
import { defaultDrizzleSnapshot } from './defaultSnapshot.js';
|
|
6
|
-
import { getMigrationTemplate } from './getMigrationTemplate.js';
|
|
7
|
-
const require = createRequire(import.meta.url);
|
|
8
|
-
export const createMigration = async function createMigration({ dirname, file, forceAcceptWarning, migrationName, payload, skipEmpty }) {
|
|
9
|
-
const dir = payload.db.migrationDir;
|
|
10
|
-
if (!fs.existsSync(dir)) {
|
|
11
|
-
fs.mkdirSync(dir);
|
|
12
|
-
}
|
|
13
|
-
const { generateDrizzleJson, generateMigration, upPgSnapshot } = require('drizzle-kit/api');
|
|
14
|
-
const drizzleJsonAfter = generateDrizzleJson(this.schema);
|
|
15
|
-
const [yyymmdd, hhmmss] = new Date().toISOString().split('T');
|
|
16
|
-
const formattedDate = yyymmdd.replace(/\D/g, '');
|
|
17
|
-
const formattedTime = hhmmss.split('.')[0].replace(/\D/g, '');
|
|
18
|
-
let imports = '';
|
|
19
|
-
let downSQL;
|
|
20
|
-
let upSQL;
|
|
21
|
-
({ downSQL, imports, upSQL } = await getPredefinedMigration({
|
|
22
|
-
dirname,
|
|
23
|
-
file,
|
|
24
|
-
migrationName,
|
|
25
|
-
payload
|
|
26
|
-
}));
|
|
27
|
-
const timestamp = `${formattedDate}_${formattedTime}`;
|
|
28
|
-
const name = migrationName || file?.split('/').slice(2).join('/');
|
|
29
|
-
const fileName = `${timestamp}${name ? `_${name.replace(/\W/g, '_')}` : ''}`;
|
|
30
|
-
const filePath = `${dir}/${fileName}`;
|
|
31
|
-
let drizzleJsonBefore = defaultDrizzleSnapshot;
|
|
32
|
-
if (this.schemaName) {
|
|
33
|
-
drizzleJsonBefore.schemas = {
|
|
34
|
-
[this.schemaName]: this.schemaName
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
if (!upSQL) {
|
|
38
|
-
// Get latest migration snapshot
|
|
39
|
-
const latestSnapshot = fs.readdirSync(dir).filter((file)=>file.endsWith('.json')).sort().reverse()?.[0];
|
|
40
|
-
if (latestSnapshot) {
|
|
41
|
-
drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'));
|
|
42
|
-
if (drizzleJsonBefore.version < drizzleJsonAfter.version) {
|
|
43
|
-
drizzleJsonBefore = upPgSnapshot(drizzleJsonBefore);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter);
|
|
47
|
-
const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore);
|
|
48
|
-
const sqlExecute = 'await payload.db.drizzle.execute(sql`';
|
|
49
|
-
if (sqlStatementsUp?.length) {
|
|
50
|
-
upSQL = `${sqlExecute}\n ${sqlStatementsUp?.join('\n')}\`)`;
|
|
51
|
-
}
|
|
52
|
-
if (sqlStatementsDown?.length) {
|
|
53
|
-
downSQL = `${sqlExecute}\n ${sqlStatementsDown?.join('\n')}\`)`;
|
|
54
|
-
}
|
|
55
|
-
if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {
|
|
56
|
-
if (skipEmpty) {
|
|
57
|
-
process.exit(0);
|
|
58
|
-
}
|
|
59
|
-
const { confirm: shouldCreateBlankMigration } = await prompts({
|
|
60
|
-
name: 'confirm',
|
|
61
|
-
type: 'confirm',
|
|
62
|
-
initial: false,
|
|
63
|
-
message: 'No schema changes detected. Would you like to create a blank migration file?'
|
|
64
|
-
}, {
|
|
65
|
-
onCancel: ()=>{
|
|
66
|
-
process.exit(0);
|
|
67
|
-
}
|
|
68
|
-
});
|
|
69
|
-
if (!shouldCreateBlankMigration) {
|
|
70
|
-
process.exit(0);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
// write schema
|
|
74
|
-
fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2));
|
|
75
|
-
}
|
|
76
|
-
// write migration
|
|
77
|
-
fs.writeFileSync(`${filePath}.ts`, getMigrationTemplate({
|
|
78
|
-
downSQL: downSQL || ` // Migration code`,
|
|
79
|
-
imports,
|
|
80
|
-
packageName: payload.db.packageName,
|
|
81
|
-
upSQL: upSQL || ` // Migration code`
|
|
82
|
-
}));
|
|
83
|
-
writeMigrationIndex({
|
|
84
|
-
migrationsDir: payload.db.migrationDir
|
|
85
|
-
});
|
|
86
|
-
payload.logger.info({
|
|
87
|
-
msg: `Migration created at ${filePath}.ts`
|
|
88
|
-
});
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
//# sourceMappingURL=createMigration.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/postgres/createMigration.ts"],"sourcesContent":["import type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\n\nimport type { BasePostgresAdapter } from './types.js'\n\nimport { defaultDrizzleSnapshot } from './defaultSnapshot.js'\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nconst require = createRequire(import.meta.url)\n\nexport const createMigration: CreateMigration = async function createMigration(\n this: BasePostgresAdapter,\n { dirname, file, forceAcceptWarning, migrationName, payload, skipEmpty },\n) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const { generateDrizzleJson, generateMigration, upPgSnapshot } = require('drizzle-kit/api')\n const drizzleJsonAfter = generateDrizzleJson(this.schema)\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n ;({ downSQL, imports, upSQL } = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n }))\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n let drizzleJsonBefore = defaultDrizzleSnapshot\n\n if (this.schemaName) {\n drizzleJsonBefore.schemas = {\n [this.schemaName]: this.schemaName,\n }\n }\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'))\n\n if (drizzleJsonBefore.version < drizzleJsonAfter.version) {\n drizzleJsonBefore = upPgSnapshot(drizzleJsonBefore)\n }\n }\n\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n const sqlExecute = 'await payload.db.drizzle.execute(sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = `${sqlExecute}\\n ${sqlStatementsUp?.join('\\n')}\\`)`\n }\n if (sqlStatementsDown?.length) {\n downSQL = `${sqlExecute}\\n ${sqlStatementsDown?.join('\\n')}\\`)`\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n if (skipEmpty) {\n process.exit(0)\n }\n\n const { confirm: shouldCreateBlankMigration } = await prompts(\n {\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n },\n {\n onCancel: () => {\n process.exit(0)\n },\n },\n )\n\n if (!shouldCreateBlankMigration) {\n process.exit(0)\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n // write migration\n fs.writeFileSync(\n `${filePath}.ts`,\n getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n packageName: payload.db.packageName,\n upSQL: upSQL || ` // Migration code`,\n }),\n )\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${filePath}.ts` })\n}\n"],"names":["fs","createRequire","getPredefinedMigration","writeMigrationIndex","prompts","defaultDrizzleSnapshot","getMigrationTemplate","require","url","createMigration","dirname","file","forceAcceptWarning","migrationName","payload","skipEmpty","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","upPgSnapshot","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","timestamp","name","slice","join","fileName","filePath","drizzleJsonBefore","schemaName","schemas","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","version","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","process","exit","confirm","shouldCreateBlankMigration","type","initial","message","onCancel","writeFileSync","stringify","packageName","migrationsDir","logger","info","msg"],"mappings":"AAEA,OAAOA,QAAQ,KAAI;AACnB,SAASC,aAAa,QAAQ,SAAQ;AACtC,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,OAAOC,aAAa,UAAS;AAI7B,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,MAAMC,UAAUN,cAAc,YAAYO,GAAG;AAE7C,OAAO,MAAMC,kBAAmC,eAAeA,gBAE7D,EAAEC,OAAO,EAAEC,IAAI,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,OAAO,EAAEC,SAAS,EAAE;IAExE,MAAMC,MAAMF,QAAQ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AW;QACnClC,OAAOA,SAAS,CAAC,mBAAmB,CAAC;IACvC;IAGFjC,oBAAoB;QAAEoE,eAAezD,QAAQG,EAAE,CAACC,YAAY;IAAC;IAE7DJ,QAAQ0D,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAEhC,SAAS,GAAG,CAAC;IAAC;AACnE,EAAC"}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import type { MigrationTemplateArgs } from 'payload';
|
|
2
|
-
export declare const indent: (text: string) => string;
|
|
3
|
-
export declare const getMigrationTemplate: ({ downSQL, imports, packageName, upSQL, }: MigrationTemplateArgs) => string;
|
|
4
|
-
//# sourceMappingURL=getMigrationTemplate.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"getMigrationTemplate.d.ts","sourceRoot":"","sources":["../../src/postgres/getMigrationTemplate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAEpD,eAAO,MAAM,MAAM,SAAU,MAAM,WAIpB,CAAA;AAEf,eAAO,MAAM,oBAAoB,8CAK9B,qBAAqB,KAAG,MAS1B,CAAA"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export const indent = (text)=>text.split('\n').map((line)=>` ${line}`).join('\n');
|
|
2
|
-
export const getMigrationTemplate = ({ downSQL, imports, packageName, upSQL })=>`import { MigrateUpArgs, MigrateDownArgs, sql } from '${packageName}'
|
|
3
|
-
${imports ? `${imports}\n` : ''}
|
|
4
|
-
export async function up({ payload, req }: MigrateUpArgs): Promise<void> {
|
|
5
|
-
${indent(upSQL)}
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
export async function down({ payload, req }: MigrateDownArgs): Promise<void> {
|
|
9
|
-
${indent(downSQL)}
|
|
10
|
-
}
|
|
11
|
-
`;
|
|
12
|
-
|
|
13
|
-
//# sourceMappingURL=getMigrationTemplate.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/postgres/getMigrationTemplate.ts"],"sourcesContent":["import type { MigrationTemplateArgs } from 'payload'\n\nexport const indent = (text: string) =>\n text\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n')\n\nexport const getMigrationTemplate = ({\n downSQL,\n imports,\n packageName,\n upSQL,\n}: MigrationTemplateArgs): string => `import { MigrateUpArgs, MigrateDownArgs, sql } from '${packageName}'\n${imports ? `${imports}\\n` : ''}\nexport async function up({ payload, req }: MigrateUpArgs): Promise<void> {\n${indent(upSQL)}\n}\n\nexport async function down({ payload, req }: MigrateDownArgs): Promise<void> {\n${indent(downSQL)}\n}\n`\n"],"names":["indent","text","split","map","line","join","getMigrationTemplate","downSQL","imports","packageName","upSQL"],"mappings":"AAEA,OAAO,MAAMA,SAAS,CAACC,OACrBA,KACGC,KAAK,CAAC,MACNC,GAAG,CAAC,CAACC,OAAS,CAAC,EAAE,EAAEA,MAAM,EACzBC,IAAI,CAAC,MAAK;AAEf,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,OAAO,EACPC,OAAO,EACPC,WAAW,EACXC,KAAK,EACiB,GAAa,CAAC,qDAAqD,EAAED,YAAY;AACzG,EAAED,UAAU,GAAGA,QAAQ,EAAE,CAAC,GAAG,GAAG;;AAEhC,EAAER,OAAOU,OAAO;;;;AAIhB,EAAEV,OAAOO,SAAS;;AAElB,CAAC,CAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../src/postgres/schema/build.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGV,eAAe,EAEhB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAe7C,OAAO,KAAK,EACV,eAAe,EACf,mBAAmB,EAInB,WAAW,EACZ,MAAM,aAAa,CAAA;AASpB,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,mBAAmB,CAAA;IA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