Skip to content

Commit

Permalink
Explicitly set journal mode to WAL using PRAGMA
Browse files Browse the repository at this point in the history
SQLITE_OPEN_WAL is only used in the vfs system.  This change calls

PRAGMA journal_mode=wal;

if the SQLITE_OPEN_WAL flag is provided.  Tests added for default and
explicit behavior.

Fixes #7
  • Loading branch information
ksshannon authored and crawshaw committed Apr 20, 2018
1 parent d5b62ad commit ae8505e
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
18 changes: 18 additions & 0 deletions sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ package sqlite
// #include <stdlib.h>
// #include <string.h>
//
// // Set typedefs for calling sqlite3_exec()
// typedef int (*_sqlite_callback)(void*,int,char**,char**);
// typedef char ** charPtrPtr;
//
// // Use a helper function here to avoid the cgo pointer detection
// // logic treating SQLITE_TRANSIENT as a Go pointer.
// static int transient_bind_text(sqlite3_stmt* stmt, int col, char* p, int n) {
Expand Down Expand Up @@ -144,6 +148,20 @@ func openConn(path string, flags OpenFlags) (*Conn, error) {
}
})

if flags&SQLITE_OPEN_WAL > 0 {
pragma := C.CString("PRAGMA journal_mode=wal")
defer C.free(unsafe.Pointer(pragma))
res = C.sqlite3_exec(conn.conn, pragma, C._sqlite_callback(nil), unsafe.Pointer(nil), C.charPtrPtr(nil))
if res != 0 {
extres := C.sqlite3_extended_errcode(conn.conn)
if extres != 0 {
res = extres
}
C.sqlite3_close_v2(conn.conn)
return nil, reserr("OpenConn", path, "", res)
}
}

return conn, nil
}

Expand Down
51 changes: 51 additions & 0 deletions sqlite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ package sqlite_test

import (
"context"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -353,3 +356,51 @@ func TestExtendedCodes(t *testing.T) {
t.Errorf("got err=%s, want %s", got, want)
}
}

func TestJournalMode(t *testing.T) {
dir, err := ioutil.TempDir("", "crawshaw.io")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)

tests := []struct {
mode string
flags sqlite.OpenFlags
}{
{
"delete",
sqlite.SQLITE_OPEN_READWRITE | sqlite.SQLITE_OPEN_CREATE,
},
{
"wal",
sqlite.SQLITE_OPEN_READWRITE | sqlite.SQLITE_OPEN_CREATE | sqlite.SQLITE_OPEN_WAL,
},
{
"wal",
0,
},
}

for _, test := range tests {
dbFile := filepath.Join(dir, "test-"+test.mode+".db")
c, err := sqlite.OpenConn(dbFile, test.flags)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := c.Close(); err != nil {
t.Error(err)
}
}()
stmt := c.Prep("PRAGMA journal_mode;")
if hasRow, err := stmt.Step(); err != nil {
t.Fatal(err)
} else if !hasRow {
t.Error("PRAGMA journal_mode: has no row")
}
if got := stmt.GetText("journal_mode"); got != test.mode {
t.Errorf("journal_mode not set properly, got: %s, want: %s", got, test.mode)
}
}
}

0 comments on commit ae8505e

Please sign in to comment.