mongreldb

package module
v0.67.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0, MIT Imports: 12 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.

README

MongrelDB logo

MongrelDB Go Client

Pure Go client for MongrelDB - embedded+server database with SQL, vector search, full-text search, and AI-native retrieval.
No cgo and no external dependencies - built on the standard library net/http. The API mirrors the MongrelDB PHP client.

Go Reference Go Report Card CI License

Package

Surface Package Install
Go client github.com/visorcraft/mongreldb-go go get github.com/visorcraft/mongreldb-go

Requirements

What It Provides

  • Typed CRUD over the Kit transaction endpoint: Put, Upsert (insert-or-update on PK conflict), Delete by row id or primary key, all with optional idempotency keys for safe retries.
  • Fluent query builder that pushes conditions down to the engine's specialized indexes for sub-millisecond lookups: bitmap equality/IN, learned-range, null checks, FM-index full-text search, HNSW vector similarity (ann), and sparse vector match. Friendly aliases (column → column_id, min/max → lo/hi) are translated to the server's on-wire keys.
  • Idempotent batch transactions - operations staged locally and committed atomically, with the engine enforcing unique, foreign-key, and check constraints at commit time. Idempotency keys return the original response on duplicate commits, even after a crash.
  • Full SQL access through the DataFusion-backed /sql endpoint: recursive CTEs, window functions, CREATE TABLE AS SELECT, materialized views, and multi-statement execution.
  • Schema management: typed table creation, full schema catalog, and per-table descriptors.
  • User/role/credentials management via SQL: Argon2id-hashed catalog users, roles, and GRANT/REVOKE table-level permissions, all executed through SQL.
  • Maintenance: compaction (all tables or per-table).
  • Pluggable transport: bring your own *http.Client, or set a per-request timeout. Bearer token and HTTP Basic auth are first-class options.
  • Typed errors: ErrAuth (401/403), ErrNotFound (404), ErrConflict (409, with error code + op index), and ErrQuery (everything else), all exposed as errors.Is-matchable sentinels plus a *ResponseError carrying the status code and decoded server envelope.

Examples

Task-focused, commented guides live in docs/:

  • Quickstart - install, start the daemon, write and run a complete program.
  • Transactions - batch commits, idempotency keys, constraint handling.
  • Queries - every native condition type and the index it pushes down to.
  • SQL - recursive CTEs, window functions, advanced SQL.
  • Authentication - Bearer token, HTTP Basic, and open modes.
  • Errors - sentinel errors, *ResponseError, and recovery patterns.

Quick Example

package main

import (
	"context"
	"fmt"
	"log"

	mdb "github.com/visorcraft/mongreldb-go"
)

