navidrome/db/pglite/pglite_test.go
Deluan 65f6bc2526 feat(pglite): run Navidrome on the embedded PostgreSQL end to end
Replace the 131 SQLite migrations with a single goose migration that creates
the whole schema in PostgreSQL (the user table becomes user_account, json
columns become jsonb, seed rows for the default library and transcodings).
Port the repositories' SQL just far enough for Navidrome to start, scan,
log in and browse artists and albums: json_agg/jsonb_* for the SQLite JSON
functions, lower() for COLLATE NOCASE, ON CONFLICT DO NOTHING, coalesce on
annotations, stricter GROUP BY, explicit casts under the simple protocol,
sequential queries in library.RefreshStats. db/ is now Postgres-only, with
backup/restore stubbed and DevExternalScanner forced off.

Embed the PGlite module like go-taglib: pglite.wasi.gz is go:embed'ed,
decompressed in memory and compiled by wazero with an on-disk compilation
cache, so the module itself is never written to disk. The cluster is
created by initdb at runtime on the first start; initdb runs in a
throwaway wasm instance and the backend in a fresh one, otherwise the next
start cannot find a valid checkpoint. Since initdb creates only template1,
a short-lived backend then runs CREATE DATABASE navidrome and the real
backend starts on it. The build recipe and patches for the -O2, no-wizer
module live in db/pglite/build.
2026-09-04 20:41:52 -04:00

119 lines
4.1 KiB
Go

package pglite_test
import (
"context"
"database/sql"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/navidrome/navidrome/db/pglite"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/tetratelabs/wazero/experimental"
"github.com/tetratelabs/wazero/experimental/logging"
)
var _ = Describe("PGlite under wazero", func() {
var pg *pglite.PGlite
var db *sql.DB
BeforeEach(func() {
ctx := context.Background()
if os.Getenv("ND_PGLITE_TRACE") != "" {
ctx = experimental.WithFunctionListenerFactory(ctx,
logging.NewHostLoggingListenerFactory(os.Stderr, logging.LogScopeFilesystem))
}
var err error
pg, err = pglite.New(ctx, pglite.Config{
DataDir: GinkgoT().TempDir(),
Stderr: GinkgoWriter,
})
Expect(err).ToNot(HaveOccurred())
DeferCleanup(pg.Close)
db, err = sql.Open("pgx", pg.DSN())
Expect(err).ToNot(HaveOccurred())
db.SetMaxOpenConns(1)
DeferCleanup(db.Close)
})
It("answers SELECT version()", func() {
var version string
Expect(db.QueryRow("SELECT version()").Scan(&version)).To(Succeed())
GinkgoWriter.Println("version:", version)
Expect(version).To(ContainSubstring("PostgreSQL 17"))
})
It("keeps the connection after a SQL error and survives a reconnect", func() {
_, err := db.Exec("SELECT * FROM nope WHERE id = $1", 1)
Expect(err).To(MatchError(ContainSubstring("does not exist")))
var one int
Expect(db.QueryRow("SELECT $1::int", 1).Scan(&one)).To(Succeed())
GinkgoWriter.Println("connections after error:", pg.Connections())
Expect(pg.Connections()).To(BeEquivalentTo(1))
// The session must still be usable for DDL, DML and transactions after the error.
_, err = db.Exec("CREATE TABLE t (id int PRIMARY KEY, name text)")
Expect(err).ToNot(HaveOccurred())
tx, err := db.Begin()
Expect(err).ToNot(HaveOccurred())
_, err = tx.Exec("INSERT INTO t VALUES ($1, $2)", 1, "one")
Expect(err).ToNot(HaveOccurred())
Expect(tx.Commit()).To(Succeed())
_, err = db.Exec("INSERT INTO t VALUES ($1, $2)", 1, "dup")
Expect(err).To(MatchError(ContainSubstring("duplicate key")))
var name string
Expect(db.QueryRow("SELECT name FROM t WHERE id = $1", 1).Scan(&name)).To(Succeed())
Expect(name).To(Equal("one"))
Expect(pg.Connections()).To(BeEquivalentTo(1))
// Force a new connection and make sure parameterized queries still work on it.
Expect(db.Close()).To(Succeed())
db, err = sql.Open("pgx", pg.DSN())
Expect(err).ToNot(HaveOccurred())
db.SetMaxOpenConns(1)
Expect(db.QueryRow("SELECT $1::int", 2).Scan(&one)).To(Succeed())
Expect(one).To(Equal(2))
Expect(pg.Connections()).To(BeEquivalentTo(2))
})
It("keeps committed rows across a close and reopen of the same data dir", func() {
_, err := db.Exec("CREATE TABLE durable (id int PRIMARY KEY, v text)")
Expect(err).ToNot(HaveOccurred())
_, err = db.Exec("INSERT INTO durable VALUES (1, 'survives')")
Expect(err).ToNot(HaveOccurred())
dataDir := pg.DataDir()
Expect(db.Close()).To(Succeed())
Expect(pg.Close()).To(Succeed())
reopened, err := pglite.New(context.Background(), pglite.Config{DataDir: dataDir, Stderr: GinkgoWriter})
Expect(err).ToNot(HaveOccurred())
DeferCleanup(reopened.Close)
db2, err := sql.Open("pgx", reopened.DSN())
Expect(err).ToNot(HaveOccurred())
DeferCleanup(db2.Close)
var v string
Expect(db2.QueryRow("SELECT v FROM durable WHERE id = 1").Scan(&v)).To(Succeed())
Expect(v).To(Equal("survives"))
// the reopened instance must not be a second copy of these tests' fixture
pg, db = reopened, db2
})
It("creates a table and reads rows back", func() {
_, err := db.Exec("CREATE TABLE property (id text PRIMARY KEY, value text)")
Expect(err).ToNot(HaveOccurred())
_, err = db.Exec("INSERT INTO property (id, value) VALUES ($1, $2)", "JWTSecret", "abc")
Expect(err).ToNot(HaveOccurred())
start := time.Now()
var value string
Expect(db.QueryRow("SELECT value FROM property WHERE id = $1", "JWTSecret").Scan(&value)).To(Succeed())
GinkgoWriter.Println("select took", time.Since(start))
Expect(value).To(Equal("abc"))
var count int
Expect(db.QueryRow("SELECT count(*) FROM property").Scan(&count)).To(Succeed())
Expect(count).To(Equal(1))
})
})