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 ¶
- Variables
- func EnsureTable[T odm.Model](ctx context.Context, db *DB, tenant string) (err error)
- type DB
- type Option
- type Table
- func (t Table[T]) Count(ctx context.Context) <-chan async.Result[int64]
- func (t Table[T]) Delete(ctx context.Context) <-chan async.Result[int64]
- func (t Table[T]) DeleteByID(ctx context.Context, id string) <-chan async.Result[struct{}]
- func (t Table[T]) Exists(ctx context.Context) <-chan async.Result[bool]
- func (t Table[T]) Find(ctx context.Context) <-chan async.Result[[]T]
- func (t Table[T]) FindByID(ctx context.Context, id string) <-chan async.Result[*T]
- func (t Table[T]) First(ctx context.Context) <-chan async.Result[*T]
- func (t Table[T]) Limit(n int) Table[T]
- func (t Table[T]) Offset(n int) Table[T]
- func (t Table[T]) OrderBy(orderings ...string) Table[T]
- func (t Table[T]) Save(ctx context.Context, model T) <-chan async.Result[struct{}]
- func (t Table[T]) TermSearch(ctx context.Context, index odm.TermSearchIndexSpec, query string, limit int) <-chan async.Result[[]odm.SearchHit[T]]
- func (t Table[T]) VectorSearch(ctx context.Context, index odm.VectorIndexSpec, embedding []float32, k int) <-chan async.Result[[]odm.SearchHit[T]]
- func (t Table[T]) Where(condition string, args ...any) Table[T]
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 OpenFromEnv ¶
OpenFromEnv connects to the uri in POSTGRES_URI.
type Option ¶
type Option func(*DB)
Option configures a DB.
func WithStemmer ¶
WithStemmer sets the term search stemmer language (default "english"); "" disables stemming. It applies to indexes EnsureTable creates.
type Table ¶
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 (Table[T]) Delete ¶
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 ¶
DeleteByID deletes the row with id (that also matches t's conditions), if there is one.
func (Table[T]) FindByID ¶
FindByID returns the row with id (that also matches t's conditions), or odm.ErrNotFound.
func (Table[T]) Save ¶
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).