func main() {
	ctx := context.Background()

	// Connect to a running mongreldb-server daemon.
	db := mdb.NewClient("http://127.0.0.1:8453")

	// Create a table. Column ids are stable on-wire identifiers.
	db.CreateTable(ctx, "orders", []mdb.Column{
		{ID: 1, Name: "id", Type: "int64", PrimaryKey: true, Nullable: false},
		{ID: 2, Name: "customer", Type: "varchar", PrimaryKey: false, Nullable: false},
		{ID: 3, Name: "amount", Type: "float64", PrimaryKey: false, Nullable: false},
	})

	// Insert rows (cells map column id -> value).
	db.Put(ctx, "orders", mdb.Cells{1: int64(1), 2: "Alice", 3: 99.50}, "")
	db.Put(ctx, "orders", mdb.Cells{1: int64(2), 2: "Bob", 3: 150.00}, "")

	// Upsert (insert or update on PK conflict).
	db.Upsert(ctx, "orders",
		mdb.Cells{1: int64(1), 2: "Alice", 3: 120.00},
		mdb.Cells{3: 120.00}, "")

	// Query with a native index condition (learned-range index).
	rows, err := db.Query("orders").
		Where("range", map[string]any{"column": int64(3), "min": 100.0}).
		Projection([]int64{1, 2}).
		Limit(100).
		Execute(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("rows:", len(rows))

	n, _ := db.Count(ctx, "orders")
	fmt.Println("count:", n) // 2

	// Run SQL.
	db.SQL(ctx, "UPDATE orders SET amount = 200.0 WHERE customer = 'Bob'")
}

Authentication

// Bearer token (--auth-token mode)
db := mdb.NewClient("http://127.0.0.1:8453", mdb.WithToken("my-secret-token"))

// HTTP Basic (--auth-users mode)
db := mdb.NewClient("http://127.0.0.1:8453", mdb.WithBasicAuth("admin", "s3cret"))

// Custom transport / timeout
db := mdb.NewClient("http://127.0.0.1:8453",
	mdb.WithHTTPClient(&http.Client{Timeout: 60 * time.Second}))

Batch transactions

Operations are staged locally and committed atomically. The engine enforces unique, foreign-key, and check constraints at commit time. Pass an optional constraints map to CreateTable to provision engine checks in the same call.

Column.DefaultValueJSON preserves a static JSON scalar and takes precedence over legacy string DefaultValue. DefaultExpr selects dynamic "now" or "uuid" defaults and takes precedence server-side. Explicit null is representable with json.RawMessage("null"); a literal "now" string default must use DefaultValueJSON, not DefaultExpr.

checks := map[string]any{"checks": []any{
	map[string]any{"id": 1, "name": "id_present", "expr": map[string]any{"IsNotNull": 1}},
}}
_, err := db.CreateTable(ctx, "orders", cols, checks)
txn := db.Begin()
txn.Put("orders", mdb.Cells{1: int64(10), 2: "Dave", 3: 50.00}, false)
txn.Put("orders", mdb.Cells{1: int64(11), 2: "Eve", 3: 75.00}, false)
txn.DeleteByPK("orders", int64(2))

results, err := txn.Commit(ctx, "") // atomic - all or nothing
if err != nil {
	// A constraint violation rolls back every op.
	var re *mdb.ResponseError
	if errors.As(err, &re) && re.Code == "UNIQUE_VIOLATION" {
		log.Println("duplicate:", re.Message, "at op", re.OpIndex)
	}
	_ = txn.Rollback() // discard locally as well
}
_ = results

// Idempotent commit - safe to retry; the daemon returns the original response.
txn2 := db.Begin()
txn2.Put("orders", mdb.Cells{1: int64(20), 2: "Frank", 3: 100.00}, false)
txn2.Commit(ctx, "order-20-create")

Native query builder

Conditions push down to the engine's specialized indexes. The builder accepts friendly aliases that are translated to the server's on-wire keys: column (→ column_id), min/max (→ lo/hi). The canonical keys are also accepted directly.

// Bitmap equality (low-cardinality columns).
db.Query("orders").Where("bitmap_eq", map[string]any{"column": int64(2), "value": "Alice"}).Execute(ctx)

// Range query (learned-range index).
db.Query("orders").
	Where("range", map[string]any{"column": int64(3), "min": 50.0, "max": 150.0}).
	Limit(100).Execute(ctx)

// Full-text search (FM-index).
db.Query("documents").
	Where("fm_contains", map[string]any{"column": int64(2), "pattern": "database performance"}).
	Limit(10).Execute(ctx)

// Vector similarity search (HNSW).
db.Query("embeddings").
	Where("ann", map[string]any{"column": int64(2), "query": []float32{0.1, 0.2, 0.3}, "k": 10}).
	Execute(ctx)

// Check whether a result was capped by the limit.
q := db.Query("orders").Where("range", map[string]any{"column": int64(3), "min": int64(0)}).Limit(100)
rows, _ := q.Execute(ctx)
if q.Truncated() {
	// result set hit the limit; more matches exist on the server
}
_ = rows

SQL

db.SQL(ctx, "INSERT INTO orders (id, customer, amount) VALUES (99, 'Zoe', 999.0)")
db.SQL(ctx, "CREATE TABLE archive AS SELECT * FROM orders WHERE amount > 500")

// Recursive CTEs and window functions
db.SQL(ctx, "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM r WHERE n<10) SELECT n FROM r")
db.SQL(ctx, "SELECT id, ROW_NUMBER() OVER (PARTITION BY customer ORDER BY amount DESC) FROM orders")

ANN index backends

The engine's ann index is swappable across three backends - hnsw (the default), diskann, and ivf - selected with the algorithm option. Quantization is independently configurable: dense, binary_sign, or product (product quantization, with num_subvectors, bits_per_subvector, pq_training_samples, pq_seed, and pq_rerank_factor). These are ordinary DDL strings run through sql, so no client changes are needed.

// DiskANN (in-memory Vamana graph)
db.SQL(ctx, "CREATE INDEX orders_emb_diskann ON orders USING ann (embedding) WITH (algorithm = 'diskann', quantization = 'dense', diskann_l = 50, diskann_r = 64, beam_width = 8)")

// IVF with dense vectors (clustered)
db.SQL(ctx, "CREATE INDEX orders_emb_ivf ON orders USING ann (embedding) WITH (algorithm = 'ivf', quantization = 'dense', nlist = 1024, nprobe = 16)")

// HNSW with product quantization (recall-tuned)
db.SQL(ctx, "CREATE INDEX orders_emb_hnsw_pq ON orders USING ann (embedding) WITH (algorithm = 'hnsw', quantization = 'product', m = 16, ef_construction = 200, ef_search = 50, num_subvectors = 32, pq_training_samples = 50000, pq_rerank_factor = 8)")

History retention and time travel

The daemon keeps a sliding window of historical commit epochs. Use the retention API to control how far back AS OF EPOCH SQL queries can read. The routes are database-wide and require ADMIN permission when the daemon runs with auth.

ret, err := db.SetHistoryRetentionEpochs(ctx, 1000)
if err != nil {
    log.Fatal(err)
}
fmt.Println("window:", ret.HistoryRetentionEpochs)
fmt.Println("earliest:", ret.EarliestRetainedEpoch)

// Read a previous version of the table.
rows, _ := db.SQL(ctx, "SELECT value FROM orders AS OF EPOCH 42 WHERE id = 1")

Increasing the retention window prevents newly written epochs from being reclaimed; it cannot restore history that has already been pruned, so EarliestRetainedEpoch never moves backward.

User & role management

User, role, and permission management is performed through SQL against the daemon's catalog. Passwords are Argon2id-hashed server-side.

db.SQL(ctx, "CREATE USER admin WITH PASSWORD 's3cret-pw'")
db.SQL(ctx, "ALTER USER admin SET ADMIN TRUE")

db.SQL(ctx, "CREATE ROLE analyst")
db.SQL(ctx, "GRANT select ON orders TO analyst") // table-level permission
db.SQL(ctx, "GRANT analyst TO alice")

db.SQL(ctx, "SELECT username FROM catalog.users") // list users
db.SQL(ctx, "SELECT name FROM catalog.roles")     // list roles

Error handling

Every non-2xx response is mapped to a typed error. Match with errors.Is for the category, or errors.As into a *ResponseError for the status code and the server's decoded error envelope.

_, err := db.SchemaFor(ctx, "missing_table")
switch {
case errors.Is(err, mdb.ErrNotFound):
	log.Println("not found")
case errors.Is(err, mdb.ErrConflict):
	var re *mdb.ResponseError
	errors.As(err, &re)
	log.Printf("constraint %s at op %d", re.Code, re.OpIndex)
case errors.Is(err, mdb.ErrAuth):
	log.Println("not authorized")
case errors.Is(err, mdb.ErrQuery):
	log.Println("query/server error")
}

// Or inspect directly:
var re *mdb.ResponseError
if errors.As(err, &re) {
	fmt.Println(re.Status, re.Code, re.Message) // e.g. 404 NOT_FOUND no such table
}

API reference

Client

Method Description
NewClient(url string, opts ...Option) *Client Construct a client (url defaults to http://127.0.0.1:8453)
WithToken, WithBasicAuth, WithHTTPClient, WithTimeout Options: Bearer token, Basic auth, custom *http.Client, request timeout
Health(ctx) (bool, error) Check daemon health
TableNames(ctx) ([]string, error) List table names
CreateTable(ctx, name, columns, constraints...) (int64, error) Create a table, optionally attach engine constraints; returns the table id
CreateTableWithOptions(ctx, name, columns, options) (int64, error) Create a table with typed index options and embedding sources
DropTable(ctx, name) error Drop a table
Count(ctx, table) (int64, error) Row count
Put(ctx, table, cells, idempotencyKey) (map[string]any, error) Insert a row
Upsert(ctx, table, cells, updateCells, key) (map[string]any, error) Upsert a row
Delete(ctx, table, rowID) error Delete by row id
DeleteByPK(ctx, table, pk) error Delete by primary key
Query(table) *QueryBuilder Start a native query
SQL(ctx, sql) ([]map[string]any, error) Execute SQL
Schema(ctx) (map[string]map[string]any, error) Full schema catalog
SchemaFor(ctx, table) (map[string]any, error) Single-table descriptor
HistoryRetention(ctx) (HistoryRetention, error) Get both retention values
SetHistoryRetentionEpochs(ctx, epochs) (HistoryRetention, error) Set the durable history-retention window
HistoryRetentionEpochs(ctx) (uint64, error) Current retention window size in epochs
EarliestRetainedEpoch(ctx) (uint64, error) Earliest epoch still readable via AS OF EPOCH
Compact(ctx) (map[string]any, error) Compact all tables
CompactTable(ctx, name) (map[string]any, error) Compact one table
Begin() *Transaction Start a batch

QueryBuilder

Method Description
Where(type, params) *QueryBuilder Add a native condition (AND-ed)
Projection(columnIDs []int64) *QueryBuilder Set column projection
Limit(limit int64) *QueryBuilder Set row limit
Offset(offset int64) *QueryBuilder Skip matching rows before the limit
Build() map[string]any Build the request payload
Execute(ctx) ([]map[string]any, error) Run the query
Truncated() bool Whether the last Execute result hit the limit

Transaction

Method Description
Put(table, cells, returning) *Transaction Stage an insert
Upsert(table, cells, updateCells, returning) *Transaction Stage an upsert
Delete(table, rowID) *Transaction Stage a delete by row id
DeleteByPK(table, pk) *Transaction Stage a delete by primary key
Count() int Number of staged operations
Commit(ctx, idempotencyKey) ([]map[string]any, error) Commit atomically
Rollback() error Discard all operations

Building and testing

The test suite is a live integration suite: it boots a real mongreldb-server daemon and exercises the full client surface against it. It skips automatically when no daemon is available.

go build ./...
go vet ./...

# Run the offline unit tests (no daemon needed):
go test -short ./...

# Run the full live suite. The harness boots mongreldb-server itself if it can
# find the binary (in this order):
#   1. the MONGRELDB_SERVER env var
#   2. ./bin/mongreldb-server
#   3. mongreldb-server on PATH
# Or point it at an already-running daemon with MONGRELDB_URL.
MONGRELDB_SERVER=./bin/mongreldb-server go test -v ./...

Fetch a prebuilt server binary from the MongrelDB releases:

mkdir -p bin
curl -fsSL -o bin/mongreldb-server \
  https://github.com/visorcraft/MongrelDB/releases/download/v0.67.1/mongreldb-server-linux-x64
chmod +x bin/mongreldb-server

Contributing

Contributions are welcome. Please:

  1. Open an issue first for non-trivial changes.
  2. Add focused tests near your change - the suite must stay green.
  3. Run gofmt -l . and go vet ./... before submitting.
  4. Keep the client cgo-free and dependency-free (standard library only).
  • Mongrel — Commercial multi-system workbench with native MongrelDB support.
  • MongrelDB Viewer — Free, open-source MongrelDB GUI and MCP server.

License

Dual-licensed under the MIT License or the Apache License, Version 2.0, at your option. See MIT OR Apache-2.0 for the full text.

SPDX-License-Identifier: MIT OR Apache-2.0

Documentation

Overview

Package mongreldb is the pure-Go HTTP client for MongrelDB.

It talks to a running mongreldb-server daemon's JSON API over the standard library net/http client - no cgo, no external dependencies. The surface mirrors the MongrelDB PHP client: typed CRUD, a fluent query builder that pushes conditions down to the engine's native indexes, idempotent batch transactions, full SQL access, and schema introspection.

Connect with NewClient and a base URL:

db := mongreldb.NewClient("http://127.0.0.1:8453")
ok, _ := db.Health(context.Background())

Index

Constants

View Source
const DefaultBaseURL = "http://127.0.0.1:8453"

DefaultBaseURL is the daemon address used when none is supplied.

View Source
const MaxResponseBytes int64 = 268435456

MaxResponseBytes caps the size of a response body read from the daemon (256 MB). Bodies larger than this are aborted with a wrapped ErrQuery to guard client memory against a malicious or buggy server.

View Source
const Version = "0.67.1"

Version is the client library version (aligned with the MongrelDB train).

Variables

View Source
var (
	// ErrNotFound is returned for HTTP 404 responses (missing table, schema, etc.).
	ErrNotFound = errors.New("mongreldb: not found")
	// ErrConflict is returned for HTTP 409 responses (unique, foreign key, check,
	// or trigger constraint violations).
	ErrConflict = errors.New("mongreldb: constraint conflict")
	// ErrAuth is returned for HTTP 401 or 403 responses (bad or missing credentials).
	ErrAuth = errors.New("mongreldb: authentication failed")
	// ErrQuery is returned for HTTP 400 or 5xx responses and for any other
	// request-level failure not covered by the more specific sentinels.
	ErrQuery = errors.New("mongreldb: query failed")
)

Typed client errors. Each sentinel corresponds to a class of HTTP status returned by the daemon. Use errors.Is to discriminate:

switch {
case errors.Is(err, mongreldb.ErrNotFound):  ...
case errors.Is(err, mongreldb.ErrConflict):  ...
case errors.Is(err, mongreldb.ErrAuth):      ...
case errors.Is(err, mongreldb.ErrQuery):     ...
}
View Source
var ErrTxnCommitted = errors.New("mongreldb: transaction already committed")

ErrTxnCommitted is returned when Transaction.Commit or Transaction.Rollback is called on a transaction that has already been committed.

Functions

func BuildRetrieveTextRequest added in v0.64.2

func BuildRetrieveTextRequest(table string, embeddingColumn uint16, text string, opts RetrieveTextOptions) (map[string]any, error)

BuildRetrieveTextRequest returns the JSON body for POST /kit/retrieve_text.

Types

type AnnIndexOptions added in v0.62.0

type AnnIndexOptions struct {
	M              int             `json:"m,omitempty"`
	EFConstruction int             `json:"ef_construction,omitempty"`
	EFSearch       int             `json:"ef_search,omitempty"`
	Quantization   string          `json:"quantization,omitempty"`
	Algorithm      string          `json:"algorithm,omitempty"`
	DiskANN        *DiskANNOptions `json:"diskann,omitempty"`
}

type Cells

type Cells map[int64]any

Cells is a column-id-to-value map. The client flattens it to the server's on-wire [col_id, value, col_id, value, ...] array before sending. Pair order is irrelevant - each value is preceded by its own column id.

type Client

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

Client is the MongrelDB HTTP client. Create one with NewClient and use its methods for health, table management, CRUD, query, SQL, and schema. A Client is safe for concurrent use by multiple goroutines once configured.

func NewClient

func NewClient(url string, opts ...Option) *Client

NewClient returns a Client for the daemon at url. If url is empty, DefaultBaseURL is used. Apply Option values for auth, timeouts, or a custom *http.Client.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the daemon base URL the client was configured with.

func (*Client) Begin

func (c *Client) Begin() *Transaction

Begin starts a new batch transaction.

func (*Client) CancelQuery added in v0.64.2

func (c *Client) CancelQuery(ctx context.Context, queryID string) (map[string]any, error)

CancelQuery requests cancellation of a running SQL query.

func (*Client) CommitTxn

func (c *Client) CommitTxn(ctx context.Context, ops []map[string]any, idempotencyKey string) ([]map[string]any, error)

CommitTxn sends a batch of staged operations atomically. Exposed for the Transaction type; returns the per-operation results array.

func (*Client) Compact

func (c *Client) Compact(ctx context.Context) (map[string]any, error)

Compact merges sorted runs across all tables.

func (*Client) CompactTable

func (c *Client) CompactTable(ctx context.Context, table string) (map[string]any, error)

CompactTable merges sorted runs for a single table.

func (*Client) Count

func (c *Client) Count(ctx context.Context, table string) (int64, error)

Count returns the row count for a table.

func (*Client) CreateTable

func (c *Client) CreateTable(ctx context.Context, name string, columns []Column, constraints ...map[string]any) (int64, error)

CreateTable creates a table named name with the given columns and returns the assigned table id. Pass at most one constraints map to attach engine constraints such as {"checks": [...]}.

func (*Client) CreateTableWithOptions added in v0.62.0

func (c *Client) CreateTableWithOptions(ctx context.Context, name string, columns []Column, options CreateTableOptions) (int64, error)

CreateTableWithOptions creates a table with constraints and full index definitions.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, table string, rowID int64) error

Delete removes a row by its internal row id.

func (*Client) DeleteByPK

func (c *Client) DeleteByPK(ctx context.Context, table string, pk any) error

DeleteByPK removes a row by its primary-key value.

func (*Client) DropTable

func (c *Client) DropTable(ctx context.Context, name string) error

DropTable drops a table by name.

func (*Client) EarliestRetainedEpoch

func (c *Client) EarliestRetainedEpoch(ctx context.Context) (uint64, error)

EarliestRetainedEpoch returns the earliest epoch still available for time-travel queries. Increasing the retention window cannot move this value backward.

func (*Client) Health

func (c *Client) Health(ctx context.Context) (bool, error)

Health reports whether the daemon is reachable and healthy. A network failure returns (false, nil) so callers can treat "unhealthy" uniformly; context cancellation still propagates as an error.

func (*Client) HistoryRetention

func (c *Client) HistoryRetention(ctx context.Context) (HistoryRetention, error)

HistoryRetention returns the current retention state from GET /history/retention.

func (*Client) HistoryRetentionEpochs

func (c *Client) HistoryRetentionEpochs(ctx context.Context) (uint64, error)

HistoryRetentionEpochs returns the current history_retention_epochs value.

func (*Client) Put

func (c *Client) Put(ctx context.Context, table string, cells Cells, idempotencyKey string) (map[string]any, error)

Put inserts a row. idempotencyKey, if non-empty, makes the commit safe to retry - the daemon returns the original result on duplicate commits.

Returns the per-operation result object (the first element of the server's results array).

func (*Client) Query

func (c *Client) Query(table string) *QueryBuilder

Query starts a fluent QueryBuilder against table.

func (*Client) QueryStatus added in v0.64.2

func (c *Client) QueryStatus(ctx context.Context, queryID string) (*QueryStatus, error)

QueryStatus fetches retained SQL execution status for durable recovery.

func (*Client) RetrieveText added in v0.64.2

func (c *Client) RetrieveText(ctx context.Context, table string, embeddingColumn uint16, text string, opts RetrieveTextOptions) (*TextRetrieveResult, error)

RetrieveText embeds text under the active semantic identity for embeddingColumn and runs ANN retrieval (POST /kit/retrieve_text).

func (*Client) SQL

func (c *Client) SQL(ctx context.Context, sql string) ([]map[string]any, error)

SQL executes a SQL statement via the /sql endpoint, requesting JSON output. The server returns a JSON array of row objects keyed by column name, e.g. [{"id": 1, "name": "Alice", "score": 95.5}]. For statements that yield no rows (DDL/DML), the body is empty and an empty slice is returned.

Integers in each row are decoded as json.Number (not float64) via encoding/json.Decoder.UseNumber, preserving precision for large table ids or counts that would otherwise lose accuracy in a float64.

func (*Client) Schema

func (c *Client) Schema(ctx context.Context) (map[string]map[string]any, error)

Schema returns the full schema catalog: a table-name-to-descriptor map.

func (*Client) SchemaFor

func (c *Client) SchemaFor(ctx context.Context, table string) (map[string]any, error)

SchemaFor returns the descriptor for a single table.

func (*Client) Search added in v0.62.0

func (c *Client) Search(table string) *SearchBuilder

Search starts a hybrid search against table.

func (*Client) SetHistoryRetentionEpochs

func (c *Client) SetHistoryRetentionEpochs(ctx context.Context, epochs uint64) (HistoryRetention, error)

SetHistoryRetentionEpochs sets the database-wide history retention window to epochs and returns the post-update retention state. The call maps to PUT /history/retention with body {"history_retention_epochs": epochs}.

func (*Client) TableNames

func (c *Client) TableNames(ctx context.Context) ([]string, error)

TableNames lists all table names in the database.

func (*Client) Upsert

func (c *Client) Upsert(ctx context.Context, table string, cells Cells, updateCells Cells, idempotencyKey string) (map[string]any, error)

Upsert inserts a row, or updates it on a primary-key conflict. updateCells, when non-nil, supplies the values written on conflict (nil means DO NOTHING).

type Column

type Column struct {
	ID           int64    `json:"id"`
	Name         string   `json:"name"`
	Type         string   `json:"ty"`
	PrimaryKey   bool     `json:"primary_key"`
	Nullable     bool     `json:"nullable"`
	EnumVariants []string `json:"enum_variants,omitempty"`
	DefaultValue *string  `json:"default_value,omitempty"`
	// DefaultValueJSON preserves a static JSON scalar. It takes precedence over
	// the legacy string-only DefaultValue field.
	DefaultValueJSON any     `json:"-"`
	DefaultExpr      *string `json:"default_expr,omitempty"`
	// EmbeddingSource is the portable model/source descriptor for embedding columns.
	EmbeddingSource any `json:"embedding_source,omitempty"`
}

Column describes one column in a CREATE TABLE request. The struct is sent to the server verbatim; the JSON tags mirror the daemon's table-create extractor. Optional fields are emitted only when set.

func (Column) MarshalJSON

func (c Column) MarshalJSON() ([]byte, error)

type CommitHlc added in v0.64.2

type CommitHlc struct {
	PhysicalMicros uint64 `json:"physical_micros"`
	Logical        uint32 `json:"logical"`
	NodeTiebreaker uint32 `json:"node_tiebreaker"`
}

CommitHlc is the structural hybrid logical clock from durable recovery (0.64+).

type CreateTableOptions added in v0.62.0

type CreateTableOptions struct {
	Constraints map[string]any
	Indexes     []Index
}

type DiskANNOptions added in v0.63.0

type DiskANNOptions struct {
	R         int `json:"r,omitempty"`
	L         int `json:"l,omitempty"`
	BeamWidth int `json:"beam_width,omitempty"`
	Alpha     int `json:"alpha,omitempty"`
}

type DurableOutcome added in v0.64.2

type DurableOutcome struct {
	Committed                 *bool      `json:"committed"`
	CommittedStatements       *int       `json:"committed_statements"`
	LastCommitEpoch           *uint64    `json:"last_commit_epoch"`
	LastCommitEpochText       *string    `json:"last_commit_epoch_text"`
	LastCommitHlc             *CommitHlc `json:"last_commit_hlc"`
	FirstCommitStatementIndex *int       `json:"first_commit_statement_index"`
	LastCommitStatementIndex  *int       `json:"last_commit_statement_index"`
	CompletedStatements       *int       `json:"completed_statements"`
	StatementIndex            *int       `json:"statement_index"`
	Serialization             string     `json:"serialization"`
	SerializationState        string     `json:"serialization_state"`
	TerminalState             *string    `json:"terminal_state"`
}

DurableOutcome is the nested durable recovery payload on query status/cancel responses (parity with the server DurableOutcome / outcome JSON object).

type HistoryRetention

type HistoryRetention struct {
	HistoryRetentionEpochs uint64 `json:"history_retention_epochs"`
	EarliestRetainedEpoch  uint64 `json:"earliest_retained_epoch"`
}

HistoryRetention is the response shape for the /history/retention endpoint.

type Index added in v0.62.0

type Index struct {
	Name      string       `json:"name"`
	ColumnID  int64        `json:"column_id"`
	Kind      string       `json:"kind"`
	Predicate string       `json:"predicate,omitempty"`
	Options   IndexOptions `json:"options,omitempty"`
}

Index describes one of MongrelDB's six public secondary index kinds.

type IndexOptions added in v0.62.0

type IndexOptions struct {
	ANN          *AnnIndexOptions          `json:"ann,omitempty"`
	MinHash      *MinHashIndexOptions      `json:"minhash,omitempty"`
	LearnedRange *LearnedRangeIndexOptions `json:"learned_range,omitempty"`
}

type LearnedRangeIndexOptions added in v0.62.0

type LearnedRangeIndexOptions struct {
	Epsilon int `json:"epsilon,omitempty"`
}

type MinHashIndexOptions added in v0.62.0

type MinHashIndexOptions struct {
	Permutations int `json:"permutations,omitempty"`
	Bands        int `json:"bands,omitempty"`
}

type Option

type Option func(*Client)

Option configures a Client.

func WithBasicAuth

func WithBasicAuth(username, password string) Option

WithBasicAuth authenticates requests with HTTP Basic credentials (--auth-users mode). Ignored if WithToken is also supplied.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient installs a custom *http.Client (e.g. with a custom transport). Overrides WithTimeout. Passing nil is a no-op (keeps the default client).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout by configuring the underlying *http.Client. Overrides WithHTTPClient if called after it.

func WithToken

func WithToken(token string) Option

WithToken authenticates requests with a Bearer token (--auth-token mode). When set, it takes precedence over basic-auth credentials.

type QueryBuilder

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

QueryBuilder builds a request for the daemon's /kit/query endpoint, where conditions push down to the engine's specialized indexes for sub-millisecond lookups.

Condition parameters accept friendly aliases that are translated to the server's exact on-wire keys before sending (see QueryBuilder.Where):

  • column -> column_id
  • min / max -> lo / hi
  • min_inclusive -> lo_inclusive
  • max_inclusive -> hi_inclusive

The server's canonical keys are accepted directly too.

func (*QueryBuilder) Build

func (q *QueryBuilder) Build() map[string]any

Build returns the request payload that will be sent to /kit/query.

func (*QueryBuilder) Execute

func (q *QueryBuilder) Execute(ctx context.Context) ([]map[string]any, error)

Execute runs the query and returns the matching rows. It also records whether the result was truncated by the QueryBuilder.Limit; check it with QueryBuilder.Truncated.

func (*QueryBuilder) Limit

func (q *QueryBuilder) Limit(limit int64) *QueryBuilder

Limit caps the number of rows returned.

func (*QueryBuilder) Offset

func (q *QueryBuilder) Offset(offset int64) *QueryBuilder

Offset skips matching rows before applying the limit.

func (*QueryBuilder) Projection

func (q *QueryBuilder) Projection(columnIDs []int64) *QueryBuilder

Projection sets the column ids to return (nil means all columns).

func (*QueryBuilder) Truncated

func (q *QueryBuilder) Truncated() bool

Truncated reports whether the most recent QueryBuilder.Execute result was capped by the query limit. It returns false until Execute has been called.

func (*QueryBuilder) Where

func (q *QueryBuilder) Where(condType string, params map[string]any) *QueryBuilder

Where adds a native condition. Available condition types include:

  • pk exact primary-key match ({"value": pk})
  • bitmap_eq equality on a bitmap-indexed column
  • bitmap_in IN predicate on a bitmap-indexed column
  • range integer range predicate (lo/hi, inclusive)
  • range_f64 float range predicate (lo/hi + lo_inclusive/hi_inclusive)
  • is_null null check
  • is_not_null non-null check
  • fm_contains full-text substring search (FM-index)
  • fm_contains_all multiple substring patterns (all must match)
  • ann dense vector similarity search (HNSW)
  • sparse_match sparse vector match
  • min_hash_similar MinHash similarity search

Conditions are AND-ed. The builder returns itself for chaining.

type QueryStatus added in v0.64.2

type QueryStatus struct {
	QueryID             string          `json:"query_id"`
	Status              string          `json:"status"`
	State               string          `json:"state"`
	ServerState         string          `json:"server_state"`
	TerminalState       *string         `json:"terminal_state"`
	Operation           string          `json:"operation"`
	Committed           *bool           `json:"committed"`
	CommittedStatements *int            `json:"committed_statements"`
	LastCommitEpoch     *uint64         `json:"last_commit_epoch"`
	LastCommitEpochText *string         `json:"last_commit_epoch_text"`
	LastCommitHlc       *CommitHlc      `json:"last_commit_hlc"`
	FirstCommitStmtIdx  *int            `json:"first_commit_statement_index"`
	LastCommitStmtIdx   *int            `json:"last_commit_statement_index"`
	CompletedStatements *int            `json:"completed_statements"`
	StatementIndex      *int            `json:"statement_index"`
	CancelOutcome       *string         `json:"cancel_outcome"`
	CancellationReason  string          `json:"cancellation_reason"`
	Retryable           bool            `json:"retryable"`
	Outcome             DurableOutcome  `json:"outcome"`
	Durable             *DurableOutcome `json:"durable"`
	TerminalError       json.RawMessage `json:"terminal_error"`
	Trace               json.RawMessage `json:"trace"`
}

QueryStatus is GET /queries/{query_id} (SQL control / durable recovery).

func ParseQueryStatusJSON added in v0.64.2

func ParseQueryStatusJSON(data []byte) (*QueryStatus, error)

ParseQueryStatusJSON decodes a query-status body (test/helpers).

func (*QueryStatus) CommitHlc added in v0.64.2

func (s *QueryStatus) CommitHlc() *CommitHlc

CommitHlc returns the authoritative HLC from nested durable / outcome / top-level.

func (*QueryStatus) SerializationState added in v0.64.2

func (s *QueryStatus) SerializationState() string

SerializationState prefers nested durable/outcome serialization_state, then serialization.

type ResponseError

type ResponseError struct {
	// Status is the HTTP status code returned by the daemon.
	Status int
	// Message is the human-readable error message.
	Message string
	// Code is the server's structured error code, when present (e.g.
	// "UNIQUE_VIOLATION", "FK_VIOLATION").
	Code string
	// OpIndex is the offending operation index within a transaction, when the
	// server reports one (constraint violations during commit).
	OpIndex *int
	// contains filtered or unexported fields
}

ResponseError carries the HTTP status code and the server's decoded error envelope for a failed request. It wraps the relevant sentinel (ErrNotFound, ErrConflict, ErrAuth, or ErrQuery) so that both errors.Is(err, mongreldb.ErrXxx) and a type assertion (var re *mongreldb.ResponseError) work.

func (*ResponseError) Error

func (e *ResponseError) Error() string

Error implements the error interface.

func (*ResponseError) Unwrap

func (e *ResponseError) Unwrap() error

Unwrap allows errors.Is to match the wrapped sentinel.

type RetrieveTextOptions added in v0.64.2

type RetrieveTextOptions struct {
	K          int
	DeadlineMs *uint64
	MaxWork    *uint64
}

RetrieveTextOptions configures text → embed → ANN retrieve.

type SearchBuilder added in v0.62.0

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

SearchBuilder builds a request for the daemon's POST /kit/search endpoint: multi-retriever hybrid search with reciprocal-rank fusion and optional exact-vector rerank. This is the scored counterpart to QueryBuilder (which only AND-s conditions via /kit/query).

Wire format matches the server's KitSearchRequest (flattened retrievers, snake_case fusion/rerank tags) so HTTP language clients stay interchangeable.

func (*SearchBuilder) AnnRetriever added in v0.62.0

func (s *SearchBuilder) AnnRetriever(name string, columnID int64, query []float64, k int, weight float64) *SearchBuilder

AnnRetriever adds a dense ANN retriever (HNSW) over columnID. Wire: {"name","weight","ann":{"column_id","query","k"}} (flattened).

func (*SearchBuilder) Build added in v0.62.0

func (s *SearchBuilder) Build() (map[string]any, error)

Build returns the JSON body for POST /kit/search.

func (*SearchBuilder) Cursor added in v0.62.0

func (s *SearchBuilder) Cursor(cursor string) *SearchBuilder

Cursor continues a previous page from next_cursor.

func (*SearchBuilder) ExactRerank added in v0.62.0

func (s *SearchBuilder) ExactRerank(embeddingColumn int64, query []float64, metric string, candidateLimit int, weight float64) *SearchBuilder

ExactRerank enables exact float-vector rerank after fusion. metric is "cosine", "dot_product", or "euclidean".

func (*SearchBuilder) Execute added in v0.62.0

func (s *SearchBuilder) Execute(ctx context.Context) (*SearchResult, error)

Execute runs the hybrid search.

func (*SearchBuilder) Explain added in v0.62.0

func (s *SearchBuilder) Explain(on bool) *SearchBuilder

Explain requests server-side trace metadata when supported.

func (*SearchBuilder) Fusion added in v0.62.0

func (s *SearchBuilder) Fusion(constant uint32) *SearchBuilder

Fusion sets reciprocal-rank fusion (the only supported kind today).

func (*SearchBuilder) Limit added in v0.62.0

func (s *SearchBuilder) Limit(limit int) *SearchBuilder

Limit caps the number of final hits (default 10).

func (*SearchBuilder) MinHashRetriever added in v0.62.0

func (s *SearchBuilder) MinHashRetriever(name string, columnID int64, members []string, k int, weight float64) *SearchBuilder

MinHashRetriever adds a MinHash set-similarity retriever.

func (*SearchBuilder) Must added in v0.62.0

func (s *SearchBuilder) Must(condType string, params map[string]any) *SearchBuilder

Must adds a hard filter condition (same shapes as QueryBuilder.Where). Conditions are AND-ed against candidate rows.

func (*SearchBuilder) Projection added in v0.62.0

func (s *SearchBuilder) Projection(columnIDs []int64) *SearchBuilder

Projection restricts returned cell column ids.

func (*SearchBuilder) SparseRetriever added in v0.62.0

func (s *SearchBuilder) SparseRetriever(name string, columnID int64, terms [][2]float64, k int, weight float64) *SearchBuilder

SparseRetriever adds a sparse (SPLADE-style) retriever. terms are [token_id, weight] pairs.

type SearchResult added in v0.62.0

type SearchResult struct {
	Hits       []map[string]any
	Trace      any
	NextCursor string
}

SearchResult is the decoded /kit/search response.

type TextRetrieveResult added in v0.64.2

type TextRetrieveResult struct {
	Hits       []map[string]any `json:"hits"`
	Provenance map[string]any   `json:"provenance"`
}

TextRetrieveResult is POST /kit/retrieve_text (0.64+).

type Transaction

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

Transaction stages operations locally and commits them atomically in a single /kit/txn request. The engine enforces unique, foreign-key, check, and trigger constraints at commit time; on any violation all operations roll back and Commit returns a ResponseError wrapping ErrConflict.

A Transaction is not safe to reuse after Commit; create a new one with Client.Begin.

func (*Transaction) Commit

func (t *Transaction) Commit(ctx context.Context, idempotencyKey string) ([]map[string]any, error)

Commit sends all staged operations atomically and returns the per-operation results. idempotencyKey, when non-empty, makes the commit safe to retry - the daemon returns the original response on duplicate commits.

Returns ErrTxnCommitted if called twice on the same transaction.

func (*Transaction) Count

func (t *Transaction) Count() int

Count returns the number of staged operations.

func (*Transaction) Delete

func (t *Transaction) Delete(table string, rowID int64) *Transaction

Delete stages a delete by the internal row id.

func (*Transaction) DeleteByPK

func (t *Transaction) DeleteByPK(table string, pk any) *Transaction

DeleteByPK stages a delete by primary-key value.

func (*Transaction) Put

func (t *Transaction) Put(table string, cells Cells, returning bool) *Transaction

Put stages an insert. returning, when true, asks the daemon to echo the row in the per-operation result.

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback discards all staged operations. Returns ErrTxnCommitted if the transaction was already committed.

func (*Transaction) Upsert

func (t *Transaction) Upsert(table string, cells Cells, updateCells Cells, returning bool) *Transaction

Upsert stages an insert-or-update. updateCells, when non-nil, supplies the values written on a primary-key conflict (nil means DO NOTHING).

Directories

Path Synopsis
examples
basic_crud command
Example: basic CRUD operations with the MongrelDB Go client.
Example: basic CRUD operations with the MongrelDB Go client.
query_builder command
Example: query builder conditions with the MongrelDB Go client.
Example: query builder conditions with the MongrelDB Go client.
transactions command
Example: atomic batch transactions with the MongrelDB Go client.
Example: atomic batch transactions with the MongrelDB Go client.

Jump to

Keyboard shortcuts

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