Socket
Socket
Sign inDemoInstall

github.com/xo/dburl

Package Overview
Dependencies
Alerts
File Explorer
Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

github.com/xo/dburl


Version published
Created
Source

About dburl

Package dburl provides a standard, URL style mechanism for parsing and opening SQL database connection strings for Go. Provides standardized way to parse and open URLs for popular databases PostgreSQL, MySQL, SQLite3, Oracle Database, Microsoft SQL Server, in addition to most other SQL databases with a publicly available Go driver.

Overview | Quickstart | Examples | Schemes | Installing | Using | About

Unit Tests Go Reference Discord Discussion

Database Connection URL Overview

Supported database connection URLs are of the form:

protocol+transport://user:pass@host/dbname?opt1=a&opt2=b
protocol:/path/to/file

Where:

ComponentDescription
protocoldriver name or alias (see below)
transport"tcp", "udp", "unix" or driver name (odbc/oleodbc)
userusername
passpassword
hosthost
dbname*database, instance, or service name/ID to connect to
?opt1=...additional database driver options (see respective SQL driver for available options)

* for Microsoft SQL Server, /dbname can be /instance/dbname, where /instance is optional. For Oracle Database, /dbname is of the form /service/dbname where /service is the service name or SID, and /dbname is optional. Please see below for examples.

Quickstart

Database connection URLs in the above format can be parsed with the dburl.Parse func as such:

import (
    "github.com/xo/dburl"
)

u, err := dburl.Parse("postgresql://user:pass@localhost/mydatabase/?sslmode=disable")
if err != nil { /* ... */ }

Additionally, a simple helper, dburl.Open, is provided that will parse, open, and return a standard sql.DB database connection:

import (
    "github.com/xo/dburl"
)

db, err := dburl.Open("sqlite:mydatabase.sqlite3?loc=auto")
if err != nil { /* ... */ }

Example URLs

The following are example database connection URLs that can be handled by dburl.Parse and dburl.Open:

postgres://user:pass@localhost/dbname
pg://user:pass@localhost/dbname?sslmode=disable
mysql://user:pass@localhost/dbname
mysql:/var/run/mysqld/mysqld.sock
sqlserver://user:pass@remote-host.com/dbname
mssql://user:pass@remote-host.com/instance/dbname
ms://user:pass@remote-host.com:port/instance/dbname?keepAlive=10
oracle://user:pass@somehost.com/sid
sap://user:pass@localhost/dbname
sqlite:/path/to/file.db
file:myfile.sqlite3?loc=auto
odbc+postgres://user:pass@localhost:port/dbname?option1=

Database Schemes, Aliases, and Drivers

The following table lists the supported dburl protocol schemes (ie, driver), additional aliases, and the related Go driver:

