Documentation
¶
Overview ¶
Package query builds, compiles and evaluates syncplane.v1.Condition predicates against protoreflect messages. It is the one query implementation in the engine: the Query RPC, ViewTx.Query and application code all go through it, so a predicate means the same thing wherever it is asked.
Build predicates with the constructors (Eq, In, Contains, And, …) rather than assembling Condition protos by hand:
rows, err := srv.View(ctx, ws, func(tx *server.ViewTx) error {
return tx.Query(&todov1.Todo{}, query.Spec{
Where: query.And(query.Eq("done", false), query.Contains("title", "milk")),
OrderBy: []*syncplanev1.OrderKey{query.Desc("created_at_ms")},
Limit: 20,
}, func(msg proto.Message, version uint64) error { … })
})
Cost to know before reaching for it: a query is served from a declared secondary index only when one covers its predicate and ordering. With none — or while an index is still building — it scans and decodes every live row of the entity, O(entity) in time however selective the predicate is and however small the limit. Memory is bounded to Offset+Limit rows when an order is given. An unindexed query is fine for a background job and a trap in a hot HTTP handler over a large entity. This package compiles the predicate and encodes index entries (see indexkey.go); engine/server chooses the plan.
Semantics mirror the client evaluator (client/src/query/evaluate.ts) exactly; the shared conformance vectors in testdata/queryeval enforce the parity. The load-bearing rules:
- An unset intermediate message makes every condition on the path false, except isNotSet, which is true.
- A question about the CONTENTS of message elements is spelled with an exists condition, which scopes an element and evaluates a sub-condition against it. The quantifier is explicit so that two conditions can be said to describe the same element; see ExistsCond in the proto for why a bare path through a repeated field is not enough. has/hasAny/hasAll over a repeated single-key reference desugar to one, since a reference compares by its target's key.
- Values keep their client-side kind: 64-bit integer fields are bigints, everything else numeric is a float64. Mixed number/bigint compares as big integer when the float is integral, otherwise as float64 (with the same precision loss as JS Number(bigint)).
- Strings order by UTF-16 code unit (JS `<`), not UTF-8 bytes.
- NaN is NOT COMPARABLE. A NaN on either side makes gt/gte/lt/lte false, the same way eq fails and neq succeeds, so no comparison operator ever matches it. For ordering it is not a tie either: values rank real < NaN < missing, and the rank decides before the direction does, so NaN sorts after every real value and before missing under both asc and desc. Two NaNs (like two missing values) tie and fall through to the next order key. That total order is what lets a row ordering be encoded into sortable index keys. ±Inf is ordinary and compares as you would expect.
- A mismatch between a condition's LITERAL and the field's value makes the condition false (orderings tie), never an error: eq("x") against an int32 field is a legitimate no-match. A field that could never take part in the comparison at all — bytes, message, a whole map, repeated — is a different thing and is rejected by Compile instead of quietly matching nothing (see requireComparable).
- The path segment after a MAP field is the entry KEY, the same convention an lww field-mask path uses, so there is one rule rather than two. One entry is an ordinary value, and because an entry has explicit presence a path naming one variant of an app-defined oneof value reads as NOT FOUND on a row whose entry holds another variant. That is what lets the value type be app-defined: no cross-variant comparison ever has to exist.
- The mirror question — "which entry holds X", rather than "does THIS entry hold X" — is an exists condition over the map, whose element is the ENTRY and whose sub-condition addresses `key` and `value`. It answers whether some entry matched, never which one; nothing here projects.
Index ¶
- Constants
- Variables
- func And(conds ...*syncplanev1.Condition) *syncplanev1.Condition
- func Any(path string, cond *syncplanev1.Condition) *syncplanev1.Condition
- func Asc(path string) *syncplanev1.OrderKey
- func CompareGroupValues(a, b GroupValue) int
- func CompareStringsUTF16(a, b string) int
- func Contains(path, substr string) *syncplanev1.Condition
- func Desc(path string) *syncplanev1.OrderKey
- func EndsWith(path, suffix string) *syncplanev1.Condition
- func Eq[T Value](path string, v T) *syncplanev1.Condition
- func Gt[T Value](path string, v T) *syncplanev1.Condition
- func Gte[T Value](path string, v T) *syncplanev1.Condition
- func Has[T Value](path string, v T) *syncplanev1.Condition
- func HasAll[T Value](path string, vs ...T) *syncplanev1.Condition
- func HasAny[T Value](path string, vs ...T) *syncplanev1.Condition
- func In[T Value](path string, vs ...T) *syncplanev1.Condition
- func IsEmpty(path string) *syncplanev1.Condition
- func IsNotSet(path string) *syncplanev1.Condition
- func IsSet(path string) *syncplanev1.Condition
- func Lt[T Value](path string, v T) *syncplanev1.Condition
- func Lte[T Value](path string, v T) *syncplanev1.Condition
- func Match(q string) *syncplanev1.Condition
- func Neq[T Value](path string, v T) *syncplanev1.Condition
- func Not(cond *syncplanev1.Condition) *syncplanev1.Condition
- func Or(conds ...*syncplanev1.Condition) *syncplanev1.Condition
- func Path(path string) []string
- func Rel(path string, cond *syncplanev1.Condition) *syncplanev1.Condition
- func RelReplacement(node *RelNode, targets [][]*syncplanev1.QueryValue, workspace string) *syncplanev1.Condition
- func Relevance() *syncplanev1.OrderKey
- func RewriteRels(cond *syncplanev1.Condition, ...) *syncplanev1.Condition
- func SearchOverflowRange() (lo, hi []byte)
- func SearchTermRange(t search.QueryTerm) (lo, hi []byte)
- func SortGroups(groups []GroupCount)
- func SpecHash(comps []IndexComponent) string
- func StartsWith(path, prefix string) *syncplanev1.Condition
- func TargetKeyValues(node *RelNode, msg protoreflect.Message) []*syncplanev1.QueryValue
- func UpperBound(prefix []byte) []byte
- type Compiled
- type Group
- type GroupCount
- type GroupPlan
- type GroupValue
- type Index
- type IndexComponent
- type IndexEncoder
- func (e *IndexEncoder) Components() []IndexComponent
- func (e *IndexEncoder) Encode(msg protoreflect.Message, rowKey string) [][]byte
- func (e *IndexEncoder) EncodePrefix(values []protoreflect.Value) ([]byte, error)
- func (e *IndexEncoder) Sparse() bool
- func (e *IndexEncoder) SpecHash() string
- func (e *IndexEncoder) SplitEntry(entry []byte) (components, rowKey []byte, err error)
- type Matcher
- type Order
- func (o *Order) Compare(a, b protoreflect.Message, keyA, keyB string) int
- func (o *Order) Cursor(msg protoreflect.Message, rowKey string) []byte
- func (o *Order) CursorPrefix(entry []byte) ([]byte, error)
- func (o *Order) DecodeCursor(entity string, cursor []byte) ([]byte, error)
- func (o *Order) EncodeCursor(entity string, msg protoreflect.Message, rowKey string) []byte
- func (o *Order) Less(a, b protoreflect.Message, keyA, keyB string) bool
- func (o *Order) Shape(entity string) string
- type Plan
- type PlanBranch
- type Range
- type RelNode
- type SearchDecl
- type Spec
- type Value
Constants ¶
const SearchTermsPerRow = 256
SearchTermsPerRow caps the distinct terms one row stores postings for; past it the row stores the overflow marker alone. It is a constant rather than a tunable because both sides maintain their own copy of the index and have to agree on which rows overflow.
Variables ¶
var ErrCursorShape = errors.New("query: cursor belongs to a different entity or ordering")
ErrCursorShape reports a cursor minted for a different entity or a different ordering than the query replaying it. Nothing is lost by it: a query run without the cursor issues one that fits.
Functions ¶
func And ¶
func And(conds ...*syncplanev1.Condition) *syncplanev1.Condition
And matches rows satisfying every condition. No arguments matches everything.
func Any ¶
func Any(path string, cond *syncplanev1.Condition) *syncplanev1.Condition
Any matches rows where at least one element of the repeated message field at path satisfies cond. The paths inside cond are relative to the ELEMENT:
query.Any("members", query.And(query.Eq("uid", "u1"), query.Gt("role", 2)))
It is the only way to ask about the contents of message elements, and the element scope is what lets two conditions describe the SAME element — And(Any(…eq…), Any(…gt…)) is a different, weaker question. Over a repeated single-key reference, Has is the shorter spelling of the same thing.
Over a MAP the element is one ENTRY, whose sides the sub-condition addresses as `key` and `value` — the same two words an index component's `*` selector uses:
query.Any("custom", query.Eq("value.number", 5)) // which field holds 5
query.Any("custom", query.And(
query.StartsWith("key", "cf_"), query.Eq("value.checked", true)))
That is the mirror of addressing one entry by key: Eq("custom.priority.number", 5) asks whether THIS field holds 5, and this asks whether ANY does. It is a predicate, not a projection — the answer never says which entry matched.
func CompareGroupValues ¶
func CompareGroupValues(a, b GroupValue) int
CompareGroupValues orders two groups the way an ascending order key on the same path orders their rows: real values by value, then NaN, then the no-value group. Zero means the two are one group.
func CompareStringsUTF16 ¶
CompareStringsUTF16 orders strings by UTF-16 code unit — what JS `<`/`>` do — instead of Go's native UTF-8 byte order. The two diverge when exactly one side contains astral-plane characters (surrogate pairs start at 0xD800, below later BMP code points; in UTF-8 astral characters sort above all BMP ones). The shared vectors pin the astral cases.
One divergence this cannot close: a JS string holding a LONE surrogate is not valid UTF-8, so it reaches the server as U+FFFD. The client compares the original code unit and the server compares the replacement, and no protojson vector can express the difference — a query filtering on such a string can legitimately disagree between optimistic local evaluation and the server's answer.
func Contains ¶
func Contains(path, substr string) *syncplanev1.Condition
Contains matches a string (or collaborative-text) field by substring, case-sensitively. It is a substring test per row, not search: no tokenization, no stemming, no ranking, and no index behind it. For search, declare the entity's search fields and use Match.
func EndsWith ¶
func EndsWith(path, suffix string) *syncplanev1.Condition
EndsWith matches a string (or collaborative-text) field by suffix, case-sensitively.
func Eq ¶
func Eq[T Value](path string, v T) *syncplanev1.Condition
Eq matches rows whose field equals v.
func Gt ¶
func Gt[T Value](path string, v T) *syncplanev1.Condition
Gt matches rows whose field is greater than v.
func Gte ¶
func Gte[T Value](path string, v T) *syncplanev1.Condition
Gte matches rows whose field is greater than or equal to v.
func Has ¶
func Has[T Value](path string, v T) *syncplanev1.Condition
Has matches rows whose repeated field contains v.
func HasAll ¶
func HasAll[T Value](path string, vs ...T) *syncplanev1.Condition
HasAll matches rows whose repeated field contains every one of vs.
func HasAny ¶
func HasAny[T Value](path string, vs ...T) *syncplanev1.Condition
HasAny matches rows whose repeated field contains at least one of vs.
func In ¶
func In[T Value](path string, vs ...T) *syncplanev1.Condition
In matches rows whose field equals any of vs. An empty vs matches nothing.
func IsEmpty ¶
func IsEmpty(path string) *syncplanev1.Condition
IsEmpty matches rows whose repeated field has no elements, or whose MAP field has no entries — it asks about the collection itself, so both answer it, and on a map it is the one thing isSet cannot say (a map is always set).
func IsNotSet ¶
func IsNotSet(path string) *syncplanev1.Condition
IsNotSet matches rows where the field is absent. See IsSet for what presence means.
func IsSet ¶
func IsSet(path string) *syncplanev1.Condition
IsSet matches rows where the field is present. Presence means what proto means by it: an explicit-presence field (optional, message, reference) is set only when written, while an implicit-presence scalar, list or map is ALWAYS set — IsSet on one is constitutionally true, not "has a non-zero value". Compare against the zero value for that.
func Lt ¶
func Lt[T Value](path string, v T) *syncplanev1.Condition
Lt matches rows whose field is less than v.
func Lte ¶
func Lte[T Value](path string, v T) *syncplanev1.Condition
Lte matches rows whose field is less than or equal to v.
func Match ¶
func Match(q string) *syncplanev1.Condition
Match matches rows whose declared search fields contain every term of q, case- and accent-insensitively, with the final term matching as a prefix when q ends inside it. It requires the entity to declare search fields (SearchSpec or searchable marks) and rejects at compile time otherwise. An empty q matches every row. Order the result by Relevance to rank it.
func Neq ¶
func Neq[T Value](path string, v T) *syncplanev1.Condition
Neq matches rows whose field differs from v. An unset field does NOT match: every condition on a missing value is false, including this one.
func Not ¶
func Not(cond *syncplanev1.Condition) *syncplanev1.Condition
Not inverts a condition. Note that it inverts the MATCH, not the field's meaning: because every condition on a missing value is false, Not(Eq(...)) matches rows where the field is unset, which Neq does not.
func Or ¶
func Or(conds ...*syncplanev1.Condition) *syncplanev1.Condition
Or matches rows satisfying at least one condition. No arguments matches nothing.
func Path ¶
Path splits a dotted field path into the segments the wire form carries. Segments are PROTO field names ("created_at_ms"), not Go struct field names — the same names a client sends. Compile rejects a path that names an unknown field, so a typo fails at compile time, not silently at match time.
A segment following a MAP field is the entry key rather than a field name ("custom_fields.priority.number"), and a key is arbitrary data, so a dot inside one is escaped with a backslash: `custom_fields.due\.date.text` addresses the key "due.date". The escaping is only needed here — the wire form is already a list of segments, so a key travels verbatim in it — and it is the same rule an lww field-mask path uses for the same reason.
func Rel ¶
func Rel(path string, cond *syncplanev1.Condition) *syncplanev1.Condition
Rel matches rows where at least one row referenced through the ref field at path exists and satisfies cond — a one-hop semi-join. path names a forward reference field (singular or repeated); cond's paths are relative to the TARGET entity's row, the same scoping Any gives its element:
// issues assigned to anyone on this team
query.Rel("assignee", query.Eq("team_id", "t1"))
// tasks blocked by an unresolved task (repeated ref: SOME target matches)
query.Rel("blocked_by", query.Eq("done", false))
An unset to-one ref, an orphaned stub and a deleted target all make the condition false. One hop only: a Rel inside a Rel, or inside an Any, is rejected at compile time.
Unlike every other condition it needs the target entity's rows to answer, so it is accepted only where those are in reach — the Query RPC and the ViewTx/EntityTx/ApplyTx Query methods, which resolve it against current server state before evaluating. Compile rejects it anywhere else (orderings, subscription predicates, index specs).
func RelReplacement ¶
func RelReplacement(node *RelNode, targets [][]*syncplanev1.QueryValue, workspace string) *syncplanev1.Condition
RelReplacement builds the row-local condition a rel node collapses to once the pre-pass has selected its matching targets: a membership test on the stored ref stubs. targets holds one value tuple per matching target row, in the node's KeyFields order — read the values off the target rows with TargetKeyValues. No matching targets means the node matches no row, which the empty membership test already says.
A single-key ref becomes in(path.key, K) — for a repeated ref, an exists over the element's key field — the exact shape the reverse-relation push-down produces, so the per-ref-field index serves it. A composite-key ref becomes a disjunction of key-tuple equalities: comparing whole tuples is what keeps a matching id under the wrong ns from matching.
workspace is the one the pre-pass ran in. A reference message carrying a workspace field adds the test that the stub resolves there — it names that workspace, or names none — because the targets were read from it alone: a stub pointing into another workspace matches nothing here (see ReferenceOptions).
func Relevance ¶
func Relevance() *syncplanev1.OrderKey
Relevance orders best match first. It requires exactly one Match condition in the query's predicate — the rank is that condition's. Rows ranking equally fall through to the next key and finally the row key.
func RewriteRels ¶
func RewriteRels(cond *syncplanev1.Condition, replacements map[*syncplanev1.RelCond]*syncplanev1.Condition) *syncplanev1.Condition
RewriteRels returns cond with every rel node replaced by the row-local condition replacements maps it to (keyed by the RelCond message identity, as ExtractRels reported it). Subtrees without a rel are shared, not copied; the input is never mutated. A rel absent from the map is left in place, so the caller's Compile rejects it rather than silently matching nothing.
func SearchOverflowRange ¶
func SearchOverflowRange() (lo, hi []byte)
SearchOverflowRange brackets the overflow marker key — the rows whose term sets outgrew their postings. Every term probe unions these rows into its candidates.
func SearchTermRange ¶
SearchTermRange brackets the posting keys a query term selects: the term's own key, or — for a prefix term — the keys of every term it prefixes.
func SortGroups ¶
func SortGroups(groups []GroupCount)
SortGroups puts groups in the order the surface promises: ascending value, then NaN, then the no-value group.
No two groups ever tie — CompareGroupValues returns 0 only for values GroupValue.Key already put in one bucket — so the result does not depend on the order they were bucketed in.
func SpecHash ¶
func SpecHash(comps []IndexComponent) string
SpecHash fingerprints everything an index's stored bytes depend on and nothing else: the component paths, their directions, the payload shape each leaf resolves to, where the component fans out, and the encoding version. The fan-out position is derived from the path but not stated by it, so a field that becomes repeated keeps its path and changes how many entries a row has — exactly the drift a fingerprint exists to catch. A stored index whose hash no longer matches its declaration is stale, not wrong — its entries are simply not readable under the current spec, and the index rebuilds.
The map-fan additions are APPENDED rather than folded into the existing fields, so an index shape that predates them fingerprints byte for byte as it did: the entries already stored for every reference, field mark and list index stay valid instead of all rebuilding at once for a feature they do not use.
It is deliberately written in terms both languages state identically (proto field names, a payload-shape word) rather than in each language's own type enum, so client/src/query/indexkey.ts is a literal mirror. The two must agree: a stored index only ever compares its own hash to its own declaration, but Order.Shape folds this hash into a query cursor, and a cursor is minted on one side and replayed on the other.
func StartsWith ¶
func StartsWith(path, prefix string) *syncplanev1.Condition
StartsWith matches a string (or collaborative-text) field by prefix, case-sensitively.
func TargetKeyValues ¶
func TargetKeyValues(node *RelNode, msg protoreflect.Message) []*syncplanev1.QueryValue
TargetKeyValues reads one matching target row's key values in the node's KeyFields order, as the wire literals the replacement condition compares with. The kinds mirror what a client would send for the same values, so the coercion rules the evaluators share apply unchanged.
func UpperBound ¶
UpperBound is the exclusive end of the range of every entry starting with prefix. A nil result means "no upper bound" — prefix is all 0xff, so nothing sorts above it.
Types ¶
type Compiled ¶
type Compiled struct {
// contains filtered or unexported fields
}
Compiled is a predicate with all paths resolved to descriptor chains.
func Compile ¶
func Compile(desc protoreflect.MessageDescriptor, cond *syncplanev1.Condition) (*Compiled, error)
Compile validates the condition against the message descriptor and resolves every path once. A nil condition compiles to match-all. Errors (unknown fields, descents through non-message fields, operators the leaf can never satisfy, malformed conditions) belong at the RPC boundary as InvalidArgument.
func (*Compiled) Eval ¶
func (c *Compiled) Eval(msg protoreflect.Message) bool
Eval reports whether the message matches the predicate.
func (*Compiled) Matchers ¶
Matchers collects the predicate's compiled match conditions, in tree order. A relevance order key binds to the single one CompileOrderWith requires, and an index-serving executor probes postings with their terms.
func (*Compiled) RequiredMatcher ¶
RequiredMatcher returns a match condition every row satisfying the predicate must satisfy — one reachable from the root through conjunctions alone — or nil when there is none. A match under or/not constrains nothing by itself, so only a required one can narrow an index walk's candidates.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a compiled grouping key: one resolved path, plus what reading a row's group values out of it needs.
func CompileGroup ¶
func CompileGroup(desc protoreflect.MessageDescriptor, path []string) (*Group, error)
CompileGroup validates a grouping path against the message descriptor and resolves it once.
The leaf must be comparable — the same rule an order key obeys, and for the same reason: a group is identified by its value, so a leaf nothing can be compared against would make every row one group. A repeated scalar is the one exception, and groups per element.
func (*Group) Multi ¶
Multi reports whether one row can belong to several groups, which happens exactly when the path ends at a repeated field. Group counts sum to the number of matching rows only when it is false.
func (*Group) Values ¶
func (g *Group) Values(msg protoreflect.Message) []GroupValue
Values are the groups msg belongs to: one per element for a repeated path, exactly one otherwise. Never empty — a row with no value at the path belongs to the no-value group, and an EMPTY list does too, which is what keeps a row out of no group at all.
type GroupCount ¶
type GroupCount struct {
Value GroupValue
// Count is the matching rows in the group. A distinct read never resolves
// one and leaves it at zero.
Count uint64
}
GroupCount is one group of a finished grouped read.
type GroupPlan ¶
type GroupPlan struct {
// Index names the index to read, matching the name the caller registered.
Index string
// Range is the byte range holding every entry that can contribute a group.
// A grouped plan has exactly ONE: several would have to be merged group by
// group, and a row an `in` puts in two of them would be counted twice.
Range Range
// Residual is the part of the predicate the range does not guarantee, to be
// re-checked against each fetched row. Nil means the range is exact, which
// is what lets a count be read off entries with no row decode.
Residual *Compiled
// Desc reports that the partition component stores its values descending, so
// the walk must read the range BACKWARD to yield groups in ascending value
// order.
Desc bool
// EntriesAreRows reports that inside one group's sub-range every entry names
// a distinct row, so counting entries counts rows. False when a component
// PAST the partition fans out, which puts one row at several positions of
// the same group.
EntriesAreRows bool
// Ordered reports that reading one group's sub-range forward yields its rows
// in the requested order, so a walk after the head of a group can stop. It
// is false whenever the caller asked for no order and the partition is not
// the last component: the entries then sort by whatever follows it, where an
// unordered read sorts by row key.
Ordered bool
// contains filtered or unexported fields
}
GroupPlan is a chosen index access path for a grouped read: one range whose entries the walk partitions on a component the prefix left free.
func PlanGroup ¶
PlanGroup picks an index that can partition a predicate's match set by `group`, or returns nil to mean "bucket a scan instead". Candidates are considered in order and the one that narrows most wins; an exact plan, whose counts need no row reads, beats a residual-bearing one that pins as much.
func PlanGroupRows ¶
PlanGroupRows picks an index that can answer the head of each group in `order`, or returns nil to mean "bucket a scan and sort each bucket".
It is PlanGroup under one more requirement: the components past the partition must BE the requested order, and each entry of a group must name a distinct row. Without both, walking a group in index order says nothing about which of its rows come first, and the head of the group could only be found by reading all of them — which is what the scan already does.
func (*GroupPlan) GroupPrefix ¶
GroupPrefix is the leading bytes of an index entry that every entry of the same group shares: the equality-pinned components plus the partition one. Seeking to its upper bound is what skips the rest of a group.
It errors on bytes that are not an entry of this index, which cannot happen for entries the store yielded and is reported rather than assumed away.
func (*GroupPlan) ValueOf ¶
func (p *GroupPlan) ValueOf(g *Group, msg protoreflect.Message, groupPrefix []byte) (GroupValue, bool)
ValueOf names the group a prefix from GroupPrefix stands for, by matching the row's own group values against the partition component's bytes inside it.
A singular path has one value, so the match is a formality. A repeated one has several, and only this comparison says WHICH element put the row in this group — the entry carries the value and the row carries the list, and the encoding is what joins them.
The second result is false when no value of the row encodes to these bytes, which means the entry outlived the value it was written for.
type GroupValue ¶
type GroupValue struct {
// contains filtered or unexported fields
}
GroupValue is one group, identified by the value its rows share at the grouping path. The zero value is the group of rows holding no value there.
func (GroupValue) Key ¶
func (gv GroupValue) Key() string
Key identifies the group for bucketing: two values that compare equal share a key, and no two that do not. Numbers and bigints normalize onto one key for the reason equalsScalar crosses them — an integral double and a bigint of the same magnitude are one group.
func (GroupValue) Proto ¶
func (gv GroupValue) Proto() *syncplanev1.QueryValue
Proto is the group's value on the wire, nil for the no-value group.
type Index ¶
type Index struct {
Name string
Encoder *IndexEncoder
}
Index is what the planner needs to know about one candidate index. Callers hold their own richer type (the engine's compiledIndex) and adapt.
type IndexComponent ¶
type IndexComponent struct {
// contains filtered or unexported fields
}
IndexComponent is one resolved component of an index key: a path through the message, and the direction its values are stored in.
A path may FAN OUT: a step marked `fan` is a repeated field the component takes one value per element of, or — written `*` in the declared path — a map it takes one value per ENTRY of. Fan steps nest: `custom.*.value.labels.values` fans over every entry of `custom` and, within each entry, over every element of that entry's `labels.values`. There is no cross product in that, because the second fan lives inside one element of the first.
func CompileIndexComponent ¶
func CompileIndexComponent( desc protoreflect.MessageDescriptor, path []string, descending bool, ) (IndexComponent, error)
CompileIndexComponent resolves one declared index key into the ONE component it contributes. It rejects the same leaves CompileOrder does — an index whose component could never take part in a comparison would sort every row into one bucket — plus collaborative text, which is comparable but would rewrite its entry on every keystroke.
Unlike a condition path, this one may FAN OUT: through a repeated field (and may end at one), which is what an index over "some element's value" is made of, and through `*` after a map, which is what an index over user-defined fields is made of. At most one repeated field per component, since a second list would need a cross product within the component itself; a `*` nests inside one entry rather than crossing with it, so it composes with a list.
A `*` is followed by `key` or `value`, so one declared path is one component and an index states its own layout:
[ custom.*.key, custom.*.value.number ] one custom field: equality, ranges
and an ordering within it
[ custom.*.value.number, custom.*.key ] which custom field holds 5:
equality, cross-key or named-key
The two are complementary and neither subsumes the other, which is why the order is declared rather than fixed here: `[key, value]` clusters one field's values so they can be ranged and ordered, `[value, key]` clusters one VALUE so the fields holding it can be found.
func (IndexComponent) MaskTouches ¶
func (c IndexComponent) MaskTouches(segs []string) bool
MaskTouches reports whether a field-mask path could change the value this component reads, given the path split into segments the way lww splits a mask (lww.SplitPath). It is what lets a PATCH whose mask reaches no index skip the entry rewrite entirely — a pure descriptor-and-name comparison, with no decode, no read and no encode.
Two paths interact when either is a PREFIX of the other: a mask that stops above the component replaces the subtree the component reads through, and one that continues below it writes inside the value the component reads. Four cases make the comparison conservative where a bare name comparison would be wrong, and every one of them answers TRUE:
- A mask segment may name a ONEOF group rather than a field (lww merges a oneof whole, by group name), so it changes any member the component reads.
- A mask may address one ITEM of a map or keyed list ("tags.red"), so a segment following a repeated or map field is an item key, not a field name, and lands inside the collection the component fans out over.
- A mask may name a sub-path into a field lww replaces whole (an opaque field or a singular reference message, see lww.ReplacedWhole), so a sibling of the component's path rewrites the value it reads too.
- A path that runs out mid-comparison is a prefix, whichever side it was.
Anything else is a genuine divergence at a field the component does not read, and only that returns false.
func (IndexComponent) Multi ¶
func (c IndexComponent) Multi() bool
Multi reports whether a row can occupy several positions because of this component.
type IndexEncoder ¶
type IndexEncoder struct {
// contains filtered or unexported fields
}
IndexEncoder turns rows into the entries of one index. It is immutable and safe to share across goroutines.
func NewDeclaredIndexEncoder ¶ added in v0.9.0
func NewDeclaredIndexEncoder(comps []IndexComponent) (*IndexEncoder, error)
NewDeclaredIndexEncoder builds the encoder for an index that a schema declares. When the leading component fans out over a map (a `*` path, for example `custom.*.key` or `custom.*.value.number`), the encoder is sparse as NewSparseIndexEncoder builds it: a row with an empty or unset map has no entry, and neither has a map entry whose leading component is missing, such as an entry that holds another variant than a `custom.*.value.number` component reads. Otherwise the encoder is dense as NewIndexEncoder builds it.
Because a sparse encoder has a different SpecHash, a stored index whose leading component fans out over a map rebuilds once when it was built by a version that kept it dense. It fails as NewIndexEncoder does.
func NewIndexEncoder ¶
func NewIndexEncoder(comps []IndexComponent) (*IndexEncoder, error)
NewIndexEncoder builds an encoder over already-compiled components. An encoder with no components is legal and yields entries that are the row key alone.
It fails when two components fan out over different chains. Their cross product would be the only way to store both, and a cross product pairs values that never belonged to the same element — so such an index is refused at declaration rather than answering a subtly wrong question at read time. A SHORTER chain is fine, and is the normal case: the entry-key component of a `custom.*.labels.values` index stops at the map, and its value simply repeats across the positions below it.
func NewSparseFieldIndexEncoder ¶ added in v0.10.0
func NewSparseFieldIndexEncoder(c IndexComponent) (*IndexEncoder, error)
NewSparseFieldIndexEncoder builds the encoder for the index of a field that sets both (syncplane.v1.field_behavior).indexed and sparse_index, over the one component c compiled from that field.
The encoder is sparse as NewSparseIndexEncoder builds it, and when the leaf field has implicit presence it also leaves out each entry that holds the zero value of that field: the empty string, 0, false or the zero enum value. The index then holds an entry only for a row that sets the field. Its SpecHash differs from that of the dense and the sparse encoder, so a stored index rebuilds once when a schema turns the option on or off.
It fails when c fans out over a repeated field, and otherwise as NewIndexEncoder does.
func NewSparseIndexEncoder ¶ added in v0.4.0
func NewSparseIndexEncoder(comps []IndexComponent) (*IndexEncoder, error)
NewSparseIndexEncoder builds an encoder like NewIndexEncoder, except that Encode leaves out every entry whose leading component is missing: a row with that component unset, or a position of an empty collection. Every entry it keeps is byte for byte the entry the dense encoder writes.
A sparse index holds fewer rows than its entity, so PlanQuery and PlanGroup use one only for a range inside the present ranks of the leading component. It fails as NewIndexEncoder does, and also for an empty component list, which has no leading component to leave rows out by.
func (*IndexEncoder) Components ¶
func (e *IndexEncoder) Components() []IndexComponent
Components exposes the compiled components, for a planner deciding whether this index serves a query.
func (*IndexEncoder) Encode ¶
func (e *IndexEncoder) Encode(msg protoreflect.Message, rowKey string) [][]byte
Encode produces the entries msg occupies in this index — one per position of the fan chain, or a single entry when no component fans out. rowKey is the row's storage key, which terminates every entry so that entries are unique and tie exactly the way Order.Compare does.
For a dense encoder the result is never empty: a row whose collection is empty or unset still takes one position, with the missing tag at each fan-out component, so every live row is reachable through the index. A sparse encoder leaves out each entry whose leading component is missing, and returns no entries when that is all of them.
func (*IndexEncoder) EncodePrefix ¶
func (e *IndexEncoder) EncodePrefix(values []protoreflect.Value) ([]byte, error)
EncodePrefix encodes the first len(values) components from explicit values — the leading equality terms of a probe — and returns the inclusive lower bound of the range holding every row that agrees with them. Pair it with UpperBound for the exclusive end.
values[i] is a value of comps[i]'s LEAF field, so a probe on a reference index passes the target's key-field values straight through.
func (*IndexEncoder) Sparse ¶ added in v0.4.0
func (e *IndexEncoder) Sparse() bool
Sparse reports whether the encoder leaves out the entries whose leading component is missing, as one built by NewSparseIndexEncoder or NewSparseFieldIndexEncoder does.
func (*IndexEncoder) SpecHash ¶ added in v0.4.0
func (e *IndexEncoder) SpecHash() string
SpecHash fingerprints what the stored entries of this index depend on. For a dense encoder it equals SpecHash over the same components; a sparse encoder, and one that also leaves out a zero value, each fingerprint differently, so entries stored under one form are stale under the others and rebuild.
func (*IndexEncoder) SplitEntry ¶
func (e *IndexEncoder) SplitEntry(entry []byte) (components, rowKey []byte, err error)
SplitEntry cuts an entry of this index into its component half and its row-key suffix, by walking the components the encoder was built from. It rejects bytes that are not an entry of this index — an unknown tag, a payload that runs off the end, an unterminated string, bytes left over past the row key — which is what makes it usable on input a client supplied.
A query cursor's seek bound is the component half alone whenever the index it is composed with carries components past the ordering's keys: a bound that ran on into the row key would not be a prefix of any entry in such an index.
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher is one compiled match condition: the declaration it reads and the required terms of its query. It memoizes ranks per row message, so it is safe for concurrent use and cheap to consult from both an evaluation and an ordering of the same rows.
func (*Matcher) Matches ¶
func (m *Matcher) Matches(msg protoreflect.Message) bool
Matches reports whether every required term occurs in some declared field of msg. A matcher with no terms matches every row.
func (*Matcher) Rank ¶
func (m *Matcher) Rank(msg protoreflect.Message) uint64
Rank scores msg against the query: a 48-bit integer where SMALLER IS BETTER, so ascending rank order is best-match-first and the value encodes into cursors as an ordinary number component. From most to least significant byte:
miss required terms not found anywhere (0 for a matching row) prefixOnly terms found only as a prefix of a longer term, never exactly attribute first declared field containing every term, 255 when none does proximity smallest token window covering every term in that field first earliest matched token position in that field occurrence 255 minus the total number of matching tokens
Every byte caps at 255, and a matcher with no terms ranks every row 0. The rank reads msg alone — never the store — which is what keeps a client ranking over its synced subset identical to the server ranking over everything.
type Order ¶
type Order struct {
// contains filtered or unexported fields
}
Order is a compiled multi-key row ordering.
func CompileOrder ¶
func CompileOrder(desc protoreflect.MessageDescriptor, keys []*syncplanev1.OrderKey) (*Order, error)
CompileOrder validates order keys against the message descriptor and resolves their paths once. An empty key list is valid (ties on row key). A key on an incomparable leaf is rejected rather than accepted: it would tie every pair, so the result would silently come back in row-key order.
A relevance key is rejected here: it binds to the predicate's match condition, which this surface does not hold. Use CompileOrderWith.
func CompileOrderWith ¶
func CompileOrderWith(desc protoreflect.MessageDescriptor, keys []*syncplanev1.OrderKey, predicate *Compiled) (*Order, error)
CompileOrderWith is CompileOrder for orderings that may rank by relevance: a relevance key resolves against predicate, which must contain exactly one match condition. A nil predicate (or one without a match) rejects relevance keys with an error naming what is missing.
func (*Order) Compare ¶
func (o *Order) Compare(a, b protoreflect.Message, keyA, keyB string) int
Compare mirrors the client's compareRows: values rank real < NaN < missing and the rank decides before the direction does, so NaN and missing both sort last under asc and desc alike; equal non-real ranks and real ties fall through to the next key and finally to the row key ascending (UTF-16 order).
func (*Order) Cursor ¶
func (o *Order) Cursor(msg protoreflect.Message, rowKey string) []byte
Cursor is msg's position in this ordering, unframed — the bytes rows are compared against. EncodeCursor is the form a client is handed.
It cannot fail: an order key never fans out, because CompileOrder rejects the repeated and map leaves that would make it, so a row occupies exactly one position.
func (*Order) CursorPrefix ¶
CursorPrefix is the component half of an entry from Cursor or DecodeCursor: the position without the row-key tiebreak. An index seek composes this rather than the whole entry when the index carries components past the ordering — see IndexEncoder.SplitEntry.
func (*Order) DecodeCursor ¶
DecodeCursor unwraps a cursor a client sent back, returning the entry to compare rows against. It reports ErrCursorShape for a cursor belonging to another entity or ordering, and a descriptive error for bytes that are not a cursor at all.
It does not bound the length: a caller handling untrusted input caps that before calling, since a malformed cursor is otherwise as much work as it is long.
func (*Order) EncodeCursor ¶
EncodeCursor frames msg's position for a client: the version byte, the shape for entity, and the entry Cursor returns.
type Plan ¶
type Plan struct {
// Index names the index to read, matching the name the caller registered.
Index string
// Ranges are the byte ranges to read, in the order they must be read.
// Usually one; an `in` over the leading component produces several, and a
// caller serving an ORDERED query from several ranges must merge them
// rather than concatenate. A Reverse plan is the exception: its ranges are
// read one after the other, as listed.
Ranges []Range
// Residual is the part of the predicate the ranges do not guarantee, to be
// re-checked against each fetched row. Nil means the range is exact and no
// re-check is needed.
Residual *Compiled
// Ordered reports whether reading the ranges in order yields rows in the
// query's requested order. When false the caller must still sort, and the
// index bought only a narrower candidate set.
Ordered bool
// Reverse reports that an Ordered plan supplies its ordering by reading
// each range from its high end to its low end, the ranges in the order
// listed. It is set when every order key runs against its component's
// direction. The ranges then hold the first order component's real values,
// its NaN rank and its missing rank, in that order and each only when the
// predicate admits it: the two non-real ranks sort last in either
// direction, where reading backward would put them first.
Reverse bool
// Prefix is the encoded equality-pinned components every entry in the range
// shares. A range component is NOT part of it: only the components the
// range fixes to a single value are.
//
// It is what an Ordered plan composes a seek bound from — appending a
// cursor to it names the position in the index the page resumes at, and
// OrderSpansIndex says how much of that cursor the index can take. Nil when
// the plan produced several ranges,
// which share no single prefix, and empty when it pinned nothing.
Prefix []byte
// OrderSpansIndex reports whether the equality prefix and the order keys
// together consume EVERY component of the index, so that appending a
// cursor's whole entry — row-key tiebreak included — to Prefix names one
// existing entry rather than something no entry starts with.
//
// It is what lets a seek bound land past the tie group at the boundary
// instead of at the start of it, which is the difference between a deep page
// costing O(page) and O(depth). False for an index carrying components past
// the ordering, and for any plan that is not Ordered.
OrderSpansIndex bool
// Union, when non-empty, is a plan for a top-level `or`: one access path
// per branch, each naming its own index, read through Branches. Index,
// Ranges and Prefix are unset, Ordered is false, and Residual — nil only
// when every branch's range was exact — is the whole predicate: a branch's
// range can yield a row that fails that branch yet matches another, so no
// branch-local re-check is correct.
Union []PlanBranch
// contains filtered or unexported fields
}
Plan is a chosen index access path.
func PlanQuery ¶
PlanQuery picks an index for a predicate plus an ordering, or returns nil to mean "scan". The narrowest exact-ordered match wins; failing that, the one that narrows the most. Ties keep the earliest-declared candidate.
A nil predicate with a nil/empty order is a full scan of the entity in key order, which no index improves on — the row keyspace IS that index — so it declines rather than reading a second copy of the same thing.
func (*Plan) Branches ¶
func (p *Plan) Branches() []PlanBranch
Branches lists the access paths to read — the union's branches, or the plan itself as the single one — so executing any plan is one loop over it.
func (*Plan) TieGroup ¶ added in v0.4.0
TieGroup returns the leading bytes of entry that every entry of the plan's index tying with it on the order keys shares, or nil when the plan has no tie group to finish: one that is not Ordered, or a forward one whose OrderSpansIndex holds. The result aliases entry.
Past the order keys the index orders a tie by its remaining components, where Order.Less orders it by row key, so the entry that follows a full page in the walk can still sort before a row the page holds. A Reverse plan has the same problem whatever the index holds: reading backward inverts the row-key tiebreak, and puts a later order key's NaN and missing ranks before its real values. Its tie group is therefore cut at the first order key alone, where the ranges keep the order exact. A walk that stops when its page is full has to read on while the next entry returns the same tie group as the previous one, and can stop at the first that does not.
It errors on bytes that are not an entry of the plan's index.
type PlanBranch ¶
PlanBranch is one access path of a union plan: the index to read and the ranges to read from it.
type Range ¶
type Range struct {
Lo, Hi []byte
}
Range is a half-open byte range over an index: Lo inclusive, Hi exclusive. A nil bound is open on that end.
type RelNode ¶
type RelNode struct {
// Cond is the rel condition's own message inside the predicate tree —
// the identity a rewrite replaces (see RewriteRels).
Cond *syncplanev1.RelCond
// Field is the resolved forward reference field the path ends at — or,
// for a case of a polymorphic reference message, the message field the
// case sits in.
Field protoreflect.FieldDescriptor
// Path is the wire path to Field: the condition's own path, shortened by
// the case segment when the condition names a case.
Path []string
// Target is the referenced entity's message descriptor.
Target protoreflect.MessageDescriptor
// KeyFields are the target's key fields, the values a stored stub carries.
KeyFields []protoreflect.FieldDescriptor
// Ref is the reference's stored shape: where the key and, for a reference
// message, the workspace sit inside the stored value.
Ref *lww.Ref
}
RelNode is one rel condition found in a predicate: the ref field it crosses and the inner condition selecting target rows. See ExtractRels.
func ExtractRels ¶
func ExtractRels(desc protoreflect.MessageDescriptor, cond *syncplanev1.Condition) ([]*RelNode, error)
ExtractRels finds and validates every rel condition in cond, in evaluation order. Each node's path must resolve to a forward reference field of desc, its inner condition must compile against the target descriptor, and a rel nested inside another rel or inside an exists is rejected — the semi-join is one hop, scoped to the row.
An empty result means the predicate is row-local and needs no pre-pass.
type SearchDecl ¶
type SearchDecl struct {
// contains filtered or unexported fields
}
SearchDecl is an entity's compiled search declaration: the fields a match condition reads, most important first, and the analyzer options their text and every query against them are analyzed with.
func CompileSearchDecl ¶
func CompileSearchDecl(desc protoreflect.MessageDescriptor) (*SearchDecl, error)
CompileSearchDecl resolves an entity's search declaration from its descriptor options: fields marked (syncplane.v1.field_behavior).searchable first, in field order, then the fields of EntityOptions.search, in declaration order. It returns nil for an entity that declares neither, and an error for a declaration that cannot search — a path that does not resolve, a leaf that is not a singular string or collaborative-text field, a duplicate path, or a search declaration naming no fields at all.
func (*SearchDecl) Heads ¶ added in v0.2.0
func (d *SearchDecl) Heads() []protoreflect.FieldDescriptor
Heads returns the top-level field of each search field, in declaration order and without repeats.
func (*SearchDecl) MaskTouches ¶
func (d *SearchDecl) MaskTouches(segs []string) bool
MaskTouches reports whether a field-mask path could change any searchable field, given the path split the way lww splits a mask. Conservative the same way IndexComponent.MaskTouches is: undecidable cases answer true.
func (*SearchDecl) SearchEntries ¶
func (d *SearchDecl) SearchEntries(msg protoreflect.Message) [][]byte
SearchEntries returns the posting keys msg holds in the entity's search index: one per distinct term of its searchable fields in first-occurrence order, or the overflow marker alone past SearchTermsPerRow. A row whose fields analyze to nothing holds no keys — such a row can match no term probe, and the overflow union covers only rows that opted out by size.
func (*SearchDecl) SearchSpecHash ¶
func (d *SearchDecl) SearchSpecHash() string
SearchSpecHash fingerprints everything the stored search postings depend on: the declaration (fields and analyzer options), the per-row term cap, and the encoding version. A stored index whose hash no longer matches is stale and rebuilds, exactly like a value index.
type Spec ¶
type Spec struct {
// Where selects rows. Nil matches every live row of the entity.
Where *syncplanev1.Condition
// OrderBy sorts the result. Missing values sort last regardless of
// direction, ties fall through to the next key and finally to the row key
// ascending. Empty means row-key order.
OrderBy []*syncplanev1.OrderKey
// Limit caps the returned rows. Zero or negative means no cap — which,
// combined with an Offset, is the only way to ask for an unbounded result.
Limit int
// Offset drops the first Offset rows of the ordering. It costs what it
// says: the rows are still scanned, decoded and compared, so deep paging
// re-does the work of every page before it, and a row inserted ahead of the
// page between two requests shifts every later one. Prefer After/Before,
// which have neither problem; reach for Offset only to jump to an arbitrary
// rank, which a cursor structurally cannot do.
//
// Setting it together with After or Before is an error.
Offset int
// After bounds the result to rows sorting strictly after this cursor, and
// Before to rows sorting strictly before it. Both are cursors an earlier
// run of the SAME query produced (Order.EncodeCursor, or a QueryResponse's
// start_cursor/end_cursor); one minted under a different entity or ordering
// is rejected with ErrCursorShape rather than answered wrongly.
//
// Limit counts from the After end, except when only Before is set, where it
// counts back from the Before end — so After pages forward and Before pages
// back. Both together read a bounded range, paged forward.
After, Before []byte
}
Spec is a whole query: an optional predicate, an optional ordering, and a page. It is what ViewTx.Query takes, and it mirrors the QueryRequest fields a client sends, so server-side code and client code express the same query the same way.
type Value ¶
type Value interface {
~string | ~bool |
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
Value is the set of Go types that can appear as a query literal. Constraining the constructors to it makes an unsupported literal a compile error instead of a runtime one, which is why none of them return an error.