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
- Variables
- func BindParams(sql string, args ...Arg) (string, error)
- func BuildTransactionScript(statements []Statement) (string, error)
- func QuoteSQL(s string) string
- func SQLLiteral(value any) (string, error)
- func SQLParam(value any) (any, error)
- type AccumulatorOp
- type AggregateStage
- func StageCount(field string) AggregateStage
- func StageGroup(by GroupKey, accumulators ...GroupAccumulator) AggregateStage
- func StageLimit(n int) AggregateStage
- func StageMatch(filter DocumentFilter) AggregateStage
- func StageProject(fields []string, include bool) AggregateStage
- func StageSkip(n int) AggregateStage
- func StageSort(keys ...SortKey) AggregateStage
- type Arg
- type ArgumentError
- type AuthError
- type CacheKeyInfo
- type CachePair
- type Client
- func (c *Client) AdminPing() error
- func (c *Client) AdminStatus() (map[string]any, error)
- func (c *Client) Begin() (*TransactionResult, error)
- func (c *Client) CacheClearNamespace(namespace string) (int64, error)
- func (c *Client) CacheDelete(namespace, key string) (existed bool, err error)
- func (c *Client) CacheExists(namespace, key string) (bool, error)
- func (c *Client) CacheExpire(namespace, key string, ttlMs int64) (bool, error)
- func (c *Client) CacheGet(namespace, key string) (value []byte, found bool, err error)
- func (c *Client) CacheHDel(namespace, key string, fields ...[]byte) (int64, error)
- func (c *Client) CacheHExists(namespace, key string, field []byte) (bool, error)
- func (c *Client) CacheHGet(namespace, key string, field []byte) (value []byte, found bool, err error)
- func (c *Client) CacheHGetAll(namespace, key string) ([]CachePair, error)
- func (c *Client) CacheHLen(namespace, key string) (int64, error)
- func (c *Client) CacheHSet(namespace, key string, entries []CachePair) (int64, error)
- func (c *Client) CacheHSetText(namespace, key string, entries map[string]string) (int64, error)
- func (c *Client) CacheIncr(namespace, key string, by int64) (int64, error)
- func (c *Client) CacheKeys(namespace, pattern string, limit int) ([]CacheKeyInfo, error)
- func (c *Client) CacheLIndex(namespace, key string, index int64) (value []byte, found bool, err error)
- func (c *Client) CacheLLen(namespace, key string) (int64, error)
- func (c *Client) CacheLPop(namespace, key string) (value []byte, found bool, err error)
- func (c *Client) CacheLPush(namespace, key string, values ...[]byte) (int64, error)
- func (c *Client) CacheLRange(namespace, key string, start, stop int64) ([][]byte, error)
- func (c *Client) CachePersist(namespace, key string) (bool, error)
- func (c *Client) CachePing() error
- func (c *Client) CacheRPop(namespace, key string) (value []byte, found bool, err error)
- func (c *Client) CacheRPush(namespace, key string, values ...[]byte) (int64, error)
- func (c *Client) CacheSAdd(namespace, key string, members ...[]byte) (int64, error)
- func (c *Client) CacheSCard(namespace, key string) (int64, error)
- func (c *Client) CacheSIsMember(namespace, key string, member []byte) (bool, error)
- func (c *Client) CacheSMembers(namespace, key string) ([][]byte, error)
- func (c *Client) CacheSRem(namespace, key string, members ...[]byte) (int64, error)
- func (c *Client) CacheSet(namespace, key string, value []byte) error
- func (c *Client) CacheSetNx(namespace, key string, value []byte, ttlMs int64) (bool, error)
- func (c *Client) CacheSetTTL(namespace, key string, value []byte, ttlMs int64) error
- func (c *Client) CacheTTL(namespace, key string) (ttlMs int64, has bool, err error)
- func (c *Client) CacheXAdd(namespace, key string, fields []CachePair, id string) (string, error)
- func (c *Client) CacheXAddText(namespace, key string, fields map[string]string, id string) (string, error)
- func (c *Client) CacheXDel(namespace, key string, ids ...string) (int64, error)
- func (c *Client) CacheXLen(namespace, key string) (int64, error)
- func (c *Client) CacheXRange(namespace, key, start, end string, count int) ([]StreamEntry, error)
- func (c *Client) CacheXRead(namespace, key, after string, count int) ([]StreamEntry, error)
- func (c *Client) CacheXTrim(namespace, key string, maxLen int) (int64, error)
- func (c *Client) Cancel(requestID string) (int, error)
- func (c *Client) Close() error
- func (c *Client) Commit() (*TransactionResult, error)
- func (c *Client) DocumentAggregate(collection string, pipeline ...AggregateStage) ([]Document, error)
- func (c *Client) DocumentAnalyze(collection string) (*DocumentStats, error)
- func (c *Client) DocumentCreateCollection(collection string) error
- func (c *Client) DocumentCreateIndex(collection, indexName, field string, unique bool) error
- func (c *Client) DocumentDelete(collection, id string) error
- func (c *Client) DocumentDropCollection(collection string) error
- func (c *Client) DocumentDropIndex(collection, indexName string) error
- func (c *Client) DocumentFind(collection string, filter DocumentFilter) ([]Document, error)
- func (c *Client) DocumentFindLimit(collection string, filter DocumentFilter, limit int) ([]Document, error)
- func (c *Client) DocumentGet(collection, id string) (doc Document, found bool, err error)
- func (c *Client) DocumentInsert(collection string, document any) (string, error)
- func (c *Client) DocumentInsertWithID(collection, id string, document any) (string, error)
- func (c *Client) DocumentListCollections() ([]string, error)
- func (c *Client) DocumentListIndexes(collection string) ([]DocumentIndex, error)
- func (c *Client) DocumentUpdate(collection, id string, set map[string]any) error
- func (c *Client) DocumentUpdateMany(collection string, filter DocumentFilter, update DocumentUpdate) (UpdateManyResult, error)
- func (c *Client) DocumentUpdateOne(collection, id string, update DocumentUpdate) error
- func (c *Client) DocumentUpsertOne(collection, id string, update DocumentUpdate) (inserted bool, err error)
- func (c *Client) Execute(sql string) (*Response, error)
- func (c *Client) ExecuteParams(sql string, args ...Arg) (*Response, error)
- func (c *Client) GrantedFeatures() uint64
- func (c *Client) GraphAddEdge(graph, id, from, to, label string, properties map[string]any) error
- func (c *Client) GraphAddNode(graph, id string, labels []string, properties map[string]any) error
- func (c *Client) GraphCreate(graph string) error
- func (c *Client) GraphDegree(graph, nodeID string, direction GraphDirection) (int, error)
- func (c *Client) GraphDeleteEdge(graph, id string) error
- func (c *Client) GraphDeleteNode(graph, id string) error
- func (c *Client) GraphDrop(graph string) error
- func (c *Client) GraphGetEdge(graph, id string) (edge *GraphEdge, found bool, err error)
- func (c *Client) GraphGetNode(graph, id string) (node *GraphNode, found bool, err error)
- func (c *Client) GraphList() ([]string, error)
- func (c *Client) GraphListEdges(graph string, limit, offset int) (*GraphEdgePage, error)
- func (c *Client) GraphListNodes(graph string, limit, offset int) (*GraphNodePage, error)
- func (c *Client) GraphNeighbors(graph, nodeID string, opts NeighborOptions) ([]GraphNeighbor, error)
- func (c *Client) GraphQuery(graph, cypher string) (*GraphRows, error)
- func (c *Client) GraphShortestPath(graph, from, to string, opts PathOptions) (*GraphPath, error)
- func (c *Client) GraphTraverse(graph, start string, opts TraverseOptions) (*GraphTraversal, error)
- func (c *Client) GraphWeightedShortestPath(graph, from, to string, opts WeightedPathOptions) (*GraphPath, error)
- func (c *Client) InTransaction() bool
- func (c *Client) LastRequestID() string
- func (c *Client) LlmContext(sources []LlmSource, format OutputFormat, opts *LlmOptions) (string, error)
- func (c *Client) LlmSchema(format OutputFormat, opts *LlmOptions) (string, error)
- func (c *Client) Ping() error
- func (c *Client) Poisoned() bool
- func (c *Client) Query(sql string) (*Rows, error)
- func (c *Client) QueryParams(sql string, args ...Arg) (*Rows, error)
- func (c *Client) Request(op any) (*Response, error)
- func (c *Client) Rollback() (*TransactionResult, error)
- func (c *Client) ServerParamsGranted() bool
- func (c *Client) SessionID() string
- func (c *Client) SessionTxnGranted() bool
- func (c *Client) SetReadTimeout(d time.Duration)
- func (c *Client) SetRequestTimeout(d time.Duration)
- func (c *Client) Transaction(statements ...Statement) (*TransactionResult, error)
- func (c *Client) VectorCreateCollection(collection string, dimension int, metric VectorMetric) error
- func (c *Client) VectorCreateCollectionQuantized(collection string, dimension int, metric VectorMetric, ...) error
- func (c *Client) VectorDelete(collection, id string) error
- func (c *Client) VectorDescribeCollection(collection string) (*VectorCollectionInfo, error)
- func (c *Client) VectorDropCollection(collection string) error
- func (c *Client) VectorGet(collection, id string) (item *VectorItem, found bool, err error)
- func (c *Client) VectorListCollections() ([]VectorCollectionSummary, error)
- func (c *Client) VectorListVectors(collection string, limit, offset int) (*VectorPage, error)
- func (c *Client) VectorSearch(collection string, vector []float32, topK int) (*VectorSearchResult, error)
- func (c *Client) VectorSearchFiltered(collection string, vector []float32, topK int, filter map[string]any) (*VectorSearchResult, error)
- func (c *Client) VectorUpsert(collection, id string, vector []float32, metadata map[string]any) error
- func (c *Client) WithTransaction(fn func(*Client) error) error
- type Decimal
- type Document
- type DocumentFilter
- func FilterAll() DocumentFilter
- func FilterAnd(filters ...DocumentFilter) DocumentFilter
- func FilterContains(field string, value any) DocumentFilter
- func FilterEq(field string, value any) DocumentFilter
- func FilterGt(field string, value any) DocumentFilter
- func FilterGte(field string, value any) DocumentFilter
- func FilterIn(field string, values ...any) DocumentFilter
- func FilterLt(field string, value any) DocumentFilter
- func FilterLte(field string, value any) DocumentFilter
- func FilterNe(field string, value any) DocumentFilter
- type DocumentIndex
- type DocumentStats
- type DocumentUpdate
- type GraphDirection
- type GraphEdge
- type GraphEdgePage
- type GraphNeighbor
- type GraphNode
- type GraphNodePage
- type GraphPath
- type GraphRows
- type GraphTraversal
- type GraphVisit
- type GroupAccumulator
- type GroupKey
- type LlmOptions
- type LlmSource
- type NeighborOptions
- type Options
- type OutputFormat
- type PathOptions
- type Pool
- type ProtocolError
- type Response
- type Rows
- type ServerError
- type SortKey
- type Statement
- type StreamEntry
- type TLSOptions
- type TimeoutError
- type TransactionResult
- type TraverseOptions
- type UpdateManyResult
- type VectorCollectionInfo
- type VectorCollectionSummary
- type VectorHit
- type VectorItem
- type VectorMetric
- type VectorPage
- type VectorQuantization
- type VectorSearchResult
- type WeightedPathOptions
Constants ¶
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.
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.
const DefaultPort = 8427
DefaultPort is the port tricore-server listens on when not configured otherwise.
const ErrorCodeNotLeader = "not_leader"
ErrorCodeNotLeader is the server's `diagnostics.error_code` for a write or linearizable read that reached a Raft follower.
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.
const Version = "0.1.0"
Version is this SDK's own version, so a consumer can pin one (V2 P2).
Go resolves module versions from git tags, not from source, so a consumer of an untagged checkout previously had nothing to state at all. This constant is the SDK's version and is deliberately separate from protocolVersion: the two move for different reasons.
Variables ¶
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.
var ErrPoolClosed = errors.New("tricoredb: pool is closed")
ErrPoolClosed is returned by a Pool whose Close has already run.
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 ¶
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 ¶
BuildTransactionScript assembles BEGIN; ...; COMMIT from a list of statements.
Caller-supplied transaction control is refused rather than passed through: nesting a second BEGIN, or committing early, changes what the script means in a way the caller almost certainly did not intend.
func QuoteSQL ¶
QuoteSQL escapes and quotes a string: double every ', which is the only escape the server's tokenizer recognises.
func SQLLiteral ¶
SQLLiteral renders one Go value as a SQL literal.
func SQLParam ¶
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 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 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 StageSort ¶
func StageSort(keys ...SortKey) AggregateStage
StageSort orders the stream by the given keys.
func (AggregateStage) MarshalJSON ¶
func (s AggregateStage) MarshalJSON() ([]byte, error)
MarshalJSON emits the externally-tagged form the server deserializes.
type Arg ¶
type Arg = any
Arg is one bound value. It exists so ExecuteParams/QueryParams can take a variadic list without shadowing the plain Execute/Query signatures.
type ArgumentError ¶
type ArgumentError struct {
Message string
}
ArgumentError reports a request this driver refused to send.
func (*ArgumentError) Error ¶
func (e *ArgumentError) Error() string
func (*ArgumentError) Unwrap ¶
func (e *ArgumentError) Unwrap() error
type AuthError ¶
type AuthError struct {
Message string
}
AuthError reports an authentication failure. Message is the server's explanation, if it supplied one.
type CacheKeyInfo ¶
type CacheKeyInfo struct {
Key string `json:"key"`
TTLMs *int64 `json:"ttl_ms"`
Bytes int64 `json:"bytes"`
}
CacheKeyInfo is one live key in a namespace.
type CachePair ¶
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.
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 ¶
Connect dials the server, performs HELLO, and — when Options.User is set — AUTH. ctx bounds the whole handshake (dial + HELLO + AUTH); it does not linger over the lifetime of the returned Client.
func (*Client) AdminPing ¶
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 ¶
AdminStatus is the server status as reported by the cluster core.
Stub cores answer with a plain message rather than structured JSON, which is returned under the "message" key rather than raised as an error, so a status call never hard-fails on a healthy single node.
func (*Client) Begin ¶
func (c *Client) Begin() (*TransactionResult, error)
Begin opens a session transaction on this connection.
Every statement sent on this connection until Client.Commit or Client.Rollback runs inside it, at one snapshot, and is invisible to other connections until committed. The block belongs to this connection's socket: it cannot be committed from another connection, a pooled one included, and a dropped socket rolls it back.
Requires the server to have granted FeatureSessionTxn in the handshake (see Client.SessionTxnGranted). If it did not — an older server, or a sharded / forwarding node — this fails by name *before writing anything*, rather than sending a BEGIN the server would run as a one-statement autocommit script; the returned error unwraps to ErrArgument, and Client.Transaction works everywhere.
What the server enforces inside a block, in its own words when it happens: a failed statement aborts the block and every statement after it is refused until ROLLBACK; a second Begin is refused (no savepoints); DDL and multi-statement scripts are refused; a block left idle past the server's idle-in-transaction window (60s by default) is rolled back and the connection closed; and a block that buffers more than max_pending_writes_per_transaction writes is aborted.
The returned result's Outcome is "began".
func (*Client) CacheClearNamespace ¶
CacheClearNamespace deletes every key in a namespace, returning how many were removed.
func (*Client) CacheDelete ¶
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 ¶
CacheExists reports whether the key is present and unexpired.
func (*Client) CacheExpire ¶
CacheExpire sets or replaces a key's TTL. False when the key does not exist.
func (*Client) CacheGet ¶
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) CacheHExists ¶
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 ¶
CacheHGetAll returns every field/value pair, in ascending field order.
func (*Client) CacheHSet ¶
CacheHSet sets fields, returning how many were newly created (as opposed to overwritten).
func (*Client) CacheHSetText ¶
CacheHSetText sets string fields, encoded UTF-8.
func (*Client) CacheIncr ¶
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) CacheLPop ¶
CacheLPop removes and returns the first element. found is false on an empty or missing key.
func (*Client) CacheLPush ¶
CacheLPush prepends elements, returning the new length.
func (*Client) CacheLRange ¶
CacheLRange reads an inclusive index range. Negative indices count from the end (-1 is the last element) and out-of-range bounds clamp.
func (*Client) CachePersist ¶
CachePersist removes a key's TTL, making it permanent. False when it had none.
func (*Client) CachePing ¶
CachePing is a liveness check routed through the cache core.
Distinct from Ping, which exchanges a PING frame and never reaches a module. This one proves auth, routing and dispatch are working.
func (*Client) CacheRPop ¶
CacheRPop removes and returns the last element. found is false on an empty or missing key.
func (*Client) CacheRPush ¶
CacheRPush appends elements, returning the new length.
func (*Client) CacheSCard ¶
CacheSCard is the number of members; 0 when the key is missing.
func (*Client) CacheSIsMember ¶
CacheSIsMember reports whether member is in the set.
func (*Client) CacheSMembers ¶
CacheSMembers returns every member, in ascending byte order.
func (*Client) CacheSet ¶
CacheSet stores value under (namespace, key) with no expiry. Use CacheSetTTL to attach one.
func (*Client) CacheSetNx ¶
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 ¶
CacheSetTTL stores value under (namespace, key), expiring after ttlMs milliseconds. ttlMs <= 0 means no expiry.
func (*Client) CacheTTL ¶
CacheTTL returns the remaining time to live in milliseconds.
has is false when the key is missing *or* has no expiry; use CacheExists to tell those two apart.
func (*Client) CacheXAdd ¶
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) 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 ¶
CacheXTrim caps the stream by evicting the oldest entries, returning how many were evicted.
func (*Client) Cancel ¶
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 ¶
Close ends the session politely (CLOSE/BYE) and releases the socket.
A failure during the goodbye handshake is not surfaced — the socket is closed either way, mirroring the reference Python driver's stance that a teardown error isn't worth failing over — but Close is idempotent and safe to call more than once (e.g. from both a defer and an explicit call).
func (*Client) Commit ¶
func (c *Client) Commit() (*TransactionResult, error)
Commit commits the block opened by Client.Begin, durably and as one atomic batch. The returned result's Outcome is "committed".
A refusal is the server's own and ends the block either way: after a failed statement the server has already rolled it back and says so; a first-committer-wins conflict discards it.
func (*Client) DocumentAggregate ¶
func (c *Client) DocumentAggregate(collection string, pipeline ...AggregateStage) ([]Document, error)
DocumentAggregate runs an aggregation pipeline over a collection. An empty pipeline returns the collection unchanged.
Stages this build does not implement ($lookup, $unwind, $facet, $out, $addFields, computed expressions) are not representable here at all.
func (*Client) DocumentAnalyze ¶
func (c *Client) DocumentAnalyze(collection string) (*DocumentStats, error)
DocumentAnalyze collects approximate statistics the query optimizer uses to choose between an index lookup and a scan.
func (*Client) DocumentCreateCollection ¶
DocumentCreateCollection creates a document collection.
func (*Client) DocumentCreateIndex ¶
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 ¶
DocumentDelete removes one document by id. Deleting an absent document is not an error.
func (*Client) DocumentDropCollection ¶
DocumentDropCollection removes a collection, its documents, and its indexes. Dropping a collection that does not exist is an error.
func (*Client) DocumentDropIndex ¶
DocumentDropIndex removes a named index from a collection.
func (*Client) DocumentFind ¶
func (c *Client) DocumentFind(collection string, filter DocumentFilter) ([]Document, error)
DocumentFind returns every document matching filter. Use DocumentFindLimit to cap the result.
func (*Client) DocumentFindLimit ¶
func (c *Client) DocumentFindLimit(collection string, filter DocumentFilter, limit int) ([]Document, error)
DocumentFindLimit returns at most limit documents matching filter. A limit of zero or less means no limit.
func (*Client) DocumentGet ¶
DocumentGet fetches one document by id. found is false when no such document exists, which is how an absent document is told apart from a stored empty one — both otherwise look like an empty map.
func (*Client) DocumentInsert ¶
DocumentInsert stores document under a server-generated id, which it returns. document must marshal to a JSON object.
Use DocumentInsertWithID to choose the id yourself.
func (*Client) DocumentInsertWithID ¶
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 ¶
DocumentListCollections names every document collection in the database.
func (*Client) DocumentListIndexes ¶
func (c *Client) DocumentListIndexes(collection string) ([]DocumentIndex, error)
DocumentListIndexes lists a collection's indexes.
func (*Client) DocumentUpdate ¶
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 ¶
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 ¶
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 ¶
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 ¶
GraphAddEdge stores a directed edge from -> to under id. Both endpoints must already exist; a dangling endpoint is refused rather than created. properties may be nil.
func (*Client) GraphAddNode ¶
GraphAddNode stores a node, replacing any node already under id. labels and properties may be nil.
func (*Client) GraphCreate ¶
GraphCreate creates an empty graph.
func (*Client) GraphDegree ¶
func (c *Client) GraphDegree(graph, nodeID string, direction GraphDirection) (int, error)
GraphDegree counts the edges incident to a node in a direction. DirectionBoth counts each edge once, self-loops included.
func (*Client) GraphDeleteEdge ¶
GraphDeleteEdge removes an edge by id. Deleting an absent edge is not an error; a missing graph is.
func (*Client) GraphDeleteNode ¶
GraphDeleteNode removes a node by id. Deleting an absent node is not an error; a missing graph is.
func (*Client) GraphDrop ¶
GraphDrop removes a graph with its nodes and edges. Dropping a graph that does not exist is an error.
func (*Client) GraphGetEdge ¶
GraphGetEdge fetches one edge by id. found is false when no such edge exists.
func (*Client) GraphGetNode ¶
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) GraphListEdges ¶
func (c *Client) GraphListEdges(graph string, limit, offset int) (*GraphEdgePage, error)
GraphListEdges reads one page of a graph's edges, ordered by id. limit <= 0 asks for the server default (500, capped at 1000); offset skips that many.
func (*Client) GraphListNodes ¶
func (c *Client) GraphListNodes(graph string, limit, offset int) (*GraphNodePage, error)
GraphListNodes reads one page of a graph's nodes, ordered by id. limit <= 0 asks for the server default (500, capped at 1000); offset skips that many.
func (*Client) GraphNeighbors ¶
func (c *Client) GraphNeighbors(graph, nodeID string, opts NeighborOptions) ([]GraphNeighbor, error)
GraphNeighbors lists the edges incident to a node and the node at the far end of each. A node with no matching edges yields an empty slice, not an error.
func (*Client) GraphQuery ¶
GraphQuery runs a read-only Cypher-subset query and returns its rows.
The server implements MATCH / WHERE / RETURN with labels, property predicates, relationship direction and type, bounded variable-length paths, DISTINCT, ORDER BY / SKIP / LIMIT, and global aggregates. Every other clause — all write clauses, OPTIONAL MATCH, WITH, UNWIND, CALL, path variables, shortestPath(), parameters — is refused by name rather than ignored, so a rejected query returns an error instead of an answer computed from a partially-understood statement.
func (*Client) GraphShortestPath ¶
func (c *Client) GraphShortestPath(graph, from, to string, opts PathOptions) (*GraphPath, error)
GraphShortestPath finds a path from `from` to `to` with the fewest hops. Both endpoints must exist. "No path" comes back as a GraphPath with Found false, not as an error.
func (*Client) GraphTraverse ¶
func (c *Client) GraphTraverse(graph, start string, opts TraverseOptions) (*GraphTraversal, error)
GraphTraverse walks outward from start by breadth-first search, bounded by opts. The start node must exist.
func (*Client) GraphWeightedShortestPath ¶
func (c *Client) GraphWeightedShortestPath(graph, from, to string, opts WeightedPathOptions) (*GraphPath, error)
GraphWeightedShortestPath finds the least-cost path from `from` to `to` by summed edge weight.
This is a different question from GraphShortestPath, which minimises hops: with unequal weights the two return different paths and neither substitutes for the other. "No path" comes back as Found false, not as an error.
func (*Client) InTransaction ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
QueryParams runs a read, binding ? placeholders from args server-side. See Client.ExecuteParams for what that means and what it requires.
func (*Client) Request ¶
Request sends a raw, externally-tagged operation and returns the decoded response — the escape hatch every other TriCoreDB driver exposes, and which this one was missing.
The typed helpers cover every operation a V1 client should need, so reach for this only when there is genuinely no typed method: a server operation that exists solely to be refused (`Cache::XGroup`), or one added to the server ahead of this driver. `op` is the wire form, e.g.
db.Request(map[string]any{"Cache": map[string]any{"Ping": nil}})
Nothing here validates the shape, so a malformed op is refused by the server rather than by the driver. That is the trade: full reach, no type safety.
func (*Client) Rollback ¶
func (c *Client) Rollback() (*TransactionResult, error)
Rollback discards the block opened by Client.Begin. The returned result's Outcome is "rolled_back".
func (*Client) ServerParamsGranted ¶
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 ¶
SessionID is the server-assigned session identifier from AUTH_OK, or "" if the connection never authenticated.
func (*Client) SessionTxnGranted ¶
SessionTxnGranted reports whether the server granted FeatureSessionTxn on this connection — the bit Client.Begin requires.
func (*Client) SetReadTimeout ¶
SetReadTimeout sets a client-side deadline on each subsequent read. A non-positive duration clears it. See Options.ReadTimeout.
func (*Client) SetRequestTimeout ¶
SetRequestTimeout stamps a server-side deadline on every subsequent request. A non-positive duration clears it.
This is not a client-side timeout: cancelling on this side abandons the read while the server keeps working. This makes the server stop.
func (*Client) Transaction ¶
func (c *Client) Transaction(statements ...Statement) (*TransactionResult, error)
Transaction runs a pre-declared script atomically, in one request.
The server runs the BEGIN ... COMMIT script against an MVCC snapshot and flushes it as one atomic batch; ROLLBACK, or any error mid-script, discards the buffer. This is the right tool when every statement is known up front: one round trip, one replication event, and it works on every node — including the sharded and forwarding ones that withhold FeatureSessionTxn.
db.Transaction(
tricoredb.Stmt("INSERT INTO t VALUES (?, ?)", 1, "ada"),
tricoredb.Stmt("INSERT INTO t VALUES (?, ?)", 2, "bob"),
)
When a later statement depends on what an earlier one read, use Client.Begin/Client.Commit/Client.Rollback or Client.WithTransaction instead.
func (*Client) VectorCreateCollection ¶
func (c *Client) VectorCreateCollection(collection string, dimension int, metric VectorMetric) error
VectorCreateCollection creates an unquantized collection of the given dimension and metric. Use VectorCreateCollectionQuantized to opt into index compression.
func (*Client) VectorCreateCollectionQuantized ¶
func (c *Client) VectorCreateCollectionQuantized(collection string, dimension int, metric VectorMetric, quantization VectorQuantization) error
VectorCreateCollectionQuantized creates a collection with an explicit index quantization. Dimension and metric are fixed for the collection's lifetime.
func (*Client) VectorDelete ¶
VectorDelete removes one vector by id. Deleting an absent id is not an error; a missing collection is.
func (*Client) VectorDescribeCollection ¶
func (c *Client) VectorDescribeCollection(collection string) (*VectorCollectionInfo, error)
VectorDescribeCollection reads one collection's catalog metadata and its live vector count.
func (*Client) VectorDropCollection ¶
VectorDropCollection removes a collection and every vector in it. Dropping a collection that does not exist is an error.
func (*Client) VectorGet ¶
func (c *Client) VectorGet(collection, id string) (item *VectorItem, found bool, err error)
VectorGet fetches one stored vector by id. found is false when no such vector exists — the server answers a miss with a null payload, which would otherwise decode into a zero-valued VectorItem indistinguishable from a real one.
func (*Client) VectorListCollections ¶
func (c *Client) VectorListCollections() ([]VectorCollectionSummary, error)
VectorListCollections describes every vector collection in the database.
func (*Client) VectorListVectors ¶
func (c *Client) VectorListVectors(collection string, limit, offset int) (*VectorPage, error)
VectorListVectors reads one page of a collection's vectors, ordered by id, for browsing and export. limit <= 0 asks for the server default (500, capped at 1000); offset skips that many items.
func (*Client) VectorSearch ¶
func (c *Client) VectorSearch(collection string, vector []float32, topK int) (*VectorSearchResult, error)
VectorSearch returns the topK nearest vectors to the query vector. topK must be in 1..=1000 and len(vector) must equal the collection's dimension.
func (*Client) VectorSearchFiltered ¶
func (c *Client) VectorSearchFiltered(collection string, vector []float32, topK int, filter map[string]any) (*VectorSearchResult, error)
VectorSearchFiltered is VectorSearch restricted to vectors whose metadata matches filter — a map of top-level metadata field to required equal value. A nil or empty filter means no filtering.
Exact equality only: the server implements no ranges and no nesting here.
func (*Client) VectorUpsert ¶
func (c *Client) VectorUpsert(collection, id string, vector []float32, metadata map[string]any) error
VectorUpsert stores vector under id, replacing any vector already there. len(vector) must equal the collection's dimension; a mismatch is refused rather than padded or truncated. metadata may be nil.
func (*Client) WithTransaction ¶
WithTransaction runs Begin, then fn, then Commit — or Rollback and the original error if fn returns one. A panic inside fn rolls the block back and re-panics, so no path leaves a block open.
err := db.WithTransaction(func(tx *tricoredb.Client) error {
if _, err := tx.ExecuteParams("UPDATE accounts SET balance = balance - ? WHERE id = ?", 10, 1); err != nil {
return err
}
_, err := tx.ExecuteParams("UPDATE accounts SET balance = balance + ? WHERE id = ?", 10, 2)
return err
})
fn must issue its statements on the client it is given — this one — and only this one. A statement on any other connection, a pooled one included, is outside the block: the server binds the transaction to this socket and refuses COMMIT from any other by name.
type Decimal ¶
type Decimal string
Decimal is an exact decimal number carried as its text, such as "1.50" or "-0.000000000000000001".
Bound with Client.ExecuteParams or Client.QueryParams, it travels as a JSON string of plain digits, which a DECIMAL column parses exactly. A JSON number would be read by the server as a double and lose every digit past a double's precision, and an exponent ("1.5E+3") makes the server's tokenizer read a DOUBLE, so a Decimal with an exponent is refused before anything is sent. Trailing zeros are kept as written.
The server allows a scale of at most 18 and at most 38 significant digits and refuses anything beyond that by name; this driver does not repeat that check.
type Document ¶
Document is one JSON document as the server stores it. Every stored document carries an "_id" string, whether the caller supplied it or the server generated one.
type DocumentFilter ¶
type DocumentFilter struct {
// contains filtered or unexported fields
}
DocumentFilter is a document query predicate — the Go form of the server's DocumentFilter (crates/tricore_core/src/request/document_ops.rs).
Build one with the Filter* constructors. Every field path accepts dot notation ("a.b.c") resolving into nested objects; a missing path never matches, including for FilterNe.
The zero DocumentFilter is invalid, not "match everything": a forgotten-to-initialize filter that silently matched the whole collection would turn a typo into a full-collection update. Use FilterAll to say that on purpose.
This is not MongoDB's query language: there is no Or, no Not, and no regex, because the server implements none of them.
func FilterAnd ¶
func FilterAnd(filters ...DocumentFilter) DocumentFilter
FilterAnd matches documents satisfying every sub-filter. With no arguments it matches everything, which is what the server does with an empty And.
func FilterContains ¶
func FilterContains(field string, value any) DocumentFilter
FilterContains matches a string field containing value as a substring, or an array field containing an element equal to value.
func FilterEq ¶
func FilterEq(field string, value any) DocumentFilter
FilterEq matches documents whose field equals value.
func FilterGt ¶
func FilterGt(field string, value any) DocumentFilter
FilterGt matches documents whose field is greater than value.
func FilterGte ¶
func FilterGte(field string, value any) DocumentFilter
FilterGte matches documents whose field is greater than or equal to value.
func FilterIn ¶
func FilterIn(field string, values ...any) DocumentFilter
FilterIn matches documents whose field equals any of values.
func FilterLt ¶
func FilterLt(field string, value any) DocumentFilter
FilterLt matches documents whose field is less than value.
func FilterLte ¶
func FilterLte(field string, value any) DocumentFilter
FilterLte matches documents whose field is less than or equal to value.
func FilterNe ¶
func FilterNe(field string, value any) DocumentFilter
FilterNe matches documents whose field exists and does not equal value. A document missing the field does not match.
func (DocumentFilter) MarshalJSON ¶
func (f DocumentFilter) MarshalJSON() ([]byte, error)
MarshalJSON emits the externally-tagged form the server deserializes.
type DocumentIndex ¶
type DocumentIndex struct {
// Name is the index name.
Name string `json:"index_name"`
// Field is the indexed field.
Field string `json:"field"`
// Unique reports whether the index enforces uniqueness.
Unique bool `json:"unique"`
}
DocumentIndex describes one secondary index on a collection.
type DocumentStats ¶
type DocumentStats struct {
// Collection is the analyzed collection.
Collection string `json:"analyzed"`
// DocumentCount is the number of documents in it.
DocumentCount int64 `json:"document_count"`
// IndexedFields is the number of fields with a secondary index.
IndexedFields int `json:"indexed_fields"`
}
DocumentStats is what DocumentAnalyze collected.
type DocumentUpdate ¶
type DocumentUpdate struct {
// Set maps a dot path to its new value.
Set map[string]any `json:"set,omitempty"`
// Inc maps a dot path to a numeric delta. Every value must be a number.
Inc map[string]any `json:"inc,omitempty"`
}
DocumentUpdate is a set of field mutations applied to one document: Set overwrites the value at a dot path, Inc adds a number to it. Every Set is applied before every Inc.
Inc never coerces. Incrementing a field holding a string, bool, null, array, or object is a server error, not a silent conversion; a missing field increments from 0. A negative Inc is how you decrement — there is no Dec.
type GraphDirection ¶
type GraphDirection string
GraphDirection selects which edges of a node an operation follows.
The empty GraphDirection means "let the server decide", which is DirectionOutgoing everywhere it appears.
const ( // DirectionOutgoing follows edges where the node is the `from` endpoint. DirectionOutgoing GraphDirection = "outgoing" // DirectionIncoming follows edges where the node is the `to` endpoint. DirectionIncoming GraphDirection = "incoming" // DirectionBoth follows edges in either direction. DirectionBoth GraphDirection = "both" )
type GraphEdge ¶
type GraphEdge struct {
// ID is the edge id, unique within its graph.
ID string `json:"id"`
// From is the id of the node the edge leaves.
From string `json:"from"`
// To is the id of the node the edge enters.
To string `json:"to"`
// Label is the edge's label.
Label string `json:"label"`
// Properties are the edge's properties as decoded JSON.
Properties map[string]any `json:"properties"`
}
GraphEdge is one stored edge, directed From -> To.
type GraphEdgePage ¶
type GraphEdgePage struct {
// Graph is the graph name.
Graph string `json:"graph"`
// Count is the number of edges on this page.
Count int `json:"count"`
// Edges are this page's edges.
Edges []GraphEdge `json:"edges"`
// Truncated reports that more edges remain past this page.
Truncated bool `json:"truncated"`
// Total is the graph's full edge count.
Total int64 `json:"total"`
}
GraphEdgePage is one page of GraphListEdges.
type GraphNeighbor ¶
type GraphNeighbor struct {
// EdgeID is the incident edge.
EdgeID string `json:"edge_id"`
// NodeID is the node at the edge's other end.
NodeID string `json:"node_id"`
// Label is the edge's label.
Label string `json:"label"`
// Direction is the edge's orientation relative to the node asked about.
Direction GraphDirection `json:"direction"`
}
GraphNeighbor is one incident edge of a node and the node at its other end. Direction is this edge's orientation relative to the node asked about, which is what makes a DirectionBoth result readable.
type GraphNode ¶
type GraphNode struct {
// ID is the node id, unique within its graph.
ID string `json:"id"`
// Labels are the node's labels.
Labels []string `json:"labels"`
// Properties are the node's properties as decoded JSON.
Properties map[string]any `json:"properties"`
}
GraphNode is one stored node.
type GraphNodePage ¶
type GraphNodePage struct {
// Graph is the graph name.
Graph string `json:"graph"`
// Count is the number of nodes on this page.
Count int `json:"count"`
// Nodes are this page's nodes.
Nodes []GraphNode `json:"nodes"`
// Truncated reports that more nodes remain past this page.
Truncated bool `json:"truncated"`
// Total is the graph's full node count.
Total int64 `json:"total"`
}
GraphNodePage is one page of GraphListNodes.
type GraphPath ¶
type GraphPath struct {
// Found reports whether a path was found.
Found bool `json:"found"`
// From is the start node id.
From string `json:"from"`
// To is the target node id.
To string `json:"to"`
// Direction is the edge direction that was followed.
Direction string `json:"direction"`
// Hops is the number of edges on the path.
Hops int `json:"hops"`
// NodePath is the node ids along the path, From first.
NodePath []string `json:"node_path"`
// EdgePath is the edge ids along the path.
EdgePath []string `json:"edge_path"`
// TotalCost is the summed weight, for the weighted search only.
TotalCost float64 `json:"total_cost"`
// Message says why Found is false, when it is.
Message string `json:"message"`
}
GraphPath is the outcome of a path search.
Found false is an ordinary answer, not an error: either no path exists or the search stopped at a bound. Message says which — a cap-stopped search is inconclusive, not proof that no path exists — so do not read Found false as "there is definitely no path" without checking it.
TotalCost is meaningful only for GraphWeightedShortestPath; it is zero for the unweighted search, which minimises hops.
type GraphRows ¶
type GraphRows struct {
// Graph is the graph that was queried.
Graph string `json:"graph"`
// Columns are the RETURN column names.
Columns []string `json:"columns"`
// Rows are the result rows, each cell as decoded JSON.
Rows [][]any `json:"rows"`
// Count is the number of rows returned.
Count int `json:"count"`
// Truncated reports that the server's row cap cut the result short.
Truncated bool `json:"truncated"`
}
GraphRows is the result of a Cypher query: named columns and their rows, with each cell left as decoded JSON because a Cypher RETURN can yield a scalar, a list, or a whole node.
type GraphTraversal ¶
type GraphTraversal struct {
// Start is the node the walk began at.
Start string `json:"start"`
// Direction is the edge direction that was followed.
Direction string `json:"direction"`
// MaxDepth is the hop bound the server applied.
MaxDepth int `json:"max_depth"`
// Limit is the node bound the server applied.
Limit int `json:"limit"`
// Count is the number of nodes returned.
Count int `json:"count"`
// Truncated reports that a bound stopped the walk early.
Truncated bool `json:"truncated"`
// Nodes are the visited nodes in BFS order.
Nodes []GraphVisit `json:"nodes"`
}
GraphTraversal is the outcome of a bounded BFS. Truncated reports that a limit or the server's visited-node cap stopped the walk before it ran out of nodes — the nodes returned are real, the answer is just not exhaustive.
type GraphVisit ¶
type GraphVisit struct {
// ID is the node id.
ID string `json:"id"`
// Depth is the hop count at which the node was first reached.
Depth int `json:"depth"`
// Labels are the node's labels.
Labels []string `json:"labels"`
// Properties are the node's properties as decoded JSON.
Properties map[string]any `json:"properties"`
}
GraphVisit is one node reached by GraphTraverse, with the hop count at which it was first reached.
type GroupAccumulator ¶
type GroupAccumulator struct {
// Output is the field the accumulated value is written to.
Output string `json:"output"`
// Op is the accumulator, built with AccSum, AccCount and friends.
Op AccumulatorOp `json:"op"`
}
GroupAccumulator is an accumulator plus the field name it writes into the grouped document. Output must not be "_id" (that holds the group key) and must not repeat within one StageGroup.
type GroupKey ¶
type GroupKey struct {
// contains filtered or unexported fields
}
GroupKey is how StageGroup derives a group key from a document.
func GroupByConstant ¶
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 ¶
GroupByField groups by the value at a dot path. A document missing that path groups under null rather than being dropped.
func (GroupKey) MarshalJSON ¶
MarshalJSON emits the externally-tagged form the server deserializes.
type LlmOptions ¶
type LlmOptions struct {
// MaxRows caps rows included; 0 leaves the cap to the server.
MaxRows int
// RedactSensitive redacts sensitive fields before export.
RedactSensitive bool
// IncludeSchema includes type information alongside the data.
IncludeSchema bool
}
LlmOptions bounds and redacts an export.
RedactSensitive defaults to false in the zero value, which is the opposite of the server's default — so LlmContext and LlmSchema take a *LlmOptions and substitute DefaultLlmOptions when it is nil. A zero-value struct passed by accident should not silently turn redaction off.
func DefaultLlmOptions ¶
func DefaultLlmOptions() LlmOptions
DefaultLlmOptions matches the server's defaults: redact, no schema, no cap.
type LlmSource ¶
type LlmSource struct {
// contains filtered or unexported fields
}
LlmSource is one read-only source contributing to a context bundle.
func DocumentFindSource ¶
func DocumentFindSource(collection string, filter DocumentFilter, limit int) LlmSource
DocumentFindSource is a document find. The caller needs document read permission. A zero DocumentFilter means "match everything".
type NeighborOptions ¶
type NeighborOptions struct {
// Direction defaults to DirectionOutgoing when empty.
Direction GraphDirection
// Label keeps only edges with this label. Empty means every label.
Label string
// Limit caps the neighbors returned. Zero or less asks for the server
// default (10,000, which is also the hard cap).
Limit int
}
NeighborOptions narrows GraphNeighbors. The zero value follows outgoing edges of every label, up to the server's cap.
type Options ¶
type Options struct {
// Host is the server address. Defaults to "127.0.0.1".
Host string
// Port is the server's native protocol port. Defaults to [DefaultPort].
Port int
// User is the principal to authenticate as. Empty skips AUTH.
User string
// Secret is the password or token sent with User.
Secret string
// Database is sent as the `database` field of every REQUEST frame.
// Defaults to "main".
Database string
// ClientName identifies this driver in the HELLO frame. Defaults to
// "tricoredb-go".
ClientName string
// DialTimeout bounds the TCP connect only. Use ctx for the deadline
// on the handshake/auth that follow.
DialTimeout time.Duration
// ReadTimeout is a client-side deadline on each steady-state read, or
// zero (the default) for none.
//
// Deliberately separate from ctx's handshake deadline, which Connect
// clears once AUTH completes: conflating the two is how the Python driver
// turned a documented 10s *connect* timeout into an undocumented 10s
// deadline on every query it would ever run. Deliberately separate also
// from SetRequestTimeout, which makes the *server* stop; this one only
// stops the wait.
//
// There is no default. A read legitimately blocks for exactly as long as
// the statement runs, the server's own statement_timeout_ms defaults to
// unlimited, and any number this driver picked would be a guess at a
// guarantee the server does not make.
ReadTimeout time.Duration
// TLS turns on TLS when non-nil. Plain TCP otherwise — on which the
// Secret above crosses the wire in the clear.
TLS *TLSOptions
// Features is the capability bitmap announced in HELLO. Nil (the default)
// means [Features] — everything this build understands. The server grants
// only what was asked for, so masking a bit out here is how a caller opts
// out of one:
//
// mask := tricoredb.Features &^ tricoredb.FeatureSessionTxn
// opts.Features = &mask
//
// A pointer rather than a plain uint64 because zero is a meaningful value
// here — "announce nothing" — and must not be indistinguishable from
// "unset".
Features *uint64
}
Options configures a new connection. Host, Port, Database, and ClientName fall back to sane defaults when left zero; User/Secret are only sent (via an AUTH frame) when User is non-empty, matching servers that allow unauthenticated sessions.
type OutputFormat ¶
type OutputFormat string
OutputFormat is how the server should render an export.
const ( // FormatNative is TriCoreDB's own representation. FormatNative OutputFormat = "native" // FormatJSON is standard JSON. FormatJSON OutputFormat = "json" // FormatTOON is the token-oriented rendering for LLM context windows. FormatTOON OutputFormat = "toon" // FormatMarkdown is human-readable Markdown. FormatMarkdown OutputFormat = "markdown" )
type PathOptions ¶
type PathOptions struct {
// Direction defaults to DirectionOutgoing when empty.
Direction GraphDirection
// Label keeps only edges with this label. Empty means every label.
Label string
// MaxDepth bounds the hop count. Zero or less asks for the server default,
// which is also its maximum (10).
MaxDepth int
}
PathOptions bounds a GraphShortestPath. The zero value searches outgoing edges of every label to the server's default depth (10).
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is a bounded, concurrency-safe pool of connections.
Why this exists ¶
A Client is a single request/response stream: two goroutines sharing one would interleave frames and read each other's replies. So concurrency needs one connection per concurrent caller — and the server scales ~3.3x across 8 concurrent connections (see benchmarks/concurrency/RESULTS.md), which is only reachable if an application actually opens several. Doing that per request costs a TCP connect plus HELLO and AUTH round trips every time (~14.5ms measured, against ~127µs pooled).
Exclusive ownership ¶
Pool.Use runs a callback with a connection that is exclusively the callback's for its duration. That is deliberately a callback rather than an Acquire/Release pair returning a *Client: a returned handle is something a caller can retain and share across goroutines, which is exactly the corruption this type exists to prevent. (Release-on-panic is also handled, which a manual pair invites callers to get wrong.)
pool, err := tricoredb.NewPool(tricoredb.Options{Host: "127.0.0.1", Port: 8427,
User: "admin", Secret: "pw"}, 8)
err = pool.Use(ctx, func(c *tricoredb.Client) error {
_, err := c.Execute("INSERT INTO t VALUES (1, 'ada')")
return err
})
pool.Close()
func NewPool ¶
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 ¶
Close closes every idle connection. Connections currently in use are closed when their Use returns.
func (*Pool) Stats ¶
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 ¶
Use borrows a connection for the duration of fn.
It blocks until one is free or ctx is done, returning ErrPoolTimeout in the latter case rather than growing past `size` — an unbounded pool does not fix overload, it relocates it to the server.
A connection is retired rather than returned when fn reports a transport or protocol failure, because the stream may be mid-frame and reusing it would hand the next caller someone else's bytes.
A session transaction (Client.Begin) is bound to the connection, so one must never go back to the pool mid-block: the next borrower would be writing into somebody else's transaction. If fn returns with a block still open it is rolled back and Use returns an error naming it; if fn returns an error with one open it is rolled back and fn's error is what propagates; and a connection whose rollback fails is retired rather than reused. Use Client.WithTransaction inside the callback and none of this arises.
type ProtocolError ¶
type ProtocolError struct {
Message string
}
ProtocolError reports a violation of the wire protocol itself: an unexpected tag, a truncated frame, or a body that doesn't parse as the JSON shape the spec promises.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
func (*ProtocolError) Unwrap ¶
func (e *ProtocolError) Unwrap() error
type Response ¶
type Response struct {
// RequestID is the request_id the server echoed back.
RequestID string
// Status is the server's status string; "ok" on success.
Status string
// DataKind is the externally-tagged variant name of Data — one of
// "Json", "CacheValue", "Rows", "Documents", "Message", "Empty".
DataKind string
// DataRaw is that variant's payload, still JSON-encoded, for callers
// that need a shape this driver doesn't decode into a named field.
DataRaw json.RawMessage
Route string
ElapsedMs int64
// Warnings are non-fatal, and not decorative: a broadcast DDL that
// couldn't reach every shard reports it here while Status is still
// "ok". A caller that ignores this can silently run on a divergent
// cluster.
Warnings []string
// ErrorCode is the server's machine-readable reason a request failed
// (diagnostics.error_code), empty when it did not fail or the server sent
// none. Branch on this, never on the message text.
ErrorCode string
// LeaderHint is the `host:port` a refused write belongs to, set only
// alongside an ErrorCode of [ErrorCodeNotLeader]. It is an address a client
// can dial, resolved by the server from `[[raft.peers]].address`, not a node
// id.
//
// Empty when the code is something else, and empty *even for a not_leader
// refusal* in three cases: raised mid-election, raised on a non-Raft node,
// and raised when the leader's id has no `[[raft.peers]]` entry to resolve.
// So a caller must treat its absence as "destination unknown, wait and
// retry", not as "no redirect happened". See [ServerError.LeaderHint].
LeaderHint string
}
Response is a server response: the operation's typed result plus how it was produced.
type Rows ¶
Rows is a SQL result set: column names plus each row's values, both as the strings the server returns them as.
type ServerError ¶
type ServerError struct {
Message string
// Status is the raw status string from the RESPONSE frame; kept for
// callers that need to distinguish the cases rather than treat them
// identically.
Status string
// Code is the server's machine-readable reason
// (`diagnostics.error_code`), or "" when it sent none.
//
// This is the field to branch on. The message is prose and stays free to be
// reworded; substring-matching it is how an authorization denial once
// reached clients as something else entirely, which is the failure the code
// was added to end.
Code string
// LeaderHint is a `host:port` this request should have gone to, carried
// only with a Code of [ErrorCodeNotLeader].
//
// It is an **address a client can dial**, not a node id: the server resolves
// the leader's id through `[[raft.peers]].address`, which names that node's
// native protocol listener — the same endpoint this driver already speaks,
// not a separate consensus port.
//
// Empty means "no address was named", which is NOT the same as "this is not
// a redirect". Three situations produce a code with no hint: a refusal
// raised mid-election, a node running without Raft, and a leader whose id
// has no `[[raft.peers]]` entry — where the server deliberately sends
// nothing rather than a bare id, because a label in an address field is a
// connection attempt to a host that does not exist. All three mean the same
// thing to a caller: wait and retry.
//
// The refusal's Message still names the leader's **node id**, on purpose:
// prose is for a human reading logs and the hint is for a machine dialling.
// Never scrape the id out of the message and use it as a destination — that
// is exactly what this field replaces.
//
// Test [ServerError.Code] for the redirect and treat an empty hint as an
// unknown destination.
LeaderHint string
}
ServerError reports a REQUEST that the server processed but did not complete: any RESPONSE whose status is not "ok".
The kernel has three statuses — "ok", "error" and "not_implemented", the last meaning "a recognized hook that was NOT run" (crates/tricore_core/src/response/mod.rs). This driver compares against "ok" rather than enumerating the bad ones, so a status added to the kernel later fails closed instead of being handed to a caller as a success.
func (*ServerError) Error ¶
func (e *ServerError) Error() string
func (*ServerError) IsNotLeader ¶
func (e *ServerError) IsNotLeader() bool
IsNotLeader reports whether this refusal is a leader redirect: the request was valid, and this node is not the one that may serve it.
A true result says nothing about whether ServerError.LeaderHint is set — see that field. This driver deliberately does not follow the redirect itself: re-sending a write to another address is a policy decision (which endpoints are reachable, which credentials apply there, whether the operation is safe to repeat) that belongs to the caller, not to a connection object.
func (*ServerError) Unwrap ¶
func (e *ServerError) Unwrap() error
type SortKey ¶
type SortKey struct {
// Field is the field to sort by.
Field string `json:"field"`
// Descending sorts largest first when true.
Descending bool `json:"descending"`
}
SortKey is one StageSort key. After a StageGroup the addressable fields are "_id" and the accumulator outputs, not the original document's fields.
type Statement ¶
type Statement struct {
// SQL is the statement text, with ? placeholders.
SQL string
// Args are the values bound to SQL's placeholders, in order.
Args []Arg
}
Statement is one statement of a transaction script, with optional bound arguments.
type StreamEntry ¶
StreamEntry is one entry in a stream. Fields is authoritative — stream fields are arbitrary bytes; Text is a convenience for the all-UTF-8 case.
func (StreamEntry) Text ¶
func (e StreamEntry) Text() map[string]string
Text decodes the fields as UTF-8. Wrong for binary payloads; Fields stays authoritative.
type TLSOptions ¶
type TLSOptions struct {
// CAFile is a PEM bundle used to verify the server. When empty the trust
// store is left EMPTY rather than falling back to the system roots —
// matching the Rust client, and making a typo'd path fail closed instead
// of quietly succeeding against some unrelated public CA.
CAFile string
// ServerName is the expected server name (SNI and certificate name).
// Defaults to "localhost".
ServerName string
// DangerAcceptInvalidCerts disables certificate and hostname verification.
// DEVELOPMENT ONLY. A connection with this set looks encrypted but
// authenticates nothing, so an active attacker can sit in the middle
// undetected — which is strictly worse than visibly using plain TCP.
DangerAcceptInvalidCerts bool
// ClientCertFile is a PEM client certificate chain to present (mTLS).
// Requires ClientKeyFile.
ClientCertFile string
// ClientKeyFile is the PEM private key for ClientCertFile (mTLS).
ClientKeyFile string
}
TLSOptions configures the TLS session. It mirrors the Rust client's TlsOptions (crates/tricore_client/src/tls.rs).
Supplying a *TLSOptions at all is what enables TLS. Once enabled the server certificate is verified and its name checked, unless DangerAcceptInvalidCerts is set.
mTLS ¶
Set ClientCertFile and ClientKeyFile to present a client identity. A server with require_client_cert = true rejects a client that does not.
Secret hygiene ¶
Private key contents are never logged. Errors name the *path* so an operator can find the file, never the bytes in it.
type TimeoutError ¶
type TimeoutError struct {
Message string
}
TimeoutError reports that a read (or the connect phase) exceeded its budget.
A distinct type rather than the bare net.Error the standard library returns, so `errors.Is(err, tricoredb.ErrTimeout)` works and so a timeout cannot escape this driver's error vocabulary the way a raw os.ErrDeadlineExceeded would.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
func (*TimeoutError) Temporary ¶
func (e *TimeoutError) Temporary() bool
Temporary reports false. See Timeout.
func (*TimeoutError) Timeout ¶
func (e *TimeoutError) Timeout() bool
Timeout and Temporary together satisfy net.Error, so code already branching on that interface keeps working — before this type existed a read deadline surfaced as a raw *net.OpError, which is a net.Error, and silently losing that would break callers that were handling it correctly.
Temporary is false: this driver poisons a timed-out connection, because the reply it stopped waiting for may still be in flight and reusing the socket would read it as the answer to the next request. Retrying on the same connection is exactly what must not happen. (net.Error.Temporary is deprecated but remains part of the interface, so it has to be implemented to satisfy it.)
func (*TimeoutError) Unwrap ¶
func (e *TimeoutError) Unwrap() error
type TransactionResult ¶
type TransactionResult struct {
// Statements is the number of statements the server ran.
Statements int64 `json:"statements"`
// CommittedWrites is the number of writes made durable.
CommittedWrites int64 `json:"committed_writes"`
// DiscardedWrites is the number of buffered writes thrown away.
DiscardedWrites int64 `json:"discarded_writes"`
// Outcome is "began", "committed" or "rolled_back".
Outcome string `json:"transaction"`
}
TransactionResult is what the server did with a transaction script.
type TraverseOptions ¶
type TraverseOptions struct {
// Direction defaults to DirectionOutgoing when empty.
Direction GraphDirection
// Label keeps only edges with this label. Empty means every label.
Label string
// MaxDepth bounds the hop count. Zero or less asks for the server default
// (3); the server clamps anything above 10.
MaxDepth int
// Limit caps the nodes returned. Zero or less asks for the server default
// (100); the server clamps to 1..=1000.
Limit int
}
TraverseOptions bounds a GraphTraverse. The zero value walks outgoing edges of every label to the server's default depth (3) and node limit (100).
type UpdateManyResult ¶
UpdateManyResult counts what a DocumentUpdateMany did. Matched counts documents the filter selected; Modified counts those whose contents actually changed, so an update that rewrote a document to the value it already held is matched but not modified.
type VectorCollectionInfo ¶
type VectorCollectionInfo struct {
// Collection is the collection name.
Collection string `json:"collection"`
// Dimension is the length every vector in the collection must have.
Dimension int `json:"dimension"`
// Metric is the distance metric searches rank by.
Metric VectorMetric `json:"metric"`
// Count is the number of vectors currently stored.
Count int64 `json:"count"`
// Quantization is the index quantization the collection was created with.
Quantization VectorQuantization `json:"quantization"`
}
VectorCollectionInfo is a collection's catalog metadata plus its live vector count, from VectorDescribeCollection.
type VectorCollectionSummary ¶
type VectorCollectionSummary struct {
// Name is the collection name.
Name string `json:"name"`
// Dimension is the length every vector in the collection must have.
Dimension int `json:"dimension"`
// Metric is the distance metric searches rank by.
Metric VectorMetric `json:"metric"`
}
VectorCollectionSummary is one entry of VectorListCollections.
type VectorHit ¶
type VectorHit struct {
ID string `json:"id"`
Score float32 `json:"score"`
Metadata map[string]any `json:"metadata"`
}
VectorHit is one search result.
Score is a similarity, never a distance: **higher is closer under every metric**, and Results is ordered best-first. MetricL2 is the case worth stating outright — the server negates the squared Euclidean distance (crates/tricore_vector/src/search/mod.rs) so the ranking stays uniform, which means an l2 Score is <= 0 and -0.02 is nearer than -196.0. Sorting these ascending, or reading Score as a distance, inverts an l2 ranking while a "is the expected id in the top-k" check still passes.
type VectorItem ¶
type VectorItem struct {
ID string `json:"id"`
Vector []float32 `json:"vector"`
Metadata map[string]any `json:"metadata"`
}
VectorItem is one stored vector with its metadata.
type VectorMetric ¶
type VectorMetric string
VectorMetric is a vector collection's distance/similarity measure. It is fixed when the collection is created and cannot be changed afterwards.
const ( // MetricCosine is cosine similarity: higher is closer. MetricCosine VectorMetric = "cosine" // MetricDot is the dot product: higher is closer. MetricDot VectorMetric = "dot" // MetricL2 is squared Euclidean distance. Note the sign: the server // returns it *negated*, so an l2 VectorHit.Score is <= 0 and -0.02 is // nearer than -196.0. See VectorHit.Score. MetricL2 VectorMetric = "l2" )
type VectorPage ¶
type VectorPage struct {
// Collection is the collection name.
Collection string `json:"collection"`
// Count is the number of vectors on this page.
Count int `json:"count"`
// Vectors are this page's items.
Vectors []VectorItem `json:"vectors"`
// Truncated reports that more vectors remain past this page.
Truncated bool `json:"truncated"`
// Total is the collection's full vector count.
Total int64 `json:"total"`
}
VectorPage is one page of VectorListVectors. Truncated reports that items remain past this page; Total is the collection's full count.
type VectorQuantization ¶
type VectorQuantization string
VectorQuantization selects how a collection's ANN index stores vectors in memory. It is an index-level choice only: the durable records always keep full float32 precision, so VectorGet and VectorListVectors return byte-identical values either way.
const ( // QuantizationNone keeps full float32 vectors in the index. The default. QuantizationNone VectorQuantization = "none" // QuantizationInt8 stores int8-quantized vectors in the index (roughly 4x // smaller) and re-ranks the candidate pool against the durable float32 // vectors, at the cost of one point read per candidate. QuantizationInt8 VectorQuantization = "int8" )
type VectorSearchResult ¶
VectorSearchResult is a search's hits plus which path answered it: "flat" for the exact scan a small collection gets, "hnsw" or "hnsw-int8" for the ANN index.
type WeightedPathOptions ¶
type WeightedPathOptions struct {
// Direction defaults to DirectionOutgoing when empty.
Direction GraphDirection
// Label keeps only edges with this label. Empty means every label.
Label string
// WeightProperty names the edge property holding the cost. Empty means
// "weight". An edge missing it, or holding a non-number, weighs 1.0; a
// negative weight is refused rather than mis-solved.
WeightProperty string
}
WeightedPathOptions bounds a GraphWeightedShortestPath.
There is deliberately no MaxDepth: a weighted search is bounded by settled cost, not by hop count, and a depth clamp would silently discard the cheap-but-long path that is the whole reason to run one.