Help us shape the future of Go! Take the 2026 Go Developer Survey

tricoredb

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 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
  • The methods added in 0.3.0, marked below, need tricore-server 0.1.0-rc.3 or later. An older server does not know those operations and answers them with an error; everything else works against it as before.
  • 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
DisableFollowLeader false Return not_leader refusals instead of sending them to the leader
LeaderRetries 5 How many times a refused request is sent again
LeaderRetryDelay 250ms First pause before asking again; doubles up to 2s
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

Added in 0.3.0, for server 0.1.0-rc.3 and later (an older server answers them with an error):

Family Methods
Many keys, conditions CacheMGet, CacheMSet, CacheWarm, CacheSetIf, CacheCompareAndSwap, CacheGetDel, CacheGetSet, CacheGetEx, CacheAppend, CacheExpireAt
Stale-while-revalidate CacheSetFresh, CacheGetFresh, CacheSetMissing
Sorted sets CacheZAdd, CacheZRem, CacheZScore, CacheZCard, CacheZRank, CacheZRange, CacheZRangeWithScores, CacheZRangeByScore, CacheZRangeByScoreWithScores, CacheZIncrBy
Locks CacheLockAcquire, CacheLockRenew, CacheLockRelease
Bitmaps CacheSetBit, CacheGetBit, CacheBitCount, CacheBitPos, CacheBitOp
HyperLogLog CachePfAdd, CachePfCount, CachePfMerge
Lists, sets, hashes CacheLMove, CacheLTrim, CacheBLPop, CacheBRPop, CacheSUnion, CacheSInter, CacheSDiff, CacheSRandMember, CacheSRandMembers, CacheHIncrBy
Pipelines and scripts CachePipeline, CacheTransaction, CacheScriptLoad, CacheScriptRun
Publish and poll CachePublish, CachePoll
Node and database CacheStats, CacheHotKeys, CachePurgeExpired, CacheFlushDatabase, CacheSetNamespaceLimit, CacheGetNamespaceLimit
db.CacheZAdd("game", "board", tricoredb.ScoredMember{Score: 120, Member: []byte("ada")})
top, err := db.CacheZRangeWithScores("game", "board", 0, 9, true)

lock, err := db.CacheLockAcquire("jobs", "nightly", "worker-1", 30_000)
if err == nil && lock.Acquired {
	// Pass lock.Token to whatever the lock protects.
	db.CacheLockRelease("jobs", "nightly", "worker-1")
}

replies, err := db.CachePipeline(
	tricoredb.CmdSet("sessions", "u1", []byte("token"), 0),
	tricoredb.CmdGet("sessions", "u1"),
)

A sorted-set score is always finite, and JSON has no spelling for an infinity, so an open range end is ScoreLowest() or ScoreHighest(); a non-finite score or bound is refused before anything is sent. CacheHotKeys answers only when the server's [cache] hot_keys setting is above zero, and returns the payload as the server sent it. CacheFlushDatabase deletes every cache key in the connection's database.

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.

Added in 0.3.0, for server 0.1.0-rc.3 and later: DocumentReplace, DocumentInsertMany, DocumentDeleteMany, DocumentBulkWrite, DocumentRenameCollection, DocumentPurgeExpired, DocumentExplain, DocumentRebuildIndex, DocumentSetCollectionOptions, DocumentGetCollectionOptions, DocumentBeginTransaction, DocumentCommitTransaction and DocumentRollbackTransaction.

// One atomic batch: every operation lands or none does.
res, err := db.DocumentBulkWrite("orders",
	tricoredb.BulkInsertWithID("o1", map[string]any{"total": 10}),
	tricoredb.BulkUpdateOne("o2", tricoredb.DocumentUpdate{Inc: map[string]any{"total": 5}}).Upsert(),
	tricoredb.BulkDelete("o3"),
)

// A transaction spans requests. Requests join it by naming it.
txn, err := db.DocumentBeginTransaction(false)
db.SetRequestTxn(txn)
db.DocumentInsertWithID("orders", "o4", map[string]any{"total": 1})
_, err = db.DocumentCommitTransaction(txn) // also stops naming it

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.

Added in 0.3.0, for server 0.1.0-rc.3 and later: VectorUpsertMany, VectorUpsertText, VectorUpsertNamed, VectorAddNamedVector, VectorDeleteMany, VectorDeleteByFilter, VectorUpdateByFilter, VectorCount, VectorSearchBatch, VectorSearchMulti, VectorSearchByExamples, VectorEmbed, VectorSetAlias, VectorListAliases, VectorListPartitions, VectorRenameCollection, VectorCopyCollection, VectorSetCollectionConfig, VectorRebuildIndex, VectorIndexStats and VectorMeasureRecall. VectorSearchOptions carries the filter, the named vector to search (Using) and the other per-search settings; a field left at its zero value is not sent.

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.

Added in 0.3.0, for server 0.1.0-rc.3 and later:

Family Methods
Batch writes GraphAddMany, GraphRemoveMany, GraphUpdateNode, GraphUpdateEdge, GraphCopy, GraphImportCSV
Walks and paths GraphDfs, GraphSubgraph, GraphKShortestPaths, GraphAllPaths
Algorithms GraphConnectedComponents, GraphDetectCycle, GraphCentrality, GraphCommunities, GraphTriangleCount, GraphNodeSimilarity, GraphPageRank
Descriptions GraphStats, GraphSchema, GraphCheckConsistency
Indexes and constraints GraphCreateNodeIndex, GraphCreateConstraint, GraphDropSchemaObject, GraphListSchemaObjects, GraphFindNodes
Cypher writes GraphExecute, GraphBeginTransaction, GraphCommitTransaction, GraphRollbackTransaction

A graph transaction queues GraphExecute statements sent while SetRequestTxn names it, and the commit applies them all or none.

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 only the leader accepts writes, and a follower refuses with Code == "not_leader". The client handles that itself:

  • when the refusal names the leader, it opens a connection there with the same User, Secret and TLS settings (the leader's host is the TLS server name), sends the request again, and keeps that connection (Address() reports it);
  • while an election is in progress (no leader named), it waits and asks the same node again, pausing 250ms, then 500ms, up to 2s;
  • after LeaderRetries (5) it returns the last refusal, with Retried set.

This is safe because a not_leader refusal was applied nowhere. Nothing is sent again inside a session transaction, and never a refusal with Code == "outcome_unknown" (ErrorCodeOutcomeUnknown): a follower handed that request to the leader and lost the answer, so it may have been applied. The leader's address must be reachable from your application; when it is not, the client keeps its connection and waits.

To handle redirects yourself, set DisableFollowLeader:

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.

e2e_models can instead use a server that is already running: set TRICORE_TEST_ADDR to its host:port together with TRICORE_TEST_USER and TRICORE_TEST_SECRET. All three are required; the suite does not guess a password.

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 ErrorCodeOutcomeUnknown = "outcome_unknown"

ErrorCodeOutcomeUnknown is the code of a request a follower handed to the leader and lost the answer to. It may or may not have been applied, so the driver never sends it again.

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.3.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 ExpectVersion added in v0.3.0

func ExpectVersion(v uint64) *uint64

ExpectVersion is an expected document version, for the ExpectedVersion fields. It exists because 0 is meaningful there — "must not exist yet" — so the absence of a check has to be nil rather than zero.

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 AnnIndex added in v0.3.0

type AnnIndex string

AnnIndex is which approximate index a search uses.

const (
	AnnHnsw  AnnIndex = "hnsw"
	AnnIvf   AnnIndex = "ivf"
	AnnIvfPq AnnIndex = "ivf_pq"
)

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 BitOpKind added in v0.3.0

type BitOpKind string

BitOpKind is the bitwise operation CacheBitOp applies across its sources.

const (
	BitAnd BitOpKind = "And"
	BitOr  BitOpKind = "Or"
	BitXor BitOpKind = "Xor"
	// BitNot inverts every bit, and takes exactly one source.
	BitNot BitOpKind = "Not"
)

type BulkOp added in v0.3.0

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

BulkOp is one operation of DocumentBulkWrite. Build one with BulkInsert, BulkInsertWithID, BulkUpdateOne, BulkReplace or BulkDelete.

The zero BulkOp is invalid and is refused rather than skipped: a batch that quietly dropped an operation would report success for work it did not do.

func BulkDelete added in v0.3.0

func BulkDelete(id string) BulkOp

BulkDelete deletes one document by id.

func BulkInsert added in v0.3.0

func BulkInsert(document any) BulkOp

BulkInsert inserts a document under its own _id, or a generated one.

func BulkInsertWithID added in v0.3.0

func BulkInsertWithID(id string, document any) BulkOp

BulkInsertWithID inserts a document under an id you choose.

func BulkReplace added in v0.3.0

func BulkReplace(id string, document any) BulkOp

BulkReplace swaps one document's whole body.

func BulkUpdateOne added in v0.3.0

func BulkUpdateOne(id string, update DocumentUpdate) BulkOp

BulkUpdateOne applies an update to one document by id.

func (BulkOp) ExpectedVersion added in v0.3.0

func (o BulkOp) ExpectedVersion(version uint64) BulkOp

ExpectedVersion applies the operation only if the document's _version is still version, compared with the version it had before the batch. It changes nothing on an insert.

func (BulkOp) MarshalJSON added in v0.3.0

func (o BulkOp) MarshalJSON() ([]byte, error)

MarshalJSON writes the server's externally-tagged form.

func (BulkOp) Upsert added in v0.3.0

func (o BulkOp) Upsert() BulkOp

Upsert creates the document when it does not exist. It changes nothing on an insert or a delete, which have no such choice.

type BulkWriteResult added in v0.3.0

type BulkWriteResult struct {
	Inserted int64 `json:"inserted"`
	Updated  int64 `json:"updated"`
	// Upserted counts documents created by an upsert.
	Upserted int64 `json:"upserted"`
	Replaced int64 `json:"replaced"`
	Deleted  int64 `json:"deleted"`
	// InsertedIDs are the ids of the inserted documents, in the order their
	// operations were given.
	InsertedIDs []string `json:"inserted_ids"`
}

BulkWriteResult is what DocumentBulkWrite applied.

type ByteRange added in v0.3.0

type ByteRange struct {
	Start int64
	End   int64
}

ByteRange is an inclusive range of bytes within a value. Negative indices count from the end, so {0, -1} is the whole value.

type CacheCommand added in v0.3.0

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

CacheCommand is one cache operation inside CachePipeline, CacheTransaction or a script. Build one with the Cmd* constructors; CmdRaw builds any other from the server's own variant name and fields.

The zero CacheCommand is invalid and is refused rather than skipped.

func CmdDelete added in v0.3.0

func CmdDelete(namespace, key string) CacheCommand

CmdDelete deletes a key.

func CmdExists added in v0.3.0

func CmdExists(namespace, key string) CacheCommand

CmdExists reports whether a key is present and unexpired.

func CmdGet added in v0.3.0

func CmdGet(namespace, key string) CacheCommand

CmdGet reads a value.

func CmdIncr added in v0.3.0

func CmdIncr(namespace, key string, by int64) CacheCommand

CmdIncr adds by to a counter.

func CmdRaw added in v0.3.0

func CmdRaw(variant string, body map[string]any) CacheCommand

CmdRaw is any cache operation, by the server's variant name and its fields. A nil body is an operation that takes no fields, such as "Ping".

func CmdSet added in v0.3.0

func CmdSet(namespace, key string, value []byte, ttlMs int64) CacheCommand

CmdSet stores a value; ttlMs <= 0 means no expiry.

func (CacheCommand) MarshalJSON added in v0.3.0

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

MarshalJSON writes the server's externally-tagged form.

type CacheEntry added in v0.3.0

type CacheEntry struct {
	Key   string
	Value []byte
}

CacheEntry is one key and its value, as CacheMSet and CacheWarm take them.

type CacheExpiry added in v0.3.0

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

CacheExpiry says what an operation does with a key's deadline. Build one with ExpiryKeep, ExpirySet or ExpiryClear.

Three intents rather than an optional duration, because "leave the TTL alone" and "remove it" would otherwise share a spelling. The zero CacheExpiry is invalid and is refused rather than guessed at.

func ExpiryClear added in v0.3.0

func ExpiryClear() CacheExpiry

ExpiryClear removes the deadline, making the key permanent.

func ExpiryKeep added in v0.3.0

func ExpiryKeep() CacheExpiry

ExpiryKeep leaves the deadline as it is.

func ExpirySet added in v0.3.0

func ExpirySet(ttlMs int64) CacheExpiry

ExpirySet expires the key ttlMs milliseconds from now.

func (CacheExpiry) MarshalJSON added in v0.3.0

func (e CacheExpiry) MarshalJSON() ([]byte, error)

MarshalJSON writes the server's externally-tagged form.

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 CacheLock added in v0.3.0

type CacheLock struct {
	Acquired bool `json:"acquired"`
	// Token is the fencing token when the lock was acquired, and zero
	// otherwise. It rises with every acquisition and is never reused; pass it
	// to the resource the lock protects.
	Token uint64 `json:"token"`
	// Holder is who holds the lock.
	Holder string `json:"holder"`
	// ExpiresAtMs is when the current lease ends, in Unix epoch milliseconds.
	ExpiresAtMs int64 `json:"expiresAtMs"`
}

CacheLock is the answer to CacheLockAcquire.

type CacheLockRenewal added in v0.3.0

type CacheLockRenewal struct {
	// Renewed is false once the lease has lapsed, even when nobody else took
	// the lock since.
	Renewed     bool   `json:"renewed"`
	Token       uint64 `json:"token"`
	ExpiresAtMs int64  `json:"expiresAtMs"`
}

CacheLockRenewal is the answer to CacheLockRenew.

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 CacheReply added in v0.3.0

type CacheReply struct {
	// Err is the server's message when the operation failed, and empty when
	// it succeeded. The operations after a failed one still ran.
	Err string
	// DataKind names the data variant of a success, as Response.DataKind does.
	DataKind string
	// DataRaw is that variant's payload.
	DataRaw json.RawMessage
}

CacheReply is what one operation of a pipeline, transaction or script answered.

func (CacheReply) OK added in v0.3.0

func (r CacheReply) OK() bool

OK reports whether the operation succeeded.

func (CacheReply) Value added in v0.3.0

func (r CacheReply) Value() (value []byte, found bool)

Value is the bytes of a CacheValue reply. found is false for a miss, and for a reply that is not a value at all.

type CacheStats added in v0.3.0

type CacheStats struct {
	Hits   uint64 `json:"hits"`
	Misses uint64 `json:"misses"`
	// HitRatio is hits over lookups, and nil before the first lookup.
	HitRatio *float64 `json:"hitRatio"`
	Memory   struct {
		Enabled       bool    `json:"enabled"`
		MaxBytes      *uint64 `json:"maxBytes"`
		LowWaterBytes *uint64 `json:"lowWaterBytes"`
		// ResidentBytes is nil until a measurement has been taken.
		ResidentBytes *uint64 `json:"residentBytes"`
		Measurements  uint64  `json:"measurements"`
	} `json:"memory"`
	Eviction struct {
		Policy  string `json:"policy"`
		Evicted uint64 `json:"evicted"`
	} `json:"eviction"`
}

CacheStats is what one node's cache is doing. Node-wide, not per database.

type CentralityMeasure added in v0.3.0

type CentralityMeasure string

CentralityMeasure is the measure GraphCentrality computes.

const (
	CentralityBetweenness CentralityMeasure = "betweenness"
	CentralityCloseness   CentralityMeasure = "closeness"
	CentralityEigenvector CentralityMeasure = "eigenvector"
)

type CentralityOptions added in v0.3.0

type CentralityOptions struct {
	// Undirected treats every edge as two-way; the server follows edge
	// direction by default.
	Undirected bool
	Label      string
	// Limit is how many nodes to return (default 20, capped at 1000).
	Limit int
	// Iterations and Tolerance tune eigenvector centrality only.
	Iterations int
	Tolerance  float64
}

CentralityOptions narrows GraphCentrality.

type ChannelMessage added in v0.3.0

type ChannelMessage struct {
	// ID rises across every channel.
	ID      uint64 `json:"id"`
	Channel string `json:"channel"`
	Message string `json:"message"`
	// AtMs is when it was published, in Unix epoch milliseconds.
	AtMs int64 `json:"at_ms"`
}

ChannelMessage is one message read by CachePoll.

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) Address added in v0.3.0

