ids.alfacom.it/database-schema/apply_migrations.sh
marco370 7b85fcc020 Implement a database versioning system to speed up updates
Add a database versioning system that tracks applied migrations and only runs new ones, significantly improving update speed.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: ab56b852-52de-4cd1-a489-5cf48f3a2965
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/449cf7c4-c97a-45ae-8234-e5c5b8d6a84f/7a657272-55ba-4a79-9a2e-f1ed9bc7a528/myJmPIa
2025-11-22 07:51:56 +00:00

148 lines
5.9 KiB
Bash
Executable File

#!/bin/bash
# =============================================================================
# IDS - Applica Migrazioni Database (con Version Tracking)
# =============================================================================
# Sistema intelligente di migrazioni:
# - Controlla versione corrente database
# - Applica SOLO migrazioni mancanti (più veloce!)
# - Aggiorna versione dopo ogni migrazione
# =============================================================================
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MIGRATIONS_DIR="$SCRIPT_DIR/migrations"
IDS_DIR="$(dirname "$SCRIPT_DIR")"
# Carica variabili ambiente ed esportale
if [ -f "$IDS_DIR/.env" ]; then
set -a
source "$IDS_DIR/.env"
set +a
fi
# Colori
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m'
echo -e "${BLUE}🗄️ Sistema Migrazioni Database (Versioned)${NC}"
# Verifica DATABASE_URL
if [ -z "$DATABASE_URL" ]; then
echo -e "${RED}❌ DATABASE_URL non impostato${NC}"
echo -e "${YELLOW} File .env non trovato o DATABASE_URL mancante${NC}"
exit 1
fi
# Crea directory migrations se non esiste
mkdir -p "$MIGRATIONS_DIR"
# =============================================================================
# STEP 1: Inizializza tracking versione (se necessario)
# =============================================================================
echo -e "${CYAN}📋 Verifica sistema versioning...${NC}"
# Esegue 000_init_schema_version.sql (idempotente)
INIT_MIGRATION="$MIGRATIONS_DIR/000_init_schema_version.sql"
if [ -f "$INIT_MIGRATION" ]; then
psql "$DATABASE_URL" -f "$INIT_MIGRATION" -q
echo -e "${GREEN}✅ Sistema versioning attivo${NC}"
else
echo -e "${YELLOW}⚠️ Migration 000_init_schema_version.sql non trovata${NC}"
echo -e "${YELLOW} Creazione tabella schema_version...${NC}"
psql "$DATABASE_URL" << 'EOF' -q
CREATE TABLE IF NOT EXISTS schema_version (
id INTEGER PRIMARY KEY DEFAULT 1,
version INTEGER NOT NULL DEFAULT 0,
applied_at TIMESTAMP NOT NULL DEFAULT NOW(),
description TEXT
);
INSERT INTO schema_version (id, version, description)
SELECT 1, 0, 'Initial schema version tracking'
WHERE NOT EXISTS (SELECT 1 FROM schema_version WHERE id = 1);
EOF
echo -e "${GREEN}✅ Tabella schema_version creata${NC}"
fi
# =============================================================================
# STEP 2: Leggi versione corrente database
# =============================================================================
CURRENT_VERSION=$(psql "$DATABASE_URL" -tAc "SELECT COALESCE(version, 0) FROM schema_version WHERE id = 1;" 2>/dev/null || echo "0")
echo -e "${CYAN}📊 Versione database corrente: ${YELLOW}${CURRENT_VERSION}${NC}"
# =============================================================================
# STEP 3: Trova migrazioni da applicare
# =============================================================================
# Formato migrazioni: 001_description.sql, 002_another.sql, etc.
MIGRATIONS_TO_APPLY=()
for migration_file in $(find "$MIGRATIONS_DIR" -name "[0-9][0-9][0-9]_*.sql" | sort); do
MIGRATION_NAME=$(basename "$migration_file")
# Estrai numero versione dal nome file (001, 002, etc.)
MIGRATION_VERSION=$(echo "$MIGRATION_NAME" | sed 's/^\([0-9]\{3\}\)_.*/\1/' | sed 's/^0*//')
# Se versione vuota (000), salta
if [ -z "$MIGRATION_VERSION" ]; then
continue
fi
# Se migrazione > versione corrente, aggiungila
if [ "$MIGRATION_VERSION" -gt "$CURRENT_VERSION" ]; then
MIGRATIONS_TO_APPLY+=("$migration_file:$MIGRATION_VERSION:$MIGRATION_NAME")
fi
done
# =============================================================================
# STEP 4: Applica migrazioni mancanti
# =============================================================================
if [ ${#MIGRATIONS_TO_APPLY[@]} -eq 0 ]; then
echo -e "${GREEN}✅ Database già aggiornato (nessuna migrazione da applicare)${NC}"
exit 0
fi
echo -e "${BLUE}📋 Trovate ${#MIGRATIONS_TO_APPLY[@]} migrazioni da applicare${NC}"
echo ""
for migration_info in "${MIGRATIONS_TO_APPLY[@]}"; do
IFS=':' read -r migration_file migration_version migration_name <<< "$migration_info"
echo -e "${BLUE}🔄 Applicando migrazione ${migration_version}: ${CYAN}${migration_name}${NC}"
# Applica migrazione
if psql "$DATABASE_URL" -f "$migration_file" -q 2>&1 | tee /tmp/migration_output.log | grep -qiE "error|fatal"; then
echo -e "${RED}❌ Errore in migrazione ${migration_version}${NC}"
cat /tmp/migration_output.log
exit 1
fi
# Aggiorna versione nel database
DESCRIPTION=$(head -n 5 "$migration_file" | grep -E "^--.*Migration" | sed 's/^--.*Migration [0-9]*: //' || echo "Migration $migration_version")
psql "$DATABASE_URL" -q << EOF
UPDATE schema_version
SET version = $migration_version,
applied_at = NOW(),
description = '$DESCRIPTION'
WHERE id = 1;
EOF
echo -e "${GREEN} ✅ Migrazione ${migration_version} applicata con successo${NC}"
echo ""
done
# =============================================================================
# STEP 5: Verifica versione finale
# =============================================================================
FINAL_VERSION=$(psql "$DATABASE_URL" -tAc "SELECT version FROM schema_version WHERE id = 1;")
echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ ✅ MIGRAZIONI COMPLETATE ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
echo -e "${CYAN}📊 Versione database: ${YELLOW}${CURRENT_VERSION}${CYAN}${GREEN}${FINAL_VERSION}${NC}"
echo ""