Documentation
¶
Overview ¶
Package query reads a collection of stored messages by refs, as a table: the columns a query selects, its rows filtered and sorted. A ref names a field by its path in the message (usage.cost_usd) and may cross to another collection through a field that holds an id (wish_id->title), as its (djinn.v1.ref) option declares. The schema comes from the descriptor: a column's type never depends on the values a row holds. A collection adds refs computed in Go (prompt::size), and a query may aggregate its rows: groups by refs, a time truncated to its day, week or month, and measures named ref::fn (running::median).
The store keeps each entity as a protobuf payload, its *_id fields aside as columns: an equality on one of them narrows the rows SQLite reads, and everything else runs in Go, on the decoded messages.
A table writes itself in Arrow, typed, for the window, or as aligned text and CSV, for the command line; Handler serves Djinn's collections as QueryService, its filters, sorts, groups and measures read from their texts.
Index ¶
- Constants
- Variables
- func Handler(r store.Reader) (string, http.Handler, error)
- func Label(col Column) string
- type Aggregation
- type Catalog
- type Collection
- type Column
- type Derived
- type Equal
- type Filter
- type Fn
- type Granularity
- type Group
- type GroupBy
- type In
- type IsNull
- type Measure
- type Meta
- type Op
- type Query
- type Range
- type Sort
- type Source
- type Table
- type Text
- type Type
Constants ¶
const MetaKey = "djinn"
MetaKey is the key of a field's metadata in Arrow.
Variables ¶
var ErrInvalid = errors.New("invalid query")
ErrInvalid wraps the errors of a query that cannot run as written: an unknown or hidden ref, a value of the wrong type, an empty group.
var QuestionRefs = []Derived{ Derive("context::size", TypeInt, "The context's size in tokens, estimated as its characters divided by 4, "+ "rounded up: the context itself stays hidden.", func(q *planv1.Question) any { return size(q.GetContext()) }).WithUnit(tokens), Derive("answer.note::size", TypeInt, "The answer's note size in tokens, estimated as its characters divided by 4, "+ "rounded up.", func(q *planv1.Question) any { return size(q.GetAnswer().GetNote()) }).WithUnit(tokens), Derive("answer::delay", TypeDuration, "How long the question waited for its answer (answer.create_time - "+ "create_time), whoever answered.", func(q *planv1.Question) any { return between(q.GetCreateTime(), q.GetAnswer().GetCreateTime()) }), }
QuestionRefs are the derived refs of the questions.
var TaskRefs = []Derived{ Derive("prompt::size", TypeInt, "The size in tokens of the task's first prompt, the text it was given, estimated "+ "as its characters divided by 4, rounded up: the prompt itself stays hidden.", func(t *planv1.Task) any { return tokensOf(t.GetPromptLength()) }).WithUnit(tokens), Derive("integration::delay", TypeDuration, "From the task's end to its work's commit into its wish's integration "+ "branch (integration.update_time - end_time), for a work committed only.", func(t *planv1.Task) any { if t.GetIntegration().GetState() != planv1.IntegrationState_INTEGRATION_STATE_COMMITTED { return nil } return between(t.GetEndTime(), t.GetIntegration().GetUpdateTime()) }), DeriveEnum("type", "What the task is, for every task, as plan.Kind reads it: its kind, work when it holds none.", plan.Kind), }
TaskRefs are the derived refs of the tasks.
Functions ¶
Types ¶
type Aggregation ¶
type Aggregation struct {
By []GroupBy
Measures []Measure
// Location is where a day, a week or a month starts: the machine's local time when nil.
Location *time.Location
}
Aggregation turns a query's rows into groups: a row per group of rows whose By refs hold the same values, with a column per group ref, then a column per measure. Without By, the whole set is one group, and the table one row, even when no row holds: its count is 0, its other measures null. Otherwise a group holds one row at least, but for the bins of GroupBy.Bounds: an empty period never shows, an empty bin does. Rows come ordered by their groups' values, nulls last, before the query's sorts, which name the table's columns.
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog holds the collections a query reads, one per message type: a jump reads its target by its type.
func Collections ¶
Collections are the collections QueryService reads, by the name its Collection enum gives each (COLLECTION_TASKS is TASKS), with their usual columns and their derived refs. The tasks come with their times, as of now (Timed).
func NewCatalog ¶
func NewCatalog(collections ...Collection) (*Catalog, error)
NewCatalog checks the collections: a name and a type each once, and default refs that compile.
type Collection ¶
type Collection struct {
// Name is how a query names it, such as TASKS.
Name string
Source Source
// Defaults are the refs a query without selects reads: every ref of the schema when empty.
Defaults []string
// Derived are the refs it computes in Go, besides its fields' (TaskRefs, QuestionRefs).
Derived []Derived
}
Collection is a source a query names.
type Column ¶
type Column struct {
// Ref is how a query names it: code, usage.cost_usd, wish_id->title.
Ref string
Type Type
// List is a repeated field: its value is a []any of Type, nil when empty.
List bool
// Field is the field read last, past the jumps: its descriptor holds its comment, its enum, its options. It is
// nil for a derived ref, and for a count of rows.
Field protoreflect.FieldDescriptor
// Enum is the enum of a TypeEnum column: its field's, or the one a derived ref declares.
Enum protoreflect.EnumDescriptor
// Jump is the full name of the message whose id the field holds, by its (djinn.v1.ref) option: the ref
// Ref+"->"+r reads r there.
Jump protoreflect.FullName
// Doc says what a derived ref is.
Doc string
// Unit is the unit of its numbers, when they have one: usd, tokens. A time or a duration has none: its type says
// it.
Unit string
// In an aggregated table, Of is the ref a group or a measure reads ("" for a count of rows), Fn the measure's
// function, Granularity the period a group of times truncates them to, and Bounds the bounds of a group's bins,
// in Type.
Of string
Fn Fn
Granularity Granularity
Bounds []any
}
Column is one ref of a collection.
func Schema ¶
func Schema(md protoreflect.MessageDescriptor) []Column
Schema gives the refs of md, flattened: a nested message's fields as path.field, never a hidden field, nor a map, nor a repeated message, nor a message that holds itself. Jumps are not followed: Column.Jump names their target.
type Derived ¶
type Derived struct {
Ref string
Type Type
// Doc says what it is, as a field's comment would.
Doc string
// Unit is the unit of its numbers, when they have one (WithUnit).
Unit string
// Enum is the enum of its values, for a TypeEnum (DeriveEnum).
Enum protoreflect.EnumDescriptor
// contains filtered or unexported fields
}
Derived is a ref a collection computes in Go, where no field holds the value: the size of a hidden text, the time between two of its fields. A query reads it as any ref, across a jump too (wait_question_id->answer::delay). Its name holds :: by convention, after the field it reads: prompt::size.
func Derive ¶
Derive declares a derived ref of the collection whose messages are M's. get gives a value of typ, as Column says, or nil when absent: never a zero for a value it cannot compute.
func DeriveEnum ¶
DeriveEnum declares a derived ref whose values are those of the enum E: get gives one, never its zero, or nil.
type Equal ¶
Equal holds when Ref's value is Value: text compared ignoring case, as the store compares it.
type Filter ¶
type Filter interface {
// contains filtered or unexported methods
}
Filter keeps the rows it holds for. A null value holds for none but IsNull, and In with IncludeNull. On a list, a filter holds when it holds for one of the list's values.
type Fn ¶
type Fn int
Fn is a measure's function.
const ( // Count counts the rows, or the rows where Ref is not null: an int, 0 for none. Count Fn = iota + 1 // Sum adds ints, floats or durations, of the type it reads. Sum // Avg is the mean of ints or floats as a float, of durations as a duration. Avg // Min and Max take ints, floats, durations or times, of the type they read. Min Max // Median and P90 interpolate between the two closest values (as Postgres's percentile_cont does): a float for // ints and floats, a duration for durations. Median P90 )
The functions of a measure, and the types they take. A list only counts, as a row whose list is not empty.
type Granularity ¶
type Granularity int
Granularity is the period a group truncates a time to.
const ( // Day starts at midnight. Day Granularity = iota + 1 // Week starts on Monday at midnight. Week // Month starts on its first day at midnight. Month )
The granularities of a group.
func (Granularity) String ¶
func (g Granularity) String() string
type GroupBy ¶
type GroupBy struct {
Ref string
// Granularity truncates a time to the start of its period: the column is then named Ref::day, ::week or ::month,
// and holds that start, in UTC.
Granularity Granularity
// Bounds split a number or a duration into bins, two bounds at least, each above the one before, of the ref's type
// or a text that reads as one (10s, 1m). A value goes to the bin of the greatest bound at or below it, the first
// bound's when it is below them all: the first bin holds every value below the second bound, the last one every
// value from the last bound up. The column is then named Ref::bins and holds the bin's bound. Unlike a period,
// every bin shows, a count of 0 for an empty one, beside each set of the other groups' values that rows hold.
Bounds []any
}
GroupBy groups rows by a ref's value, which cannot be a list. Text groups as written, case included; null is a group of its own.
type Measure ¶
type Measure struct {
// Ref is the ref read: empty for a count of rows.
Ref string
Fn Fn
Alias string
}
Measure computes a function over the values of a ref in each group. Every function skips the nulls: the count counts the values, the others are null for a group without value. Its column is named Alias, or Ref::fn (running::median), or count for a count of rows.
type Meta ¶
type Meta struct {
Ref string `json:"ref"`
Label string `json:"label"`
// Unit is the unit of the numbers, when they have one: usd, tokens.
Unit string `json:"unit,omitempty"`
// Type is Djinn's type of the column: string, enum, int, float, bool, time or duration.
Type string `json:"type"`
List bool `json:"list,omitempty"`
// Of, Fn, Granularity and Bounds are an aggregated column's: the ref it reads, its function, the period of a group
// of times, the bounds of a group's bins (durations in milliseconds, as the column holds them).
Of string `json:"of,omitempty"`
Fn string `json:"fn,omitempty"`
Granularity string `json:"granularity,omitempty"`
Bounds []any `json:"bounds,omitempty"`
}
Meta is the "djinn" metadata of each field of a table in Arrow, as JSON.
type Query ¶
type Query struct {
Collection string
// Filters all hold for a row the table keeps.
Filters []Filter
// Sorts order the rows, the first one first; then rows keep the source's order, oldest first. A null comes
// last either way.
Sorts []Sort
// Selects are the refs of the table's columns, in order: the collection's defaults when empty.
Selects []string
// Limit keeps the first rows only, when above 0.
Limit int
// Aggregation, when set, makes the table a row per group, its columns the groups' and the measures': it
// selects them, and the sorts name them.
Aggregation *Aggregation
}
Query asks a collection for a table.
type Range ¶
Range holds when Ref's value, a number, a time or a duration, is within each bound given.
type Source ¶
type Source interface {
// Descriptor is the message the source gives.
Descriptor() protoreflect.MessageDescriptor
// Indexed names the singular text fields where narrows by.
Indexed() []string
// Load gives the messages whose fields equal where's values, text ignoring case: all of them for an empty where.
Load(ctx context.Context, where map[string]string) ([]proto.Message, error)
}
Source gives the messages of a collection.
func FromStore ¶
FromStore is the source of the entities of m's type in the store: where narrows by their text columns, the *_id fields and the unique ones, in SQL. Entities not migrated at start (store.ErrUnmigrated) make a source each load of which fails with that error, as each use of them does: the other collections read, and djinn up starts (Q42).
func Timed ¶
Timed gives the tasks of src with their times, which the store does not keep: running, waiting_gate, paused and waiting_before_start, as the task list computes them from their runs and gate waits as of now (plan.ReadTimes), an azima's summing its parts'. A task that never started has none but waiting_before_start: null, never 0. Each comes with the length of its first prompt (plan.PromptLengths). Loads asked at the same time with the same where share one read: the Statistics tab asks a dozen at once, and the store reads on one connection.
type Table ¶
type Table struct {
Columns []Column
// Rows hold a value per column, nil when absent.
Rows [][]any
// Total counts the rows before the limit: the groups when aggregated.
Total int
}
Table is a query's answer.
func (*Table) Arrow ¶
Arrow writes t as an Arrow IPC stream of one record batch: a field per column, named by its ref, of the type its column has (a list of them for a list, of names for a list of enums), each holding its Meta. An absent value is null, never 0.
func (*Table) WriteCSV ¶
WriteCSV writes t as CSV: a header of refs, then a line per row. An absent value is an empty cell; an enum is its value's name without its prefix, in lower case (running); a time is RFC 3339 in UTC; a duration is Go's without its trailing zero units (1h30m, 1h); a list joins its values with ", "; a bin is its range (< 10s, 10s to 1m, >= 1h).
type Text ¶
Text holds when Ref's text contains Contains, or begins with BeginsWith, ignoring case: one of the two.