Files
pagodera/lib/db/migrations/run-migrations.ts
T
Evandro Fonseca Junior 55eebde0ba feat: add user authentication UI to header component
Add login and register dialogs, user dropdown menu with profile link and logout option, and integrate with session management hook. Prevent hydration mismatches by conditionally rendering auth elements after mount. Update package-lock.json with new @esbuild dependencies for build tooling.
2025-11-04 02:33:29 -03:00

114 lines
2.9 KiB
TypeScript

/**
* Script de execução de migrations
* Executa todas as migrations SQL em ordem
*/
// Carregar variáveis de ambiente
import { config } from "dotenv";
import { resolve } from "path";
// Tentar carregar .env.local primeiro, depois .env
config({ path: resolve(process.cwd(), ".env.local") });
config({ path: resolve(process.cwd(), ".env") });
import { readFileSync } from "fs";
import { join } from "path";
import { getPool, query, healthCheck } from "../index";
const MIGRATIONS_DIR = join(__dirname, ".");
// Lista de migrations em ordem
const MIGRATIONS = [
"001_users.sql",
"002_servers.sql",
"003_fix_servers_location.sql",
"004_listings.sql",
"005_bids.sql",
"006_transactions.sql",
"007_escrow_deposits.sql",
"008_disputes.sql",
"009_item_price_history.sql",
"010_notifications.sql",
"011_donations.sql",
];
async function runMigrations() {
console.log("🚀 Iniciando execução de migrations...\n");
// Verificar conexão com banco
console.log("🔍 Verificando conexão com PostgreSQL...");
const isHealthy = await healthCheck();
if (!isHealthy) {
console.error("❌ Falha na conexão com PostgreSQL. Verifique a variável PG_DB.");
process.exit(1);
}
console.log("✅ Conexão estabelecida com sucesso\n");
// Verificar tabela de controle de migrations (opcional)
try {
await query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(255) PRIMARY KEY,
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
} catch (error) {
console.error("❌ Erro ao criar tabela de controle:", error);
process.exit(1);
}
// Executar cada migration
for (const migrationFile of MIGRATIONS) {
const migrationPath = join(MIGRATIONS_DIR, migrationFile);
const version = migrationFile.replace(".sql", "");
try {
// Verificar se já foi executada
const checkResult = await query<{ version: string }>(
"SELECT version FROM schema_migrations WHERE version = $1",
[version]
);
if (checkResult.rows.length > 0) {
console.log(`⏭️ Migration ${version} já executada, pulando...`);
continue;
}
console.log(`📝 Executando migration: ${migrationFile}...`);
// Ler arquivo SQL
const sql = readFileSync(migrationPath, "utf-8");
// Executar migration
await query(sql);
// Registrar como executada
await query(
"INSERT INTO schema_migrations (version) VALUES ($1)",
[version]
);
console.log(`✅ Migration ${version} executada com sucesso\n`);
} catch (error) {
console.error(`❌ Erro ao executar migration ${version}:`, error);
process.exit(1);
}
}
console.log("🎉 Todas as migrations foram executadas com sucesso!");
// Fechar pool
const pool = getPool();
await pool.end();
process.exit(0);
}
// Executar
runMigrations().catch((error) => {
console.error("❌ Erro fatal:", error);
process.exit(1);
});