-
Notifications
You must be signed in to change notification settings - Fork 18k
database/sql: ability to get drivername from instance #12600
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I don't know what an |
In this case, I am trying to avoid having to store another variable with the driver name and having to pass it around. Expect it could be added to the Db instance itself for convenienace instead. |
Maybe we could add it to |
I need this functionality also. I am using some external libraries and they want the database connection and the driver name (as string). |
One way you can do this today is to get the DB.Driver() and reflect on that type. See https://github.com/golang-sql/sqlexp/blob/c2488a8be21d20d31abf0d05c2735efd2d09afe4/quoter.go#L46 |
Well thats one way to skin a cat, what I am having to do as a workaroundzzz, and it seems daft to me that there is not a "field" for the want of the word that simply contains the driver_name and some meta data.. Example case.. Here u are with a new db connection... and a new project.. so its daft.. in my case btw i run www sites + scripts and interfacing db's of all types.. so this is a "bane of contention" as I now need to move around all driver info et all, instead of a DB "object" that COULD do that for me.. Its a simple solution and i dont unserstand quite why it aint there.. to be honest.. https://golang.org/pkg/database/sql/driver/#Driver
|
@kardianos Make is "method" or something.. help me .. Im my case I am using multiple db's(as a new integrator).. |
@pedromorgan You're fine. Are you aware of the DB.Driver method? Let me think on this though. I created a playground for possible extensions: In the meantime I could create something like:
Then you just have to pass around the *sql.DB, right? |
No.. I don't want contstants.. I want to know which driver am using.. from string If its mysql = No spatial// The only things I want passed is the Name() of the interface.. Is it postgis ?? is it mysql ?? is it gitsql ?? I need to know that cos 8000 I cant even create a connection+addoen unless I know that... !! Othewise Please implement asap the Reflact Inteterface() which @bradfitz is probally correct in the stats module.. |
Here is the problem.. I want a local cache vs online one in same interface.. |
The name should be considered for Flavor vs Dialect. 👍 |
@mattn, yeah, Dialect would probably be a better name. I don't think this needs to be in the std lib right away. I'll prototype something in sqlexp. @pedromorgan I may not be completly understanding your usecase, but if you want to see if postgresql has the postgis extensions installed, that seems like a capability you would query initially when connection. But I'm not arguing with you, a name would be useful attached to a driver. Let me work something up. |
FWIW, this "hack" worked for me: var sqlDriverNamesByType map[reflect.Type]string
// The database/sql API doesn't provide a way to get the registry name for
// a driver from the driver type.
func sqlDriverToDriverName(driver driver.Driver) string {
if sqlDriverNamesByType == nil {
sqlDriverNamesByType = map[reflect.Type]string{}
for _, driverName := range sql.Drivers() {
// Tested empty string DSN with MySQL, PostgreSQL, and SQLite3 drivers.
db, _ := sql.Open(driverName, "")
if db != nil {
driverType := reflect.TypeOf(db.Driver())
sqlDriverNamesByType[driverType] = driverName
}
}
}
driverType := reflect.TypeOf(driver)
if driverName, found := sqlDriverNamesByType[driverType]; found {
return driverName
}
return ""
} |
I encountered the same problem. func init(db *sql.DB) {
swith(getDbType(db)) {
case "mysql":
// logic 1
case "oracle":
// logic 2
case "postgres":
// logic 3
}
} |
|
As an author of database libraries that work with multiple drivers (PostgreSQL, MySQL, SQLite, MSSQL, etc) I also think it'd be extremely useful to be able to detect which driver the user is using (without having to ask for an additional parameter). |
I also need this feature to know the driver name while doing database migrations cause different driver requires different SQL. |
I have a similar need to know what is the SQL dialect of a database (MySQL, Oracle, etc.). For now, I manually maintain a list of Go driver package names and their dialects (eg. github.com/go-sql-driver/mysql => MySQL). So I get the package name using |
I believe this issue has been solved. var db *sql.DB
switch db.Driver().(type) {
case *mysql.MySQLDriver:
break // mysql
...
} |
@terorie The ability to get only the driver name would be better. As you suggested, a given library would have to import many SQL drivers to be able to match them, even if the user will only use one of them. If it returned a string, libraries would not need to import any driver at all, and the user will only import those he uses. |
@andreynering It's hard to understand the use-case for this. If your code tries to match a specific driver, with a code path that is only taken when that driver is |
@terorie In short, it'll be imported and bloat the binary size without being used. And an important detail: some SQL drivers require a C compiler to be available if imported, notably SQLite. That's annoying if the user is not using that driver at all. I've shortly dealt with some Oracle drivers in the past, and they require even more complicated setups, just to compile the binary, even if you don't use it. |
@andreynering I understand the concern about the import graph but there are other ways to solve this. To elaborate on my previous comment here are some options:
|
there are any updates on the SQL get river name feature? this issue is still open. |
This is useful when your function receives *sql.DB or *sql.TX as a input parameter and you want to figure out what placeholders should be used. |
If this is done someday, please don't forget we want the db type from *sql.Tx as well. Go's sql sucks. |
Here is my hacks, how dirty! // due to the lack of a common interface between *sql.DB and *sql.Tx
// when I said go's sql sucks, I meant it.
type DB interface {
Query(query string, args ...any) (*sql.Rows, error)
Exec(query string, args ...any) (sql.Result, error)
}
type DbType int
const (
Unknown DbType = iota
SQLite
MySQL
PostgreSQL
SQLServer
Oracle
)
var dbTypeMap = map[string]DbType{}
func GetDbType(conn DB) DbType {
connPtrStr := fmt.Sprintf("%p\n", conn)
if val, ok := dbTypeMap[connPtrStr]; ok {
return val
}
v, err := QueryToMaps(conn, "SELECT VERSION() AS version")
if err == nil && len(v) > 0 {
version := strings.ToLower(fmt.Sprint(v[0]["version"]))
if strings.Contains(version, "postgres") {
dbTypeMap[connPtrStr] = PostgreSQL
return PostgreSQL
} else {
dbTypeMap[connPtrStr] = MySQL
return MySQL
}
}
v, err = QueryToMaps(conn, "SELECT @@VERSION AS version")
if err == nil && len(v) > 0 {
version := strings.ToLower(fmt.Sprint(v[0]["version"]))
if strings.Contains(version, "microsoft") {
dbTypeMap[connPtrStr] = SQLServer
return SQLServer
} else {
dbTypeMap[connPtrStr] = MySQL
return MySQL
}
}
v, err = QueryToMaps(conn, "SELECT * FROM v$version")
if err == nil && len(v) > 0 {
dbTypeMap[connPtrStr] = Oracle
return Oracle
}
v, err = QueryToMaps(conn, "SELECT sqlite_version()")
if err == nil && len(v) > 0 {
dbTypeMap[connPtrStr] = SQLite
return SQLite
}
return Unknown
} |
I'd like to be able to get the driver name..
eg
Case Example.. I want to derive an sqlx instance from an existing connection
https://github.com/daffodil/go-mailkit/blob/master/postfixadmin/setup.go#L15
The text was updated successfully, but these errors were encountered: