# ===============================
# PostgreSQL Maintenance Script
# ===============================

# .\dbmaintance.ps1 -psql 

param(
    [switch]$psql = "D:\Program Files\PostgreSQL\17\bin\psql.exe"
)

# Config
$env:PGPASSWORD = "obelix"   # Or better: use pgpass.conf instead
$dbUser = "postgres"
$dbName = "lst_db"
$dbHost = "localhost"
$dbPort = "5432"

# Path to psql (adjust if PostgreSQL is installed elsewhere)


# Show DB size before
& $psql -h $dbHost -p $dbPort -U $dbUser -d $dbName -c "SELECT pg_size_pretty(pg_database_size(current_database())) AS size_before;"

# Run safe maintenance
& $psql -h $dbHost -p $dbPort -U $dbUser -d $dbName -c "VACUUM (ANALYZE);"
& $psql -h $dbHost -p $dbPort -U $dbUser -d $dbName -c "REINDEX DATABASE $dbName;"

# Show DB size after
& $psql -h $dbHost -p $dbPort -U $dbUser -d $dbName -c "SELECT pg_size_pretty(pg_database_size(current_database())) AS size_after;"

# Optional: per-table size breakdown
& $psql -h $dbHost -p $dbPort -U $dbUser -d $dbName -c @"
SELECT 
    schemaname || '.' || relname AS table_name,
    pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
    pg_size_pretty(pg_relation_size(relid)) AS table_size,
    pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) AS index_size
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC;
"@
