sqlapi/connect.go

45 lines
932 B
Go
Raw Normal View History

package main
import (
"database/sql"
"fmt"
2024-06-30 13:14:29 +00:00
"net/url"
"github.com/go-sql-driver/mysql"
2024-06-30 12:32:58 +00:00
_ "github.com/jackc/pgx/v5/stdlib"
)
func connect(database string) (db *sql.DB, err error) {
switch cfg.DBType {
case "mysql", "mariadb":
connInfo, err := mysql.ParseDSN(cfg.DSN)
if err != nil {
return nil, fmt.Errorf("parsing DSN: %w", err)
}
connInfo.DBName = database
if db, err = sql.Open("mysql", connInfo.FormatDSN()); err != nil {
return nil, fmt.Errorf("opening db connection: %w", err)
}
return db, nil
case "postgres", "pg", "crdb":
2024-06-30 13:14:29 +00:00
u, err := url.Parse(cfg.DSN)
if err != nil {
2024-06-30 13:14:29 +00:00
return nil, fmt.Errorf("parsing DSN URL: %w", err)
}
2024-06-30 13:14:29 +00:00
u.Path = fmt.Sprintf("/%s", database)
if db, err = sql.Open("pgx", u.String()); err != nil {
return nil, fmt.Errorf("opening db connection: %w", err)
}
return db, nil
default:
return nil, fmt.Errorf("unknown database type %q", cfg.DBType)
}
}