Files

58 lines
2.2 KiB
Go

package main
import (
"context"
"log/slog"
"os"
"time"
"git.amiirkhl.ir/starcoach-hackathon/zarinpal-analytics-backend/internal/config"
"git.amiirkhl.ir/starcoach-hackathon/zarinpal-analytics-backend/internal/database"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
cfg, err := config.Load()
if err != nil {
logger.Error("configuration failed", "error", err)
os.Exit(1)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pool, err := database.Open(ctx, cfg.DatabaseURL)
if err != nil {
logger.Error("database connection failed", "error", err)
os.Exit(1)
}
defer pool.Close()
if _, err := pool.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (version bigint PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT now())`); err != nil {
logger.Error("migration bootstrap failed", "error", err)
os.Exit(1)
}
migrations := []struct {
version int64
path string
}{{1, "migrations/000001_mvp.sql"}, {2, "migrations/000002_growth_analyst.sql"}, {3, "migrations/000003_ai_summary_refresh.sql"}, {4, "migrations/000004_ai_page_insights.sql"}, {5, "migrations/000005_growth_coach.sql"}, {6, "migrations/000006_growth_coach_completion_guard.sql"}, {7, "migrations/000007_growth_coach_manual_completion_provenance.sql"}, {8, "migrations/000008_section_refresh_monthly_goals.sql"}, {9, "migrations/000009_ranked_campaign_calendar.sql"}, {10, "migrations/000010_transaction_insight_period_scope.sql"}}
for _, item := range migrations {
var applied bool
if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)`, item.version).Scan(&applied); err != nil {
logger.Error("checking migration version failed", "version", item.version, "error", err)
os.Exit(1)
}
if applied {
continue
}
path := item.path
migration, err := os.ReadFile(path)
if err != nil {
logger.Error("reading migration failed", "path", path, "error", err)
os.Exit(1)
}
if err := database.Migrate(ctx, pool, string(migration)); err != nil {
logger.Error("migration failed", "path", path, "error", err)
os.Exit(1)
}
}
logger.Info("migration complete", "version", 10)
}