@launchql/core
Version:
LaunchQL Package and Migration Tools
161 lines (160 loc) • 8.04 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;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.deployProject = void 0;
const env_1 = require("@launchql/env");
const logger_1 = require("@launchql/logger");
const types_1 = require("@launchql/types");
const path_1 = require("path");
const path = __importStar(require("path"));
const pg_cache_1 = require("pg-cache");
const launchql_1 = require("../core/class/launchql");
const client_1 = require("../migrate/client");
const package_1 = require("../packaging/package");
// Cache for fast deployment
const deployFastCache = {};
const getCacheKey = (pg, name, database) => {
const { host, port, user } = pg ?? {};
return `${host}:${port}:${user}:${database}:${name}`;
};
const log = new logger_1.Logger('deploy');
const deployProject = async (opts, name, database, pkg, toChange) => {
const mergedOpts = (0, env_1.getEnvOptions)(opts);
log.info(`🔍 Gathering modules from ${pkg.workspacePath}...`);
const modules = pkg.getModuleMap();
if (!modules[name]) {
log.error(`❌ Module "${name}" not found in modules list.`);
throw types_1.errors.MODULE_NOT_FOUND({ name });
}
const modulePath = path.resolve(pkg.workspacePath, modules[name].path);
const moduleProject = new launchql_1.LaunchQLPackage(modulePath);
log.info(`📦 Resolving dependencies for ${name}...`);
const extensions = moduleProject.getModuleExtensions();
const pgPool = (0, pg_cache_1.getPgPool)({ ...opts.pg, database });
log.success(`🚀 Starting deployment to database ${database}...`);
for (const extension of extensions.resolved) {
try {
if (extensions.external.includes(extension)) {
const msg = `CREATE EXTENSION IF NOT EXISTS "${extension}" CASCADE;`;
log.info(`📥 Installing external extension: ${extension}`);
log.debug(`> ${msg}`);
await pgPool.query(msg);
}
else {
const modulePath = (0, path_1.resolve)(pkg.workspacePath, modules[extension].path);
log.info(`📂 Deploying local module: ${extension}`);
log.debug(`→ Path: ${modulePath}`);
if (mergedOpts.deployment.fast) {
// Use fast deployment strategy
const localProject = new launchql_1.LaunchQLPackage(modulePath);
const cacheKey = getCacheKey(mergedOpts.pg, extension, database);
if (mergedOpts.deployment.cache && deployFastCache[cacheKey]) {
log.warn(`⚡ Using cached package for ${extension}.`);
await pgPool.query(deployFastCache[cacheKey].sql);
continue;
}
let modulePackage;
try {
modulePackage = await (0, package_1.packageModule)(localProject.modulePath, {
usePlan: mergedOpts.deployment.usePlan,
extension: false
});
}
catch (err) {
// Build comprehensive error message
const errorLines = [];
errorLines.push(`❌ Failed to package module "${extension}" at path: ${modulePath}`);
errorLines.push(` Module Path: ${modulePath}`);
errorLines.push(` Workspace Path: ${pkg.workspacePath}`);
errorLines.push(` Error Code: ${err.code || 'N/A'}`);
errorLines.push(` Error Message: ${err.message || 'Unknown error'}`);
// Provide debugging hints
if (err.code === 'ENOENT') {
errorLines.push('💡 Hint: File or directory not found. Check if the module path is correct.');
}
else if (err.code === 'EACCES') {
errorLines.push('💡 Hint: Permission denied. Check file permissions.');
}
else if (err.message && err.message.includes('launchql.plan')) {
errorLines.push('💡 Hint: launchql.plan file issue. Check if the plan file exists and is valid.');
}
// Log the consolidated error message
log.error(errorLines.join('\n'));
console.error(err); // Preserve full stack trace
throw types_1.errors.DEPLOYMENT_FAILED({
type: 'Deployment',
module: extension
});
}
log.debug(`→ Command: sqitch deploy db:pg:${database}`);
log.debug(`> ${modulePackage.sql}`);
await pgPool.query(modulePackage.sql);
if (mergedOpts.deployment.cache) {
deployFastCache[cacheKey] = modulePackage;
}
}
else {
// Use new migration system
log.debug(`→ Command: launchql migrate deploy db:pg:${database}`);
try {
const client = new client_1.LaunchQLMigrate(mergedOpts.pg);
const result = await client.deploy({
modulePath,
toChange,
useTransaction: mergedOpts.deployment.useTx,
logOnly: mergedOpts.deployment.logOnly
});
if (result.failed) {
throw types_1.errors.OPERATION_FAILED({ operation: 'Deployment', target: result.failed });
}
}
catch (deployError) {
log.error(`❌ Deployment failed for module ${extension}`);
console.error(deployError);
throw types_1.errors.DEPLOYMENT_FAILED({ type: 'Deployment', module: extension });
}
}
}
}
catch (err) {
log.error(`🛑 Error during deployment: ${err instanceof Error ? err.message : err}`);
console.error(err); // Keep raw error output for stack traces
throw types_1.errors.DEPLOYMENT_FAILED({ type: 'Deployment', module: extension });
}
}
log.success(`✅ Deployment complete for ${name}.`);
return extensions;
};
exports.deployProject = deployProject;
;