Files
member-console/cmd/database.go
T

46 lines
1.3 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
package cmd
import (
"context"
"database/sql"
"log/slog"
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
"github.com/spf13/viper"
)
// dbMode says what openDB does after it connects.
type dbMode int
const (
// dbPlain connects and leaves the schema as it is.
dbPlain dbMode = iota
// dbMigrated connects and applies every pending migration first.
dbMigrated
)
// openDB opens the database the db-dsn setting names, in the given mode. The
// returned closer is for the caller to defer; it logs a failed Close at Warn,
// because by then the command has nothing left to do with the error.
func openDB(ctx context.Context, logger *slog.Logger, mode dbMode) (*sql.DB, func(), error) {
dbConfig := db.DefaultDBConfig(viper.GetString("db-dsn"))
var database *sql.DB
var err error
if mode == dbMigrated {
database, err = db.ConnectAndMigrate(ctx, logger, dbConfig, migrationSources())
} else {
database, err = db.ConnectPlain(ctx, logger, dbConfig)
}
if err != nil {
return nil, nil, err
}
return database, func() {
if err := database.Close(); err != nil {
logger.Warn("closing the database", slog.Any("error", err))
}
}, nil
}