Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get sqlite to error instead of creating a missing database file in golang?

Tags:

sqlite

go

I'm opening a connection to a sqlite database of the user's choosing in my golang program. If they supply a path to a non-existent file then I want to throw an error instead of creating the file.

I'm using the mattn/gp-sqlite3 driver. The documentation doesn't mention this capability as far as I can see.

  • The sqlite C documentation mentions the querystring format but not the existence of the target file.
  • The C# connection strings have a FailIfMissing option but are in a different format.

This is the same as Make SQLite connection fail if database is missing? (deleted/moved) but for golang instead of C#. The golang driver seems to use a different format for describing connections to the C# driver so I don't know if the answers there translate to golang or not.

like image 338
Tim Abell Avatar asked Mar 08 '23 07:03

Tim Abell


1 Answers

This is not currently possible with the go-sqlite3 library. Looking at the source, you can see SQLITE_OPEN_CREATE is always passed to the open function:

rv := C._sqlite3_open_v2(name, &db,
    C.SQLITE_OPEN_FULLMUTEX|
        C.SQLITE_OPEN_READWRITE|
        C.SQLITE_OPEN_CREATE,
    nil)

I would suggest you open a ticket on the package to add such functionality.

In the mean time, you could add the following code before your DB is created (keep in mind that a race condition exists, which is why you should still request this feature in the library itself):

_, err := os.Stat("db.sqlite3")
if os.IsNotExist(err) {
    panic("database doesn't exist")
}
// TODO: create db
like image 165
Tim Cooper Avatar answered Mar 10 '23 20:03

Tim Cooper