func (c *Client) Address() string

Address is the host:port this connection talks to. It changes when the driver follows the leader.

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) CacheAppend added in v0.3.0

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

CacheAppend concatenates bytes onto a key's value, creating it when absent, and returns the new length. An existing key keeps its expiry.

func (*Client) CacheBLPop added in v0.3.0

func (c *Client) CacheBLPop(namespace string, timeoutMs int64, keys ...string) (key string, value []byte, found bool, err error)

CacheBLPop pops the head of the first non-empty list among keys, waiting up to timeoutMs for one to receive an element. It returns the key the element came from; found is false when the wait ran out.

The wait happens on the server, so keep timeoutMs under this connection's read timeout.

func (*Client) CacheBRPop added in v0.3.0

func (c *Client) CacheBRPop(namespace string, timeoutMs int64, keys ...string) (key string, value []byte, found bool, err error)

CacheBRPop is CacheBLPop from the tail.

func (*Client) CacheBitCount added in v0.3.0

func (c *Client) CacheBitCount(namespace, key string, r *ByteRange) (int64, error)

CacheBitCount counts the set bits, optionally within a byte range. A nil range counts the whole value.

func (*Client) CacheBitOp added in v0.3.0

func (c *Client) CacheBitOp(namespace string, kind BitOpKind, dest string, keys ...string) (int64, error)

CacheBitOp combines several values bitwise, stores the result at dest, and returns its size in bytes. Shorter sources are zero-padded to the longest.

func (*Client) CacheBitPos added in v0.3.0

func (c *Client) CacheBitPos(namespace, key string, bit bool, r *ByteRange) (int64, error)

CacheBitPos returns the position of the first bit equal to bit, optionally within a byte range, or -1 when there is none.

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) CacheCompareAndSwap added in v0.3.0

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

CacheCompareAndSwap writes only if the key still holds what the caller last read.

A nil expected requires the key to be absent, and a nil value deletes it; an empty non-nil slice is the empty value. On a mismatch nothing is written and the result carries what is actually there. ttlMs <= 0 means no expiry.

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) CacheExpireAt added in v0.3.0

func (c *Client) CacheExpireAt(namespace, key string, atMs int64) (*ExpireAtResult, error)

CacheExpireAt sets the instant an existing live key dies, in Unix epoch milliseconds. A deadline already passed deletes the key.

func (*Client) CacheFlushDatabase added in v0.3.0

func (c *Client) CacheFlushDatabase() (int64, error)

CacheFlushDatabase deletes every cache key in this connection's database, across every namespace, returning how many went.

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) CacheGetBit added in v0.3.0

func (c *Client) CacheGetBit(namespace, key string, offset uint64) (bool, error)

CacheGetBit reads one bit. Past the end of the value, and on a missing key, every bit is unset.

func (*Client) CacheGetDel added in v0.3.0

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

CacheGetDel reads a key and deletes it in one atomic step. found is false when it was absent.

func (*Client) CacheGetEx added in v0.3.0

func (c *Client) CacheGetEx(namespace, key string, expiry CacheExpiry) ([]byte, bool, error)

CacheGetEx reads a key and changes its deadline in the same atomic step.

func (*Client) CacheGetFresh added in v0.3.0

func (c *Client) CacheGetFresh(namespace, key, owner string, leaseMs int64) (*FreshRead, error)

CacheGetFresh reads with stale-while-revalidate and stampede protection.

owner names this caller; of the callers that find a value stale or missing, one is handed a lease of leaseMs to recompute it and the rest are told to serve the stale value or wait.

func (*Client) CacheGetNamespaceLimit added in v0.3.0

func (c *Client) CacheGetNamespaceLimit(namespace string) (*NamespaceLimit, error)

CacheGetNamespaceLimit returns a namespace's limit and what it holds now.

func (*Client) CacheGetSet added in v0.3.0

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

CacheGetSet writes a value and returns the one it replaced, atomically. The old value's TTL is dropped; ttlMs > 0 sets one. found is false when there was no previous value.

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) CacheHIncrBy added in v0.3.0

func (c *Client) CacheHIncrBy(namespace, key string, field []byte, by int64) (int64, error)

CacheHIncrBy adds by to one hash field, atomically, and returns the new value. A missing field starts at zero.

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) CacheHotKeys added in v0.3.0

func (c *Client) CacheHotKeys(limit int) (json.RawMessage, error)

CacheHotKeys returns the most frequently addressed keys on this node since it started. limit <= 0 leaves the cap to the server.

The server answers only when [cache] hot_keys is above zero in its configuration, and refuses otherwise. The payload is returned as the server sent it.

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) CacheLMove added in v0.3.0

func (c *Client) CacheLMove(namespace, source, destination string, from, to ListEnd) ([]byte, bool, error)

CacheLMove atomically pops an element from one end of source and pushes it onto one end of destination. found is false when source is empty. The two may be the same key, which rotates the list.

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) CacheLTrim added in v0.3.0

func (c *Client) CacheLTrim(namespace, key string, start, stop int64) (*TrimResult, error)

CacheLTrim keeps only the inclusive index range of a list, dropping the rest. A range selecting nothing empties the list, which deletes the key.

func (*Client) CacheLockAcquire added in v0.3.0

func (c *Client) CacheLockAcquire(namespace, key, owner string, ttlMs int64) (*CacheLock, error)

CacheLockAcquire takes a lease on a lock, or refreshes one owner already holds. Acquiring a lock you hold returns the same token with a refreshed lease, so a retried acquire is safe.

func (*Client) CacheLockRelease added in v0.3.0

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

CacheLockRelease gives up a lock. False when owner is not its live holder.

func (*Client) CacheLockRenew added in v0.3.0

func (c *Client) CacheLockRenew(namespace, key, owner string, ttlMs int64) (*CacheLockRenewal, error)

