crawlkit/store/store_test.go
2026-05-01 12:30:13 -07:00

96 lines
2.1 KiB
Go

package store
import (
"context"
"database/sql"
"os"
"path/filepath"
"testing"
)
func TestOpenAppliesSchemaPragmasAndPermissions(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "archive.db")
st, err := Open(ctx, Options{
Path: path,
Schema: `create table things(id text primary key, value text not null);`,
SchemaVersion: 3,
})
if err != nil {
t.Fatal(err)
}
defer st.Close()
var journalMode string
if err := st.DB().QueryRowContext(ctx, `pragma journal_mode`).Scan(&journalMode); err != nil {
t.Fatal(err)
}
if journalMode != "wal" {
t.Fatalf("journal mode = %q", journalMode)
}
version, err := st.SchemaVersion(ctx)
if err != nil {
t.Fatal(err)
}
if version != 3 {
t.Fatalf("schema version = %d", version)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if got := info.Mode().Perm(); got != 0o600 {
t.Fatalf("mode = %o", got)
}
}
func TestWithTxAndQuery(t *testing.T) {
ctx := context.Background()
st, err := Open(ctx, Options{
Path: filepath.Join(t.TempDir(), "archive.db"),
Schema: `create table things(id text primary key, value text not null);`,
})
if err != nil {
t.Fatal(err)
}
defer st.Close()
if err := st.WithTx(ctx, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, `insert into things(id, value) values('a', 'one')`)
return err
}); err != nil {
t.Fatal(err)
}
result, err := st.Query(ctx, `select id, value from things`)
if err != nil {
t.Fatal(err)
}
if len(result.Rows) != 1 || result.Values[0]["value"] != "one" {
t.Fatalf("unexpected query result: %+v", result)
}
}
func TestReadOnlyRejectsWrites(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "archive.db")
st, err := Open(ctx, Options{
Path: path,
Schema: `create table things(id text primary key);`,
})
if err != nil {
t.Fatal(err)
}
if err := st.Close(); err != nil {
t.Fatal(err)
}
ro, err := OpenReadOnly(ctx, path)
if err != nil {
t.Fatal(err)
}
defer ro.Close()
if _, err := ro.DB().ExecContext(ctx, `insert into things(id) values('x')`); err == nil {
t.Fatal("expected readonly write to fail")
}
}