Skip to content

Commit

Permalink
Fix readonly shared memory (see #94).
Browse files Browse the repository at this point in the history
  • Loading branch information
ncruces committed Jun 9, 2024
1 parent 35a3bfe commit e7f8311
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 9 deletions.
47 changes: 38 additions & 9 deletions tests/wal_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package tests

import (
"os"
"path/filepath"
"testing"

"github.com/ncruces/go-sqlite3"
"github.com/ncruces/go-sqlite3/driver"
_ "github.com/ncruces/go-sqlite3/embed"
_ "github.com/ncruces/go-sqlite3/internal/testcfg"
"github.com/ncruces/go-sqlite3/vfs"
Expand Down Expand Up @@ -52,26 +52,55 @@ func TestWAL_readonly(t *testing.T) {
}
t.Parallel()

tmp := filepath.Join(t.TempDir(), "test.db")
err := os.WriteFile(tmp, walDB, 0666)
tmp := filepath.ToSlash(filepath.Join(t.TempDir(), "test.db"))

db1, err := driver.Open("file:"+tmp+"?_pragma=journal_mode(wal)&_txlock=immediate", nil)
if err != nil {
t.Fatal(err)
}
defer db1.Close()

db, err := sqlite3.OpenFlags(tmp, sqlite3.OPEN_READONLY)
db2, err := driver.Open("file:"+tmp+"?_pragma=journal_mode(wal)&mode=ro", nil)
if err != nil {
t.Fatal(err)
}
defer db.Close()
defer db2.Close()

// Create the table using the first (writable) connection.
_, err = db1.Exec(`
CREATE TABLE t(id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO t(name) VALUES('alice');
`)
if err != nil {
t.Fatal(err)
}

// Select the data using the second (readonly) connection.
var name string
err = db2.QueryRow("SELECT name FROM t").Scan(&name)
if err != nil {
t.Fatal(err)
}
if name != "alice" {
t.Errorf("got %q want alice", name)
}

stmt, _, err := db.Prepare(`SELECT * FROM sqlite_master`)
// Update table.
_, err = db1.Exec(`
DELETE FROM t;
INSERT INTO t(name) VALUES('bob');
`)
if err != nil {
t.Fatal(err)
}
defer stmt.Close()

if stmt.Step() {
t.Error("want no rows")
// Select the data using the second (readonly) connection.
err = db2.QueryRow("SELECT name FROM t").Scan(&name)
if err != nil {
t.Fatal(err)
}
if name != "bob" {
t.Errorf("got %q want bob", name)
}
}

Expand Down
3 changes: 3 additions & 0 deletions vfs/shm.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ func (s *vfsShm) shmMap(ctx context.Context, mod api.Module, id, size int32, ext
return 0, _IOERR_SHMMAP
}
s.regions = append(s.regions, r)
if s.readOnly {
return r.Ptr, _READONLY
}
return r.Ptr, _OK
}

Expand Down
3 changes: 3 additions & 0 deletions vfs/shm_bsd.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,9 @@ func (s *vfsShm) shmMap(ctx context.Context, mod api.Module, id, size int32, ext
return 0, _IOERR_SHMMAP
}
s.regions = append(s.regions, r)
if s.readOnly {
return r.Ptr, _READONLY
}
return r.Ptr, _OK
}

Expand Down

0 comments on commit e7f8311

Please sign in to comment.