CacheLockRenew extends a lease the caller still holds.

func (*Client) CacheMGet added in v0.3.0

func (c *Client) CacheMGet(namespace string, keys ...string) ([][]byte, error)

CacheMGet reads many values in one round trip.

It returns one value per key, in the order asked, with nil where the key is absent or expired; a stored empty value is an empty, non-nil slice. Not a snapshot: another writer may land between two of the reads.

func (*Client) CacheMSet added in v0.3.0

func (c *Client) CacheMSet(namespace string, entries []CacheEntry, ttlMs int64) (int64, error)

CacheMSet writes many values as one batch, all with the same optional TTL, and returns how many were written. A repeated key is refused by the server rather than resolved last-wins. ttlMs <= 0 means no expiry.

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) CachePfAdd added in v0.3.0

func (c *Client) CachePfAdd(namespace, key string, elements ...[]byte) (bool, error)

CachePfAdd adds elements to a HyperLogLog, creating it when absent. It reports whether the estimate may have moved.

func (*Client) CachePfCount added in v0.3.0

func (c *Client) CachePfCount(namespace string, keys ...string) (int64, error)

CachePfCount returns the estimated number of distinct elements. With several keys, the estimate is of their union.

func (*Client) CachePfMerge added in v0.3.0

func (c *Client) CachePfMerge(namespace, dest string, sources ...string) error

CachePfMerge merges several HyperLogLogs into dest, which counts as a source when it already exists.

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) CachePipeline added in v0.3.0

func (c *Client) CachePipeline(ops ...CacheCommand) ([]CacheReply, error)

CachePipeline runs operations in order in one round trip, each exactly as if it had been sent alone. A failing operation does not stop the rest.

func (*Client) CachePoll added in v0.3.0

func (c *Client) CachePoll(after uint64, limit int, channels ...string) (*PollResult, error)

CachePoll returns the messages after id after on these channels. It never blocks.

A channel name ending in * is a pattern, and __keyspace__* or __keyevent__* turns keyspace notifications on while it is polled. limit <= 0 leaves the cap to the server (100).

func (*Client) CachePublish added in v0.3.0

func (c *Client) CachePublish(channel, message string) (uint64, error)

CachePublish appends a message to a channel, returning the id it was given.

func (*Client) CachePurgeExpired added in v0.3.0

func (c *Client) CachePurgeExpired() (int64, error)

CachePurgeExpired deletes every expired cache key in this database now, rather than leaving it to compaction, returning how many went.

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) CacheSDiff added in v0.3.0

func (c *Client) CacheSDiff(namespace string, keys ...string) ([][]byte, error)

CacheSDiff returns the members of the first set that are in none of the rest.

func (*Client) CacheSInter added in v0.3.0

func (c *Client) CacheSInter(namespace string, keys ...string) ([][]byte, error)

CacheSInter returns the members present in every named set.

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) CacheSRandMember added in v0.3.0

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

CacheSRandMember returns one random member of a set without removing it, or none when the set is empty.

func (*Client) CacheSRandMembers added in v0.3.0

func (c *Client) CacheSRandMembers(namespace, key string, count int64) ([][]byte, error)

CacheSRandMembers returns random members of a set without removing them.

A positive count gives up to count distinct members; a negative one gives exactly -count members with repeats allowed; zero gives none.

func (*Client) CacheSRem

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

CacheSRem removes members, returning how many were present.

func (*Client) CacheSUnion added in v0.3.0

func (c *Client) CacheSUnion(namespace string, keys ...string) ([][]byte, error)

CacheSUnion returns every member of every named set, without duplicates. A missing key is the empty set.

func (*Client) CacheScriptLoad added in v0.3.0

func (c *Client) CacheScriptLoad(name string, ops ...CacheCommand) error

CacheScriptLoad stores a script: operations that run as one transaction, where any string or value written $1, $2, ... is replaced by that argument at run time. Loading the same name again replaces it.

func (*Client) CacheScriptRun added in v0.3.0

func (c *Client) CacheScriptRun(name string, args ...string) ([]CacheReply, error)

CacheScriptRun runs a stored script with these arguments as one transaction.

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) CacheSetBit added in v0.3.0

func (c *Client) CacheSetBit(namespace, key string, offset uint64, value bool) (previous bool, err error)

CacheSetBit sets one bit of a string value, growing it with zero bytes if needed, and returns the bit's old value. Bits are numbered from the most significant bit of byte 0.

func (*Client) CacheSetFresh added in v0.3.0

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

CacheSetFresh writes a value that reads as fresh for freshMs and as stale after that, until its TTL (if any) ends. It returns when the value stops being fresh, in Unix epoch milliseconds.

func (*Client) CacheSetIf added in v0.3.0

func (c *Client) CacheSetIf(namespace, key string, value []byte, condition SetCondition, expiry CacheExpiry) (bool, error)

CacheSetIf writes a value under a condition, saying what happens to the deadline. False means the condition was not met, not that anything failed. ExpiryKeep is Redis's KEEPTTL; ExpiryClear is what a plain set does.

func (*Client) CacheSetMissing added in v0.3.0

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

CacheSetMissing remembers for ttlMs that the source has no value for key: negative caching.

func (*Client) CacheSetNamespaceLimit added in v0.3.0

func (c *Client) CacheSetNamespaceLimit(namespace string, maxKeys, maxBytes uint64) (*NamespaceLimit, error)

CacheSetNamespaceLimit caps a namespace at maxKeys live keys and maxBytes of values. A write that would pass either is refused. Zero means no cap of that kind, and both zero removes the limit.

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) CacheStats added in v0.3.0

func (c *Client) CacheStats() (*CacheStats, error)

CacheStats reports what this node's cache is doing: hits and misses, the memory budget and the eviction policy. Node-wide, not per database.

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) CacheTransaction added in v0.3.0

func (c *Client) CacheTransaction(ops ...CacheCommand) ([]CacheReply, error)

CacheTransaction runs operations in order holding the cache write lock throughout, so no other writer interleaves with them.

Every operation's inputs are checked before any runs. After that there is no rollback: one that fails is reported and the rest still run.

func (*Client) CacheWarm added in v0.3.0

func (c *Client) CacheWarm(namespace string, entries []CacheEntry, ttlMs int64) (*WarmResult, error)

CacheWarm writes the entries that are not already cached, leaving live values alone. ttlMs <= 0 means no expiry.

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) CacheZAdd added in v0.3.0

func (c *Client) CacheZAdd(namespace, key string, members ...ScoredMember) (*ZAddResult, error)

CacheZAdd adds scored members to a sorted set, or re-scores ones already there. A score that is not finite is refused.

func (*Client) CacheZCard added in v0.3.0

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

CacheZCard returns how many members the sorted set holds; zero when the key is missing.

func (*Client) CacheZIncrBy added in v0.3.0

func (c *Client) CacheZIncrBy(namespace, key string, member []byte, by float64) (float64, error)

CacheZIncrBy adds by to a member's score, creating it at by when absent, and returns the new score.

func (*Client) CacheZRange added in v0.3.0

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

CacheZRange returns members by rank, start..=stop inclusive. Negative indices count from the end, so 0, -1 is the whole set.

func (*Client) CacheZRangeByScore added in v0.3.0

func (c *Client) CacheZRangeByScore(namespace, key string, min, max ScoreBound, opts ScoreRangeOptions) ([][]byte, error)

CacheZRangeByScore returns members by score, between two bounds.

func (*Client) CacheZRangeByScoreWithScores added in v0.3.0

func (c *Client) CacheZRangeByScoreWithScores(namespace, key string, min, max ScoreBound, opts ScoreRangeOptions) ([]ScoredMember, error)

CacheZRangeByScoreWithScores is CacheZRangeByScore with each member's score.

func (*Client) CacheZRangeWithScores added in v0.3.0

func (c *Client) CacheZRangeWithScores(namespace, key string, start, stop int64, rev bool) ([]ScoredMember, error)

CacheZRangeWithScores is CacheZRange with each member's score.

func (*Client) CacheZRank added in v0.3.0

func (c *Client) CacheZRank(namespace, key string, member []byte, rev bool) (rank int64, found bool, err error)

CacheZRank returns a member's position in the ordering. rev counts from the high-scoring end. found is false when the member is absent.

func (*Client) CacheZRem added in v0.3.0

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

CacheZRem removes members from a sorted set, returning how many were there.

func (*Client) CacheZScore added in v0.3.0

func (c *Client) CacheZScore(namespace, key string, member []byte) (score float64, found bool, err error)

CacheZScore returns one member's score. found is false when it is not in the set.

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) DocumentBeginTransaction added in v0.3.0

func (c *Client) DocumentBeginTransaction(serializable bool) (string, error)

DocumentBeginTransaction opens a transaction spanning requests, and returns its id.

Nothing joins the transaction by itself: pass the id to SetRequestTxn, and every later request reads and writes inside it, seeing its own writes and nobody else's since it began. With serializable, its reads are validated at commit as well.

txn, err := db.DocumentBeginTransaction(false)
db.SetRequestTxn(txn)
db.DocumentInsertWithID("orders", "o1", map[string]any{"total": 10})
_, err = db.DocumentCommitTransaction(txn) // also stops naming it

func (*Client) DocumentBulkWrite added in v0.3.0

func (c *Client) DocumentBulkWrite(collection string, ops ...BulkOp) (*BulkWriteResult, error)

DocumentBulkWrite applies many inserts, updates, replaces and deletes on one collection, in order, as one atomic batch: every operation lands or none does. A later operation sees the effect of an earlier one on the same id.

func (*Client) DocumentCommitTransaction added in v0.3.0

func (c *Client) DocumentCommitTransaction(txn string) (*DocumentCommit, error)

DocumentCommitTransaction commits a transaction: every write lands as one atomic batch, or a conflict is returned and nothing lands.

It stops SetRequestTxn naming this transaction whatever the outcome: a transaction that failed to commit is over.

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) DocumentDeleteMany added in v0.3.0

func (c *Client) DocumentDeleteMany(collection string, filter DocumentFilter) (int64, error)

DocumentDeleteMany deletes every document matching filter, returning how many went.

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) DocumentExplain added in v0.3.0

func (c *Client) DocumentExplain(collection string, filter DocumentFilter, opts ExplainOptions) (*DocumentPlan, error)

DocumentExplain runs a find and describes how it ran instead of returning its documents.

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) DocumentGetCollectionOptions added in v0.3.0

func (c *Client) DocumentGetCollectionOptions(collection string) (*CollectionOptions, error)

DocumentGetCollectionOptions reads a collection's options.

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) DocumentInsertMany added in v0.3.0

func (c *Client) DocumentInsertMany(collection string, documents ...any) ([]string, error)

DocumentInsertMany inserts several documents as one atomic batch — every document lands or none does — and returns their ids in order.

Each document's id is its own _id when it carries one, and is generated otherwise.

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) DocumentPurgeExpired added in v0.3.0

func (c *Client) DocumentPurgeExpired(collection string) (*PurgeResult, error)

DocumentPurgeExpired deletes the documents a TTL index says have expired, now.