DatabaseScheme / TagScheme AliasesDriver Package / Notes
PostgreSQLpostgrespg, pgsql, postgresqlgithub.com/lib/pq
MySQLmysqlmy, maria, aurora, mariadb, perconagithub.com/go-sql-driver/mysql
Microsoft SQL Serversqlserverms, mssql, azuresqlgithub.com/microsoft/go-mssqldb
Oracle Databaseoracleor, ora, oci, oci8, odpi, odpi-cgithub.com/sijms/go-ora/v2
SQLite3sqlite3sq, sqlite, filegithub.com/mattn/go-sqlite3
ClickHouseclickhousechgithub.com/ClickHouse/clickhouse-go/v2
CSVQcsvqcs, csv, tsv, jsongithub.com/mithrandie/csvq-driver
Alibaba MaxComputemaxcomputemcsqlflow.org/gomaxcompute
Alibaba Tablestoreotsot, tablestoregithub.com/aliyun/aliyun-tablestore-go-sql-driver
Apache Avaticaavaticaav, phoenixgithub.com/apache/calcite-avatica-go/v5
Apache H2h2github.com/jmrobles/h2go
Apache Hivehivehi, hive2sqlflow.org/gohive
Apache Igniteigniteig, gridgaingithub.com/amsokol/ignite-go-client/sql
AWS Athenaathenas3, aws, awsathenagithub.com/uber/athenadriver/go
Azure CosmosDBcosmoscmgithub.com/btnguyen2k/gocosmos
Cassandracassandraca, scy, scylla, datastax, cqlgithub.com/MichaelS11/go-cql-driver
ChaiSQLchaici, genji, chaisqlgithub.com/chaisql/chai/driver
Couchbasecouchbasen1, n1qlgithub.com/couchbase/go_n1ql
Cznic QLqlcznic, cznicqlmodernc.org/ql
Databenddatabenddd, bendgithub.com/datafuselabs/databend-go
Databricksdatabricksbr, brick, bricks, databrickgithub.com/databricks/databricks-sql-go
DuckDBduckdbdk, ddb, duck, filegithub.com/marcboeker/go-duckdb
DynamoDbdynamodbdy, dyn, dynamo, dynamodbgithub.com/btnguyen2k/godynamo
Exasolexasolex, exagithub.com/exasol/exasol-driver-go
Firebirdfirebirdfb, firebirdsqlgithub.com/nakagami/firebirdsql
FlightSQLflightsqlfl, flightgithub.com/apache/arrow/go/v12/arrow/flight/flightsql/driver
Google BigQuerybigquerybqgorm.io/driver/bigquery/driver
Google Spannerspannerspgithub.com/googleapis/go-sql-spanner
Microsoft ADODBadodbad, adogithub.com/mattn/go-adodb
ModernC SQLite3moderncsqlitemq, modernsqlitemodernc.org/sqlite
MySQL MyMySQLmymysqlzm, mymygithub.com/ziutek/mymysql/godrv
Netezzanetezzanz, nzgogithub.com/IBM/nzgo/v12
PostgreSQL PGXpgxpxgithub.com/jackc/pgx/v5/stdlib
Prestoprestopr, prs, prestos, prestodb, prestodbsgithub.com/prestodb/presto-go-client/presto
RamSQLramsqlrm, ramgithub.com/proullon/ramsql/driver
SAP ASEsapaseax, ase, tdsgithub.com/thda/tds
SAP HANAsaphanasa, sap, hana, hdbgithub.com/SAP/go-hdb/driver
Snowflakesnowflakesfgithub.com/snowflakedb/gosnowflake
Trinotrinotr, trs, trinosgithub.com/trinodb/trino-go-client/trino
Verticaverticavegithub.com/vertica/vertica-sql-go
VoltDBvoltdbvo, vdb, voltgithub.com/VoltDB/voltdb-client-go/voltdbclient
YDBydbyd, yds, ydbsgithub.com/ydb-platform/ydb-go-sdk/v3
GO DRiver for ORaclegodrorgrgithub.com/godror/godror
ODBCodbcodgithub.com/alexbrainman/odbc
Amazon Redshiftpostgresrs, redshiftgithub.com/lib/pq
CockroachDBpostgrescr, cdb, crdb, cockroach, cockroachdbgithub.com/lib/pq
OLE ODBCadodboo, ole, oleodbcgithub.com/mattn/go-adodb
SingleStore MemSQLmysqlme, memsqlgithub.com/go-sql-driver/mysql
TiDBmysqlti, tidbgithub.com/go-sql-driver/mysql
Vitess Databasemysqlvt, vitessgithub.com/go-sql-driver/mysql
Apache Impalaimpalaimgithub.com/bippio/go-impala

Requires CGO
Wire compatible (see respective driver)

Any protocol scheme alias:// can be used in place of protocol://, and will work identically with dburl.Parse and dburl.Open.

Installing

Install in the usual Go fashion:

$ go get github.com/xo/dburl@latest

Using

dburl does not import any of Go's SQL drivers, as it only provides a way to parse and open database URL stylized connection strings. As such, it is necessary to explicitly import the relevant SQL driver:

import (
    // import Microsoft SQL Server driver
    _ "github.com/microsoft/go-mssqldb"
)

See the database schemes table above for a list of the expected Go driver import's.

Additional examples and API details can be found in the dburl package documentation.

URL Parsing Rules

dburl.Parse and dburl.Open rely primarily on Go's standard net/url.URL type, and as such, parsing or opening database connection URLs with dburl are subject to the same rules, conventions, and semantics as Go's net/url.Parse func.

Example

A full example for reference:

// _example/example.go
package main

import (
	"fmt"
	"log"

	_ "github.com/microsoft/go-mssqldb"
	"github.com/xo/dburl"
)

func main() {
	db, err := dburl.Open("sqlserver://user:pass@localhost/dbname")
	if err != nil {
		log.Fatal(err)
	}
	var name string
	if err := db.QueryRow(`SELECT name FROM mytable WHERE id=10`).Scan(&name); err != nil {
		log.Fatal(err)
	}
	fmt.Println("name:", name)
}

Scheme Resolution

By default on non-Windows systems, dburl will resolve paths on disk, and URLs with file: schemes to an appropriate database driver:

  1. Directories will resolve as postgres: URLs
  2. Unix sockets will resolve as mysql: URLs
  3. Regular files will have their headers checked to determine if they are either sqlite3: or duckdb: files
  4. Non-existent files will test their file extension against well-known sqlite3: and duckdb: file extensions and open with the appropriate scheme

If this behavior is undesired, it can be disabled by providing different implementations for dburl.Stat and dburl.OpenFile, or alternately by setting dburl.ResolveSchemeType to false:

import "github.com/xo/dburl"

func init() {
    dburl.ResolveSchemeType = false
}

About

dburl was built primarily to support these projects:

  • usql - a universal command-line interface for SQL databases
  • xo - a command-line tool to generate code for SQL databases

FAQs

Package last updated on 10 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc