Filtros de version al reves

This commit is contained in:
2026-02-19 10:36:03 +01:00
parent 8571454835
commit f589132f37
2 changed files with 32 additions and 20 deletions

View File

@@ -1,5 +1,5 @@
{
"name": "migration_tool",
"name": "migration-tool",
"version": "1.0.0",
"description": "Herramienta de migracion de bdd",
"main": "src/index.ts",

View File

@@ -1,19 +1,14 @@
#!/usr/bin/node
import { constants } from 'buffer';
import { existsSync } from 'fs';
import fs from 'fs/promises';
import path from 'path';
import { Pool } from 'pg';
import { env } from 'process';
import { env, version } from 'process';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
const db = new Pool({
host: env.POSTGRES_HOST,
user: env.POSTGRES_USER,
port: Number(env.POSTGRES_PORT),
password: env.POSTGRES_PASSWORD
})
type MigrationFile = {
version: string;
@@ -111,10 +106,10 @@ function compareVersions(va: string, vb: string) {
return 0
}
async function getCurrentVersion() {
async function getCurrentVersion(db: Pool) {
try {
const lastVersion = await db.query<DBVersion>(`
SELECT * form db_versions
SELECT * FROM db_versions
ORDER BY creation_date DESC
LIMIT 1
`)
@@ -135,13 +130,33 @@ async function runMigrations(args: {
currentVersion?: string,
migrationDir: string
}) {
let db;
try {
db = new Pool({
host: env.POSTGRES_HOST,
user: env.POSTGRES_USER,
port: Number(env.POSTGRES_PORT),
password: env.POSTGRES_PASSWORD,
database: env.POSTGRES_DATABASE
})
} catch (e) {
console.error("[x] Error conectando a la base datos. Host: ", env.POSTGRES_HOST, " DB: ", env.POSTGRES_DATABASE)
console.error(e)
return;
}
const dbClient = await db.connect()
try {
// 1º La version explicita 2º La versión almacenada en BDD 3º 0.0.0 como version base
const currentVersion = args.currentVersion ?? (await getCurrentVersion())?.version ?? "0.0.0"
console.log("[i] Migrando desde la version " + currentVersion)
const versionBdd = (await getCurrentVersion(db))?.version
if (versionBdd == undefined) {
console.log("[x] Error buscando la ultima version de la base de datos")
}
const currentVersion = args.currentVersion ?? versionBdd ?? "0.0.0"
console.log("[i] Migrando desde la version " + currentVersion + " a la version " + args.targetVersion)
const files = await fs.readdir(args.migrationDir);
console.log("Directorio de migraciones", args.migrationDir)
console.log("Archivos de migraciones", files)
const pendingMigrations: MigrationFile[] = files
.map(f => (<MigrationFile>{
version: path.parse(f).name,
@@ -149,9 +164,9 @@ async function runMigrations(args: {
fullPath: path.join(args.migrationDir, f)
}))
// 1. Filtrar las migraciones > que la actual
.filter(v => compareVersions(v.version, currentVersion) == -1)
.filter(v => compareVersions(v.version, currentVersion) >= 0)
// 2. Filtra las migraciones <= que la objetivo
.filter(v => compareVersions(v.version, args.targetVersion) >= 0)
.filter(v => compareVersions(v.version, args.targetVersion) == -1)
.sort((a, b) => compareVersions(a.version, b.version));
if (pendingMigrations.length === 0) {
@@ -187,13 +202,10 @@ async function runMigrations(args: {
*/
}
// await db.query('COMMIT');
await db.query("COMMIT")
console.log(" Migraciones completadas con éxito.");
console.log("[o] Migraciones completadas con éxito.");
} catch (error) {
// Si algo falla, el rollback es vital en DevOps
// await db.query('ROLLBACK');
console.error("❌ Error durante la migración. Se ha realizado un rollback automático.");
console.error("[x] Error durante la migración. Se ha realizado un rollback automático.");
console.error(error);
await db.query("ROLLBACK")
process.exit(1);