tricoredb

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

tricoredb-sdk-go

Official Go client for TriCoreDB: SQL, documents, vectors, graphs and cache over one native connection.

Go Reference Go version License

  • No dependencies. It uses only the Go standard library.
  • Server-side parameters. Values never become part of the SQL text.
  • Typed errors that work with errors.Is and errors.As.
  • Transactions, connection pooling, TLS and mutual TLS.

Contents

Requirements

  • Go 1.21 or later
  • A TriCoreDB server speaking protocol 1.0 (tricore-server 0.1.0-rc.1 or later). See Running a server.

Installation

go get github.com/trinesh14/tricoredb-sdk-go
import tricoredb "github.com/trinesh14/tricoredb-sdk-go"

The package name is tricoredb.

Running a server

The quickest way is the official Docker image, trinesh14/tricoredb.

Local development (no TLS and no encryption, for this machine only). Set TRICORE_ADMIN_PASSWORD in your shell first. Then create the admin and start the server:

docker run --rm -v tricoredb-dev:/var/lib/tricoredb -e TRICORE_ADMIN_PASSWORD --entrypoint /usr/local/bin/tricore trinesh14/tricoredb:0.1.0-rc.1-r2 auth init-admin --user admin --password-env TRICORE_ADMIN_PASSWORD --data-dir /var/lib/tricoredb/data
docker run -d --name tricoredb-dev -p 127.0.0.1:8427:8427 -e TRICORE_TLS=off -e TRICORE_ENCRYPTION=off -e TRICORE_MODULES=all -v tricoredb-dev:/var/lib/tricoredb trinesh14/tricoredb:0.1.0-rc.1-r2

Anything else: by default the image runs with TLS on and an encrypted data volume. Follow the quick start on the Docker Hub page to create the certificate and key, then connect with TLS.

TRICORE_MODULES=all enables every data model. The image's default is sql, document and cache. A call to a disabled model returns a *ServerError whose Code is engine.disabled.

Quick start

package main

import (
	"context"
	"fmt"
	"log"

	tricoredb "github.com/trinesh14/tricoredb-sdk-go"
)