func (*Client) DocumentRebuildIndex added in v0.3.0

func (c *Client) DocumentRebuildIndex(collection, indexName string) (*IndexRebuild, error)

DocumentRebuildIndex rebuilds one index from the stored documents, replacing its entries in one batch.

func (*Client) DocumentRenameCollection added in v0.3.0

func (c *Client) DocumentRenameCollection(collection, to string) error

DocumentRenameCollection moves a collection, with its documents and indexes, to a new name. Refused when to already exists.

func (*Client) DocumentReplace added in v0.3.0

func (c *Client) DocumentReplace(collection, id string, document any, opts ReplaceOptions) (*ReplaceResult, error)

DocumentReplace swaps a document's whole body for a new one.

DocumentUpdate merges, so a field left out survives; after a replace the stored body is exactly document plus _id. An _id inside document may agree with id or be absent, never disagree.

func (*Client) DocumentRollbackTransaction added in v0.3.0

func (c *Client) DocumentRollbackTransaction(txn string) error

DocumentRollbackTransaction discards a transaction and everything written inside it.

func (*Client) DocumentSetCollectionOptions added in v0.3.0

func (c *Client) DocumentSetCollectionOptions(collection string, options CollectionOptions) (int64, error)

DocumentSetCollectionOptions sets a collection's options, replacing any it had, and returns how many stored documents were checked against the new schema. Refused when an existing document would break it.

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) GraphAddMany added in v0.3.0

func (c *Client) GraphAddMany(graph string, nodes []GraphNodeInput, edges []GraphEdgeInput) (*GraphCounts, error)

GraphAddMany writes many nodes and edges as one unit: every record lands or none does.

Nodes are written before edges, so an edge may join nodes created in the same batch. The whole batch is validated before anything is written.

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) GraphAllPaths added in v0.3.0

func (c *Client) GraphAllPaths(graph, from, to string, opts TraverseOptions) (*GraphPaths, error)

GraphAllPaths returns every simple path between two nodes within a hop bound. A work budget bounds the search, and Complete says whether it finished.

func (*Client) GraphBeginTransaction added in v0.3.0

func (c *Client) GraphBeginTransaction(graph string) (string, error)

GraphBeginTransaction opens a transaction on a graph, and returns its id.

Pass the id to SetRequestTxn: every GraphExecute sent while it is set is queued, and the commit applies them all or none.

func (*Client) GraphCentrality added in v0.3.0

func (c *Client) GraphCentrality(graph string, measure CentralityMeasure, opts CentralityOptions) (*GraphCentralityResult, error)

GraphCentrality computes betweenness, closeness or eigenvector centrality, top nodes first.

func (*Client) GraphCheckConsistency added in v0.3.0

func (c *Client) GraphCheckConsistency(graph string) (*GraphConsistency, error)

GraphCheckConsistency checks a graph's stored records against each other and against the resident mirror.

func (*Client) GraphCommitTransaction added in v0.3.0

func (c *Client) GraphCommitTransaction(graph, txn string) (*GraphWriteSummary, error)

GraphCommitTransaction applies every statement queued in a transaction as one write: all of them or none. It stops SetRequestTxn naming the transaction.

func (*Client) GraphCommunities added in v0.3.0

func (c *Client) GraphCommunities(graph string, opts CommunityOptions) (*GraphCommunitiesResult, error)

GraphCommunities finds communities by Louvain modularity optimisation, direction ignored.

func (*Client) GraphConnectedComponents added in v0.3.0

func (c *Client) GraphConnectedComponents(graph string, opts ComponentOptions) (*GraphComponents, error)

GraphConnectedComponents partitions the graph's nodes into connected components, largest first.

func (*Client) GraphCopy added in v0.3.0

func (c *Client) GraphCopy(graph, to string) (*GraphCounts, error)

GraphCopy copies a graph, with its nodes, edges and schema, to a new name. Refused when to exists.

func (*Client) GraphCreate

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

GraphCreate creates an empty graph.

func (*Client) GraphCreateConstraint added in v0.3.0

func (c *Client) GraphCreateConstraint(graph, name, label, property string, kind ConstraintKind, target ConstraintTarget) error

GraphCreateConstraint enforces a rule on a property of every node — or, with TargetEdge, every relationship — labelled label. An empty target is TargetNode. Refused when a stored record already breaks it.

func (*Client) GraphCreateNodeIndex added in v0.3.0

func (c *Client) GraphCreateNodeIndex(graph, name, label string, properties ...string) error

GraphCreateNodeIndex indexes node properties for GraphFindNodes. Several properties make a composite index that serves an equality on all of them; a non-empty label limits it to nodes carrying that label.

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) GraphDetectCycle added in v0.3.0

func (c *Client) GraphDetectCycle(graph string, undirected bool, label string) (*GraphCycleCheck, error)

GraphDetectCycle reports whether the graph contains a cycle, with one cycle as evidence.

The server follows edge direction unless undirected is set; undirected, two parallel edges between a pair are a cycle and a single edge is not. An empty label considers every edge.

func (*Client) GraphDfs added in v0.3.0

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

GraphDfs walks outward from a node depth-first. It returns exactly the nodes GraphTraverse does, in DFS preorder.

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) GraphDropSchemaObject added in v0.3.0

func (c *Client) GraphDropSchemaObject(graph, name string) error

GraphDropSchemaObject drops an index or a constraint by name.

func (*Client) GraphExecute added in v0.3.0

func (c *Client) GraphExecute(graph, cypher string) (*GraphWriteSummary, error)

GraphExecute runs a Cypher write: CREATE, MERGE, SET, REMOVE, [DETACH] DELETE, optionally after MATCH ... [WHERE ...]. It is separate from GraphQuery because it writes. While SetRequestTxn names a graph transaction the statement is queued rather than applied.

func (*Client) GraphFindNodes added in v0.3.0

func (c *Client) GraphFindNodes(graph, label string, properties map[string]any, limit int) (*GraphFoundNodes, error)

GraphFindNodes returns nodes with label, when non-empty, whose properties equal the given values, in id order. Plan says whether an index answered. limit <= 0 leaves the cap to the server (100).

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) GraphImportCSV added in v0.3.0

func (c *Client) GraphImportCSV(graph, nodes, edges string) (*GraphCounts, error)

GraphImportCSV imports nodes and edges from CSV text as one atomic batch, through the same path as GraphAddMany, so constraints apply. An empty text is left out.

func (*Client) GraphKShortestPaths added in v0.3.0

func (c *Client) GraphKShortestPaths(graph, from, to string, opts KPathOptions) (*GraphPaths, error)

GraphKShortestPaths returns the k cheapest loopless paths between two nodes, cheapest first.

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) GraphListSchemaObjects added in v0.3.0

func (c *Client) GraphListSchemaObjects(graph string) (*GraphSchemaObjects, error)

GraphListSchemaObjects lists a graph's indexes and constraints.

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) GraphNodeSimilarity added in v0.3.0

func (c *Client) GraphNodeSimilarity(graph, node string, opts SimilarityOptions) ([]GraphScore, error)

GraphNodeSimilarity returns the nodes whose neighbour sets most resemble node's, most similar first.

func (*Client) GraphPageRank added in v0.3.0

func (c *Client) GraphPageRank(graph string, opts PageRankOptions) (*GraphPageRankResult, error)

GraphPageRank ranks nodes by PageRank over edge direction, top nodes first.

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) GraphRemoveMany added in v0.3.0

func (c *Client) GraphRemoveMany(graph string, nodes, edges []string, detach bool) (*GraphRemoved, error)

GraphRemoveMany deletes many nodes and edges as one unit. An id that is not there is skipped. With detach, every edge touching a removed node goes too.

func (*Client) GraphRollbackTransaction added in v0.3.0

func (c *Client) GraphRollbackTransaction(graph, txn string) (int64, error)

GraphRollbackTransaction discards a transaction and its queued statements, returning how many there were.

func (*Client) GraphSchema added in v0.3.0

func (c *Client) GraphSchema(graph string) (*GraphSchemaInfo, error)

GraphSchema describes what the graph's data looks like: its node labels and edge types, each with a count and the property keys seen on it.

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) GraphStats added in v0.3.0

func (c *Client) GraphStats(graph string) (*GraphStatistics, error)

GraphStats returns counts describing a graph.

func (*Client) GraphSubgraph added in v0.3.0

func (c *Client) GraphSubgraph(graph string, seeds []string, opts TraverseOptions) (*GraphSubgraphResult, error)

GraphSubgraph returns the part of the graph within some hops of seeds: the nodes reached and every edge joining two of them. The server's defaults differ from a traversal's: both directions, one hop, and up to 1000 nodes.

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) GraphTriangleCount added in v0.3.0

func (c *Client) GraphTriangleCount(graph, label string, limit int) (*GraphTriangles, error)

GraphTriangleCount counts triangles and clustering coefficients, direction ignored. An empty label considers every edge; limit <= 0 leaves the cap to the server.

func (*Client) GraphUpdateEdge added in v0.3.0

func (c *Client) GraphUpdateEdge(graph, id string, properties map[string]any, label string) (*GraphEdge, error)

GraphUpdateEdge changes an existing edge in place, and returns it as it now stands. properties is a JSON merge patch (nil changes none) and a non-empty label changes the edge's type; the endpoints cannot change.

func (*Client) GraphUpdateNode added in v0.3.0

func (c *Client) GraphUpdateNode(graph, id string, update NodeUpdate) (*GraphNode, error)

GraphUpdateNode changes an existing node in place, and returns it as it now stands.

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) RequestTxn added in v0.3.0

func (c *Client) RequestTxn() string

RequestTxn is the transaction named on every request, or empty when none is.

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) SetRequestTxn added in v0.3.0

func (c *Client) SetRequestTxn(txn string)

SetRequestTxn names a document or graph transaction on every subsequent request. An empty id clears it.

A document transaction (DocumentBeginTransaction) and a graph one (GraphBeginTransaction) span requests: the requests that belong to one say so by carrying its id, and a request that does not carry it runs outside the transaction. Committing or rolling the transaction back through this client clears the id again.

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) VectorAddNamedVector added in v0.3.0

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

VectorAddNamedVector declares a named vector on a collection: a second vector per item, with its own dimension and metric.

func (*Client) VectorCopyCollection added in v0.3.0

func (c *Client) VectorCopyCollection(collection, to string) (int64, error)

VectorCopyCollection copies a collection, configuration and every vector, to a new name, and returns how many vectors were copied. Refused when to exists.

func (*Client) VectorCount added in v0.3.0

func (c *Client) VectorCount(collection string, filter map[string]any) (int64, error)

VectorCount returns how many vectors a collection holds — or, with a non-empty filter, how many match it. A count, not an estimate.

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) VectorDeleteByFilter added in v0.3.0

func (c *Client) VectorDeleteByFilter(collection string, filter map[string]any) (int64, error)

VectorDeleteByFilter deletes every vector whose metadata matches filter, as one atomic batch, returning how many went. An empty filter is refused by the server: emptying a collection is VectorDropCollection's job.

func (*Client) VectorDeleteMany added in v0.3.0

