Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Last active May 31, 2025 08:04
Show Gist options
  • Save wjkoh/cb486d7ad7cf5c3dd60b31de7fed22fa to your computer and use it in GitHub Desktop.
Save wjkoh/cb486d7ad7cf5c3dd60b31de7fed22fa to your computer and use it in GitHub Desktop.
Go: Open two SQLite connections, one for read-write-create and the other for read only
// https://github.com/mattn/go-sqlite3/issues/1022#issuecomment-1067353980
func newSqlDb(name string) (*sql.DB, *sql.DB, error) {
u := url.URL{
Scheme: "file",
Opaque: name,
}
q := make(url.Values)
q.Set("mode", "rwc")
q.Set("_foreign_keys", "true")
q.Set("_journal_mode", "WAL")
q.Set("_synchronous", "NORMAL")
q.Set("_txlock", "immediate")
u.RawQuery = q.Encode()
rwc, err := sql.Open("sqlite3", u.String())
if err != nil {
return nil, nil, err
}
rwc.SetMaxOpenConns(1)
q = make(url.Values)
q.Set("mode", "ro")
u.RawQuery = q.Encode()
ro, err := sql.Open("sqlite3", u.String())
if err != nil {
return nil, nil, err
}
return rwc, ro, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment