template-saas-database-v2/scripts/drop-and-recreate.sh
rckrdmrd 3ce06fbce4 Initial commit - Database de template-saas migrado desde monorepo
Migración desde workspace-v2/projects/template-saas/apps/database
Este repositorio es parte del estándar multi-repo v2

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 08:07:11 -06:00

71 lines
2.2 KiB
Bash
Executable File

#!/bin/bash
# ============================================
# TEMPLATE-SAAS: Drop and Recreate Database
# Version: 1.0.0
# ============================================
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Default values
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_NAME="${DB_NAME:-template_saas_dev}"
DB_USER="${DB_USER:-template_saas_user}"
DB_PASSWORD="${DB_PASSWORD:-template_saas_dev_2026}"
DB_ADMIN_USER="${DB_ADMIN_USER:-postgres}"
DB_ADMIN_PASSWORD="${DB_ADMIN_PASSWORD:-postgres}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE} TEMPLATE-SAAS Drop & Recreate Database${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""
echo -e "Database: ${YELLOW}$DB_NAME${NC}"
echo ""
# Confirm
if [ "$FORCE" != "1" ]; then
echo -e "${RED}WARNING: This will DROP the database $DB_NAME and all its data!${NC}"
read -p "Are you sure you want to continue? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Aborted."
exit 1
fi
fi
# Drop database
echo -e "${BLUE}[1/2] Dropping database...${NC}"
# Terminate connections
PGPASSWORD="$DB_ADMIN_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_ADMIN_USER" -d postgres -c "
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = '$DB_NAME'
AND pid <> pg_backend_pid();
" 2>/dev/null || true
# Drop database if exists
DB_EXISTS=$(PGPASSWORD="$DB_ADMIN_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_ADMIN_USER" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'")
if [ "$DB_EXISTS" = "1" ]; then
PGPASSWORD="$DB_ADMIN_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_ADMIN_USER" -d postgres -c "DROP DATABASE $DB_NAME;"
echo -e "${GREEN}✓ Database $DB_NAME dropped${NC}"
else
echo -e "${YELLOW}→ Database $DB_NAME does not exist${NC}"
fi
# Recreate database
echo -e "${BLUE}[2/2] Creating database...${NC}"
"$SCRIPT_DIR/create-database.sh"
echo ""
echo -e "${GREEN}Database recreated successfully!${NC}"