otpm/database/database.go
“xHuPo” 079542e431 alpha
2025-05-22 12:06:34 +08:00

48 lines
967 B
Go

package database
import (
_ "embed"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/spf13/viper"
_ "modernc.org/sqlite"
)
var (
//go:embed init/users.sql
userTable string
//go:embed init/otp.sql
otpTable string
)
func InitDB() (*sqlx.DB, error) {
driver := viper.GetString("database.driver")
dsn := viper.GetString("database.dsn")
db, err := sqlx.Open(driver, dsn)
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("failed to ping database: %w", err)
}
log.Println("Connected to database!")
return db, nil
}
func MigrateDB(db *sqlx.DB) error {
if _, err := db.Exec(userTable); err != nil {
return fmt.Errorf("failed to create user migration: %w", err)
}
if _, err := db.Exec(otpTable); err != nil {
return fmt.Errorf("failed to create otp migration: %w", err)
}
return nil
}