func (c *Client) VectorDeleteMany(collection string, ids ...string) (int64, error)

VectorDeleteMany deletes many vectors by id as one atomic batch, returning how many of the ids were present.

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) VectorEmbed added in v0.3.0

func (c *Client) VectorEmbed(texts []string, dimension int) (*Embedding, error)

VectorEmbed embeds texts with the server's built-in embedder and returns the vectors. Nothing is stored.

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) VectorIndexStats added in v0.3.0

func (c *Client) VectorIndexStats(collection string) (*VectorIndexStats, error)

VectorIndexStats describes the collection's search index. It loads or builds the index as a search would.

func (*Client) VectorListAliases added in v0.3.0

func (c *Client) VectorListAliases() ([]VectorAlias, error)

VectorListAliases lists every alias and the collection it names.

func (*Client) VectorListCollections

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

VectorListCollections describes every vector collection in the database.

func (*Client) VectorListPartitions added in v0.3.0

func (c *Client) VectorListPartitions(collection, field string) (*VectorPartitions, error)

VectorListPartitions lists the partitions of a collection: each distinct value of field with its vector count. field is "_namespace" or "_tenant"; empty leaves it to the server, which uses "_namespace".

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) VectorMeasureRecall added in v0.3.0

func (c *Client) VectorMeasureRecall(collection string, opts RecallOptions) (*VectorRecall, error)

VectorMeasureRecall measures the index's recall: sampled stored vectors are each searched through the index and by an exact scan, and the overlap is reported. It costs one exact scan per sample.

func (*Client) VectorRebuildIndex added in v0.3.0

func (c *Client) VectorRebuildIndex(collection string) (*VectorIndexRebuild, error)

VectorRebuildIndex rebuilds the collection's search index from its stored vectors and persists it, clearing every tombstone.

func (*Client) VectorRenameCollection added in v0.3.0

func (c *Client) VectorRenameCollection(collection, to string) (int64, error)

VectorRenameCollection renames a collection, moving every vector with it in one atomic batch, and returns how many moved. Refused when to already exists.

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) VectorSearchBatch added in v0.3.0

func (c *Client) VectorSearchBatch(collection string, vectors [][]float32, topK int, opts VectorSearchOptions) ([][]VectorHit, error)

VectorSearchBatch runs several query vectors against one collection in one round trip.

It returns one result list per query, in the order asked, each what a single search with the same arguments returns. Not a snapshot.

func (*Client) VectorSearchByExamples added in v0.3.0

func (c *Client) VectorSearchByExamples(collection string, query ExampleSearch, topK int, opts VectorSearchOptions) (*VectorSearchResult, error)

VectorSearchByExamples searches with a query built from examples.

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) VectorSearchMulti added in v0.3.0

func (c *Client) VectorSearchMulti(collection string, vectors [][]float32, topK int, fusion FusionMethod, filter map[string]any) (*FusedSearchResult, error)

VectorSearchMulti searches with several query vectors and returns one fused ranking. An empty fusion leaves the server's default (FusionRRF); a nil or empty filter means no filtering.

func (*Client) VectorSetAlias added in v0.3.0

func (c *Client) VectorSetAlias(alias, collection string) error

VectorSetAlias points an alias at a collection; an empty collection removes it. Every operation naming the alias acts on the collection, so a rebuilt collection can replace the old one by moving the alias.

func (*Client) VectorSetCollectionConfig added in v0.3.0

func (c *Client) VectorSetCollectionConfig(collection string, change VectorConfigChange) (*VectorConfig, error)

VectorSetCollectionConfig changes a collection's configuration, and returns it as it now stands. A change that sets nothing is refused before it is sent, as the server would refuse it.

func (*Client) VectorUpdateByFilter added in v0.3.0

func (c *Client) VectorUpdateByFilter(collection string, filter, set map[string]any) (int64, error)

VectorUpdateByFilter merges set into the metadata of every vector matching filter, as one atomic batch, returning how many changed. Vectors are never touched.

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) VectorUpsertMany added in v0.3.0

func (c *Client) VectorUpsertMany(collection string, items []VectorUpsertItem) (int64, error)

VectorUpsertMany writes many vectors as one atomic batch, returning how many were written. One bad item refuses the whole batch, and so does a repeated id.

func (*Client) VectorUpsertNamed added in v0.3.0

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

VectorUpsertNamed writes an item's vectors by name, each with the same metadata. The name "default" is the collection's own vector.

func (*Client) VectorUpsertText added in v0.3.0

func (c *Client) VectorUpsertText(collection string, items []TextUpsert) (int64, error)

VectorUpsertText embeds each text at the collection's dimension and upserts the vectors as one atomic batch, returning how many were written.

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 CollectionOptions added in v0.3.0

type CollectionOptions struct {
	// Schema must be satisfied by every document written; a violation refuses
	// the write.
	Schema *DocumentSchema `json:"schema,omitempty"`
	// Defaults maps a path to the value a newly created document is given
	// when it lacks the path.
	Defaults map[string]any `json:"defaults,omitempty"`
	// Versioned keeps a _version counter on every document, which is what
	// lets a write name an expected version.
	Versioned bool `json:"versioned"`
}

CollectionOptions are rules a collection applies to every document written into it.

type CommunityOptions added in v0.3.0

type CommunityOptions struct {
	Label      string
	Iterations int
	// Limit caps the communities listed.
	Limit int
}

CommunityOptions narrows GraphCommunities.

type CompareAndSwapResult added in v0.3.0

type CompareAndSwapResult struct {
	Swapped bool
	// Current, on a mismatch, is the value actually present when it is valid
	// UTF-8, and nil otherwise.
	Current []byte
	// CurrentIsBinary, on a mismatch, says the value present is binary. The
	// server does not return such a value; read it with CacheGet.
	CurrentIsBinary bool
}

CompareAndSwapResult is the answer to CacheCompareAndSwap.

type ComponentKind added in v0.3.0

type ComponentKind string

ComponentKind is how GraphConnectedComponents groups nodes. Empty leaves the server's default, ComponentWeak.

const (
	// ComponentWeak ignores edge direction.
	ComponentWeak ComponentKind = "weak"
	// ComponentStrong groups nodes that can each reach the other along edge
	// direction.
	ComponentStrong ComponentKind = "strong"
)

type ComponentOptions added in v0.3.0

type ComponentOptions struct {
	Kind ComponentKind
	// Label considers only edges with this label.
	Label string
	// Limit caps the components listed, never the number counted (default
	// 100, capped at 1000).
	Limit int
}

ComponentOptions narrows GraphConnectedComponents.

type ConstraintKind added in v0.3.0

type ConstraintKind string

ConstraintKind is the rule a constraint enforces.

const (
	// ConstraintUnique: no two records with the label share a value for the
	// property.
	ConstraintUnique ConstraintKind = "unique"
	// ConstraintRequired: every record with the label has the property.
	ConstraintRequired ConstraintKind = "required"
)

type ConstraintTarget added in v0.3.0

type ConstraintTarget string

ConstraintTarget is what a constraint applies to. Empty leaves the server's default, TargetNode.

const (
	TargetNode ConstraintTarget = "node"
	TargetEdge ConstraintTarget = "edge"
)

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 DocumentCommit added in v0.3.0

type DocumentCommit struct {
	Committed bool  `json:"committed"`
	Writes    int64 `json:"writes"`
}

DocumentCommit is what DocumentCommitTransaction landed.

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 DocumentPlan added in v0.3.0

type DocumentPlan struct {
	// Plan is the plan's name: "FindScan", or an index lookup.
	Plan string `json:"plan"`
	// Index is the index that answered, and empty when none did.
	Index     string `json:"index"`
	IndexUsed bool   `json:"index_used"`
	// ScanReason says why the collection was scanned, when it was.
	ScanReason    string  `json:"scan_reason"`
	ScanSource    string  `json:"scan_source"`
	EstimatedRows float64 `json:"estimated_rows"`
	EstimatedCost float64 `json:"estimated_cost"`
	RowsExamined  int64   `json:"rows_examined"`
	RowsReturned  int64   `json:"rows_returned"`
	ElapsedUs     int64   `json:"elapsed_us"`
}

DocumentPlan is how a find ran, as DocumentExplain reports it.

type DocumentSchema added in v0.3.0

type DocumentSchema struct {
	// Required lists paths every document must have. A stored null counts as
	// present.
	Required []string `json:"required,omitempty"`
	// Fields maps a path to its rule, checked when the path is present.
	Fields map[string]FieldRule `json:"fields,omitempty"`
	// AdditionalFields says whether a top-level field the schema does not
	// name is allowed. Nil leaves the server's default, which allows them;
	// a schema read back from the server always carries a value.
	AdditionalFields *bool `json:"additional_fields,omitempty"`
}

DocumentSchema is a document shape: required paths, per-path rules, and whether top-level fields the schema does not name are allowed.

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 Embedding added in v0.3.0

type Embedding struct {
	// Embedder names the embedder. "hash-v1" is deterministic feature
	// hashing: lexical, with no model behind it.
	Embedder  string `json:"embedder"`
	Dimension int    `json:"dimension"`
	// Vectors holds one dense vector per text, in the order given.
	Vectors [][]float32 `json:"vectors"`
	// Sparse holds one sparse vector per text, in the order given.
	Sparse []SparseVector `json:"sparse"`
}

Embedding is what VectorEmbed produced.

type ExampleSearch added in v0.3.0

type ExampleSearch struct {
	Positive []VectorExample
	Negative []VectorExample
	// IncludeExamples keeps the examples named by id in the results. The
	// server leaves them out by default.
	IncludeExamples bool
}

ExampleSearch is the query of VectorSearchByExamples: the sum of the Positive examples minus the sum of the Negative ones, so king - man + woman is Positive [king, woman], Negative [man].

type ExpireAtResult added in v0.3.0

type ExpireAtResult struct {
	// Updated says a live key was given the deadline.
	Updated bool `json:"updated"`
	// Deleted says the key was deleted because the deadline had passed.
	Deleted bool `json:"deleted"`
}

ExpireAtResult is what CacheExpireAt did.

type ExplainOptions added in v0.3.0

type ExplainOptions struct {
	// Limit caps the documents returned. Zero or less means no cap.
	Limit int
	// Sort orders the documents.
	Sort []SortKey
	// Skip drops this many documents from the front.
	Skip int
}

ExplainOptions shapes the find DocumentExplain runs. The zero value explains an unbounded, unsorted find.

type FieldRule added in v0.3.0

type FieldRule struct {
	Type FieldType `json:"type,omitempty"`
	// OneOf requires the value to equal one of these.
	OneOf   []any    `json:"one_of,omitempty"`
	Minimum *float64 `json:"minimum,omitempty"`
	Maximum *float64 `json:"maximum,omitempty"`
	// MinLength and MaxLength count the characters of a string, or the
	// elements of an array.
	MinLength *int `json:"min_length,omitempty"`
	MaxLength *int `json:"max_length,omitempty"`
	// Pattern is a regular expression a string must contain a match for.
	Pattern string `json:"pattern,omitempty"`
}

FieldRule is what one field may hold. Every rule given must pass; a rule left at its zero value is not applied.

