55 lines
1.6 KiB
Go
55 lines
1.6 KiB
Go
package config
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/uptrace/bun"
|
|
"github.com/uptrace/bun/dialect/pgdialect"
|
|
"github.com/uptrace/bun/dialect/sqlitedialect"
|
|
"github.com/uptrace/bun/driver/pgdriver"
|
|
"github.com/uptrace/bun/driver/sqliteshim"
|
|
)
|
|
|
|
func NewDB(db Database) (*bun.DB, error) {
|
|
db_type := db.Type
|
|
slog.Info("using database", "type", db_type)
|
|
|
|
switch db_type {
|
|
case "postgres":
|
|
dsn := fmt.Sprintf("postgres://%s:%s@%s:%d/%s", db.User, db.Password, db.Host, db.Port, db.Name)
|
|
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
|
|
db := bun.NewDB(sqldb, pgdialect.New())
|
|
return db, nil
|
|
case "sqlite":
|
|
sqldb, _ := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared")
|
|
db := bun.NewDB(sqldb, sqlitedialect.New())
|
|
return db, nil
|
|
default:
|
|
return nil, fmt.Errorf("unknown db.type=%s", db_type)
|
|
}
|
|
// Configure GORM with custom settings
|
|
// The logger helps with debugging SQL queries during development
|
|
// if err != nil {
|
|
// log.Fatal("Failed to connect to database:", err)
|
|
// }
|
|
|
|
// // Get the underlying SQL database connection for pool configuration
|
|
// sqlDB, err := db.DB()
|
|
// if err != nil {
|
|
// log.Fatal("Failed to get database instance:", err)
|
|
// }
|
|
|
|
// // Configure connection pool settings
|
|
// // MaxIdleConns: number of connections kept open when idle
|
|
// sqlDB.SetMaxIdleConns(10)
|
|
// // MaxOpenConns: maximum total connections to the database
|
|
// sqlDB.SetMaxOpenConns(100)
|
|
// // ConnMaxLifetime: how long a connection can be reused
|
|
// sqlDB.SetConnMaxLifetime(time.Hour)
|
|
|
|
// slog.Info("Database connected successfully")
|
|
|
|
}
|