61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package db_test
|
|
|
|
import (
|
|
"context"
|
|
"path"
|
|
"show-rss/src/cleanup"
|
|
"show-rss/src/db"
|
|
"testing"
|
|
)
|
|
|
|
func TestDB(t *testing.T) {
|
|
ctx := context.Background()
|
|
|
|
ctx, err := db.Inject(ctx, path.Join(t.TempDir(), "db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
cleanup.Extract(ctx)()
|
|
}()
|
|
|
|
if err := db.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS test (k TEXT);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS test_idx ON test (k);
|
|
INSERT INTO test (k) SELECT 'a';
|
|
INSERT INTO test (k) SELECT 'b';
|
|
`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
type result struct {
|
|
K string `json:"k"`
|
|
}
|
|
if got, err := db.QueryOne[result](ctx, `SELECT k FROM test WHERE k='a'`); err != nil {
|
|
t.Errorf("failed query one: %v", err)
|
|
} else if got.K != "a" {
|
|
t.Errorf("bad query one: %+v", got)
|
|
}
|
|
|
|
if gots, err := db.Query[result](ctx, `SELECT k FROM test`); err != nil {
|
|
t.Errorf("failed query: %v", err)
|
|
} else if len(gots) != 2 {
|
|
t.Errorf("expected 2 but got %d gots", len(gots))
|
|
} else if gots[0].K != "a" {
|
|
t.Errorf("expected [0]='a' but got %q", gots[0].K)
|
|
} else if gots[1].K != "b" {
|
|
t.Errorf("expected [1]='b' but got %q", gots[1].K)
|
|
}
|
|
|
|
type NestedResult struct {
|
|
Nest struct {
|
|
K string `json:"k"`
|
|
}
|
|
}
|
|
if got, err := db.QueryOne[NestedResult](ctx, `SELECT k AS "Nest.k" FROM test WHERE k='a'`); err != nil {
|
|
t.Errorf("failed nested query one: %v", err)
|
|
} else if got.Nest.K != "a" {
|
|
t.Errorf("bad nested query one: %+v", got)
|
|
}
|
|
}
|