type FieldType added in v0.3.0

type FieldType string

FieldType is a JSON type a FieldRule can demand. FieldInteger is a number with no fractional part.

const (
	FieldString  FieldType = "string"
	FieldNumber  FieldType = "number"
	FieldInteger FieldType = "integer"
	FieldBoolean FieldType = "boolean"
	FieldObject  FieldType = "object"
	FieldArray   FieldType = "array"
	FieldNull    FieldType = "null"
)

type FilterStrategy added in v0.3.0

type FilterStrategy string

FilterStrategy is how a filtered search combines the filter with the index. Empty lets the server choose.

const (
	FilterStrategyAuto FilterStrategy = "auto"
	// FilterStrategyGraph walks the index and tests each candidate.
	FilterStrategyGraph FilterStrategy = "graph"
	// FilterStrategyExact scans the vectors the filter admits.
	FilterStrategyExact FilterStrategy = "exact"
)

type FreshRead added in v0.3.0

type FreshRead struct {
	State FreshState
	// Value is the cached value when State is fresh or stale, and nil
	// otherwise.
	Value []byte
	// Refresh, on a stale read, says this caller holds the refresh lease and
	// should recompute the value.
	Refresh bool
	// Lease, on a miss, says this caller holds the lease and should compute
	// the value.
	Lease bool
	// RetryAfterMs, on a miss another caller is computing, is how long to wait
	// before asking again. Zero when the server gave none.
	RetryAfterMs int64
}

FreshRead is the answer to CacheGetFresh.

type FreshState added in v0.3.0

type FreshState string

FreshState is which of its four answers CacheGetFresh gave.

const (
	// FreshStateFresh: the value is cached and within its fresh window.
	FreshStateFresh FreshState = "fresh"
	// FreshStateStale: the value is cached but past its fresh window.
	FreshStateStale FreshState = "stale"
	// FreshStateMissing: the source is known to have no value for the key.
	FreshStateMissing FreshState = "missing"
	// FreshStateMiss: nothing is cached for the key.
	FreshStateMiss FreshState = "miss"
)

type FusedHit added in v0.3.0

type FusedHit struct {
	ID string `json:"id"`
	// Score is the fused score. Higher is better, but the scale is the fusion
	// method's, not the collection metric's.
	Score float32 `json:"score"`
	// Matched is how many of the queries ranked it.
	Matched  int            `json:"matched"`
	Metadata map[string]any `json:"metadata"`
}

FusedHit is one hit of a fused ranking.

type FusedSearchResult added in v0.3.0

type FusedSearchResult struct {
	Fusion  FusionMethod `json:"fusion"`
	Queries int          `json:"queries"`
	// Depth is how deep each query ranked before fusing.
	Depth   int        `json:"depth"`
	Results []FusedHit `json:"results"`
}

FusedSearchResult is the answer to VectorSearchMulti.

type FusionMethod added in v0.3.0

type FusionMethod string

FusionMethod is how VectorSearchMulti merges its queries' rankings. Empty leaves the server's default, reciprocal rank fusion.

const (
	// FusionRRF is reciprocal rank fusion.
	FusionRRF FusionMethod = "rrf"
	// FusionMax takes each vector's best score across the queries.
	FusionMax FusionMethod = "max"
	// FusionMean takes each vector's mean score across the queries.
	FusionMean FusionMethod = "mean"
)

type GraphCentralityResult added in v0.3.0

type GraphCentralityResult struct {
	Measure  CentralityMeasure `json:"measure"`
	Directed bool              `json:"directed"`
	// Nodes is how many nodes the graph holds.
	Nodes   int64        `json:"nodes"`
	Results []GraphScore `json:"results"`
	// Converged and Iterations are reported for eigenvector centrality only.
	Converged  *bool `json:"converged"`
	Iterations int   `json:"iterations"`
}

GraphCentralityResult is the answer to GraphCentrality.

type GraphCommunitiesResult added in v0.3.0

type GraphCommunitiesResult struct {
	Algorithm   string       `json:"algorithm"`
	Count       int          `json:"count"`
	Modularity  float64      `json:"modularity"`
	Converged   bool         `json:"converged"`
	Iterations  int          `json:"iterations"`
	Communities []GraphGroup `json:"communities"`
}

GraphCommunitiesResult is the communities of a graph, largest first.

type GraphComponents added in v0.3.0

type GraphComponents struct {
	Kind ComponentKind `json:"kind"`
	// Count is how many components the graph has.
	Count   int `json:"count"`
	Largest int `json:"largest"`
	// Truncated says more components exist than are listed.
	Truncated  bool         `json:"truncated"`
	Components []GraphGroup `json:"components"`
}

GraphComponents is the connected components of a graph, largest first.

type GraphConsistency added in v0.3.0

type GraphConsistency struct {
	// Consistent says nothing was found.
	Consistent bool  `json:"consistent"`
	Nodes      int64 `json:"nodes"`
	Edges      int64 `json:"edges"`
	// DanglingEdges are edges whose endpoint no longer exists.
	DanglingEdges GraphFindings `json:"dangling_edges"`
	Undecodable   GraphFindings `json:"undecodable"`
	// Misfiled are records stored under another id.
	Misfiled GraphFindings `json:"misfiled"`
	// Mirror compares the resident mirror with storage.
	Mirror struct {
		Loaded      bool          `json:"loaded"`
		Differences GraphFindings `json:"differences"`
	} `json:"mirror"`
}

GraphConsistency is the answer to GraphCheckConsistency.

type GraphConstraint added in v0.3.0

type GraphConstraint struct {
	Name     string           `json:"name"`
	Label    string           `json:"label"`
	Property string           `json:"property"`
	Kind     ConstraintKind   `json:"kind"`
	Target   ConstraintTarget `json:"target"`
}

GraphConstraint is one constraint.

type GraphCounts added in v0.3.0

type GraphCounts struct {
	Nodes int64 `json:"nodes"`
	Edges int64 `json:"edges"`
}

GraphCounts is how many nodes and edges a batch write or a copy handled.

type GraphCycle added in v0.3.0

type GraphCycle struct {
	Nodes []string `json:"nodes"`
	Edges []string `json:"edges"`
}

GraphCycle is one cycle, as the evidence GraphDetectCycle returns.

type GraphCycleCheck added in v0.3.0

type GraphCycleCheck struct {
	HasCycle bool `json:"hasCycle"`
	Directed bool `json:"directed"`
	// Cycle is one cycle when there is one, and nil otherwise.
	Cycle *GraphCycle `json:"cycle"`
}

GraphCycleCheck is the answer to GraphDetectCycle.

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 GraphEdgeInput added in v0.3.0

type GraphEdgeInput struct {
	ID         string         `json:"id"`
	From       string         `json:"from"`
	To         string         `json:"to"`
	Label      string         `json:"label"`
	Properties map[string]any `json:"properties,omitempty"`
}

GraphEdgeInput is one edge of GraphAddMany.

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 GraphEdgeTypeSchema added in v0.3.0

type GraphEdgeTypeSchema struct {
	Type       string                `json:"type"`
	Count      int64                 `json:"count"`
	Properties []GraphPropertySchema `json:"properties"`
}

GraphEdgeTypeSchema is one edge type in a GraphSchemaInfo.

type GraphFindings added in v0.3.0

type GraphFindings struct {
	Count int64 `json:"count"`
	// Listed are the ones listed, as the server describes them.
	Listed []json.RawMessage `json:"listed"`
}

GraphFindings is one class of finding in a GraphConsistency.

type GraphFoundNodes added in v0.3.0

type GraphFoundNodes struct {
	Count int         `json:"count"`
	Nodes []GraphNode `json:"nodes"`
	// Plan says how the request was answered: an index by name, the label
	// index, or a scan.
	Plan      string `json:"plan"`
	Truncated bool   `json:"truncated"`
}

GraphFoundNodes is the answer to GraphFindNodes.

type GraphGroup added in v0.3.0

type GraphGroup struct {
	Nodes []string `json:"nodes"`
	// Size is how many nodes the group has, which may be more than are listed.
	Size      int  `json:"size"`
	Truncated bool `json:"truncated"`
}

GraphGroup is one group of nodes: a connected component, or a community.

type GraphIndex added in v0.3.0

type GraphIndex struct {
	Name string `json:"name"`
	// Label is the label the index is limited to, and empty when it is not.
	Label      string   `json:"label"`
	Properties []string `json:"properties"`
}

GraphIndex is one node index.

type GraphLabelSchema added in v0.3.0

type GraphLabelSchema struct {
	// Label is empty for the unlabelled nodes.
	Label      string                `json:"label"`
	Count      int64                 `json:"count"`
	Properties []GraphPropertySchema `json:"properties"`
}

GraphLabelSchema is one node label, or the unlabelled nodes, in a GraphSchemaInfo.

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 GraphNodeInput added in v0.3.0

type GraphNodeInput struct {
	ID         string         `json:"id"`
	Labels     []string       `json:"labels"`
	Properties map[string]any `json:"properties,omitempty"`
}

GraphNodeInput is one node of GraphAddMany.

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 GraphPageRankResult added in v0.3.0

type GraphPageRankResult struct {
	// Ranks are the top nodes. The ranks of the whole graph sum to 1.
	Ranks []GraphScore `json:"ranks"`
	// Count is how many nodes were ranked.
	Count      int     `json:"count"`
	Damping    float64 `json:"damping"`
	Iterations int     `json:"iterations"`
	Converged  bool    `json:"converged"`
	Truncated  bool    `json:"truncated"`
}

GraphPageRankResult is the answer to GraphPageRank.

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 GraphPathEntry added in v0.3.0

type GraphPathEntry struct {
	// Nodes are the node ids along the path, the start first.
	Nodes []string `json:"nodes"`
	Edges []string `json:"edges"`
	Hops  int      `json:"hops"`
	// Cost is the summed cost of the path's edges.
	Cost float64 `json:"cost"`
}

GraphPathEntry is one path of a GraphPaths.

type GraphPaths added in v0.3.0

type GraphPaths struct {
	From      string           `json:"from"`
	To        string           `json:"to"`
	Direction string           `json:"direction"`
	Count     int              `json:"count"`
	Paths     []GraphPathEntry `json:"paths"`
	// Complete, from GraphAllPaths, says whether the enumeration finished. It
	// is nil from a search that does not report it.
	Complete *bool `json:"complete"`
	// StoppedBy names what stopped an enumeration that did not finish.
	StoppedBy string `json:"stopped_by"`
}

GraphPaths is several paths between two nodes.

type GraphPropertySchema added in v0.3.0

type GraphPropertySchema struct {
	Key   string `json:"key"`
	Count int64  `json:"count"`
	// Types are the JSON types seen under the key.
	Types []string `json:"types"`
}

GraphPropertySchema is one property key seen on a label or an edge type.

type GraphRemoved added in v0.3.0

type GraphRemoved struct {
	NodesRemoved int64 `json:"nodes_removed"`
	// EdgesRemoved includes the edges detached with a node.
	EdgesRemoved int64 `json:"edges_removed"`
}

