Some checks failed
Build & Deploy / 🔍 Prepare (push) Successful in 20s
Build & Deploy / 🧪 QA (push) Failing after 34s
Build & Deploy / 🏗️ Build (push) Has started running
Build & Deploy / 🚀 Deploy (push) Has been cancelled
Build & Deploy / 🧪 Smoke Test (push) Has been cancelled
Build & Deploy / ⚡ Lighthouse (push) Has been cancelled
Build & Deploy / 🔔 Notify (push) Has been cancelled
121 lines
5.1 KiB
Plaintext
121 lines
5.1 KiB
Plaintext
import fs from 'fs';
|
|
import path from 'path';
|
|
import { getPredefinedMigration, writeMigrationIndex } from 'payload';
|
|
import prompts from 'prompts';
|
|
import { getMigrationTemplate } from './getMigrationTemplate.js';
|
|
export const buildCreateMigration = ({ executeMethod, filename, sanitizeStatements })=>{
|
|
const dirname = path.dirname(filename);
|
|
return async function createMigration({ file, forceAcceptWarning, migrationName, payload, skipEmpty }) {
|
|
const dir = payload.db.migrationDir;
|
|
if (!fs.existsSync(dir)) {
|
|
fs.mkdirSync(dir);
|
|
}
|
|
const { generateDrizzleJson, generateMigration, upSnapshot } = this.requireDrizzleKit();
|
|
const drizzleJsonAfter = await generateDrizzleJson(this.schema);
|
|
const [yyymmdd, hhmmss] = new Date().toISOString().split('T');
|
|
const formattedDate = yyymmdd.replace(/\D/g, '');
|
|
const formattedTime = hhmmss.split('.')[0].replace(/\D/g, '');
|
|
let imports = '';
|
|
let downSQL;
|
|
let upSQL;
|
|
const predefinedMigration = await getPredefinedMigration({
|
|
dirname,
|
|
file,
|
|
migrationName,
|
|
payload
|
|
});
|
|
imports = predefinedMigration.imports;
|
|
downSQL = predefinedMigration.downSQL;
|
|
upSQL = predefinedMigration.upSQL;
|
|
const timestamp = `${formattedDate}_${formattedTime}`;
|
|
const name = migrationName || file?.split('/').slice(2).join('/');
|
|
const fileName = `${timestamp}${name ? `_${name.replace(/\W/g, '_')}` : ''}`;
|
|
const filePath = `${dir}/${fileName}`;
|
|
if (typeof predefinedMigration.dynamic === 'function') {
|
|
const dynamicResult = await predefinedMigration.dynamic({
|
|
filePath,
|
|
payload
|
|
});
|
|
if (dynamicResult.upSQL) {
|
|
upSQL = dynamicResult.upSQL;
|
|
}
|
|
if (dynamicResult.downSQL) {
|
|
downSQL = dynamicResult.downSQL;
|
|
}
|
|
if (dynamicResult.imports) {
|
|
imports = dynamicResult.imports;
|
|
}
|
|
}
|
|
let drizzleJsonBefore = this.defaultDrizzleSnapshot;
|
|
if (this.schemaName) {
|
|
drizzleJsonBefore.schemas = {
|
|
[this.schemaName]: this.schemaName
|
|
};
|
|
}
|
|
if (!upSQL) {
|
|
// Get latest migration snapshot
|
|
const latestSnapshot = fs.readdirSync(dir).filter((file)=>file.endsWith('.json')).sort().reverse()?.[0];
|
|
if (latestSnapshot) {
|
|
drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'));
|
|
if (upSnapshot && drizzleJsonBefore.version < drizzleJsonAfter.version) {
|
|
drizzleJsonBefore = upSnapshot(drizzleJsonBefore);
|
|
}
|
|
}
|
|
payload.logger.info('Starting migration: generating UP statements...');
|
|
const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter);
|
|
payload.logger.info('Migration UP complete. Generating DOWN statements...');
|
|
const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore);
|
|
payload.logger.info('Migration DOWN statements generation complete.');
|
|
const sqlExecute = `await db.${executeMethod}(` + 'sql`';
|
|
if (sqlStatementsUp?.length) {
|
|
upSQL = sanitizeStatements({
|
|
sqlExecute,
|
|
statements: sqlStatementsUp
|
|
});
|
|
}
|
|
if (sqlStatementsDown?.length) {
|
|
downSQL = sanitizeStatements({
|
|
sqlExecute,
|
|
statements: sqlStatementsDown
|
|
});
|
|
}
|
|
if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {
|
|
if (skipEmpty) {
|
|
process.exit(0);
|
|
}
|
|
const { confirm: shouldCreateBlankMigration } = await prompts({
|
|
name: 'confirm',
|
|
type: 'confirm',
|
|
initial: false,
|
|
message: 'No schema changes detected. Would you like to create a blank migration file?'
|
|
}, {
|
|
onCancel: ()=>{
|
|
process.exit(0);
|
|
}
|
|
});
|
|
if (!shouldCreateBlankMigration) {
|
|
process.exit(0);
|
|
}
|
|
}
|
|
// write schema
|
|
fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2));
|
|
}
|
|
const data = getMigrationTemplate({
|
|
downSQL: downSQL || ` // Migration code`,
|
|
imports,
|
|
packageName: payload.db.packageName,
|
|
upSQL: upSQL || ` // Migration code`
|
|
});
|
|
const fullPath = `${filePath}.ts`;
|
|
// write migration
|
|
fs.writeFileSync(fullPath, data);
|
|
writeMigrationIndex({
|
|
migrationsDir: payload.db.migrationDir
|
|
});
|
|
payload.logger.info({
|
|
msg: `Migration created at ${fullPath}`
|
|
});
|
|
};
|
|
};
|
|
|
|
//# sourceMappingURL=buildCreateMigration.js.map |