1package goose
2
3import (
4 "database/sql"
5 "fmt"
6)
7
8// OpenDBWithDriver creates a connection to a database, and modifies goose internals to be
9// compatible with the supplied driver by calling SetDialect.
10func OpenDBWithDriver(driver string, dbstring string) (*sql.DB, error) {
11 if err := SetDialect(driver); err != nil {
12 return nil, err
13 }
14
15 // The Go ecosystem has added more and more drivers over the years. As a result, there's no
16 // longer a one-to-one match between the driver name and the dialect name. For instance, there's
17 // no "redshift" driver, but that's the internal dialect name within goose. Hence, we need to
18 // convert the dialect name to a supported driver name. This conversion is a best-effort
19 // attempt, as we can't support both lib/pq and pgx, which some users might have.
20 //
21 // We recommend users to create a [NewProvider] with the desired dialect, open a connection
22 // using their preferred driver, and provide the *sql.DB to goose. This approach removes the
23 // need for mapping dialects to drivers, rendering this function unnecessary.
24
25 switch driver {
26 case "mssql":
27 driver = "sqlserver"
28 case "tidb":
29 driver = "mysql"
30 case "turso":
31 driver = "libsql"
32 case "sqlite3":
33 driver = "sqlite"
34 case "postgres", "redshift":
35 driver = "pgx"
36 case "starrocks":
37 driver = "mysql"
38 }
39
40 switch driver {
41 case "postgres", "pgx", "sqlite3", "sqlite", "mysql", "sqlserver", "clickhouse", "vertica", "azuresql", "ydb", "libsql", "starrocks":
42 return sql.Open(driver, dbstring)
43 default:
44 return nil, fmt.Errorf("unsupported driver %s", driver)
45 }
46}