GraphRemoved is what GraphRemoveMany deleted.

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 GraphSchemaInfo added in v0.3.0

type GraphSchemaInfo struct {
	Nodes          int64                 `json:"nodes"`
	Edges          int64                 `json:"edges"`
	NodeLabels     []GraphLabelSchema    `json:"node_labels"`
	EdgeTypes      []GraphEdgeTypeSchema `json:"edge_types"`
	UnlabeledNodes GraphLabelSchema      `json:"unlabeled_nodes"`
}

GraphSchemaInfo is what a graph's data looks like.

type GraphSchemaObjects added in v0.3.0

type GraphSchemaObjects struct {
	Indexes     []GraphIndex      `json:"indexes"`
	Constraints []GraphConstraint `json:"constraints"`
}

GraphSchemaObjects is a graph's indexes and constraints.

type GraphScore added in v0.3.0

type GraphScore struct {
	ID    string  `json:"id"`
	Score float64 `json:"score"`
}

GraphScore is one node and the score an algorithm gave it.

type GraphStatistics added in v0.3.0

type GraphStatistics struct {
	Nodes int64 `json:"nodes"`
	Edges int64 `json:"edges"`
	// NodeLabels counts nodes per label; EdgeTypes counts edges per type.
	NodeLabels     map[string]int64 `json:"nodeLabels"`
	EdgeTypes      map[string]int64 `json:"edgeTypes"`
	UnlabeledNodes int64            `json:"unlabeledNodes"`
	SelfLoops      int64            `json:"selfLoops"`
	IsolatedNodes  int64            `json:"isolatedNodes"`
	AvgOutDegree   float64          `json:"avgOutDegree"`
	MaxOutDegree   int64            `json:"maxOutDegree"`
	MaxInDegree    int64            `json:"maxInDegree"`
	// DanglingEdges counts edges whose endpoint no longer exists.
	DanglingEdges int64 `json:"danglingEdges"`
}

GraphStatistics is counts describing a graph.

type GraphSubgraphResult added in v0.3.0

type GraphSubgraphResult struct {
	Direction string `json:"direction"`
	MaxDepth  int    `json:"max_depth"`
	Limit     int    `json:"limit"`
	NodeCount int    `json:"node_count"`
	EdgeCount int    `json:"edge_count"`
	// Nodes are the nodes reached, each with the depth it was reached at.
	Nodes []GraphVisit `json:"nodes"`
	// Edges are every edge joining two of those nodes.
	Edges          []GraphEdge `json:"edges"`
	NodesTruncated bool        `json:"nodes_truncated"`
	EdgesTruncated bool        `json:"edges_truncated"`
}

GraphSubgraphResult is the part of a graph around some seed nodes.

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 GraphTriangles added in v0.3.0

type GraphTriangles struct {
	Triangles         int64   `json:"triangles"`
	Transitivity      float64 `json:"transitivity"`
	AverageClustering float64 `json:"average_clustering"`
	Nodes             []struct {
		ID         string  `json:"id"`
		Triangles  int64   `json:"triangles"`
		Clustering float64 `json:"clustering"`
	} `json:"nodes"`
}

GraphTriangles is the answer to GraphTriangleCount.

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 GraphWriteSummary added in v0.3.0

type GraphWriteSummary struct {
	Statements           int64 `json:"statements"`
	NodesCreated         int64 `json:"nodesCreated"`
	NodesDeleted         int64 `json:"nodesDeleted"`
	RelationshipsCreated int64 `json:"relationshipsCreated"`
	RelationshipsDeleted int64 `json:"relationshipsDeleted"`
	PropertiesSet        int64 `json:"propertiesSet"`
	LabelsAdded          int64 `json:"labelsAdded"`
	LabelsRemoved        int64 `json:"labelsRemoved"`
	// Queued is set inside a transaction; Committed is set by a commit.
	Queued    int64 `json:"queued"`
	Committed int64 `json:"committed"`
}

GraphWriteSummary is what a Cypher write changed.

Inside a transaction a statement is queued rather than applied: the counts are then zero and Queued says how many statements the transaction holds.

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 IndexRebuild added in v0.3.0

type IndexRebuild struct {
	// IndexName is the index that was rebuilt.
	IndexName string `json:"rebuilt"`
	Documents int64  `json:"documents"`
	Entries   int64  `json:"entries"`
}

IndexRebuild is what DocumentRebuildIndex rebuilt.

type KPathOptions added in v0.3.0

type KPathOptions struct {
	// K is how many paths to return (default 3, capped at 20).
	K         int
	Direction GraphDirection
	Label     string
	// WeightProperty names the edge property holding the cost. Without it
	// every edge costs 1, so paths are ranked by hops.
	WeightProperty string
}

KPathOptions narrows GraphKShortestPaths.

type ListEnd added in v0.3.0

type ListEnd string

ListEnd is which end of a list an element leaves or joins.

const (
	// ListLeft is the head, where LPush and LPop work.
	ListLeft ListEnd = "Left"
	// ListRight is the tail, where RPush and RPop work.
	ListRight ListEnd = "Right"
)

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 NamedVector added in v0.3.0

type NamedVector struct {
	// Name is what a search passes as Using.
	Name      string       `json:"name"`
	Dimension int          `json:"dimension"`
	Metric    VectorMetric `json:"metric"`
}

NamedVector is one named vector declared on a collection.

type NamespaceLimit added in v0.3.0

type NamespaceLimit struct {
	Namespace string `json:"namespace"`
	Keys      uint64 `json:"keys"`
	Bytes     uint64 `json:"bytes"`
	// MaxKeys and MaxBytes are nil when that cap is not set.
	MaxKeys  *uint64 `json:"max_keys"`
	MaxBytes *uint64 `json:"max_bytes"`
}

NamespaceLimit is a namespace's limit and what it holds now.

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 NodeUpdate added in v0.3.0

type NodeUpdate struct {
	// Properties is a JSON merge patch: a key set to a value is set, a key
	// set to nil is removed, and a key left out is left alone.
	Properties map[string]any
	// AddLabels are added; adding one the node already has is a no-op.
	AddLabels []string
	// RemoveLabels are removed, before the additions.
	RemoveLabels []string
}

NodeUpdate is what GraphUpdateNode changes. The zero value changes nothing.

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

	// DisableFollowLeader turns off following the leader.
	//
	// By default a request a cluster node refuses with not_leader is sent
	// again: to the leader the refusal names, over a new connection that
	// replaces this one (authenticated with the same User and Secret, with the
	// leader's host as the TLS server name), or, while no leader is known, to
	// the same node after a pause. That is safe because a not_leader refusal
	// was applied nowhere. It never happens inside a session transaction.
	DisableFollowLeader bool
	// LeaderRetries is how many times a refused request is sent again. Zero
	// means 5; a negative value means none.
	LeaderRetries int
	// LeaderRetryDelay is the first pause before asking again while no leader
	// is known. It doubles up to 2s. Zero means 250ms.
	LeaderRetryDelay time.Duration
}

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 PageRankOptions added in v0.3.0

type PageRankOptions struct {
	// Damping must lie in [0, 1) (default 0.85).
	Damping float64
	// Iterations bounds the iteration (default 20, capped at 100).
	Iterations int
	Tolerance  float64
	Label      string
	// Limit is how many nodes to return (default 20, capped at 1000).
	Limit int
}

PageRankOptions narrows GraphPageRank. Zero values leave the server's defaults.

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 PollResult added in v0.3.0

type PollResult struct {
	// Messages are oldest first.
	Messages []ChannelMessage `json:"messages"`
	// Next is the id to pass as after on the next poll.
	Next uint64 `json:"next"`
}

PollResult is one page of messages from CachePoll.

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 PurgeResult added in v0.3.0

type PurgeResult struct {
	Purged int64 `json:"purged"`
	// More says expired documents remain past this call's batch.
	More bool `json:"more"`
}

PurgeResult is what DocumentPurgeExpired removed.

type RecallOptions added in v0.3.0

type RecallOptions struct {
	// Sample is how many stored vectors to search with (default 100, capped
	// at 1000).
	Sample int
	// TopK is how long a result list to compare (default 10, capped at 100).
	TopK int
	// EfSearch is the candidate list size to measure at.
	EfSearch int
}

RecallOptions shapes VectorMeasureRecall. Zero values leave the server's defaults.

type ReplaceOptions added in v0.3.0

type ReplaceOptions struct {
	// Upsert creates the document when it does not exist, rather than refuse.
	Upsert bool
	// Return asks for the document as it was before or is after the write.
	Return ReturnDocument
	// ExpectedVersion applies the write only if the document's _version is
	// still this. It needs a versioned collection. Build one with ExpectVersion.
	ExpectedVersion *uint64
}

ReplaceOptions narrows DocumentReplace. The zero value refuses a missing document, returns no document and checks no version.

type ReplaceResult added in v0.3.0

type ReplaceResult struct {
	ID string `json:"id"`
	// Replaced says a document now holds the new body.
	Replaced bool `json:"replaced"`
	// Inserted says the document was created by an upsert.
	Inserted bool `json:"inserted"`
	// Document is the one asked for with ReplaceOptions.Return, and nil when
	// none was asked for or there was none.
	Document Document `json:"document"`
}

ReplaceResult is what DocumentReplace did.

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 ReturnDocument added in v0.3.0

type ReturnDocument string

ReturnDocument says whether a by-id write hands back the document it touched, and which version of it. The zero value returns none.

const (
	// ReturnBefore is the document as it was before the write. There is none
	// when an upsert inserted.
	ReturnBefore ReturnDocument = "Before"
	// ReturnAfter is the document as it is after the write.
	ReturnAfter ReturnDocument = "After"
)

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 ScoreBound added in v0.3.0

type ScoreBound struct {
	Value float64
	// Exclusive leaves out a member with exactly this score.
	Exclusive bool
}

ScoreBound is one end of a score range.

A stored score is always finite, and JSON cannot carry an infinity, so the open ends are ScoreLowest and ScoreHighest rather than math.Inf. A non-finite bound is refused before anything is sent.

func ScoreHighest added in v0.3.0

func ScoreHighest() ScoreBound

ScoreHighest is a bound above every score a set can hold.

func ScoreLowest added in v0.3.0

func ScoreLowest() ScoreBound

ScoreLowest is a bound below every score a set can hold.

type ScoreMetric added in v0.3.0

type ScoreMetric string

ScoreMetric is the measure a search scores by, when it should differ from the collection's own metric.

const (
	ScoreCosine ScoreMetric = "cosine"
	ScoreDot    ScoreMetric = "dot"
	ScoreL2     ScoreMetric = "l2"
	ScoreL1     ScoreMetric = "l1"
	ScoreLinf   ScoreMetric = "linf"
)

type ScoreRangeOptions added in v0.3.0

type ScoreRangeOptions struct {
	// Rev returns the highest score first.
	Rev bool
	// Offset skips this many members of the range. It applies only with Count.
	Offset int64
	// Count caps the members returned. Zero or less means no cap.
	Count int64
}

ScoreRangeOptions narrows CacheZRangeByScore. The zero value returns the whole range, lowest score first.

type ScoredMember added in v0.3.0

