bvpx
bvpx

Reputation: 1287

golang database Open function ambiguity

In go, you invoke a database open with

DB, err = sql.Open("sqlite3", "./bar.db")

This returns a database of type *sql.DB, the function and type are both members of database/sql.

However, in the sqlite3 driver package, there is another Open function which returns a *sqlite3.Conn type.

I've noticed that some of the functions defined in the sqlite3 driver package do not work on a database opened using the default database/sql.

Additionally, there are functions in the sqlite3 package that are similar to database/sql's functions, namely Query and Exec, which return different types.

database/sql contains a func Query that returns type *sql.Rows.

mxk/sqlite/sqlite3 and mattn/go-sqlite3 both have a Query function, which return completely different types.

I want to run functions such as mxk/sqlite/sqlite3's BusyTimeout on my database connection, but it isn't the correct type. Do I have to re-write all of my code to open the database connection with the sqlite3 driver instead of using database/sql's Open? What's the advantage of database/sql's Open function if you can't use any of the driver's functions with that generic connection?

Upvotes: 2

Views: 897

Answers (1)

RickyA
RickyA

Reputation: 16029

Well, as the docs state...

Database connections are created either by using this package directly or with the "sqlite3" database/sql driver. The direct interface, which is described below, exposes SQLite-specific features, such as incremental I/O and online backups. The driver is recommended when your application has to support multiple database engines.

... you would use the sqlite3 connection when you want the sqlite specific functions (your usecase) and for generic database connections you would use the database driver (your code).

That is perfectly logical, since how would a generic driver handle functions that are specific to various databases? Runtime errors?

So you have a choice: all sqlite functions -> sqlite conn or handle multiple sql databases -> generic driver.

Upvotes: 2

Related Questions