Documentation
¶
Overview ¶
Package pglite embeds PostgreSQL in Go by running PGlite (PostgreSQL compiled to WebAssembly) on a WebAssembly runtime — wasmtime by default, or pure-Go wazero with -tags wazero — with a hand-written Emscripten/WASI host layer and an in-memory VFS.
A DB is a cluster: Open initializes (or loads a persisted) data directory, keeps it in an in-memory filesystem, and starts one persistent PostgreSQL backend driven over the v3 wire protocol (PGlite's pgl_set_rw_cbs + PostgresMainLoopOnce). Query/Exec feed protocol messages to that live backend, so results carry column type OIDs and command tags (RowsAffected), and session state — the current transaction, temp tables, SET, prepared statements — persists across calls: BEGIN in one Query and COMMIT in a later one form a single transaction. QueryParams runs a real server-side prepared statement (extended protocol). For the standard Go database API, use the registered "pglite" database/sql driver (package pgdriver).
The backend is a single connection (as in PGlite itself), so concurrent use must be serialized — the DB does this internally, and database/sql callers should set db.SetMaxOpenConns(1).
Index ¶
Constants ¶
const PgliteVersion = pgassets.Version
PgliteVersion is the pinned PGlite release the artifacts must match.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// WasmFS, if set, supplies the wasm artifacts (pglite.wasm, initdb.wasm,
// pglite.data, pglite.manifest.json) from any io/fs — e.g. a caller-provided
// embed.FS. Takes precedence over WasmDir. See resolveWasmFS for the full
// source-selection order.
WasmFS fs.FS
// WasmDir holds the wasm artifacts on the host filesystem. Used when WasmFS
// is nil. Empty falls back to embedded assets (-tags embed), then "./wasm",
// then an on-demand download when Download is set.
WasmDir string
// Download allows fetching the pinned artifacts from the jsDelivr CDN into the
// user cache dir when no local/embedded source is available. Off by default so
// Open never performs surprise network I/O.
Download bool
// PersistDir is the host directory the initialized cluster is saved to and
// loaded from. Empty uses the user cache dir; set Ephemeral to disable.
PersistDir string
// Ephemeral, if true, keeps the cluster only in memory (no host persistence).
Ephemeral bool
// Database to connect to. Defaults to "template1".
Database string
}
Config configures a DB. The zero value is usable: it looks for wasm assets in "./wasm", persists the cluster under the user cache dir, and uses template1.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is an embedded PostgreSQL cluster backed by an in-memory filesystem.
A DB is safe for concurrent use: query execution is serialized (the WASM backend is single-threaded and the in-memory cluster is shared), so callers (including database/sql's pool) block rather than race.
func (*DB) Close ¶
Close ends the backend session, syncs the cluster to the host, and releases resources.
func (*DB) Exec ¶
Exec runs sql for its side effects and returns the command tag (e.g. "INSERT 0 1"). Use the Rows.AffectedRows from Query for a numeric count.
func (*DB) Query ¶
Query runs sql via the simple query protocol on the persistent backend and returns its rows. Session state (open transaction, temp tables, SET) persists across calls, so BEGIN in one Query and COMMIT in a later one form a single transaction.
func (*DB) QueryParams ¶
QueryParams runs sql with bind parameters via the extended query protocol (a real server-side prepared statement). Values are given as their text encodings; a true entry in isNull sends SQL NULL for that position.
func (*DB) ServeConn ¶ added in v0.2.0
ServeConn speaks the PostgreSQL v3 frontend/backend protocol to a single client over conn, relaying the client's messages to the embedded backend and the backend's responses back to the client. It lets ordinary PostgreSQL clients (psql, pgx, lib/pq, JDBC, …) talk to the in-process cluster over a real socket — e.g. in an Accept loop:
ln, _ := net.Listen("tcp", "127.0.0.1:5432")
for {
c, err := ln.Accept()
if err != nil {
return err
}
go db.ServeConn(c)
}
The embedded cluster has exactly one persistent backend session, so ServeConn does not open a new one per client: it answers the startup handshake itself (AuthenticationOk, a synthetic set of ParameterStatus values, BackendKeyData, ReadyForQuery — authentication is always trust) and then shuttles protocol messages to and from that single shared session. The SSL/GSS negotiation and StartupMessage are handled before the backend lock is taken, so a concurrently connecting client can finish its handshake; from the startup reply onward ServeConn holds the DB's backend exclusively for the rest of conn's lifetime, so other ServeConn calls and Query/Exec/QueryParams block there until the served client disconnects.
A client Terminate ('X') ends only that client; it is never forwarded to the shared backend. ServeConn closes conn before returning.
type Rows ¶
type Rows struct {
Columns []string // column names, in order
TypeOIDs []uint32 // PostgreSQL type OID per column
// Rows is row-major, one []any per row. Each value is a decoded Go value —
// int64, float64, bool, []byte, string, or nil (SQL NULL) — chosen by the
// column's type OID. Common numeric/bool/bytea types are received in binary
// format (extended-protocol queries); everything else arrives as text and is
// returned as a string.
Rows [][]any
Command string // CommandComplete tag, e.g. "INSERT 0 1", "SELECT 3"
AffectedRows int64 // rows affected/returned, parsed from Command
}
Rows is the structured result of a query, decoded from the PostgreSQL wire protocol.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
pglite
command
Command pglite is a small demo of the embedded PostgreSQL library: it opens a cluster (initdb on first run, load-and-skip-initdb after) and runs a query.
|
Command pglite is a small demo of the embedded PostgreSQL library: it opens a cluster (initdb on first run, load-and-skip-initdb after) and runs a query. |
|
wasmpass
command
Command wasmpass rewrites the PGlite Emscripten wasm into a standalone module that goccy/wasm2go can translate into a self-contained, panic-free Go package.
|
Command wasmpass rewrites the PGlite Emscripten wasm into a standalone module that goccy/wasm2go can translate into a self-contained, panic-free Go package. |
|
Package emscripten provides host function implementations for Emscripten-compiled WASM modules, specifically the syscall layer that wazero's built-in emscripten support does not cover.
|
Package emscripten provides host function implementations for Emscripten-compiled WASM modules, specifically the syscall layer that wazero's built-in emscripten support does not cover. |
|
internal
|
|
|
fetchwasm
command
Command fetchwasm downloads the pinned PGlite wasm artifacts into ./wasm.
|
Command fetchwasm downloads the pinned PGlite wasm artifacts into ./wasm. |
|
genaot
command
Command genaot emits the AOT glue for a goccy/wasm2go-transpiled PGlite package: the AOTModule shim (NewAOT + the emscripten.AOTModule methods) and the env/WASI host adapter.
|
Command genaot emits the AOT glue for a goccy/wasm2go-transpiled PGlite package: the AOTModule shim (NewAOT + the emscripten.AOTModule methods) and the env/WASI host adapter. |
|
pgassets
Package pgassets fetches the PGlite wasm artifacts (pglite.wasm, initdb.wasm, pglite.data, and the derived pglite.manifest.json) from the jsDelivr CDN mirror of the @electric-sql/pglite npm package.
|
Package pgassets fetches the PGlite wasm artifacts (pglite.wasm, initdb.wasm, pglite.data, and the derived pglite.manifest.json) from the jsDelivr CDN mirror of the @electric-sql/pglite npm package. |
|
wasmpass
Package wasmpass rewrites an Emscripten (dynamic-linked, longjmp-via-host) wasm module into a standalone module that goccy/wasm2go can translate into a self-contained, panic-free Go package.
|
Package wasmpass rewrites an Emscripten (dynamic-linked, longjmp-via-host) wasm module into a standalone module that goccy/wasm2go can translate into a self-contained, panic-free Go package. |
|
Package pgdriver registers a database/sql driver named "pglite" backed by the embedded PGlite/PostgreSQL library.
|
Package pgdriver registers a database/sql driver named "pglite" backed by the embedded PGlite/PostgreSQL library. |
|
Package vfs implements a virtual filesystem for use with Emscripten-compiled WASM modules.
|
Package vfs implements a virtual filesystem for use with Emscripten-compiled WASM modules. |