improve postgres support
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
48
db/db.go
48
db/db.go
@@ -119,6 +119,54 @@ func normalizeDriver(driver string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveDriver determines the effective database driver.
|
||||
// If driver is unset and DSN looks like PostgreSQL, it infers postgres.
|
||||
func ResolveDriver(configuredDriver, dsn string) (driver string, inferredFromDSN bool, err error) {
|
||||
normalized := strings.ToLower(strings.TrimSpace(configuredDriver))
|
||||
switch normalized {
|
||||
case "sqlite3":
|
||||
normalized = "sqlite"
|
||||
case "postgresql":
|
||||
normalized = "postgres"
|
||||
}
|
||||
|
||||
if normalized == "" {
|
||||
if looksLikePostgresDSN(dsn) {
|
||||
return "postgres", true, nil
|
||||
}
|
||||
return "sqlite", false, nil
|
||||
}
|
||||
|
||||
if normalized == "sqlite" && looksLikePostgresDSN(dsn) {
|
||||
return "", false, fmt.Errorf("database_driver is sqlite but database_url looks like a postgres DSN; set settings.database_driver=postgres")
|
||||
}
|
||||
|
||||
return normalized, false, nil
|
||||
}
|
||||
|
||||
func looksLikePostgresDSN(dsn string) bool {
|
||||
trimmed := strings.ToLower(strings.TrimSpace(dsn))
|
||||
if trimmed == "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(trimmed, "postgres://") || strings.HasPrefix(trimmed, "postgresql://") {
|
||||
return true
|
||||
}
|
||||
|
||||
// Also support key=value style PostgreSQL DSNs.
|
||||
if strings.Contains(trimmed, "=") {
|
||||
hasHost := strings.Contains(trimmed, "host=")
|
||||
hasUser := strings.Contains(trimmed, "user=")
|
||||
hasDB := strings.Contains(trimmed, "dbname=")
|
||||
hasSSL := strings.Contains(trimmed, "sslmode=")
|
||||
if (hasHost && hasUser) || (hasHost && hasDB) || (hasUser && hasDB) || (hasHost && hasSSL) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// ConvertToSQLParams is a utility function that generically converts a struct to a corresponding sqlc-generated struct
|
||||
func ConvertToSQLParams(input interface{}, output interface{}) {
|
||||
inputVal := reflect.ValueOf(input).Elem()
|
||||
|
||||
Reference in New Issue
Block a user