Files
2026-07-10 23:53:43 +02:00

40 lines
869 B
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"context"
"database/sql"
"log/slog"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
)
// OpenDB opens the MySQL pool and pings it with a timeout, mirroring the
// Corefile's pool limits. Must be called after the privilege drop.
func OpenDB(logger *slog.Logger, dsn string) *sql.DB {
db, err := sql.Open("mysql", dsn)
if err != nil {
logger.Error("failed to open mysql pool", "error", err)
os.Exit(1)
}
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(60 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
logger.Error("failed to reach mysql", "error", err)
os.Exit(1)
}
logger.Info("mysql pool ready")
return db
}