func main() {
	ctx := context.Background()
	db, err := tricoredb.Connect(ctx, tricoredb.Options{
		Host: "127.0.0.1", Port: 8427, User: "admin", Secret: "your-password",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if _, err := db.Execute("CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, name TEXT)"); err != nil {
		log.Fatal(err)
	}
	if _, err := db.ExecuteParams("INSERT INTO users VALUES (?, ?)", 1, "O'Hara"); err != nil {
		log.Fatal(err)
	}
	rows, err := db.QueryParams("SELECT name FROM users WHERE id = ?", 1)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rows.Columns, rows.Rows) // [name] [[O'Hara]]

	if err := db.CacheSet("sessions", "u1", []byte("token")); err != nil {
		log.Fatal(err)
	}
	v, found, err := db.CacheGet("sessions", "u1")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("found=%v value=%q\n", found, v)
}

Connecting

Connect opens one authenticated connection. Close releases it.

Options field Default Meaning
Host "127.0.0.1" Server host
Port 8427 (tricoredb.DefaultPort) Server port
User "" User name. Credentials are sent only when it is set.
Secret "" Password
Database "main" Database used by SQL calls
ClientName "tricoredb-go" Name reported to the server
DialTimeout driver default Time allowed to connect and complete the handshake
ReadTimeout 0 (none) Time allowed for each reply
TLS nil (plaintext) See TLS
Features all features Override the capability bitmap sent in the handshake

A *Client runs one request at a time: overlapping calls on the same client are refused instead of mixing their frames. For concurrent use, create a pool.

SQL

Query runs only SELECT. Execute runs everything else. The server enforces the split: a write sent through Query is refused.

_, err := db.Execute("INSERT INTO users VALUES (2, 'ada')")
rows, err := db.Query("SELECT id, name FROM users")
for _, r := range rows.Rows {
	fmt.Println(r) // []string, one entry per column in rows.Columns
}

QueryParams and ExecuteParams bind ? placeholders on the server. The values travel next to the statement, so a value can never be read as SQL syntax, however it is spelled. Use tricoredb.Decimal to keep exact digits.

Binding needs the SERVER_PARAMS capability, which is agreed in the handshake (db.ServerParamsGranted()). If the server did not grant it, these methods fail with ErrArgument before anything is sent. They never fall back to pasting values into the SQL text.

Transactions

There are two kinds, and they are not interchangeable.

Transaction sends a whole BEGIN … COMMIT script in one request. It works on every node and is the right choice when every statement is known up front:

res, err := db.Transaction(
	tricoredb.Stmt("UPDATE accounts SET balance = balance - ? WHERE id = ?", 10, 1),
	tricoredb.Stmt("UPDATE accounts SET balance = balance + ? WHERE id = ?", 10, 2),
)
// res.Outcome == "committed"

Begin, Commit and Rollback keep a transaction open across requests on this connection, so a later statement can depend on what an earlier one read. WithTransaction commits when the function returns nil and rolls back on an error or a panic:

err := db.WithTransaction(func(tx *tricoredb.Client) error {
	if _, err := tx.ExecuteParams("UPDATE accounts SET balance = balance - ? WHERE id = ?", 10, 1); err != nil {
		return err
	}
	_, err := tx.ExecuteParams("UPDATE accounts SET balance = balance + ? WHERE id = ?", 10, 2)
	return err
})

Session transactions need the SESSION_TXN capability (db.SessionTxnGranted()). Without it, Begin fails with ErrArgument rather than silently running each statement on its own. The transaction belongs to this connection: another connection cannot commit it, and a dropped connection rolls it back.

Connection pool

A pool is built from the same Options, so every pooled connection uses the same TLS settings.

pool, err := tricoredb.NewPool(tricoredb.Options{
	Host: "db.internal", Port: 8427, User: "admin", Secret: "your-password",
}, 8)
if err != nil {
	log.Fatal(err)
}
defer pool.Close()

err = pool.Use(ctx, func(c *tricoredb.Client) error {
	_, err := c.ExecuteParams("INSERT INTO users VALUES (?, ?)", 3, "grace")
	return err
})

Pool.Use never returns a connection with an open transaction to the pool. It rolls the transaction back first, and discards the connection if that rollback fails.

Cache

Values are byte slices. found tells a miss apart from an empty value.

db.CacheSet("sessions", "u1", []byte("token"))
db.CacheSetTTL("sessions", "u2", []byte("token"), 30_000) // expires in 30 s
v, found, err := db.CacheGet("sessions", "u1")
n, err := db.CacheIncr("counters", "hits", 1)

db.CacheLPush("queue", "jobs", []byte("a"), []byte("b"))
db.CacheSAdd("tags", "post:1", []byte("go"), []byte("db"))
db.CacheHSetText("user:1", "profile", map[string]string{"name": "ada"})
id, err := db.CacheXAddText("events", "log", map[string]string{"msg": "hi"}, "")
Family Methods
Keys CacheGet, CacheSet, CacheSetTTL, CacheSetNx, CacheDelete, CacheExists, CacheTTL, CacheExpire, CachePersist, CacheIncr, CacheKeys, CacheClearNamespace, CachePing
Lists CacheLPush, CacheRPush, CacheLPop, CacheRPop, CacheLRange, CacheLLen, CacheLIndex
Sets CacheSAdd, CacheSRem, CacheSIsMember, CacheSCard, CacheSMembers
Hashes CacheHSet, CacheHSetText, CacheHGet, CacheHDel, CacheHGetAll, CacheHExists, CacheHLen
Streams CacheXAdd, CacheXAddText, CacheXLen, CacheXRange, CacheXRead, CacheXDel, CacheXTrim

Documents

Filters and aggregation stages are built with helper functions (FilterEq, FilterGt, FilterAnd, StageMatch, StageGroup, …), so you never write the request JSON by hand.

db.DocumentCreateCollection("products")
id, err := db.DocumentInsert("products", map[string]any{"name": "widget", "price": 9})
doc, found, err := db.DocumentGet("products", id)
docs, err := db.DocumentFind("products", tricoredb.FilterGt("price", 5))
err = db.DocumentUpdateOne("products", id, tricoredb.DocumentUpdate{
	Inc: map[string]any{"price": 1},
})

Also available: DocumentInsertWithID, DocumentFindLimit, DocumentUpdate, DocumentUpsertOne, DocumentUpdateMany, DocumentDelete, DocumentListCollections, DocumentDropCollection, DocumentCreateIndex, DocumentDropIndex, DocumentListIndexes, DocumentAnalyze and DocumentAggregate.

Vectors

Fixed-dimension collections with cosine, dot or L2 distance, metadata filters and optional int8 quantization.

db.VectorCreateCollection("embeddings", 3, tricoredb.MetricCosine)
db.VectorUpsert("embeddings", "a", []float32{0.1, 0.2, 0.3}, map[string]any{"kind": "doc"})
res, err := db.VectorSearch("embeddings", []float32{0.1, 0.2, 0.3}, 5)
for _, hit := range res.Results {
	fmt.Println(hit.ID, hit.Score, hit.Metadata)
}

Also available: VectorCreateCollectionQuantized, VectorSearchFiltered, VectorGet, VectorDelete, VectorListCollections, VectorDescribeCollection, VectorListVectors and VectorDropCollection.

Graphs

Labelled nodes, typed edges, traversal, shortest paths and a read-only Cypher subset.

db.GraphCreate("social")
db.GraphAddNode("social", "u1", []string{"User"}, map[string]any{"name": "ada"})
db.GraphAddNode("social", "u2", []string{"User"}, nil)
db.GraphAddEdge("social", "e1", "u1", "u2", "FOLLOWS", nil)

neighbors, err := db.GraphNeighbors("social", "u1", tricoredb.NeighborOptions{
	Direction: tricoredb.DirectionOutgoing,
})
path, err := db.GraphShortestPath("social", "u1", "u2", tricoredb.PathOptions{})
// path.Found, path.Hops, path.NodePath

Also available: GraphGetNode, GraphGetEdge, GraphDeleteNode, GraphDeleteEdge, GraphList, GraphDrop, GraphTraverse, GraphWeightedShortestPath, GraphDegree, GraphListNodes, GraphListEdges and GraphQuery.

LLM context

Read-only export of query results and schema, in TOON, JSON, Markdown or the native format.

sources := []tricoredb.LlmSource{
	tricoredb.SQLSource("SELECT id, name FROM users"),
	tricoredb.DocumentFindSource("products", tricoredb.FilterAll(), 0),
}
bundle, err := db.LlmContext(sources, tricoredb.FormatTOON, nil)
schema, err := db.LlmSchema(tricoredb.FormatMarkdown, nil)

Admin

err := db.AdminPing()
status, err := db.AdminStatus()

Admin calls need the cluster module enabled on the server, even on a single node. db.Ping() checks the connection itself.

Errors

Every error returned by the client unwraps to one sentinel, so check with errors.Is:

_, err := db.Query("SELECT * FROM missing")
switch {
case errors.Is(err, tricoredb.ErrArgument): // refused by the client; nothing was sent
case errors.Is(err, tricoredb.ErrAuth):     // the server refused the credentials
case errors.Is(err, tricoredb.ErrServer):   // the request arrived; the operation failed
case errors.Is(err, tricoredb.ErrProtocol): // the peer did not speak the protocol
case errors.Is(err, tricoredb.ErrTimeout):  // no reply in time
}

The concrete types are *ArgumentError, *AuthError, *ServerError, *ProtocolError and *TimeoutError. Do not retry an ErrArgument: the same call will fail the same way.

*ServerError has a Code field with the server's machine-readable error code. Branch on Code, not on the message text.

Leader redirects. In a cluster, a write that reaches a follower fails with Code == "not_leader", and IsNotLeader() returns true. When the leader is known, LeaderHint holds its host:port. An empty hint means the leader is not known yet (for example during an election), so wait and retry. The client does not follow redirects for you: where to resend a write is your application's decision.

var se *tricoredb.ServerError
if errors.As(err, &se) && se.IsNotLeader() && se.LeaderHint != "" {
	// reconnect to se.LeaderHint and retry
}

TLS

TLS is off unless Options.TLS is set. Without TLS the password is sent in plain text, so use TLS for anything other than local development.

db, err := tricoredb.Connect(ctx, tricoredb.Options{
	Host: "db.internal", Port: 8427, User: "admin", Secret: "your-password",
	TLS: &tricoredb.TLSOptions{
		CAFile:     "/etc/tricore/ca.pem", // CA that signed the server certificate
		ServerName: "db.internal",         // name checked in the certificate
	},
})

With TLS on, the server certificate and host name are always verified. If CAFile is not set, the trust store is empty: the client does not fall back to the operating system's certificates, so a wrong setting fails instead of trusting an unrelated CA.

For mutual TLS, set both ClientCertFile and ClientKeyFile. Setting only one is an error.

TLSOptions field Default Meaning
CAFile "" (empty trust store) PEM file used to verify the server
ServerName "localhost" Expected server name (SNI and certificate check)
ClientCertFile "" PEM client certificate chain, for mutual TLS
ClientKeyFile "" PEM private key for that certificate
DangerAcceptInvalidCerts false Development only. Skips all verification.

Error messages name certificate and key paths, never their contents.

Testing

go vet ./...
go test ./...

The root package's tests need no server. The e2e_hardening and e2e_models suites start a real tricore-server; point TRICORE_SERVER_BIN at the binary to run them. Without it, those tests are skipped.

License

Apache License 2.0

Documentation

Overview

Package tricoredb is the Go driver for TriCoreDB's native "tricore" wire protocol.

It speaks the protocol directly over TCP (optionally TLS) and depends on nothing beyond the standard library. One Client is one connection; one Pool is a bounded set of them for concurrent use.

ctx := context.Background()
db, err := tricoredb.Connect(ctx, tricoredb.Options{
	Host: "127.0.0.1", Port: 8427, User: "admin", Secret: "pw",
})
if err != nil {
	log.Fatal(err)
}
defer db.Close()

// SQL, with ? placeholders bound by the server.
_, err = db.ExecuteParams("INSERT INTO t (id, name) VALUES (?, ?)", 1, "ada")
rows, err := db.QueryParams("SELECT name FROM t WHERE id = ?", 1)
// rows.Rows == [["ada"]]

// Cache values are bytes; found distinguishes a miss from an empty value.
err = db.CacheSet("sessions", "u1", []byte("token"))
v, found, err := db.CacheGet("sessions", "u1")

Data models

SQL (Client.Execute, Client.QueryParams, Client.Transaction, Client.Begin), cache (Client.CacheSet and the list, set, hash and stream families), documents (Client.DocumentInsert, Client.DocumentFind, Client.DocumentAggregate), vectors (Client.VectorUpsert, Client.VectorSearch), graphs (Client.GraphAddNode, Client.GraphShortestPath, Client.GraphQuery) and LLM context export (Client.LlmContext).

Negotiated capabilities

Server-side parameters and session transactions are optional protocol features negotiated in the handshake. When the server did not grant one, the methods that need it fail with ErrArgument before anything is sent; they never fall back to a weaker behaviour silently. See FeatureServerParams and FeatureSessionTxn.

Errors

Every error unwraps to one of ErrAuth, ErrServer, ErrProtocol, ErrArgument or ErrTimeout. A write refused by a Raft follower is a *ServerError whose ServerError.IsNotLeader is true; the driver does not follow redirects itself.

Index

Constants

View Source
const (
	// FeatureCorrelationID: this SDK understands a request-scoped correlation
	// id that the server joins to its access log, audit trail and cancel
	// registry.
	FeatureCorrelationID uint64 = 1 << 0

	// FeatureServerParams: the server binds `?` placeholders to a typed params
	// array carried alongside the statement, instead of the driver rendering
	// values into the SQL text before sending it.
	//
	// This is the difference between escaping and binding. Client-side
	// rendering has to reproduce the server's literal syntax exactly for every
	// type, and any mismatch is either a wrong value or a parse error; a bound
	// parameter is substituted at a value position the grammar has already
	// fixed, so a value can never become syntax however it is spelled.
	//
	// [Client.ExecuteParams] and [Client.QueryParams] require it and refuse by
	// name when it was not granted, rather than falling back to the rendering
	// they used to do — a silent downgrade from binding to escaping is exactly
	// the failure this bit exists to make visible.
	FeatureServerParams uint64 = 1 << 1

	// FeatureSessionTxn: session-scoped transactions — BEGIN, the statements,
	// and COMMIT/ROLLBACK sent as separate requests on one connection, with a
	// real rollback boundary between them.
	//
	// Granted per connection: a sharded or forwarding node may withhold it, and
	// a server too old to negotiate never grants it. Client.Begin refuses by
	// name when it was not granted, rather than sending a BEGIN the server would
	// run as a one-statement autocommit script.
	FeatureSessionTxn uint64 = 1 << 2

	// Features is everything this build understands.
	Features = FeatureCorrelationID | FeatureServerParams | FeatureSessionTxn
)

Optional protocol capabilities this SDK understands, sent in HELLO as a bitmap (V2 P2). The server replies with the subset it granted; a server too old to negotiate omits the field, which reads as 0.

View Source
const (
	MaxFrameSize        uint32 = 16 * 1024 * 1024
	MaxControlFrameSize uint32 = 64 * 1024
)

The protocol's payload ceilings, mirroring crates/tricore_protocol/src/constants/mod.rs.

A driver that trusts a declared length is six header bytes away from an unbounded allocation: payload_len is a u32, so any peer — hostile, broken, or simply the wrong port — could commit this process to a 4 GiB make([]byte, n) and a read that never ends. The server refuses these lengths on its side; the client must refuse them on its own, because the server is not the only thing this socket can be connected to.

Control frames take the far tighter ceiling (C-40): every frame that is not REQUEST/RESPONSE carries a small JSON document or nothing at all, and the two an *unauthenticated* peer may send are both in that set.

View Source
const DefaultPort = 8427

DefaultPort is the port tricore-server listens on when not configured otherwise.

View Source
const ErrorCodeNotLeader = "not_leader"

ErrorCodeNotLeader is the server's `diagnostics.error_code` for a write or linearizable read that reached a Raft follower.

View Source
const MaxSupportedFrameVersion byte = 1

MaxSupportedFrameVersion is the highest frame-header format version this driver can read.

The header's first byte is a format version. It used to be skipped entirely here, so a peer speaking a future frame layout was parsed as though it spoke this one. The server refuses an unknown version by name; so does this.

View Source
const Version = "0.1.0"

Version is this SDK's own version, so a consumer can pin one (V2 P2).

Go resolves module versions from git tags, not from source, so a consumer of an untagged checkout previously had nothing to state at all. This constant is the SDK's version and is deliberately separate from protocolVersion: the two move for different reasons.

Variables

View Source
var (
	// ErrAuth means the server rejected the AUTH frame, or answered
	// AUTH_OK with ok=false — the wire spec calls that out explicitly as
	// still a refusal despite the "OK" tag name.
	ErrAuth = errors.New("tricoredb: authentication refused")

	// ErrServer means a REQUEST came back with status "error" (or
	// "not_implemented") — the round trip worked, the operation didn't.
	ErrServer = errors.New("tricoredb: server error")

	// ErrProtocol means the peer didn't speak the tricore wire protocol
	// as documented (wrong tag, malformed frame, connection closed
	// mid-frame, unparseable JSON body).
	ErrProtocol = errors.New("tricoredb: protocol error")

	// ErrArgument means the caller passed something this driver refused
	// before any frame was written — an empty member list, a value with no
	// SQL literal form, a mismatched placeholder count.
	//
	// Kept distinct from ErrServer on purpose: a caller retrying on a
	// server error is doing something reasonable, and retrying on a bad
	// argument is an infinite loop.
	ErrArgument = errors.New("tricoredb: invalid argument")

	// ErrTimeout means a reply did not arrive within the connection's
	// ReadTimeout, or the handshake did not finish within the connect budget.
	//
	// Fatal to the connection rather than a retryable hiccup: the reply this
	// driver stopped waiting for may still be in flight, and reusing the socket
	// would read it as the answer to the *next* request. A timed-out connection
	// is poisoned, and a Pool retires it.
	ErrTimeout = errors.New("tricoredb: timed out")
)

Sentinel errors for use with errors.Is. Each concrete error type below (AuthError, ServerError, ProtocolError) unwraps to one of these, so callers can write `errors.Is(err, tricoredb.ErrAuth)` without caring about the concrete type or its message text.

View Source
var ErrPoolClosed = errors.New("tricoredb: pool is closed")

ErrPoolClosed is returned by a Pool whose Close has already run.

View Source
var ErrPoolTimeout = errors.New("tricoredb: no pooled connection available")

ErrPoolTimeout is returned when no pooled connection became available before the caller's context expired.

Functions

func BindParams

func BindParams(sql string, args ...Arg) (string, error)

BindParams renders sql with each ? replaced by the corresponding argument, escaped as a SQL literal.

This is client-side binding

TriCoreDB V1 has no server-side prepared statements: the wire carries one sql string and nothing else. Parameters are therefore rendered into that string here, in the driver, before it is sent. That is a real and useful feature — it removes the hand-rolled concatenation where injection bugs actually come from — but it is not the guarantee a server-side bind gives, and this comment is where that distinction is stated rather than blurred.

Guarantees: strings are escaped by doubling every ', which is the only escape the server's tokenizer recognises (there is no backslash escape to smuggle a quote past); numbers render in a fixed form; only a closed set of types is accepted, so a struct never reaches the statement via %v; placeholder and argument counts must match; and a ? inside a string literal is left alone.

It cannot protect an identifier. Table and column names are not values and are not bindable — build those from a whitelist you control.

func BuildTransactionScript

func BuildTransactionScript(statements []Statement) (string, error)

BuildTransactionScript assembles BEGIN; ...; COMMIT from a list of statements.

Caller-supplied transaction control is refused rather than passed through: nesting a second BEGIN, or committing early, changes what the script means in a way the caller almost certainly did not intend.

func QuoteSQL

func QuoteSQL(s string) string

QuoteSQL escapes and quotes a string: double every ', which is the only escape the server's tokenizer recognises.

func SQLLiteral

func SQLLiteral(value any) (string, error)

SQLLiteral renders one Go value as a SQL literal.

func SQLParam

func SQLParam(value any) (any, error)

SQLParam renders one Go value as a server-side parameter.

The wire carries plain JSON, because five SDKs in five languages build this payload; the server maps each JSON scalar to a typed SQL value and refuses, by name and by index, anything it cannot represent. So this function's job is only the types encoding/json would otherwise get wrong or refuse:

  • []byte becomes 0x-prefixed hex, which is what a BLOB column parses. encoding/json would have written base64 — a different string, silently stored as text. (The old client-side path was worse still: it put the bytes through string() into a quoted literal, which mangles any value that is not valid UTF-8 and cannot survive a BLOB round trip at all.)
  • time.Time becomes the sortable UTC text a TIMESTAMP column accepts, unchanged from what this driver has always sent.
  • NaN and ±Inf are refused here rather than failing inside encoding/json with a message about the frame instead of about the parameter.
  • An exact decimal (Decimal, *big.Rat, *big.Float) becomes a JSON string of plain digits with no exponent, which a DECIMAL column parses exactly. A JSON number would be held as a double, and an exponent reads as DOUBLE. A *big.Rat with no finite decimal expansion (1/3) is refused.

Everything else passes through: integers are exact in JSON at any width Go has, and a JSON string is a TEXT parameter whatever it contains.

Types

type AccumulatorOp

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

AccumulatorOp is one reduction inside a StageGroup.

func AccAvg

func AccAvg(field string) AccumulatorOp

AccAvg averages the numeric values at field, ignoring missing/non-numeric.

func AccCount

func AccCount() AccumulatorOp

AccCount counts documents. It takes no field because it counts documents, not values.

func AccMax

func AccMax(field string) AccumulatorOp

AccMax is the largest value at field.

func AccMin

func AccMin(field string) AccumulatorOp

AccMin is the smallest value at field.

func AccSum

func AccSum(field string) AccumulatorOp

AccSum totals the numeric values at field. Documents where it is missing or non-numeric are ignored, so an absent field never contributes a zero.

func (AccumulatorOp) MarshalJSON

func (a AccumulatorOp) MarshalJSON() ([]byte, error)

MarshalJSON emits the externally-tagged form the server deserializes.

type AggregateStage

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

AggregateStage is one stage of an aggregation pipeline. Build one with the Stage* constructors.

Stages apply strictly in the order given — the order is semantics, not style: $match before $group filters documents, after it filters groups.

The zero AggregateStage is invalid and is refused rather than skipped: a pipeline that quietly dropped a stage would return a confident answer to a question nobody asked.

func StageCount

func StageCount(field string) AggregateStage

StageCount replaces the stream with a single document holding the input count under field.

func StageGroup

func StageGroup(by GroupKey, accumulators ...GroupAccumulator) AggregateStage

StageGroup groups by key and applies the accumulators.

func StageLimit

func StageLimit(n int) AggregateStage

StageLimit keeps at most n documents.

func StageMatch

func StageMatch(filter DocumentFilter) AggregateStage

StageMatch filters with the same matcher DocumentFind uses.

func StageProject

func StageProject(fields []string, include bool) AggregateStage

StageProject keeps (include true) or drops (include false) the named top-level fields. Nested projection is not implemented server-side and is refused.

func StageSkip

func StageSkip(n int) AggregateStage

StageSkip drops the first n documents.

func StageSort

func StageSort(keys ...SortKey) AggregateStage

StageSort orders the stream by the given keys.

func (AggregateStage) MarshalJSON

func (s AggregateStage) MarshalJSON() ([]byte, error)

MarshalJSON emits the externally-tagged form the server deserializes.

type Arg

type Arg = any

Arg is one bound value. It exists so ExecuteParams/QueryParams can take a variadic list without shadowing the plain Execute/Query signatures.

type ArgumentError

type ArgumentError struct {
	Message string
}

ArgumentError reports a request this driver refused to send.

func (*ArgumentError) Error

func (e *ArgumentError) Error() string

func (*ArgumentError) Unwrap

func (e *ArgumentError) Unwrap() error

type AuthError

type AuthError struct {
	Message string
}

AuthError reports an authentication failure. Message is the server's explanation, if it supplied one.

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

Unwrap lets errors.Is(err, ErrAuth) succeed without exposing *AuthError.

type CacheKeyInfo

type CacheKeyInfo struct {
	Key   string `json:"key"`
	TTLMs *int64 `json:"ttl_ms"`
	Bytes int64  `json:"bytes"`
}

CacheKeyInfo is one live key in a namespace.

type CachePair

type CachePair struct {
	Field []byte
	Value []byte
}

CachePair is one (field, value) entry for a hash or a stream. Fields are arbitrary bytes and need not be UTF-8, which is why this is a slice of pairs rather than a map[string][]byte.

func TextPairs

func TextPairs(m map[string]string) []CachePair

TextPairs builds pairs from a string map, encoding both halves as UTF-8.

type Client

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

Client is one session with a TriCoreDB server: a single TCP connection plus the HELLO/AUTH handshake already completed.

A Client is not safe for concurrent use. The protocol is a strict request/response stream over one socket — two goroutines issuing requests at once would interleave frames and desync the connection. Use one Client per goroutine (or guard it with your own mutex if you truly need to share one).

func Connect

func Connect(ctx context.Context, opts Options) (*Client, error)

Connect dials the server, performs HELLO, and — when Options.User is set — AUTH. ctx bounds the whole handshake (dial + HELLO + AUTH); it does not linger over the lifetime of the returned Client.

func (*Client) AdminPing

func (c *Client) AdminPing() error

AdminPing round-trips a request through the full pipeline.

Distinct from Ping, which never reaches a module. This one proves auth, routing and dispatch are working — what a readiness check actually wants.

func (*Client) AdminStatus

func (c *Client) AdminStatus() (map[string]any, error)

AdminStatus is the server status as reported by the cluster core.

Stub cores answer with a plain message rather than structured JSON, which is returned under the "message" key rather than raised as an error, so a status call never hard-fails on a healthy single node.

func (*Client) Begin

func (c *Client) Begin() (*TransactionResult, error)

Begin opens a session transaction on this connection.

Every statement sent on this connection until Client.Commit or Client.Rollback runs inside it, at one snapshot, and is invisible to other connections until committed. The block belongs to this connection's socket: it cannot be committed from another connection, a pooled one included, and a dropped socket rolls it back.

Requires the server to have granted FeatureSessionTxn in the handshake (see Client.SessionTxnGranted). If it did not — an older server, or a sharded / forwarding node — this fails by name *before writing anything*, rather than sending a BEGIN the server would run as a one-statement autocommit script; the returned error unwraps to ErrArgument, and Client.Transaction works everywhere.

What the server enforces inside a block, in its own words when it happens: a failed statement aborts the block and every statement after it is refused until ROLLBACK; a second Begin is refused (no savepoints); DDL and multi-statement scripts are refused; a block left idle past the server's idle-in-transaction window (60s by default) is rolled back and the connection closed; and a block that buffers more than max_pending_writes_per_transaction writes is aborted.

The returned result's Outcome is "began".

func (*Client) CacheClearNamespace

func (c *Client) CacheClearNamespace(namespace string) (int64, error)

CacheClearNamespace deletes every key in a namespace, returning how many were removed.

func (*Client) CacheDelete

func (c *Client) CacheDelete(namespace, key string) (existed bool, err error)

CacheDelete removes (namespace, key), reporting whether it was there.

Deleting an absent key is not an error — existed is simply false. The flag is returned rather than discarded so this driver answers the same question as the other TriCoreDB SDKs, all of which report it: "delete succeeded" and "the key was there" are different facts, and only one of them tells you whether somebody else got there first.

func (*Client) CacheExists

func (c *Client) CacheExists(namespace, key string) (bool, error)

CacheExists reports whether the key is present and unexpired.

func (*Client) CacheExpire

func (c *Client) CacheExpire(namespace, key string, ttlMs int64) (bool, error)

CacheExpire sets or replaces a key's TTL. False when the key does not exist.

func (*Client) CacheGet

func (c *Client) CacheGet(namespace, key string) (value []byte, found bool, err error)

CacheGet fetches the value stored under (namespace, key). found is false on a miss, which is how a miss is told apart from a stored empty value — both otherwise look like a zero-length (or nil-ish) byte slice.

func (*Client) CacheHDel

func (c *Client) CacheHDel(namespace, key string, fields ...[]byte) (int64, error)

CacheHDel deletes fields, returning how many were present.

func (*Client) CacheHExists

func (c *Client) CacheHExists(namespace, key string, field []byte) (bool, error)

CacheHExists reports whether a field exists in the hash.

func (*Client) CacheHGet

func (c *Client) CacheHGet(namespace, key string, field []byte) (value []byte, found bool, err error)

CacheHGet reads one field. found is false when the field or key is absent.

func (*Client) CacheHGetAll

func (c *Client) CacheHGetAll(namespace, key string) ([]CachePair, error)

CacheHGetAll returns every field/value pair, in ascending field order.

func (*Client) CacheHLen

func (c *Client) CacheHLen(namespace, key string) (int64, error)

CacheHLen is the number of fields; 0 when the key is missing.

func (*Client) CacheHSet

func (c *Client) CacheHSet(namespace, key string, entries []CachePair) (int64, error)

CacheHSet sets fields, returning how many were newly created (as opposed to overwritten).

func (*Client) CacheHSetText

func (c *Client) CacheHSetText(namespace, key string, entries map[string]string) (int64, error)

CacheHSetText sets string fields, encoded UTF-8.

func (*Client) CacheIncr

func (c *Client) CacheIncr(namespace, key string, by int64) (int64, error)

CacheIncr adds by to a counter and returns the new value. A missing key starts at 0; a key holding a non-numeric value is an error, never a coercion.

func (*Client) CacheKeys

func (c *Client) CacheKeys(namespace, pattern string, limit int) ([]CacheKeyInfo, error)

CacheKeys lists live keys in a namespace.

pattern is a simple glob where * matches any run of characters ("user:*", "*:sess", "*tmp*"); an empty pattern lists everything. limit <= 0 leaves the cap to the server.

func (*Client) CacheLIndex

func (c *Client) CacheLIndex(namespace, key string, index int64) (value []byte, found bool, err error)

CacheLIndex reads one element by index; negative counts from the end. found is false when the index is out of range.

func (*Client) CacheLLen

func (c *Client) CacheLLen(namespace, key string) (int64, error)

CacheLLen is the number of elements; 0 when the key is missing.

func (*Client) CacheLPop

func (c *Client) CacheLPop(namespace, key string) (value []byte, found bool, err error)

CacheLPop removes and returns the first element. found is false on an empty or missing key.

func (*Client) CacheLPush

func (c *Client) CacheLPush(namespace, key string, values ...[]byte) (int64, error)

CacheLPush prepends elements, returning the new length.

func (*Client) CacheLRange

func (c *Client) CacheLRange(namespace, key string, start, stop int64) ([][]byte, error)

CacheLRange reads an inclusive index range. Negative indices count from the end (-1 is the last element) and out-of-range bounds clamp.

func (*Client) CachePersist

func (c *Client) CachePersist(namespace, key string) (bool, error)

CachePersist removes a key's TTL, making it permanent. False when it had none.

func (*Client) CachePing

func (c *Client) CachePing() error

CachePing is a liveness check routed through the cache core.

Distinct from Ping, which exchanges a PING frame and never reaches a module. This one proves auth, routing and dispatch are working.

func (*Client) CacheRPop

func (c *Client) CacheRPop(namespace, key string) (value []byte, found bool, err error)

CacheRPop removes and returns the last element. found is false on an empty or missing key.

func (*Client) CacheRPush

func (c *Client) CacheRPush(namespace, key string, values ...[]byte) (int64, error)

CacheRPush appends elements, returning the new length.

func (*Client) CacheSAdd

func (c *Client) CacheSAdd(namespace, key string, members ...[]byte) (int64, error)

CacheSAdd adds members, returning how many were newly added.

func (*Client) CacheSCard

func (c *Client) CacheSCard(namespace, key string) (int64, error)

CacheSCard is the number of members; 0 when the key is missing.

func (*Client) CacheSIsMember

func (c *Client) CacheSIsMember(namespace, key string, member []byte) (bool, error)

CacheSIsMember reports whether member is in the set.

func (*Client) CacheSMembers

func (c *Client) CacheSMembers(namespace, key string) ([][]byte, error)

CacheSMembers returns every member, in ascending byte order.

func (*Client) CacheSRem

func (c *Client) CacheSRem(namespace, key string, members ...[]byte) (int64, error)

CacheSRem removes members, returning how many were present.

func (*Client) CacheSet

func (c *Client) CacheSet(namespace, key string, value []byte) error

CacheSet stores value under (namespace, key) with no expiry. Use CacheSetTTL to attach one.

func (*Client) CacheSetNx

func (c *Client) CacheSetNx(namespace, key string, value []byte, ttlMs int64) (bool, error)

CacheSetNx stores value only if the key is absent, reporting whether the write happened. The primitive behind a distributed lock. ttlMs <= 0 means no expiry.

func (*Client) CacheSetTTL

func (c *Client) CacheSetTTL(namespace, key string, value []byte, ttlMs int64) error

CacheSetTTL stores value under (namespace, key), expiring after ttlMs milliseconds. ttlMs <= 0 means no expiry.

func (*Client) CacheTTL

func (c *Client) CacheTTL(namespace, key string) (ttlMs int64, has bool, err error)

CacheTTL returns the remaining time to live in milliseconds.

has is false when the key is missing *or* has no expiry; use CacheExists to tell those two apart.

func (*Client) CacheXAdd

func (c *Client) CacheXAdd(namespace, key string, fields []CachePair, id string) (string, error)

CacheXAdd appends an entry, returning the assigned id.

id is "" or "*" to auto-generate, "<ms>" or "<ms>-*" to fix the millisecond, or "<ms>-<seq>" for an exact id. A non-increasing id is an error.

func (*Client) CacheXAddText

func (c *Client) CacheXAddText(namespace, key string, fields map[string]string, id string) (string, error)

CacheXAddText appends an entry whose fields are strings, encoded UTF-8.

func (*Client) CacheXDel

func (c *Client) CacheXDel(namespace, key string, ids ...string) (int64, error)

CacheXDel deletes entries by exact id, returning how many were present.

func (*Client) CacheXLen

func (c *Client) CacheXLen(namespace, key string) (int64, error)

CacheXLen is the number of entries; 0 when the key is missing.

func (*Client) CacheXRange

func (c *Client) CacheXRange(namespace, key, start, end string, count int) ([]StreamEntry, error)

CacheXRange reads entries whose id falls in the inclusive range. "-" and "+" are the min/max ids; a bare "<ms>" spans that whole millisecond. count <= 0 leaves the cap to the server.

func (*Client) CacheXRead

func (c *Client) CacheXRead(namespace, key, after string, count int) ([]StreamEntry, error)

CacheXRead reads entries strictly newer than after — the non-blocking poll primitive. Pass "$" for "only new entries". This read never blocks.

func (*Client) CacheXTrim

func (c *Client) CacheXTrim(namespace, key string, maxLen int) (int64, error)

CacheXTrim caps the stream by evicting the oldest entries, returning how many were evicted.

func (*Client) Cancel

func (c *Client) Cancel(requestID string) (int, error)

Cancel asks the server to stop one of this principal's running statements, named by the request_id it was sent with (see LastRequestID).

This must be sent on a second connection. The connection running the statement is blocked reading its reply and is not reading anything else, so a cancel can never reach it there.

Scoped by the authenticated principal: you cannot stop — or learn about — somebody else's statement. An unknown id returns 0 rather than an error.

func (*Client) Close

func (c *Client) Close() error

Close ends the session politely (CLOSE/BYE) and releases the socket.

A failure during the goodbye handshake is not surfaced — the socket is closed either way, mirroring the reference Python driver's stance that a teardown error isn't worth failing over — but Close is idempotent and safe to call more than once (e.g. from both a defer and an explicit call).

func (*Client) Commit

func (c *Client) Commit() (*TransactionResult, error)

Commit commits the block opened by Client.Begin, durably and as one atomic batch. The returned result's Outcome is "committed".

A refusal is the server's own and ends the block either way: after a failed statement the server has already rolled it back and says so; a first-committer-wins conflict discards it.

func (*Client) DocumentAggregate

func (c *Client) DocumentAggregate(collection string, pipeline ...AggregateStage) ([]Document, error)

DocumentAggregate runs an aggregation pipeline over a collection. An empty pipeline returns the collection unchanged.

Stages this build does not implement ($lookup, $unwind, $facet, $out, $addFields, computed expressions) are not representable here at all.

func (*Client) DocumentAnalyze

func (c *Client) DocumentAnalyze(collection string) (*DocumentStats, error)

DocumentAnalyze collects approximate statistics the query optimizer uses to choose between an index lookup and a scan.

func (*Client) DocumentCreateCollection

func (c *Client) DocumentCreateCollection(collection string) error

DocumentCreateCollection creates a document collection.

func (*Client) DocumentCreateIndex

func (c *Client) DocumentCreateIndex(collection, indexName, field string, unique bool) error

DocumentCreateIndex builds a secondary index on a top-level field. Creating a unique index over a collection that already holds duplicates is refused, before anything is written.

func (*Client) DocumentDelete

func (c *Client) DocumentDelete(collection, id string) error

DocumentDelete removes one document by id. Deleting an absent document is not an error.

func (*Client) DocumentDropCollection

func (c *Client) DocumentDropCollection(collection string) error

DocumentDropCollection removes a collection, its documents, and its indexes. Dropping a collection that does not exist is an error.

func (*Client) DocumentDropIndex

func (c *Client) DocumentDropIndex(collection, indexName string) error

DocumentDropIndex removes a named index from a collection.

func (*Client) DocumentFind

func (c *Client) DocumentFind(collection string, filter DocumentFilter) ([]Document, error)

DocumentFind returns every document matching filter. Use DocumentFindLimit to cap the result.

func (*Client) DocumentFindLimit

func (c *Client) DocumentFindLimit(collection string, filter DocumentFilter, limit int) ([]Document, error)

DocumentFindLimit returns at most limit documents matching filter. A limit of zero or less means no limit.

func (*Client) DocumentGet

func (c *Client) DocumentGet(collection, id string) (doc Document, found bool, err error)

DocumentGet fetches one document by id. found is false when no such document exists, which is how an absent document is told apart from a stored empty one — both otherwise look like an empty map.

func (*Client) DocumentInsert

func (c *Client) DocumentInsert(collection string, document any) (string, error)

DocumentInsert stores document under a server-generated id, which it returns. document must marshal to a JSON object.

Use DocumentInsertWithID to choose the id yourself.

func (*Client) DocumentInsertWithID

func (c *Client) DocumentInsertWithID(collection, id string, document any) (string, error)

DocumentInsertWithID stores document under the given id. Inserting over an existing id is an error, not an overwrite — use DocumentUpdate or DocumentUpsertOne for that.

func (*Client) DocumentListCollections

func (c *Client) DocumentListCollections() ([]string, error)

DocumentListCollections names every document collection in the database.

func (*Client) DocumentListIndexes

func (c *Client) DocumentListIndexes(collection string) ([]DocumentIndex, error)

DocumentListIndexes lists a collection's indexes.

func (*Client) DocumentUpdate

func (c *Client) DocumentUpdate(collection, id string, set map[string]any) error

DocumentUpdate sets fields on an existing document (read-modify-write). set maps dot paths to new values; a dot path creates or overwrites nested keys.

This is not an upsert: a missing id is an error. "_id" cannot be set.

func (*Client) DocumentUpdateMany

func (c *Client) DocumentUpdateMany(collection string, filter DocumentFilter, update DocumentUpdate) (UpdateManyResult, error)

DocumentUpdateMany applies update to every document matching filter, using the same filter machinery as DocumentFind. Never an upsert: a filter matching nothing modifies nothing, and that is not an error.

func (*Client) DocumentUpdateOne

func (c *Client) DocumentUpdateOne(collection, id string, update DocumentUpdate) error

DocumentUpdateOne applies update (Set and/or Inc) to one document by id. A missing id is an error; use DocumentUpsertOne to create instead.

func (*Client) DocumentUpsertOne

func (c *Client) DocumentUpsertOne(collection, id string, update DocumentUpdate) (inserted bool, err error)

DocumentUpsertOne applies update to one document by id, creating it from the update itself (carrying _id = id) when it does not exist. inserted reports which of the two happened.

There is no id-less form: with no id there is nothing to match on, so "update or insert" would collapse to a plain insert under another name. Use DocumentInsert for that.

func (*Client) Execute

func (c *Client) Execute(sql string) (*Response, error)

Execute runs a write statement (CREATE/INSERT/UPDATE/DELETE/BEGIN...COMMIT and the like). The server refuses a write submitted through Query instead of Execute.

func (*Client) ExecuteParams

func (c *Client) ExecuteParams(sql string, args ...Arg) (*Response, error)

ExecuteParams runs a write, binding ? placeholders from args.

The values are bound by the server, not rendered into the statement

args travel beside the SQL as a typed array and the server substitutes them at value positions its grammar has already fixed. A value therefore cannot become syntax however it is spelled: a quote, a backslash, or an argument that is itself a complete SQL statement is stored as the text it is.

This requires FeatureServerParams, negotiated at HELLO. When the server did not grant it — one too old to negotiate — this fails by name with ErrArgument *before writing anything*, rather than falling back to rendering the values into the statement text. The fallback is what the driver used to do unconditionally, and doing it silently would mean the same call binds on one connection and escapes on the next with nothing to tell them apart. A caller that genuinely wants the old behaviour asks for it by name with BindParams.

Zero args need no capability: with nothing to bind this is exactly Client.Execute.

func (*Client) GrantedFeatures

func (c *Client) GrantedFeatures() uint64

GrantedFeatures reports the optional protocol capabilities this connection negotiated at HELLO (V2 P2).

Zero before a handshake, and zero against a server too old to negotiate.

func (*Client) GraphAddEdge

func (c *Client) GraphAddEdge(graph, id, from, to, label string, properties map[string]any) error

GraphAddEdge stores a directed edge from -> to under id. Both endpoints must already exist; a dangling endpoint is refused rather than created. properties may be nil.

func (*Client) GraphAddNode

func (c *Client) GraphAddNode(graph, id string, labels []string, properties map[string]any) error

GraphAddNode stores a node, replacing any node already under id. labels and properties may be nil.

func (*Client) GraphCreate

func (c *Client) GraphCreate(graph string) error

GraphCreate creates an empty graph.

func (*Client) GraphDegree

func (c *Client) GraphDegree(graph, nodeID string, direction GraphDirection) (int, error)

GraphDegree counts the edges incident to a node in a direction. DirectionBoth counts each edge once, self-loops included.

func (*Client) GraphDeleteEdge

func (c *Client) GraphDeleteEdge(graph, id string) error

GraphDeleteEdge removes an edge by id. Deleting an absent edge is not an error; a missing graph is.

func (*Client) GraphDeleteNode

func (c *Client) GraphDeleteNode(graph, id string) error

GraphDeleteNode removes a node by id. Deleting an absent node is not an error; a missing graph is.

func (*Client) GraphDrop

func (c *Client) GraphDrop(graph string) error

GraphDrop removes a graph with its nodes and edges. Dropping a graph that does not exist is an error.

func (*Client) GraphGetEdge

func (c *Client) GraphGetEdge(graph, id string) (edge *GraphEdge, found bool, err error)

GraphGetEdge fetches one edge by id. found is false when no such edge exists.

func (*Client) GraphGetNode

func (c *Client) GraphGetNode(graph, id string) (node *GraphNode, found bool, err error)

GraphGetNode fetches one node by id. found is false when no such node exists — the server answers a miss with a null payload, which would otherwise decode into a zero-valued GraphNode indistinguishable from a real one.

func (*Client) GraphList

func (c *Client) GraphList() ([]string, error)

GraphList names every graph in the database.

func (*Client) GraphListEdges

func (c *Client) GraphListEdges(graph string, limit, offset int) (*GraphEdgePage, error)

GraphListEdges reads one page of a graph's edges, ordered by id. limit <= 0 asks for the server default (500, capped at 1000); offset skips that many.

func (*Client) GraphListNodes

func (c *Client) GraphListNodes(graph string, limit, offset int) (*GraphNodePage, error)

GraphListNodes reads one page of a graph's nodes, ordered by id. limit <= 0 asks for the server default (500, capped at 1000); offset skips that many.

func (*Client) GraphNeighbors

func (c *Client) GraphNeighbors(graph, nodeID string, opts NeighborOptions) ([]GraphNeighbor, error)

GraphNeighbors lists the edges incident to a node and the node at the far end of each. A node with no matching edges yields an empty slice, not an error.

func (*Client) GraphQuery

func (c *Client) GraphQuery(graph, cypher string) (*GraphRows, error)

GraphQuery runs a read-only Cypher-subset query and returns its rows.

The server implements MATCH / WHERE / RETURN with labels, property predicates, relationship direction and type, bounded variable-length paths, DISTINCT, ORDER BY / SKIP / LIMIT, and global aggregates. Every other clause — all write clauses, OPTIONAL MATCH, WITH, UNWIND, CALL, path variables, shortestPath(), parameters — is refused by name rather than ignored, so a rejected query returns an error instead of an answer computed from a partially-understood statement.

func (*Client) GraphShortestPath

func (c *Client) GraphShortestPath(graph, from, to string, opts PathOptions) (*GraphPath, error)

GraphShortestPath finds a path from `from` to `to` with the fewest hops. Both endpoints must exist. "No path" comes back as a GraphPath with Found false, not as an error.

func (*Client) GraphTraverse

func (c *Client) GraphTraverse(graph, start string, opts TraverseOptions) (*GraphTraversal, error)

GraphTraverse walks outward from start by breadth-first search, bounded by opts. The start node must exist.

func (*Client) GraphWeightedShortestPath

func (c *Client) GraphWeightedShortestPath(graph, from, to string, opts WeightedPathOptions) (*GraphPath, error)

GraphWeightedShortestPath finds the least-cost path from `from` to `to` by summed edge weight.

This is a different question from GraphShortestPath, which minimises hops: with unequal weights the two return different paths and neither substitutes for the other. "No path" comes back as Found false, not as an error.

func (*Client) InTransaction

func (c *Client) InTransaction() bool

InTransaction reports whether a Client.Begin block is open on this connection.

A closed or poisoned connection has no transaction: the server rolls one back the moment the socket goes, and Close clears the flag for the same reason.

func (*Client) LastRequestID

func (c *Client) LastRequestID() string

LastRequestID is the request_id most recently sent by this client. Pass it to Cancel from a *second* connection to stop a running statement.

func (*Client) LlmContext

func (c *Client) LlmContext(sources []LlmSource, format OutputFormat, opts *LlmOptions) (string, error)

LlmContext assembles a context bundle from one or more read-only sources.

opts may be nil, which uses DefaultLlmOptions. The returned string is the rendered bundle: text for TOON/Markdown, JSON otherwise.

func (*Client) LlmSchema

func (c *Client) LlmSchema(format OutputFormat, opts *LlmOptions) (string, error)

LlmSchema exports the schema catalog: SQL tables plus document collections.

func (*Client) Ping

func (c *Client) Ping() error

Ping checks liveness with a PING/PONG round trip.

Routed through exchange like every other frame pair: it used to call writeFrame/readFrame directly, so a Ping from a second goroutine bypassed the in-flight guard this driver enforces everywhere else and consumed the first goroutine's reply. It bypassed ReadTimeout with it.

func (*Client) Poisoned

func (c *Client) Poisoned() bool

Poisoned reports whether this connection was closed after a protocol failure, a read deadline, or a transport error. A Pool consults it directly: a driver that knows it is un-resynchronisable is more reliable than a list of error types that a new failure mode can fall out of.

func (*Client) Query

func (c *Client) Query(sql string) (*Rows, error)

Query runs a read and returns its rows. Submitting a write here is refused by the server rather than executed — use Execute for those.

func (*Client) QueryParams

func (c *Client) QueryParams(sql string, args ...Arg) (*Rows, error)

QueryParams runs a read, binding ? placeholders from args server-side. See Client.ExecuteParams for what that means and what it requires.

func (*Client) Request

func (c *Client) Request(op any) (*Response, error)

Request sends a raw, externally-tagged operation and returns the decoded response — the escape hatch every other TriCoreDB driver exposes, and which this one was missing.

The typed helpers cover every operation a V1 client should need, so reach for this only when there is genuinely no typed method: a server operation that exists solely to be refused (`Cache::XGroup`), or one added to the server ahead of this driver. `op` is the wire form, e.g.

db.Request(map[string]any{"Cache": map[string]any{"Ping": nil}})

Nothing here validates the shape, so a malformed op is refused by the server rather than by the driver. That is the trade: full reach, no type safety.

func (*Client) Rollback

func (c *Client) Rollback() (*TransactionResult, error)

Rollback discards the block opened by Client.Begin. The returned result's Outcome is "rolled_back".

func (*Client) ServerParamsGranted

func (c *Client) ServerParamsGranted() bool

ServerParamsGranted reports whether the server granted FeatureServerParams on this connection — the bit Client.ExecuteParams and Client.QueryParams require.

False against a server too old to negotiate. Those two methods refuse by name in that case rather than rendering the values into the statement text, so a caller never binds server-side on one connection and client-side on the next without being told.

func (*Client) SessionID

func (c *Client) SessionID() string

SessionID is the server-assigned session identifier from AUTH_OK, or "" if the connection never authenticated.

func (*Client) SessionTxnGranted

func (c *Client) SessionTxnGranted() bool

SessionTxnGranted reports whether the server granted FeatureSessionTxn on this connection — the bit Client.Begin requires.

func (*Client) SetReadTimeout

func (c *Client) SetReadTimeout(d time.Duration)

SetReadTimeout sets a client-side deadline on each subsequent read. A non-positive duration clears it. See Options.ReadTimeout.

func (*Client) SetRequestTimeout

func (c *Client) SetRequestTimeout(d time.Duration)

SetRequestTimeout stamps a server-side deadline on every subsequent request. A non-positive duration clears it.

This is not a client-side timeout: cancelling on this side abandons the read while the server keeps working. This makes the server stop.

func (*Client) Transaction

func (c *Client) Transaction(statements ...Statement) (*TransactionResult, error)

Transaction runs a pre-declared script atomically, in one request.

The server runs the BEGIN ... COMMIT script against an MVCC snapshot and flushes it as one atomic batch; ROLLBACK, or any error mid-script, discards the buffer. This is the right tool when every statement is known up front: one round trip, one replication event, and it works on every node — including the sharded and forwarding ones that withhold FeatureSessionTxn.

db.Transaction(
	tricoredb.Stmt("INSERT INTO t VALUES (?, ?)", 1, "ada"),
	tricoredb.Stmt("INSERT INTO t VALUES (?, ?)", 2, "bob"),
)

When a later statement depends on what an earlier one read, use Client.Begin/Client.Commit/Client.Rollback or Client.WithTransaction instead.

func (*Client) VectorCreateCollection

func (c *Client) VectorCreateCollection(collection string, dimension int, metric VectorMetric) error

VectorCreateCollection creates an unquantized collection of the given dimension and metric. Use VectorCreateCollectionQuantized to opt into index compression.

func (*Client) VectorCreateCollectionQuantized

func (c *Client) VectorCreateCollectionQuantized(collection string, dimension int, metric VectorMetric, quantization VectorQuantization) error

VectorCreateCollectionQuantized creates a collection with an explicit index quantization. Dimension and metric are fixed for the collection's lifetime.

func (*Client) VectorDelete

func (c *Client) VectorDelete(collection, id string) error

VectorDelete removes one vector by id. Deleting an absent id is not an error; a missing collection is.

func (*Client) VectorDescribeCollection

func (c *Client) VectorDescribeCollection(collection string) (*VectorCollectionInfo, error)

VectorDescribeCollection reads one collection's catalog metadata and its live vector count.

func (*Client) VectorDropCollection

func (c *Client) VectorDropCollection(collection string) error

VectorDropCollection removes a collection and every vector in it. Dropping a collection that does not exist is an error.

func (*Client) VectorGet

func (c *Client) VectorGet(collection, id string) (item *VectorItem, found bool, err error)

VectorGet fetches one stored vector by id. found is false when no such vector exists — the server answers a miss with a null payload, which would otherwise decode into a zero-valued VectorItem indistinguishable from a real one.

func (*Client) VectorListCollections

func (c *Client) VectorListCollections() ([]VectorCollectionSummary, error)

VectorListCollections describes every vector collection in the database.

func (*Client) VectorListVectors

func (c *Client) VectorListVectors(collection string, limit, offset int) (*VectorPage, error)

VectorListVectors reads one page of a collection's vectors, ordered by id, for browsing and export. limit <= 0 asks for the server default (500, capped at 1000); offset skips that many items.

func (*Client) VectorSearch

func (c *Client) VectorSearch(collection string, vector []float32, topK int) (*VectorSearchResult, error)

VectorSearch returns the topK nearest vectors to the query vector. topK must be in 1..=1000 and len(vector) must equal the collection's dimension.

func (*Client) VectorSearchFiltered

func (c *Client) VectorSearchFiltered(collection string, vector []float32, topK int, filter map[string]any) (*VectorSearchResult, error)

VectorSearchFiltered is VectorSearch restricted to vectors whose metadata matches filter — a map of top-level metadata field to required equal value. A nil or empty filter means no filtering.

Exact equality only: the server implements no ranges and no nesting here.

func (*Client) VectorUpsert

func (c *Client) VectorUpsert(collection, id string, vector []float32, metadata map[string]any) error

VectorUpsert stores vector under id, replacing any vector already there. len(vector) must equal the collection's dimension; a mismatch is refused rather than padded or truncated. metadata may be nil.

func (*Client) WithTransaction

func (c *Client) WithTransaction(fn func(*Client) error) error

WithTransaction runs Begin, then fn, then Commit — or Rollback and the original error if fn returns one. A panic inside fn rolls the block back and re-panics, so no path leaves a block open.

err := db.WithTransaction(func(tx *tricoredb.Client) error {
	if _, err := tx.ExecuteParams("UPDATE accounts SET balance = balance - ? WHERE id = ?", 10, 1); err != nil {
		return err
	}
	_, err := tx.ExecuteParams("UPDATE accounts SET balance = balance + ? WHERE id = ?", 10, 2)
	return err
})

fn must issue its statements on the client it is given — this one — and only this one. A statement on any other connection, a pooled one included, is outside the block: the server binds the transaction to this socket and refuses COMMIT from any other by name.

type Decimal

type Decimal string

Decimal is an exact decimal number carried as its text, such as "1.50" or "-0.000000000000000001".

Bound with Client.ExecuteParams or Client.QueryParams, it travels as a JSON string of plain digits, which a DECIMAL column parses exactly. A JSON number would be read by the server as a double and lose every digit past a double's precision, and an exponent ("1.5E+3") makes the server's tokenizer read a DOUBLE, so a Decimal with an exponent is refused before anything is sent. Trailing zeros are kept as written.

The server allows a scale of at most 18 and at most 38 significant digits and refuses anything beyond that by name; this driver does not repeat that check.

type Document

type Document map[string]any

Document is one JSON document as the server stores it. Every stored document carries an "_id" string, whether the caller supplied it or the server generated one.

type DocumentFilter

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

DocumentFilter is a document query predicate — the Go form of the server's DocumentFilter (crates/tricore_core/src/request/document_ops.rs).

Build one with the Filter* constructors. Every field path accepts dot notation ("a.b.c") resolving into nested objects; a missing path never matches, including for FilterNe.

The zero DocumentFilter is invalid, not "match everything": a forgotten-to-initialize filter that silently matched the whole collection would turn a typo into a full-collection update. Use FilterAll to say that on purpose.

This is not MongoDB's query language: there is no Or, no Not, and no regex, because the server implements none of them.

func FilterAll

func FilterAll() DocumentFilter

FilterAll matches every document.

func FilterAnd

func FilterAnd(filters ...DocumentFilter) DocumentFilter

FilterAnd matches documents satisfying every sub-filter. With no arguments it matches everything, which is what the server does with an empty And.

func FilterContains

func FilterContains(field string, value any) DocumentFilter

FilterContains matches a string field containing value as a substring, or an array field containing an element equal to value.

func FilterEq

func FilterEq(field string, value any) DocumentFilter

FilterEq matches documents whose field equals value.

func FilterGt

func FilterGt(field string, value any) DocumentFilter

FilterGt matches documents whose field is greater than value.

func FilterGte

func FilterGte(field string, value any) DocumentFilter

FilterGte matches documents whose field is greater than or equal to value.

func FilterIn

func FilterIn(field string, values ...any) DocumentFilter

FilterIn matches documents whose field equals any of values.

func FilterLt

func FilterLt(field string, value any) DocumentFilter

FilterLt matches documents whose field is less than value.

func FilterLte

func FilterLte(field string, value any) DocumentFilter

FilterLte matches documents whose field is less than or equal to value.

func FilterNe

func FilterNe(field string, value any) DocumentFilter

FilterNe matches documents whose field exists and does not equal value. A document missing the field does not match.

func (DocumentFilter) MarshalJSON

func (f DocumentFilter) MarshalJSON() ([]byte, error)

MarshalJSON emits the externally-tagged form the server deserializes.

type DocumentIndex

type DocumentIndex struct {
	// Name is the index name.
	Name string `json:"index_name"`
	// Field is the indexed field.
	Field string `json:"field"`
	// Unique reports whether the index enforces uniqueness.
	Unique bool `json:"unique"`
}

DocumentIndex describes one secondary index on a collection.

type DocumentStats

type DocumentStats struct {
	// Collection is the analyzed collection.
	Collection string `json:"analyzed"`
	// DocumentCount is the number of documents in it.
	DocumentCount int64 `json:"document_count"`
	// IndexedFields is the number of fields with a secondary index.
	IndexedFields int `json:"indexed_fields"`
}

DocumentStats is what DocumentAnalyze collected.

type DocumentUpdate

type DocumentUpdate struct {
	// Set maps a dot path to its new value.
	Set map[string]any `json:"set,omitempty"`
	// Inc maps a dot path to a numeric delta. Every value must be a number.
	Inc map[string]any `json:"inc,omitempty"`
}

DocumentUpdate is a set of field mutations applied to one document: Set overwrites the value at a dot path, Inc adds a number to it. Every Set is applied before every Inc.

Inc never coerces. Incrementing a field holding a string, bool, null, array, or object is a server error, not a silent conversion; a missing field increments from 0. A negative Inc is how you decrement — there is no Dec.

type GraphDirection

type GraphDirection string

GraphDirection selects which edges of a node an operation follows.

The empty GraphDirection means "let the server decide", which is DirectionOutgoing everywhere it appears.

const (
	// DirectionOutgoing follows edges where the node is the `from` endpoint.
	DirectionOutgoing GraphDirection = "outgoing"
	// DirectionIncoming follows edges where the node is the `to` endpoint.
	DirectionIncoming GraphDirection = "incoming"
	// DirectionBoth follows edges in either direction.
	DirectionBoth GraphDirection = "both"
)

type GraphEdge

type GraphEdge struct {
	// ID is the edge id, unique within its graph.
	ID string `json:"id"`
	// From is the id of the node the edge leaves.
	From string `json:"from"`
	// To is the id of the node the edge enters.
	To string `json:"to"`
	// Label is the edge's label.
	Label string `json:"label"`
	// Properties are the edge's properties as decoded JSON.
	Properties map[string]any `json:"properties"`
}

GraphEdge is one stored edge, directed From -> To.

type GraphEdgePage

type GraphEdgePage struct {
	// Graph is the graph name.
	Graph string `json:"graph"`
	// Count is the number of edges on this page.
	Count int `json:"count"`
	// Edges are this page's edges.
	Edges []GraphEdge `json:"edges"`
	// Truncated reports that more edges remain past this page.
	Truncated bool `json:"truncated"`
	// Total is the graph's full edge count.
	Total int64 `json:"total"`
}

GraphEdgePage is one page of GraphListEdges.

type GraphNeighbor

type GraphNeighbor struct {
	// EdgeID is the incident edge.
	EdgeID string `json:"edge_id"`
	// NodeID is the node at the edge's other end.
	NodeID string `json:"node_id"`
	// Label is the edge's label.
	Label string `json:"label"`
	// Direction is the edge's orientation relative to the node asked about.
	Direction GraphDirection `json:"direction"`
}

GraphNeighbor is one incident edge of a node and the node at its other end. Direction is this edge's orientation relative to the node asked about, which is what makes a DirectionBoth result readable.

type GraphNode

type GraphNode struct {
	// ID is the node id, unique within its graph.
	ID string `json:"id"`
	// Labels are the node's labels.
	Labels []string `json:"labels"`
	// Properties are the node's properties as decoded JSON.
	Properties map[string]any `json:"properties"`
}

GraphNode is one stored node.

type GraphNodePage

type GraphNodePage struct {
	// Graph is the graph name.
	Graph string `json:"graph"`
	// Count is the number of nodes on this page.
	Count int `json:"count"`
	// Nodes are this page's nodes.
	Nodes []GraphNode `json:"nodes"`
	// Truncated reports that more nodes remain past this page.
	Truncated bool `json:"truncated"`
	// Total is the graph's full node count.
	Total int64 `json:"total"`
}

GraphNodePage is one page of GraphListNodes.

type GraphPath

type GraphPath struct {
	// Found reports whether a path was found.
	Found bool `json:"found"`
	// From is the start node id.
	From string `json:"from"`
	// To is the target node id.
	To string `json:"to"`
	// Direction is the edge direction that was followed.
	Direction string `json:"direction"`
	// Hops is the number of edges on the path.
	Hops int `json:"hops"`
	// NodePath is the node ids along the path, From first.
	NodePath []string `json:"node_path"`
	// EdgePath is the edge ids along the path.
	EdgePath []string `json:"edge_path"`
	// TotalCost is the summed weight, for the weighted search only.
	TotalCost float64 `json:"total_cost"`
	// Message says why Found is false, when it is.
	Message string `json:"message"`
}

GraphPath is the outcome of a path search.

Found false is an ordinary answer, not an error: either no path exists or the search stopped at a bound. Message says which — a cap-stopped search is inconclusive, not proof that no path exists — so do not read Found false as "there is definitely no path" without checking it.

TotalCost is meaningful only for GraphWeightedShortestPath; it is zero for the unweighted search, which minimises hops.

type GraphRows

type GraphRows struct {
	// Graph is the graph that was queried.
	Graph string `json:"graph"`
	// Columns are the RETURN column names.
	Columns []string `json:"columns"`
	// Rows are the result rows, each cell as decoded JSON.
	Rows [][]any `json:"rows"`
	// Count is the number of rows returned.
	Count int `json:"count"`
	// Truncated reports that the server's row cap cut the result short.
	Truncated bool `json:"truncated"`
}

GraphRows is the result of a Cypher query: named columns and their rows, with each cell left as decoded JSON because a Cypher RETURN can yield a scalar, a list, or a whole node.

type GraphTraversal

type GraphTraversal struct {
	// Start is the node the walk began at.
	Start string `json:"start"`
	// Direction is the edge direction that was followed.
	Direction string `json:"direction"`
	// MaxDepth is the hop bound the server applied.
	MaxDepth int `json:"max_depth"`
	// Limit is the node bound the server applied.
	Limit int `json:"limit"`
	// Count is the number of nodes returned.
	Count int `json:"count"`
	// Truncated reports that a bound stopped the walk early.
	Truncated bool `json:"truncated"`
	// Nodes are the visited nodes in BFS order.
	Nodes []GraphVisit `json:"nodes"`
}

GraphTraversal is the outcome of a bounded BFS. Truncated reports that a limit or the server's visited-node cap stopped the walk before it ran out of nodes — the nodes returned are real, the answer is just not exhaustive.

type GraphVisit

type GraphVisit struct {
	// ID is the node id.
	ID string `json:"id"`
	// Depth is the hop count at which the node was first reached.
	Depth int `json:"depth"`
	// Labels are the node's labels.
	Labels []string `json:"labels"`
	// Properties are the node's properties as decoded JSON.
	Properties map[string]any `json:"properties"`
}

GraphVisit is one node reached by GraphTraverse, with the hop count at which it was first reached.

type GroupAccumulator

type GroupAccumulator struct {
	// Output is the field the accumulated value is written to.
	Output string `json:"output"`
	// Op is the accumulator, built with AccSum, AccCount and friends.
	Op AccumulatorOp `json:"op"`
}

GroupAccumulator is an accumulator plus the field name it writes into the grouped document. Output must not be "_id" (that holds the group key) and must not repeat within one StageGroup.

type GroupKey

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

GroupKey is how StageGroup derives a group key from a document.

func GroupByConstant

func GroupByConstant(value any) GroupKey

GroupByConstant puts the whole collection in one group keyed by this constant. This is how a collection-wide total is expressed; the server has no implicit "no key".

func GroupByField

func GroupByField(path string) GroupKey

GroupByField groups by the value at a dot path. A document missing that path groups under null rather than being dropped.

func (GroupKey) MarshalJSON

func (k GroupKey) MarshalJSON() ([]byte, error)

MarshalJSON emits the externally-tagged form the server deserializes.

type LlmOptions

type LlmOptions struct {
	// MaxRows caps rows included; 0 leaves the cap to the server.
	MaxRows int
	// RedactSensitive redacts sensitive fields before export.
	RedactSensitive bool
	// IncludeSchema includes type information alongside the data.
	IncludeSchema bool
}

LlmOptions bounds and redacts an export.

RedactSensitive defaults to false in the zero value, which is the opposite of the server's default — so LlmContext and LlmSchema take a *LlmOptions and substitute DefaultLlmOptions when it is nil. A zero-value struct passed by accident should not silently turn redaction off.

func DefaultLlmOptions

func DefaultLlmOptions() LlmOptions

DefaultLlmOptions matches the server's defaults: redact, no schema, no cap.

type LlmSource

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

LlmSource is one read-only source contributing to a context bundle.

func DocumentFindSource

func DocumentFindSource(collection string, filter DocumentFilter, limit int) LlmSource

DocumentFindSource is a document find. The caller needs document read permission. A zero DocumentFilter means "match everything".

func SQLSource

func SQLSource(query string) LlmSource

SQLSource is a SQL SELECT. The caller needs SQL read permission.

type NeighborOptions

type NeighborOptions struct {
	// Direction defaults to DirectionOutgoing when empty.
	Direction GraphDirection
	// Label keeps only edges with this label. Empty means every label.
	Label string
	// Limit caps the neighbors returned. Zero or less asks for the server
	// default (10,000, which is also the hard cap).
	Limit int
}

NeighborOptions narrows GraphNeighbors. The zero value follows outgoing edges of every label, up to the server's cap.

type Options

type Options struct {
	// Host is the server address. Defaults to "127.0.0.1".
	Host string
	// Port is the server's native protocol port. Defaults to [DefaultPort].
	Port int

	// User is the principal to authenticate as. Empty skips AUTH.
	User string
	// Secret is the password or token sent with User.
	Secret string

	// Database is sent as the `database` field of every REQUEST frame.
	// Defaults to "main".
	Database string

	// ClientName identifies this driver in the HELLO frame. Defaults to
	// "tricoredb-go".
	ClientName string

	// DialTimeout bounds the TCP connect only. Use ctx for the deadline
	// on the handshake/auth that follow.
	DialTimeout time.Duration

	// ReadTimeout is a client-side deadline on each steady-state read, or
	// zero (the default) for none.
	//
	// Deliberately separate from ctx's handshake deadline, which Connect
	// clears once AUTH completes: conflating the two is how the Python driver
	// turned a documented 10s *connect* timeout into an undocumented 10s
	// deadline on every query it would ever run. Deliberately separate also
	// from SetRequestTimeout, which makes the *server* stop; this one only
	// stops the wait.
	//
	// There is no default. A read legitimately blocks for exactly as long as
	// the statement runs, the server's own statement_timeout_ms defaults to
	// unlimited, and any number this driver picked would be a guess at a
	// guarantee the server does not make.
	ReadTimeout time.Duration

	// TLS turns on TLS when non-nil. Plain TCP otherwise — on which the
	// Secret above crosses the wire in the clear.
	TLS *TLSOptions

	// Features is the capability bitmap announced in HELLO. Nil (the default)
	// means [Features] — everything this build understands. The server grants
	// only what was asked for, so masking a bit out here is how a caller opts
	// out of one:
	//
	//	mask := tricoredb.Features &^ tricoredb.FeatureSessionTxn
	//	opts.Features = &mask
	//
	// A pointer rather than a plain uint64 because zero is a meaningful value
	// here — "announce nothing" — and must not be indistinguishable from
	// "unset".
	Features *uint64
}

Options configures a new connection. Host, Port, Database, and ClientName fall back to sane defaults when left zero; User/Secret are only sent (via an AUTH frame) when User is non-empty, matching servers that allow unauthenticated sessions.

type OutputFormat

type OutputFormat string

OutputFormat is how the server should render an export.

const (
	// FormatNative is TriCoreDB's own representation.
	FormatNative OutputFormat = "native"
	// FormatJSON is standard JSON.
	FormatJSON OutputFormat = "json"
	// FormatTOON is the token-oriented rendering for LLM context windows.
	FormatTOON OutputFormat = "toon"
	// FormatMarkdown is human-readable Markdown.
	FormatMarkdown OutputFormat = "markdown"
)

type PathOptions

type PathOptions struct {
	// Direction defaults to DirectionOutgoing when empty.
	Direction GraphDirection
	// Label keeps only edges with this label. Empty means every label.
	Label string
	// MaxDepth bounds the hop count. Zero or less asks for the server default,
	// which is also its maximum (10).
	MaxDepth int
}

PathOptions bounds a GraphShortestPath. The zero value searches outgoing edges of every label to the server's default depth (10).

type Pool

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

Pool is a bounded, concurrency-safe pool of connections.

Why this exists

A Client is a single request/response stream: two goroutines sharing one would interleave frames and read each other's replies. So concurrency needs one connection per concurrent caller — and the server scales ~3.3x across 8 concurrent connections (see benchmarks/concurrency/RESULTS.md), which is only reachable if an application actually opens several. Doing that per request costs a TCP connect plus HELLO and AUTH round trips every time (~14.5ms measured, against ~127µs pooled).

Exclusive ownership

Pool.Use runs a callback with a connection that is exclusively the callback's for its duration. That is deliberately a callback rather than an Acquire/Release pair returning a *Client: a returned handle is something a caller can retain and share across goroutines, which is exactly the corruption this type exists to prevent. (Release-on-panic is also handled, which a manual pair invites callers to get wrong.)

pool, err := tricoredb.NewPool(tricoredb.Options{Host: "127.0.0.1", Port: 8427,
	User: "admin", Secret: "pw"}, 8)
err = pool.Use(ctx, func(c *tricoredb.Client) error {
	_, err := c.Execute("INSERT INTO t VALUES (1, 'ada')")
	return err
})
pool.Close()

func NewPool

func NewPool(opts Options, size int) (*Pool, error)

NewPool builds a pool of at most `size` connections. Connections are created lazily: a pool sized for peak load should not pay for peak load at startup.

func (*Pool) Close

func (p *Pool) Close() error

Close closes every idle connection. Connections currently in use are closed when their Use returns.

func (*Pool) Size

func (p *Pool) Size() int

Size is the maximum number of connections the pool may hold.

func (*Pool) Stats

func (p *Pool) Stats() (idle, inUse int)

Stats reports (idle, inUse) at this instant. For tests and diagnostics.

A checked-out connection holds a token; an idle one does not. So the number in use is exactly the number of tokens taken — idle must NOT be subtracted again, or the count goes negative the moment a connection is returned.

func (*Pool) Use

func (p *Pool) Use(ctx context.Context, fn func(*Client) error) error

Use borrows a connection for the duration of fn.

It blocks until one is free or ctx is done, returning ErrPoolTimeout in the latter case rather than growing past `size` — an unbounded pool does not fix overload, it relocates it to the server.

A connection is retired rather than returned when fn reports a transport or protocol failure, because the stream may be mid-frame and reusing it would hand the next caller someone else's bytes.

A session transaction (Client.Begin) is bound to the connection, so one must never go back to the pool mid-block: the next borrower would be writing into somebody else's transaction. If fn returns with a block still open it is rolled back and Use returns an error naming it; if fn returns an error with one open it is rolled back and fn's error is what propagates; and a connection whose rollback fails is retired rather than reused. Use Client.WithTransaction inside the callback and none of this arises.

type ProtocolError

type ProtocolError struct {
	Message string
}

ProtocolError reports a violation of the wire protocol itself: an unexpected tag, a truncated frame, or a body that doesn't parse as the JSON shape the spec promises.

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

func (*ProtocolError) Unwrap

func (e *ProtocolError) Unwrap() error

type Response

type Response struct {
	// RequestID is the request_id the server echoed back.
	RequestID string
	// Status is the server's status string; "ok" on success.
	Status string

	// DataKind is the externally-tagged variant name of Data — one of
	// "Json", "CacheValue", "Rows", "Documents", "Message", "Empty".
	DataKind string
	// DataRaw is that variant's payload, still JSON-encoded, for callers
	// that need a shape this driver doesn't decode into a named field.
	DataRaw json.RawMessage

	Route     string
	ElapsedMs int64

	// Warnings are non-fatal, and not decorative: a broadcast DDL that
	// couldn't reach every shard reports it here while Status is still
	// "ok". A caller that ignores this can silently run on a divergent
	// cluster.
	Warnings []string

	// ErrorCode is the server's machine-readable reason a request failed
	// (diagnostics.error_code), empty when it did not fail or the server sent
	// none. Branch on this, never on the message text.
	ErrorCode string

	// LeaderHint is the `host:port` a refused write belongs to, set only
	// alongside an ErrorCode of [ErrorCodeNotLeader]. It is an address a client
	// can dial, resolved by the server from `[[raft.peers]].address`, not a node
	// id.
	//
	// Empty when the code is something else, and empty *even for a not_leader
	// refusal* in three cases: raised mid-election, raised on a non-Raft node,
	// and raised when the leader's id has no `[[raft.peers]]` entry to resolve.
	// So a caller must treat its absence as "destination unknown, wait and
	// retry", not as "no redirect happened". See [ServerError.LeaderHint].
	LeaderHint string
}

Response is a server response: the operation's typed result plus how it was produced.

type Rows

type Rows struct {
	Columns []string
	Rows    [][]string
}

Rows is a SQL result set: column names plus each row's values, both as the strings the server returns them as.

func (*Rows) Dicts

func (r *Rows) Dicts() []map[string]string

Dicts returns each row as a map keyed by column name, for callers that want name-based access instead of positional.

type ServerError

type ServerError struct {
	Message string
	// Status is the raw status string from the RESPONSE frame; kept for
	// callers that need to distinguish the cases rather than treat them
	// identically.
	Status string

	// Code is the server's machine-readable reason
	// (`diagnostics.error_code`), or "" when it sent none.
	//
	// This is the field to branch on. The message is prose and stays free to be
	// reworded; substring-matching it is how an authorization denial once
	// reached clients as something else entirely, which is the failure the code
	// was added to end.
	Code string

	// LeaderHint is a `host:port` this request should have gone to, carried
	// only with a Code of [ErrorCodeNotLeader].
	//
	// It is an **address a client can dial**, not a node id: the server resolves
	// the leader's id through `[[raft.peers]].address`, which names that node's
	// native protocol listener — the same endpoint this driver already speaks,
	// not a separate consensus port.
	//
	// Empty means "no address was named", which is NOT the same as "this is not
	// a redirect". Three situations produce a code with no hint: a refusal
	// raised mid-election, a node running without Raft, and a leader whose id
	// has no `[[raft.peers]]` entry — where the server deliberately sends
	// nothing rather than a bare id, because a label in an address field is a
	// connection attempt to a host that does not exist. All three mean the same
	// thing to a caller: wait and retry.
	//
	// The refusal's Message still names the leader's **node id**, on purpose:
	// prose is for a human reading logs and the hint is for a machine dialling.
	// Never scrape the id out of the message and use it as a destination — that
	// is exactly what this field replaces.
	//
	// Test [ServerError.Code] for the redirect and treat an empty hint as an
	// unknown destination.
	LeaderHint string
}

ServerError reports a REQUEST that the server processed but did not complete: any RESPONSE whose status is not "ok".

The kernel has three statuses — "ok", "error" and "not_implemented", the last meaning "a recognized hook that was NOT run" (crates/tricore_core/src/response/mod.rs). This driver compares against "ok" rather than enumerating the bad ones, so a status added to the kernel later fails closed instead of being handed to a caller as a success.

func (*ServerError) Error

func (e *ServerError) Error() string

func (*ServerError) IsNotLeader

func (e *ServerError) IsNotLeader() bool

IsNotLeader reports whether this refusal is a leader redirect: the request was valid, and this node is not the one that may serve it.

A true result says nothing about whether ServerError.LeaderHint is set — see that field. This driver deliberately does not follow the redirect itself: re-sending a write to another address is a policy decision (which endpoints are reachable, which credentials apply there, whether the operation is safe to repeat) that belongs to the caller, not to a connection object.

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

type SortKey

type SortKey struct {
	// Field is the field to sort by.
	Field string `json:"field"`
	// Descending sorts largest first when true.
	Descending bool `json:"descending"`
}

SortKey is one StageSort key. After a StageGroup the addressable fields are "_id" and the accumulator outputs, not the original document's fields.

type Statement

type Statement struct {
	// SQL is the statement text, with ? placeholders.
	SQL string
	// Args are the values bound to SQL's placeholders, in order.
	Args []Arg
}

Statement is one statement of a transaction script, with optional bound arguments.

func Stmt

func Stmt(sql string, args ...Arg) Statement

Stmt is shorthand for building a Statement.

type StreamEntry

type StreamEntry struct {
	ID     string
	Fields []CachePair
}

StreamEntry is one entry in a stream. Fields is authoritative — stream fields are arbitrary bytes; Text is a convenience for the all-UTF-8 case.

func (StreamEntry) Text

func (e StreamEntry) Text() map[string]string

Text decodes the fields as UTF-8. Wrong for binary payloads; Fields stays authoritative.

type TLSOptions

type TLSOptions struct {
	// CAFile is a PEM bundle used to verify the server. When empty the trust
	// store is left EMPTY rather than falling back to the system roots —
	// matching the Rust client, and making a typo'd path fail closed instead
	// of quietly succeeding against some unrelated public CA.
	CAFile string

	// ServerName is the expected server name (SNI and certificate name).
	// Defaults to "localhost".
	ServerName string

	// DangerAcceptInvalidCerts disables certificate and hostname verification.
	// DEVELOPMENT ONLY. A connection with this set looks encrypted but
	// authenticates nothing, so an active attacker can sit in the middle
	// undetected — which is strictly worse than visibly using plain TCP.
	DangerAcceptInvalidCerts bool

	// ClientCertFile is a PEM client certificate chain to present (mTLS).
	// Requires ClientKeyFile.
	ClientCertFile string
	// ClientKeyFile is the PEM private key for ClientCertFile (mTLS).
	ClientKeyFile string
}

TLSOptions configures the TLS session. It mirrors the Rust client's TlsOptions (crates/tricore_client/src/tls.rs).

Supplying a *TLSOptions at all is what enables TLS. Once enabled the server certificate is verified and its name checked, unless DangerAcceptInvalidCerts is set.

mTLS

Set ClientCertFile and ClientKeyFile to present a client identity. A server with require_client_cert = true rejects a client that does not.

Secret hygiene

Private key contents are never logged. Errors name the *path* so an operator can find the file, never the bytes in it.

type TimeoutError

type TimeoutError struct {
	Message string
}

TimeoutError reports that a read (or the connect phase) exceeded its budget.

A distinct type rather than the bare net.Error the standard library returns, so `errors.Is(err, tricoredb.ErrTimeout)` works and so a timeout cannot escape this driver's error vocabulary the way a raw os.ErrDeadlineExceeded would.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Temporary

func (e *TimeoutError) Temporary() bool

Temporary reports false. See Timeout.

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Timeout and Temporary together satisfy net.Error, so code already branching on that interface keeps working — before this type existed a read deadline surfaced as a raw *net.OpError, which is a net.Error, and silently losing that would break callers that were handling it correctly.

Temporary is false: this driver poisons a timed-out connection, because the reply it stopped waiting for may still be in flight and reusing the socket would read it as the answer to the next request. Retrying on the same connection is exactly what must not happen. (net.Error.Temporary is deprecated but remains part of the interface, so it has to be implemented to satisfy it.)

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

type TransactionResult

type TransactionResult struct {
	// Statements is the number of statements the server ran.
	Statements int64 `json:"statements"`
	// CommittedWrites is the number of writes made durable.
	CommittedWrites int64 `json:"committed_writes"`
	// DiscardedWrites is the number of buffered writes thrown away.
	DiscardedWrites int64 `json:"discarded_writes"`
	// Outcome is "began", "committed" or "rolled_back".
	Outcome string `json:"transaction"`
}

TransactionResult is what the server did with a transaction script.

type TraverseOptions

type TraverseOptions struct {
	// Direction defaults to DirectionOutgoing when empty.
	Direction GraphDirection
	// Label keeps only edges with this label. Empty means every label.
	Label string
	// MaxDepth bounds the hop count. Zero or less asks for the server default
	// (3); the server clamps anything above 10.
	MaxDepth int
	// Limit caps the nodes returned. Zero or less asks for the server default
	// (100); the server clamps to 1..=1000.
	Limit int
}

TraverseOptions bounds a GraphTraverse. The zero value walks outgoing edges of every label to the server's default depth (3) and node limit (100).

type UpdateManyResult

type UpdateManyResult struct {
	Matched  int64 `json:"matched"`
	Modified int64 `json:"modified"`
}

UpdateManyResult counts what a DocumentUpdateMany did. Matched counts documents the filter selected; Modified counts those whose contents actually changed, so an update that rewrote a document to the value it already held is matched but not modified.

type VectorCollectionInfo

type VectorCollectionInfo struct {
	// Collection is the collection name.
	Collection string `json:"collection"`
	// Dimension is the length every vector in the collection must have.
	Dimension int `json:"dimension"`
	// Metric is the distance metric searches rank by.
	Metric VectorMetric `json:"metric"`
	// Count is the number of vectors currently stored.
	Count int64 `json:"count"`
	// Quantization is the index quantization the collection was created with.
	Quantization VectorQuantization `json:"quantization"`
}

VectorCollectionInfo is a collection's catalog metadata plus its live vector count, from VectorDescribeCollection.

type VectorCollectionSummary

type VectorCollectionSummary struct {
	// Name is the collection name.
	Name string `json:"name"`
	// Dimension is the length every vector in the collection must have.
	Dimension int `json:"dimension"`
	// Metric is the distance metric searches rank by.
	Metric VectorMetric `json:"metric"`
}

VectorCollectionSummary is one entry of VectorListCollections.

type VectorHit

type VectorHit struct {
	ID       string         `json:"id"`
	Score    float32        `json:"score"`
	Metadata map[string]any `json:"metadata"`
}

VectorHit is one search result.

Score is a similarity, never a distance: **higher is closer under every metric**, and Results is ordered best-first. MetricL2 is the case worth stating outright — the server negates the squared Euclidean distance (crates/tricore_vector/src/search/mod.rs) so the ranking stays uniform, which means an l2 Score is <= 0 and -0.02 is nearer than -196.0. Sorting these ascending, or reading Score as a distance, inverts an l2 ranking while a "is the expected id in the top-k" check still passes.

type VectorItem

type VectorItem struct {
	ID       string         `json:"id"`
	Vector   []float32      `json:"vector"`
	Metadata map[string]any `json:"metadata"`
}

VectorItem is one stored vector with its metadata.

type VectorMetric

type VectorMetric string

VectorMetric is a vector collection's distance/similarity measure. It is fixed when the collection is created and cannot be changed afterwards.

const (
	// MetricCosine is cosine similarity: higher is closer.
	MetricCosine VectorMetric = "cosine"
	// MetricDot is the dot product: higher is closer.
	MetricDot VectorMetric = "dot"
	// MetricL2 is squared Euclidean distance. Note the sign: the server
	// returns it *negated*, so an l2 VectorHit.Score is <= 0 and -0.02 is
	// nearer than -196.0. See VectorHit.Score.
	MetricL2 VectorMetric = "l2"
)

type VectorPage

type VectorPage struct {
	// Collection is the collection name.
	Collection string `json:"collection"`
	// Count is the number of vectors on this page.
	Count int `json:"count"`
	// Vectors are this page's items.
	Vectors []VectorItem `json:"vectors"`
	// Truncated reports that more vectors remain past this page.
	Truncated bool `json:"truncated"`
	// Total is the collection's full vector count.
	Total int64 `json:"total"`
}

VectorPage is one page of VectorListVectors. Truncated reports that items remain past this page; Total is the collection's full count.

type VectorQuantization

type VectorQuantization string

VectorQuantization selects how a collection's ANN index stores vectors in memory. It is an index-level choice only: the durable records always keep full float32 precision, so VectorGet and VectorListVectors return byte-identical values either way.

const (
	// QuantizationNone keeps full float32 vectors in the index. The default.
	QuantizationNone VectorQuantization = "none"
	// QuantizationInt8 stores int8-quantized vectors in the index (roughly 4x
	// smaller) and re-ranks the candidate pool against the durable float32
	// vectors, at the cost of one point read per candidate.
	QuantizationInt8 VectorQuantization = "int8"
)

type VectorSearchResult

type VectorSearchResult struct {
	Results []VectorHit `json:"results"`
	Index   string      `json:"index"`
}

VectorSearchResult is a search's hits plus which path answered it: "flat" for the exact scan a small collection gets, "hnsw" or "hnsw-int8" for the ANN index.

type WeightedPathOptions

type WeightedPathOptions struct {
	// Direction defaults to DirectionOutgoing when empty.
	Direction GraphDirection
	// Label keeps only edges with this label. Empty means every label.
	Label string
	// WeightProperty names the edge property holding the cost. Empty means
	// "weight". An edge missing it, or holding a non-number, weighs 1.0; a
	// negative weight is refused rather than mis-solved.
	WeightProperty string
}

WeightedPathOptions bounds a GraphWeightedShortestPath.

There is deliberately no MaxDepth: a weighted search is bounded by settled cost, not by hop count, and a depth clamp would silently discard the cheap-but-long path that is the whole reason to run one.

Directories

Path Synopsis
conformance
runner command
Command runner is the Go conformance runner for this module.
Command runner is the Go conformance runner for this module.

Jump to

Keyboard shortcuts

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