@magic-mustard/sqlsync
Version:
SQLSync simplifies database schema evolution by allowing a declarative approach to table management
115 lines (114 loc) • 5.26 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MigrationProcessor = void 0;
const lodash_1 = require("lodash");
const path = __importStar(require("path"));
const namespace_1 = require("./namespace");
const logger_1 = require("../utils/logger");
class MigrationProcessor extends namespace_1.Migration.AbstractProcessor {
constructor(fileIO, configRoot, newMigrationName) {
// Generate timestamp in YYYYMMDDHHMMSS format
const now = new Date();
const pad = (n) => n.toString().padStart(2, '0');
const timestamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
const migrationFilename = `${timestamp}_${newMigrationName}.sql`;
super(fileIO, configRoot, migrationFilename);
this.migrationTokens = [];
}
append(token) {
return __awaiter(this, void 0, void 0, function* () {
this.migrationTokens.push(token);
});
}
/**
* Returns the latest migration filename formatted with timestamp and user-provided name.
*/
getLatestMigrationName() {
return this.latestMigrationFileName;
}
/**
* Runs the migration process: creates migration file and writes all statements.
* @returns The filename of the created migration file
*/
run() {
return __awaiter(this, void 0, void 0, function* () {
if ((0, lodash_1.isEmpty)(this.migrationTokens)) {
logger_1.logger.warn('No differences detected. No migration generated.');
return '';
}
const migrationDir = path.join(this.configRoot, 'migrations');
const migrationPath = path.join(migrationDir, this.latestMigrationFileName);
if (yield this.fileIO.exists(migrationPath)) {
throw new Error(`Migration file already exists: ${migrationPath}`);
}
// Build file content with tab indentation
const fileContent = this.migrationTokens.map(token => `-- sqlsync: startStatement | file path: ${token.filePath} | checksum: ${token.checksum}\n`
+ `${token.token}\n`
+ `-- sqlsync: endStatement | file path: ${token.filePath}\n`).join('\n');
try {
yield this.fileIO.writeFile(migrationPath, fileContent.replace(/^/gm, '\t'));
}
catch (err) {
throw new Error(`Failed to write migration file: ${err}`);
}
return this.latestMigrationFileName;
});
}
/**
* Removes the migration file from disk, if it exists.
* @param filename - The migration file to remove (relative to migrations/)
*/
removeFile(filename) {
return __awaiter(this, void 0, void 0, function* () {
const migrationPath = path.join(this.configRoot, 'migrations', filename);
if (yield this.fileIO.exists(migrationPath)) {
if (this.fileIO.unlink) {
yield this.fileIO.unlink(migrationPath);
}
}
});
}
}
exports.MigrationProcessor = MigrationProcessor;