package database import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" "git.gobha.me/xcaliber/chat-switchboard/config" ) // DB is the application-wide database connection pool. var DB *sql.DB // Connect opens a connection pool to PostgreSQL using the // DATABASE_URL from config. It pings to verify connectivity. func Connect(cfg *config.Config) error { if cfg.DatabaseURL == "" { log.Println("⚠ DATABASE_URL not set — running without database") return nil } var err error DB, err = sql.Open("postgres", cfg.DatabaseURL) if err != nil { return fmt.Errorf("database open: %w", err) } // Connection pool tuning DB.SetMaxOpenConns(25) DB.SetMaxIdleConns(5) if err := DB.Ping(); err != nil { return fmt.Errorf("database ping: %w", err) } log.Println("✅ Database connected") return nil } // Close gracefully shuts down the connection pool. func Close() { if DB != nil { DB.Close() } } // IsConnected returns true if a database connection is available. func IsConnected() bool { if DB == nil { return false } return DB.Ping() == nil }