type ScoredMember struct {
	// Score is what the set is ordered by. It must be finite.
	Score  float64
	Member []byte
}

ScoredMember is one member of a sorted set and its score.

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

	// Retried is how many times the driver sent this request again before
	// returning the refusal (see [Options.DisableFollowLeader]).
	Retried int
}

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. Unless Options.DisableFollowLeader is set, the driver has already sent the request again before returning this.

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

type SetCondition added in v0.3.0

type SetCondition string

SetCondition says when CacheSetIf is allowed to write.

const (
	// SetAlways writes unconditionally.
	SetAlways SetCondition = "Always"
	// SetIfAbsent writes only when the key is absent. An expired key counts
	// as absent.
	SetIfAbsent SetCondition = "IfAbsent"
	// SetIfPresent writes only when the key is present and unexpired.
	SetIfPresent SetCondition = "IfPresent"
)

type SimilarityMetric added in v0.3.0

type SimilarityMetric string

SimilarityMetric is how GraphNodeSimilarity compares neighbour sets. Empty leaves the server's default, SimilarityJaccard.

const (
	// SimilarityJaccard is shared neighbours over all neighbours.
	SimilarityJaccard SimilarityMetric = "jaccard"
	// SimilarityOverlap is shared neighbours over the smaller set.
	SimilarityOverlap SimilarityMetric = "overlap"
)

type SimilarityOptions added in v0.3.0

type SimilarityOptions struct {
	// Direction says which edges define a node's neighbours. The server's
	// default is both.
	Direction GraphDirection
	Label     string
	Metric    SimilarityMetric
	Limit     int
}

SimilarityOptions narrows GraphNodeSimilarity.

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 SparseVector added in v0.3.0

type SparseVector struct {
	Indices []uint32  `json:"indices"`
	Values  []float32 `json:"values"`
}

SparseVector is parallel lists of term indices and their weights.

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 TextUpsert added in v0.3.0

type TextUpsert struct {
	// ID is what the embedded vector is stored under.
	ID string `json:"id"`
	// Text is embedded, and kept in the metadata under "text".
	Text     string         `json:"text"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

TextUpsert is one text of VectorUpsertText.

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". It is empty for a
	// nested block, which reports NestedDepth instead.
	Outcome string `json:"transaction"`
	// NestedDepth is set when the keyword opened or closed a nested block
	// rather than the transaction itself: how many nested blocks are still
	// open. The outer transaction is open whenever this is set, zero included.
	NestedDepth *int `json:"nested_depth"`
}

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 TrimResult added in v0.3.0

type TrimResult struct {
	// Length is how many elements the list holds now.
	Length  int64 `json:"length"`
	Removed int64 `json:"removed"`
}

TrimResult is what CacheLTrim left behind.

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 VectorAlias added in v0.3.0

type VectorAlias struct {
	Alias      string `json:"alias"`
	Collection string `json:"collection"`
}

VectorAlias is one alias and the collection it names.

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 VectorConfig added in v0.3.0

type VectorConfig struct {
	Collection     string        `json:"collection"`
	Normalize      bool          `json:"normalize"`
	M              int           `json:"m"`
	EfConstruction int           `json:"ef_construction"`
	MultiTenant    bool          `json:"multi_tenant"`
	Named          []NamedVector `json:"named"`
}

VectorConfig is a collection's configuration after VectorSetCollectionConfig.

type VectorConfigChange added in v0.3.0

type VectorConfigChange struct {
	// Normalize stores every vector, and ranks every query, at unit length.
	// It can only change on an empty collection.
	Normalize *bool
	// M and EfConstruction shape the HNSW graph and take effect at the next
	// build, which the call forces.
	M              int
	EfConstruction int
	// MultiTenant requires every vector to carry a string _tenant, and every
	// search to name one.
	MultiTenant *bool
}

VectorConfigChange is what VectorSetCollectionConfig changes. A nil or zero field leaves that setting as it is.

type VectorExample added in v0.3.0

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

VectorExample is one example for VectorSearchByExamples: a stored vector named by id, or a vector given outright. Build one with ExampleID or ExampleVector.

func ExampleID added in v0.3.0

func ExampleID(id string) VectorExample

ExampleID is the stored vector with this id.

func ExampleVector added in v0.3.0

func ExampleVector(vector []float32) VectorExample

ExampleVector is this vector.

func (VectorExample) MarshalJSON added in v0.3.0

func (e VectorExample) MarshalJSON() ([]byte, error)

MarshalJSON writes a bare id or a bare vector, which is how the server tells the two apart.

type VectorHit

type VectorHit struct {
	ID       string         `json:"id"`
	Score    float32        `json:"score"`
	Metadata map[string]any `json:"metadata"`
	// Vector is the vector itself, when the search asked for vectors.
	Vector []float32 `json:"vector,omitempty"`
	// Reason says why the hit matched, when the search asked for an
	// explanation.
	Reason string `json:"reason,omitempty"`
}

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 VectorIndexRebuild added in v0.3.0

type VectorIndexRebuild struct {
	Rebuilt           bool  `json:"rebuilt"`
	Vectors           int64 `json:"vectors"`
	BuildMs           int64 `json:"build_ms"`
	Persisted         bool  `json:"persisted"`
	TombstonesCleared int64 `json:"tombstones_cleared"`
}

VectorIndexRebuild is what VectorRebuildIndex did.

type VectorIndexStats added in v0.3.0

type VectorIndexStats struct {
	Collection string `json:"collection"`
	// Index is "flat" for an exact scan and "hnsw" for the graph.
	Index  string `json:"index"`
	Stored int64  `json:"stored"`
	// FlatScanThreshold is the size below which a search scans.
	FlatScanThreshold int64 `json:"flat_scan_threshold"`
	Layers            int   `json:"layers"`
	// Nodes counts the graph's nodes, tombstones included; Live counts the
	// live ones.
	Nodes      int64 `json:"nodes"`
	Live       int64 `json:"live"`
	Tombstones int64 `json:"tombstones"`
	// Reachable counts the live nodes the entry point can reach.
	Reachable     int64  `json:"reachable"`
	Unreachable   int64  `json:"unreachable"`
	ShouldRebuild bool   `json:"should_rebuild"`
	Persisted     bool   `json:"persisted"`
	Entry         string `json:"entry"`
	// LivePerLayer counts live nodes on each layer, the bottom first.
	LivePerLayer []int64 `json:"live_per_layer"`
	Degree       struct {
		Min  int     `json:"min"`
		Mean float64 `json:"mean"`
		Max  int     `json:"max"`
	} `json:"degree"`
	Memory struct {
		VectorBytes   int64 `json:"vector_bytes"`
		OverheadBytes int64 `json:"overhead_bytes"`
	} `json:"memory"`
	Parameters struct {
		M              int `json:"m"`
		M0             int `json:"m0"`
		EfConstruction int `json:"ef_construction"`
		EfSearch       int `json:"ef_search"`
	} `json:"parameters"`
}

VectorIndexStats is the shape of a collection's search index.

A collection small enough to be scanned has no graph: Index is "flat" and everything past FlatScanThreshold is zero.

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 VectorPartition added in v0.3.0

type VectorPartition struct {
	// Name is the partition's value of the field.
	Name  string `json:"name"`
	Count int64  `json:"count"`
}

VectorPartition is one partition of a collection.

type VectorPartitions added in v0.3.0

type VectorPartitions struct {
	// Field is the metadata field the collection was partitioned by.
	Field      string            `json:"field"`
	Partitions []VectorPartition `json:"partitions"`
	// Unpartitioned counts vectors with no value for the field.
	Unpartitioned int64 `json:"unpartitioned"`
}

VectorPartitions is the partitions of a collection.

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 VectorRecall added in v0.3.0

type VectorRecall struct {
	Collection string `json:"collection"`
	Index      string `json:"index"`
	// Measured is false for a collection small enough to be scanned: there is
	// nothing to measure, and Recall is 1 by construction.
	Measured bool `json:"measured"`
	// Recall is the mean overlap of the index's results with an exact scan's.
	Recall float64 `json:"recall"`
	// MinRecall is the worst single query's overlap.
	MinRecall     float64 `json:"min_recall"`
	Queries       int     `json:"queries"`
	TopK          int     `json:"top_k"`
	EfSearch      int     `json:"ef_search"`
	FlatFallbacks int     `json:"flat_fallbacks"`
	// Reason says why nothing was measured, when nothing was.
	Reason string `json:"reason"`
}

VectorRecall is the recall VectorMeasureRecall measured.

type VectorSearchOptions added in v0.3.0

type VectorSearchOptions struct {
	// Filter keeps only vectors whose metadata matches it.
	Filter map[string]any
	// MinScore drops hits scoring below it. Nil means no floor.
	MinScore *float32
	// IncludeVectors returns each hit's vector with it.
	IncludeVectors bool
	// OmitMetadata leaves each hit's metadata out; the server includes it by
	// default.
	OmitMetadata bool
	// Offset skips this many hits from the front.
	Offset int
	// MaxDistance drops hits farther than it. Nil means no ceiling.
	MaxDistance *float32
	// EfSearch is the size of the candidate list the index walk keeps.
	EfSearch int
	// Exact scans every vector instead of using the index.
	Exact bool
	// ScoreMetric scores by this measure instead of the collection's metric.
	ScoreMetric ScoreMetric
	// FilterStrategy says how to combine the filter with the index.
	FilterStrategy FilterStrategy
	// Using searches this named vector instead of the collection's own.
	Using string
	// Tenant and Namespace restrict the search to one partition.
	Tenant    string
	Namespace string
	// Sparse is a sparse query to combine with the dense one.
	Sparse *SparseVector
	// HybridAlpha is the dense share of a hybrid score, from 0 to 1.
	HybridAlpha *float32
	// Explain attaches to each hit the reason it matched.
	Explain bool
	// ScoreExpr is an expression that rescores each hit.
	ScoreExpr string
	// ExplainText is the query text an explanation should refer to.
	ExplainText string
	// Ann chooses the approximate index.
	Ann AnnIndex
	// Nprobe is how many inverted-file cells to probe.
	Nprobe int
}

VectorSearchOptions is what a batch or example search applies beyond its query vectors. A field left at its zero value is left off the wire, so the server's own default applies.

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 VectorUpsertItem added in v0.3.0

type VectorUpsertItem struct {
	ID     string    `json:"id"`
	Vector []float32 `json:"vector"`
	// Metadata is stored alongside the vector. Nil stores none.
	Metadata map[string]any `json:"metadata,omitempty"`
}

VectorUpsertItem is one vector of VectorUpsertMany.

type WarmResult added in v0.3.0

type WarmResult struct {
	Written int64 `json:"written"`
	// AlreadyCached counts entries left alone because a live value was there.
	AlreadyCached int64 `json:"alreadyCached"`
}

WarmResult is what CacheWarm did.

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.

type ZAddResult added in v0.3.0

type ZAddResult struct {
	// Added counts members that were not in the set before.
	Added int64 `json:"added"`
	// Updated counts members already there whose score changed.
	Updated int64 `json:"updated"`
}

ZAddResult is what CacheZAdd changed.

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