postgres

package
v1.0.45 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package postgres is go-api-boot's Postgres ORM: typed tables with SQL queries, plus vector search (pgvector) and BM25 term search (ParadeDB).

db, err := postgres.Open(ctx, os.Getenv("POSTGRES_URI"))
err = postgres.EnsureTable[Profile](ctx, db, tenant) // at deploy / startup

profiles := postgres.TableOf[Profile](db, tenant)
top, err := async.Await(profiles.
    Where("score > ?", 89).
    Where("city = ?", city).
    OrderBy("score DESC").
    Limit(10).
    Find(ctx))

Storage: a tenant is a schema and a model is a table "<tenant>"."<name>" (the model's CollectionName). Queries are SQL over its columns.

Columns: a model's exported struct fields map to columns.

  • the column name is the field's `db` tag, or the field name in snake_case; `db:"-"` skips the field;
  • fields of embedded structs without a `db` tag are flattened in;
  • the table must have an "id" text column (the primary key, written from the model's Id());
  • every table has bigint "created_on" and "updated_on" columns, which Save stamps; embed odm.Timestamps to read them.

Go types map to SQL types:

string text · bool boolean · int, int64, uint* bigint · int32 integer
int16, int8 smallint · float64 double precision · float32 real
time.Time timestamp with time zone · []byte bytea
slices of those scalars: arrays (text[], bigint[], ...)
[]float32 named by a VectorIndexSpec: vector(N) (halfvec(N) for scalar
quantization or more than 2000 dimensions)
anything else (structs, maps, other slices): jsonb, via encoding/json

Columns are NOT NULL with the type's zero value as default, so adding a field to a model adds a column existing rows can be read from. Pointer fields and vector columns are nullable.

Tables never change the schema at runtime: EnsureTable creates and migrates tables and indexes. Reads of a table that doesn't exist find nothing; writes to it fail.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPgSearchNotInstalled is returned (wrapped) when term search is used on
	// a database without ParadeDB's pg_search extension.
	ErrPgSearchNotInstalled = errors.New("term search needs ParadeDB's pg_search extension " +
		"(add pg_search to shared_preload_libraries and CREATE EXTENSION pg_search; see https://www.paradedb.com/docs)")

	// ErrVectorNotInstalled is returned (wrapped) when vector indexes are
	// declared on a database without the pgvector extension.
	ErrVectorNotInstalled = errors.New("vector search needs the pgvector extension " +
		"(CREATE EXTENSION vector; see https://github.com/pgvector/pgvector)")
)

Functions

func EnsureTable

func EnsureTable[T odm.Model](ctx context.Context, db *DB, tenant string) (err error)

EnsureTable creates T's table in tenant and reconciles it with the model. Run it when deploying or onboarding a tenant; it is idempotent and runs in one transaction.

Columns: missing ones are added (NOT NULL with the zero value as default, so existing rows stay readable). A column whose type no longer matches its field is an error, since changing it needs a data migration. Columns the model no longer has are left in place.

Indexes:

  • IndexSpecs become btree indexes over their key columns (TTL is unsupported);
  • TermSearchIndexSpecs become one ParadeDB index over all their text columns (needs pg_search, else ErrPgSearchNotInstalled);
  • VectorIndexSpecs become pgvector HNSW indexes on their vector column (needs pgvector, else ErrVectorNotInstalled). FilterPaths are MongoDB only; on Postgres, declare IndexSpecs for the columns you filter on.

Index names end in a hash of their definition. A changed definition creates a new index and drops the old one; indexes no longer declared are dropped. Indexes EnsureTable didn't create are left alone.

Types

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is a Postgres connection pool plus the ORM's settings.

func New

func New(p *pgxpool.Pool, opts ...Option) *DB

New wraps an existing pool. Close does not close it.

func Open

func Open(ctx context.Context, uri string, opts ...Option) (*DB, error)

Open connects to uri and pings the server.

func OpenFromEnv

func OpenFromEnv(ctx context.Context, opts ...Option) (*DB, error)

OpenFromEnv connects to the uri in POSTGRES_URI.

func (*DB) Close

func (db *DB) Close()

Close closes a pool opened by Open.

func (*DB) Pool

func (db *DB) Pool() *pgxpool.Pool

Pool returns the underlying pool, for SQL the ORM doesn't cover (extensions, migrations, COPY, batches, ...).

type Option

type Option func(*DB)

Option configures a DB.

func WithStemmer

func WithStemmer(language string) Option

WithStemmer sets the term search stemmer language (default "english"); "" disables stemming. It applies to indexes EnsureTable creates.

func WithTimer

func WithTimer(t odm.Timer) Option

WithTimer sets the clock Save stamps created_on and updated_on from.

type Table

type Table[T odm.Model] struct {
	// contains filtered or unexported fields
}

Table is a typed query over the table of T in one tenant. Build a query by chaining Where, OrderBy, Limit and Offset, then run it with a terminal method (Find, First, Count, Exists, Delete, VectorSearch, TermSearch):

top, err := async.Await(profiles.
    Where("score > ?", 89).
    Where("city = ?", city).
    OrderBy("score DESC").
    Limit(10).
    Find(ctx))

Conditions and orderings are SQL over the table's columns. Each ? is bound to the next argument, so values never become part of the SQL text; write ?? for a literal ? (the jsonb key-exists operator). Pass a slice to match a list: Where("city = ANY(?)", cities).

The SQL in Where and OrderBy is executed as written: it must come from your code, never from user input. Pass user values as arguments.

A Table is an immutable value: each builder method returns a new Table, so a base query can be shared and extended. Terminal methods run asynchronously and deliver one async.Result.

func TableOf

func TableOf[T odm.Model](db *DB, tenant string) Table[T]

TableOf returns the table of T in tenant (a Postgres schema).

func (Table[T]) Count

func (t Table[T]) Count(ctx context.Context) <-chan async.Result[int64]

Count counts the matching rows (within Limit and Offset, if set).

func (Table[T]) Delete

func (t Table[T]) Delete(ctx context.Context) <-chan async.Result[int64]

Delete deletes the matching rows and returns how many it deleted. It needs at least one Where (use Where("true") to delete every row) and no OrderBy, Limit or Offset.

func (Table[T]) DeleteByID

func (t Table[T]) DeleteByID(ctx context.Context, id string) <-chan async.Result[struct{}]

DeleteByID deletes the row with id (that also matches t's conditions), if there is one.

func (Table[T]) Exists

func (t Table[T]) Exists(ctx context.Context) <-chan async.Result[bool]

Exists reports whether any row matches.

func (Table[T]) Find

func (t Table[T]) Find(ctx context.Context) <-chan async.Result[[]T]

Find returns the matching rows.

func (Table[T]) FindByID

func (t Table[T]) FindByID(ctx context.Context, id string) <-chan async.Result[*T]

FindByID returns the row with id (that also matches t's conditions), or odm.ErrNotFound.

func (Table[T]) First

func (t Table[T]) First(ctx context.Context) <-chan async.Result[*T]

First returns the first matching row, or odm.ErrNotFound.

func (Table[T]) Limit

func (t Table[T]) Limit(n int) Table[T]

Limit returns at most n rows.

func (Table[T]) Offset

func (t Table[T]) Offset(n int) Table[T]

Offset skips the first n rows.

func (Table[T]) OrderBy

func (t Table[T]) OrderBy(orderings ...string) Table[T]

OrderBy adds orderings, e.g. OrderBy("score DESC", "id").

func (Table[T]) Save

func (t Table[T]) Save(ctx context.Context, model T) <-chan async.Result[struct{}]

Save inserts model, or replaces the row with the same Id. It sets created_on on insert and updated_on on every save (see odm.Timestamps). The query built on t doesn't apply.

It is a single upsert statement, so concurrent saves can't race. For a movie it runs:

INSERT INTO "tenant"."movies" ("id", "title", "year", ..., "created_on", "updated_on")
VALUES ($1, $2, $3, ..., $9, $10)
ON CONFLICT (id) DO UPDATE SET
  "title" = EXCLUDED."title",
  "year"  = EXCLUDED."year",
  ...,
  "updated_on" = EXCLUDED."updated_on"

EXCLUDED is the row that failed to insert. id and created_on are left out of the update list, so created_on keeps its first value.

func (Table[T]) TermSearch

func (t Table[T]) TermSearch(ctx context.Context, index odm.TermSearchIndexSpec, query string, limit int) <-chan async.Result[[]odm.SearchHit[T]]

TermSearch returns the limit rows best matching query (any of its words) in the columns of index, one of the model's TermSearchIndexSpecs, ranked by BM25, among the rows matching t's conditions. It needs ParadeDB's pg_search extension. OrderBy, Limit and Offset don't apply.

func (Table[T]) VectorSearch

func (t Table[T]) VectorSearch(ctx context.Context, index odm.VectorIndexSpec, embedding []float32, k int) <-chan async.Result[[]odm.SearchHit[T]]

VectorSearch returns the k rows nearest to embedding by index, one of the model's VectorIndexSpecs, best first, among the rows matching t's conditions. It runs a pgvector HNSW search; with conditions it scans the index iteratively (pgvector 0.8+) so that filtering doesn't return fewer than k rows. OrderBy, Limit and Offset don't apply.

Scores follow Atlas: cosine and dotProduct give (1 + similarity) / 2, euclidean gives 1 / (1 + distance).

func (Table[T]) Where

func (t Table[T]) Where(condition string, args ...any) Table[T]

Where adds a condition; conditions are combined with AND.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL