query

package
v0.0.0-...-20b29fd Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package query builds queries on the records of a store and plans them: it chooses between scanning the store and reading one of its indexes, and between sorting the records and reading them in the order of an index.

q := query.From(books).
	Where(author.Eq("Herbert"), year.Gte(1965)).
	OrderBy(year.Desc()).
	Limit(10)

fmt.Println(q.Explain())
it := q.Run(tx)

Definitions

A Query is a definition, which does not change: every method returns another query, so a query can be made in one place, extended in another, and run in any number of transactions and from any number of goroutines. A query is planned once, when it is first run or explained, with the indexes that the store has then.

Results

A query that has an order (OrderBy) gives the records that satisfy all the conditions in the order of its fields, a field that is Desc from the greatest value to the least, with the records that have no value for a field before the others, or after them for a field that is Desc. Records that are equal in all the fields come in the order of their keys, as encoded. So a result does not depend on the plan, and Offset and Limit take the same records whichever index is read.

A query that has no order gives the records in no order that is promised: a scan of the store gives them in the order of their keys, and an index in the order of its entries. So Offset and Limit of a query without an order page whatever order its plan gives, which can change when the indexes of the store do; they always give distinct records that satisfy the conditions, as many as are asked for and are there.

Plans

The conditions are normalised, and then the cheapest of the ways to read the records is chosen: scanning the store, or reading one of its indexes. The costs are estimated without any statistics, with the numbers in plan.go. A plan sorts the records, unless the way it reads them gives the order that is asked for, which an index does if its fields that the conditions do not fix to a value are the ones that the order is of, in the same direction or all in the opposite one. Explain shows the plan.

An index has no entry for a record that has no value for one of its fields, so an index is only read if none of the records that the query asks for lacks one: each of its fields is either one that every record has a value for (field.Always), or one that a comparison at the top of the conditions needs a value of. A condition that is a negation or a disjunction is not such a comparison. An index that no condition limits is read in full, then, if all its fields are Always, and costs what that costs: it is chosen for an order that it gives under a limit.

An index that has a condition (index.Where) has the records that satisfy it only, so it is only read if the conditions of the query imply its condition: every record that the query asks for satisfies it. The conditions of the query imply it if each part of it is implied by a condition of the query, like Year >= 1970 by Year > 1980 or by Year = 1975, or Kind IN ('a', 'b') by Kind = 'a', and a part that is not a comparison, like a function, is implied by the identical condition only. The query is still checked against all its conditions, and its results do not depend on the index. Hinting an index (Using) whose condition is not implied is an error.

Several indexes

A plan can read several indexes for one query, and combine what they find by the primary keys of the records. A disjunction that is one of the conditions of the query is read as a union if each of its branches is served by an index: a branch is read with its conditions and the other conditions of the query, so it is exact, and a record that several branches find is returned once. The records of a union come in no order. A disjunction of values of one field (Rank = 1 OR Rank = 2) is one condition of the values (Rank IN (1, 2)) before anything is planned.

A conjunction is read as an intersection if the indexes serve different conditions of it: one of them is streamed, the primary keys of the others are remembered, and a record of the streamed index is fetched only if all the others have it. The records come in the order of the streamed index. The conditions that the streamed index does not serve are checked on the records that are fetched, so the result is exact whatever the other indexes find.

The planner takes such a plan if it costs less than the plans of one index, and if the keys it holds in memory are not more than MaxKeys allows, by its estimate. UsingAll forces one. The keys are held exactly if they are numbers of the same size, of 8 bytes at most (a bitmap), and otherwise as hashes, of which two keys may have the same, so a record whose hash is known is checked against the index that has it; Explain shows "(hashed)".

Projections

A query gives records. Select makes of it a projection, which gives rows with the values of the items that are selected (fields, and values that an index covers), and Count gives the number of records. An index holds the fields of its key, the fields it includes (index.Including) and the values it covers (index.Covering), so it can give a row without the record, if it holds all that the rows need: that is an IndexOnlyScan in the plan, which costs no fetch of records. A row can still give its record (Row.Record), which is read when it is asked for.

Decoding

A query checks its conditions on the fields that they read, which it decodes for every record that it checks, and decodes the records that satisfy them in full. A projection and Count decode the fields that the conditions, the items and the order read only. This is done by the codec of the store if it can decode some fields of a record (codec.PartialDecoder, which the default codecs do for a struct), and by the conditions and fields that say what they read: a function that does not (cond.Func and field.Of without Reading) makes the query decode the whole record.

Nearest

A query can order its records by their distance from something that an index of the store measures, the nearest first (Nearest), like a vector index of package vector:

q := query.From(docs).
	Where(lang.Eq("en")).
	Nearest(byEmbedding.To(vector)).
	Limit(10)

The search is done one of two ways. The search can check the conditions on the records, nearest first, until it has the records that the limit and the offset ask for; or it can rank the records that an access path of the conditions finds, the way the planner would read them for a query without an order, with every condition checked. The second is exact, as every record that satisfies the conditions is ranked, and it reads as many records as the access path finds. So it is done when the access path is an index, or several, that is estimated to find 10,000 records at most (an equality on an indexed field, with the assumed number of records), and otherwise the search checks the conditions. A query without conditions is searched, and Using the index of the Nearness gives the first way too, while any other index or FullScan gives the second. UsingAll is an error.

How near the records found are to the nearest depends on the index: a vector index that is partitioned reads the nearest partitions only, so the first way finds the records that are nearly the nearest, and the second the nearest of what the access path finds. The order is the same in both: by distance, and by key at the same distance. The distance of each record is given by Distance and Row.Distance. A record that the index has no distance for is not among the records of the query.

Example

Example builds queries on a store, and shows how they are run.

package main

import (
	"fmt"

	"github.com/ehsanranjbar/kvutil/field"
	"github.com/ehsanranjbar/kvutil/index"
	"github.com/ehsanranjbar/kvutil/iterutil"
	"github.com/ehsanranjbar/kvutil/kv"
	"github.com/ehsanranjbar/kvutil/kv/memkv"
	"github.com/ehsanranjbar/kvutil/query"

	extstore "github.com/ehsanranjbar/kvutil/store/ext"
)

type Book struct {
	Title  string
	Author string
	Year   int
}

func main() {
	books := extstore.New[int64, Book]("books")

	author := field.Path[Book, string]("Author")
	year := field.Path[Book, int]("Year")
	title := field.Path[Book, string]("Title")
	index.Composite(books, "by_author_year", field.List(author, year.Desc()))

	db := memkv.New()
	if err := books.Check(db); err != nil {
		panic(err)
	}
	err := db.Update(func(tx kv.Tx) error {
		store := books.Instantiate(tx)
		for id, book := range []Book{
			{Title: "Dune", Author: "Herbert", Year: 1965},
			{Title: "Emma", Author: "Austen", Year: 1815},
			{Title: "Children of Dune", Author: "Herbert", Year: 1976},
			{Title: "Persuasion", Author: "Austen", Year: 1817},
			{Title: "The Dosadi Experiment", Author: "Herbert", Year: 1977},
		} {
			if err := store.Set(int64(id+1), &book); err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		panic(err)
	}

	run := func(name string, q *query.Query[int64, Book]) {
		plan, err := q.Explain()
		if err != nil {
			panic(err)
		}
		err = db.View(func(tx kv.Tx) error {
			titles, err := iterutil.Of(q.Run(tx).Iterator).
				Map(func(_ int64, b *Book) (string, error) { return b.Title, nil }).
				Values()
			fmt.Printf("%s\n%s\n%v\n\n", name, plan, titles)
			return err
		})
		if err != nil {
			panic(err)
		}
	}

	// A query is a definition: each method returns another one, and the base stays as it is.
	herbert := query.From(books).Where(author.Eq("Herbert"))

	// The index gives the order, so the records are not sorted.
	run("the latest of Herbert", herbert.OrderBy(year.Desc()).Limit(2))
	// Another order is sorted, and only the first two are kept.
	run("the first two titles of Herbert", herbert.OrderBy(title).Limit(2))
	// With no order the records come in the order of the plan, here that of the index.
	run("Herbert", herbert)
	// Nothing serves a condition on the year alone, so the store is scanned.
	run("books before 1900, page 2", query.From(books).Where(year.Lt(1900)).OrderBy(year).Offset(1).Limit(5))
	// A hint says where to read; this is the same query as the first one, from the store.
	run("the latest of Herbert, by a scan", herbert.OrderBy(year.Desc()).Limit(2).FullScan())
	// Conditions that contradict each other read nothing.
	run("nothing", herbert.Where(author.Eq("Austen")))

}
Output:
the latest of Herbert
Limit 2
└─ IndexLookup by_author_year (in order of Year desc): 1 range
[The Dosadi Experiment Children of Dune]

the first two titles of Herbert
Limit 2
└─ TopN by Title
   └─ IndexLookup by_author_year: 1 range
[Children of Dune Dune]

Herbert
IndexLookup by_author_year: 1 range
[The Dosadi Experiment Children of Dune Dune]

books before 1900, page 2
Limit 5, offset 1
└─ TopN by Year
   └─ StoreScan, then check [Year < 1900]
[Persuasion]

the latest of Herbert, by a scan
Limit 2
└─ TopN by Year desc
   └─ StoreScan, then check [Author = "Herbert"]
[The Dosadi Experiment Children of Dune]

nothing
Empty
[]

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrHint is returned for a hint that cannot be followed: an index that the store does not
	// have or that cannot serve the query.
	ErrHint = errors.New("query: the hint cannot be followed")
	// ErrOrder is returned for a field that the records cannot be ordered by: one that may have
	// several values for a record.
	ErrOrder = errors.New("query: cannot order by the field")
	// ErrNegative is returned for an offset, a limit or a number of keys (MaxKeys) that is less
	// than zero.
	ErrNegative = errors.New("query: negative offset, limit or number of keys")
)

Functions

func Distance

func Distance[K, V any](it iterutil.Iterator[K, *V]) (float32, bool)

Distance returns the distance of the current record of an iterator that a query with Nearest gave, as the index measures it, and false for any other iterator or when it is not at a record.

Types

type Nearness

type Nearness[K, V any] interface {
	// IndexName returns the name of the index that measures the distance.
	IndexName() string
	// Describe says how the index searches, for Explain, like "partitioned, quantized". It may be
	// empty.
	Describe() string
	// Nearest runs the search in a transaction and returns the records nearest first, at most limit
	// of them (all if limit is negative), that satisfy all the conditions, which it checks on the
	// records. If among is not nil, only its records are candidates, and Nearest closes it whatever
	// it returns. The iterator that it returns has a method Distance() float32, which is the
	// distance of its current record.
	Nearest(
		tx kv.Tx,
		among iterutil.Iterator[K, *V],
		conds []cond.Cond[V],
		limit int,
	) (iterutil.Iterator[K, *V], error)
}

Nearness orders the records of a store by their distance from something, which an index of the store measures: the nearest first. The vector indexes of package vector make one with To.

type Projection

type Projection[K, V any] struct {
	// contains filtered or unexported fields
}

Projection is a query that gives rows, which have the values of the items that were selected instead of the records. It is a definition like the query it is made from, and is planned once. An index that holds what a projection needs answers it without the records being read; see Select.

func (*Projection[K, V]) Explain

func (p *Projection[K, V]) Explain() (string, error)

Explain says how Run would run the projection, as Query.Explain does for a query. The plan can be an IndexOnlyScan, which makes the rows from the entries of an index:

Limit 10
└─ IndexOnlyScan by_author_year (in order of Year desc): 1 range, then check [Year >= 1970]

func (*Projection[K, V]) Run

func (p *Projection[K, V]) Run(tx kv.Tx) iterutil.AdvancedIterator[K, *Row[K, V]]

Run runs the projection in a transaction. The iterator must be closed. Its keys are the keys of the records, and its values are the rows.

An error of the plan, and an error while iterating, stop the iterator and are returned by its Err. A row can be used after the iterator has moved on, but not after the transaction is over.

type Query

type Query[K, V any] struct {
	// contains filtered or unexported fields
}

Query is a query on the records of a store. It is a definition, which every method leaves as it is, returning another one.

func From

func From[K, V any](store Store[K, V]) *Query[K, V]

From returns the query of all the records of a store.

func (*Query[K, V]) Count

func (q *Query[K, V]) Count(tx kv.Tx) (int, error)

Count runs the query and returns the number of records that it gives: the ones that satisfy the conditions, from the offset on and as many as the limit. No record is read where an index holds what the conditions need, and the order is not what is counted, so it is left out. It is the number of rows of a projection without items, whose plan Select(...).Explain shows.

func (*Query[K, V]) Explain

func (q *Query[K, V]) Explain() (string, error)

Explain says how Run would run the query, as a tree of the operators, from the last one to the first, as in

Limit 10, offset 20
└─ TopN by Year desc, Title
   └─ IndexLookup by_author_year: 1 range, then check ["Title" LIKE '%Dune']

The operators are:

  • Limit n, offset m: the records from the offset, as many as the limit.
  • Sort by fields, and TopN by fields: the records in the order of the fields, which are the keys if it is "primary key". TopN keeps the first records that the limit needs.
  • IndexLookup name: the entries of ranges of an index. The order that the entries give is shown in brackets if the plan relies on it, as in "(reversed, in order of Year desc)", which is then read from the end. After the colon come the number of ranges that are read and the conditions that the records are checked against, if there are any.
  • IndexOnlyScan name: like IndexLookup, for a projection (Select) that the index answers from its entries, without getting the records. It is shown instead of IndexLookup when the index holds what is selected, what is checked, and what the rows are sorted by.
  • Union: the records that one of its IndexLookup branches finds, each once, in no order. Each branch is read with the conditions of its branch of the disjunction and the other conditions of the query. "(hashed)" says that the keys it remembers are hashes.
  • Intersect: the records that all of its children find, in the order of the first. The first is an IndexLookup, which is streamed, and the conditions that are checked on the records are shown there; the others are IndexKeys name, the primary keys of the entries of ranges of an index that are remembered, shown "(hashed)" if they are kept as hashes.
  • Nearest name (how): the records in the order of their distance, as the index name measures it, which the search of the index describes in brackets. Under it is the access path whose records it ranks. Without one it checks the conditions on the records, which are shown after it as for an access path.
  • StoreScan: all the records of the store, with the conditions that they are checked against.
  • Empty: nothing is read, as no record can satisfy the conditions or none is asked for.

The same query always has the same text.

func (*Query[K, V]) FullScan

func (q *Query[K, V]) FullScan() *Query[K, V]

FullScan returns the query with a hint to scan the store. It replaces the hint that the query had: Using or UsingAll.

func (*Query[K, V]) Limit

func (q *Query[K, V]) Limit(n int) *Query[K, V]

Limit returns the query with the first n records only. There is no limit unless one is set, and a limit of 0 returns nothing.

func (*Query[K, V]) MaxKeys

func (q *Query[K, V]) MaxKeys(n int) *Query[K, V]

MaxKeys returns the query with a limit on the keys of records that a plan may hold in memory, which it does to intersect the results of several indexes (the keys of all but one) and to join them (the keys that were seen). A plan that is estimated to hold more is not chosen, nor followed if it is hinted (UsingAll). The estimate is the one of the planner, without statistics of the data. The default is 100,000 keys, and 0 allows no plan that holds keys.

func (*Query[K, V]) Nearest

func (q *Query[K, V]) Nearest(n Nearness[K, V]) *Query[K, V]

Nearest returns the query with its records in the order of their distance (the nearest first, and by key at the same distance), replacing the order that the query had (OrderBy). A record that the index has no distance for (one without a vector) is not among its records. OrderBy after Nearest replaces it too.

The search is done one of two ways, see the package documentation: it checks the conditions on the records, nearest first, or it ranks the records that an access path of the conditions finds. It panics if n is nil.

Example

ExampleQuery_Nearest orders the records by the distance of their vectors from a vector, which a vector index measures. The conditions are read with an index, and the nearest of what it finds are the results.

package main

import (
	"fmt"

	"github.com/ehsanranjbar/kvutil/field"
	"github.com/ehsanranjbar/kvutil/index"
	"github.com/ehsanranjbar/kvutil/kv"
	"github.com/ehsanranjbar/kvutil/kv/memkv"
	"github.com/ehsanranjbar/kvutil/query"

	extstore "github.com/ehsanranjbar/kvutil/store/ext"
	"github.com/ehsanranjbar/kvutil/vector"
)

type Post struct {
	Title     string
	Lang      string
	Embedding []float32
}

func main() {
	posts := extstore.New[int64, Post]("posts")

	lang := field.Path[Post, string]("Lang")
	index.On(posts, "by_lang", lang)
	byEmbedding := vector.On(posts, "by_embedding", 2, vector.Euclidean, func(p *Post) []float32 { return p.Embedding })

	db := memkv.New()
	if err := posts.Check(db); err != nil {
		panic(err)
	}
	err := db.Update(func(tx kv.Tx) error {
		store := posts.Instantiate(tx)
		for id, post := range []Post{
			{Title: "Tides", Lang: "en", Embedding: []float32{1, 2}},
			{Title: "Moon", Lang: "en", Embedding: []float32{4, 5}},
			{Title: "Marées", Lang: "fr", Embedding: []float32{1, 1.5}},
			{Title: "Waves", Lang: "en", Embedding: []float32{2, 3}},
			{Title: "Surf", Lang: "en", Embedding: []float32{1, 1}},
			{Title: "Untitled", Lang: "en"},
		} {
			if err := store.Set(int64(id+1), &post); err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		panic(err)
	}

	// The vector index is no index that the query reads for its conditions: the index of the
	// language is, and the vectors of what it finds are compared with the query. A post without
	// a vector is not among the results.
	q := query.From(posts).
		Where(lang.Eq("en")).
		Nearest(byEmbedding.To([]float32{1, 1})).
		Limit(3)

	plan, err := q.Explain()
	if err != nil {
		panic(err)
	}
	fmt.Println(plan)

	err = db.View(func(tx kv.Tx) error {
		it := q.Run(tx)
		defer it.Close()
		for ; it.Valid(); it.Next() {
			post, err := it.Value()
			if err != nil {
				return err
			}
			distance, _ := query.Distance(it)
			fmt.Printf("%.2f %s\n", distance, post.Title)
		}
		return it.Err()
	})
	if err != nil {
		panic(err)
	}

}
Output:
Limit 3
└─ Nearest by_embedding (exact)
   └─ IndexLookup by_lang: 1 range
0.00 Surf
1.00 Tides
2.24 Waves

func (*Query[K, V]) Offset

func (q *Query[K, V]) Offset(n int) *Query[K, V]

Offset returns the query without its first n records. Without an order (OrderBy) these are the first records of whatever order the plan gives.

func (*Query[K, V]) OrderBy

func (q *Query[K, V]) OrderBy(fields ...field.Component[V]) *Query[K, V]

OrderBy returns the query with the records in the order of fields, replacing the order that the query had. A field that is Desc sorts from the greatest value to the least. The records that are equal in all the fields are in the order of their keys. A field may have one value for a record at most, and a record that has none comes before the others (after them, for a field that is Desc); a field of several values is an error when the query is run. It also replaces the order of distance that Nearest gave.

func (*Query[K, V]) Run

func (q *Query[K, V]) Run(tx kv.Tx) iterutil.AdvancedIterator[K, *V]

Run runs the query in a transaction. The iterator must be closed.

An error of the plan, and an error while iterating, like one of a condition that cannot be evaluated on a record, stop the iterator and are returned by its Err.

func (*Query[K, V]) Select

func (q *Query[K, V]) Select(items ...field.Item[V]) *Projection[K, V]

Select returns the projection of the query on items: fields, or values that an index covers (index.Cover). A row has the values of the items, and the key of the record. Without items a row has the key only. The conditions, the order and the page are those of the query.

A row is made from the entries of an index, with no record read, when one index serves the query and holds what it needs of the records: every selected item (as a field of its key that has one value at most for a record, as a field that it includes with index.Including, or as a cover), every condition that it does not serve with its ranges (a comparison of a field that the index holds, or conjunctions, disjunctions and negations of such), and, when the rows are sorted, every field of the order. Anything else is read from the record, which is got for the plan: of it, the fields that the items, the conditions and the order read are decoded, and no more, if the store's codec can decode in part and those fields are known (see field.Field.Reading); the record of a row is then got from the store if it is asked for. Explain shows an IndexOnlyScan for the first. The values of a row do not depend on the plan: they are the same as those that the items have for the record.

Example

ExampleQuery_Select selects the values of the records instead of the records. An index that holds the values answers the query alone, and the records are only read when they are asked for.

package main

import (
	"fmt"
	"strings"

	"github.com/ehsanranjbar/kvutil/field"
	"github.com/ehsanranjbar/kvutil/index"
	"github.com/ehsanranjbar/kvutil/kv"
	"github.com/ehsanranjbar/kvutil/kv/memkv"
	"github.com/ehsanranjbar/kvutil/query"
	extstore "github.com/ehsanranjbar/kvutil/store/ext"
)

// ExampleQuery_Select selects the values of the records instead of the records. An index that
// holds the values answers the query alone, and the records are only read when they are asked for.
func main() {
	books := extstore.New[int64, Book]("books")

	author := field.Path[Book, string]("Author")
	year := field.Path[Book, int]("Year")
	title := field.Path[Book, string]("Title")
	// A value that is computed from a book, which an index can keep with its entries.
	shout := index.Cover("Shout", func(b *Book) string { return strings.ToUpper(b.Title) })

	// The title and the shouted title are kept with the entries, besides the author and the year
	// that are in their keys.
	index.Composite(books, "by_author_year", field.List(author, year.Desc()),
		index.Including(title), index.Covering(shout))

	db := memkv.New()
	if err := books.Check(db); err != nil {
		panic(err)
	}
	err := db.Update(func(tx kv.Tx) error {
		store := books.Instantiate(tx)
		for id, book := range []Book{
			{Title: "Dune", Author: "Herbert", Year: 1965},
			{Title: "Emma", Author: "Austen", Year: 1815},
			{Title: "Children of Dune", Author: "Herbert", Year: 1976},
			{Title: "Persuasion", Author: "Austen", Year: 1817},
			{Title: "The Dosadi Experiment", Author: "Herbert", Year: 1977},
		} {
			if err := store.Set(int64(id+1), &book); err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		panic(err)
	}

	herbert := query.From(books).Where(author.Eq("Herbert")).OrderBy(year.Desc())

	err = db.View(func(tx kv.Tx) error {
		// Select the items that the rows have: fields, and covers. The index holds all of them.
		p := herbert.Select(year, title, shout)
		plan, err := p.Explain()
		if err != nil {
			return err
		}
		fmt.Println(plan)

		rows := p.Run(tx)
		defer rows.Close()
		for ; rows.Valid(); rows.Next() {
			row, err := rows.Value()
			if err != nil {
				return err
			}
			// Get is typed by the item: the year is an int and the title a string.
			y, _ := row.Get(year)
			t, _ := row.Get(title)
			s, _ := row.Get(shout)
			_, selected := row.Get(author)
			fmt.Println(row.Key(), y, t, s, "author selected:", selected)
		}
		if err := rows.Err(); err != nil {
			return err
		}

		// A row can give the record, which is read when it is asked for.
		rows2 := herbert.Limit(1).Select(year).Run(tx)
		defer rows2.Close()
		row, err := rows2.Value()
		if err != nil {
			return err
		}
		book, err := row.Record()
		if err != nil {
			return err
		}
		fmt.Println("the latest:", book.Title, book.Year)

		// The plan is the same for the years alone, and for a condition that the index checks on
		// its entries, as it holds the year.
		fmt.Println(mustExplain(herbert.Select(year)))
		fmt.Println(mustExplain(query.From(books).Where(year.Lt(1900)).Select(author)))

		// Count does not read the records where an index holds the conditions.
		n, err := herbert.Count(tx)
		if err != nil {
			return err
		}
		fmt.Println("books of Herbert:", n)
		n, err = query.From(books).Where(author.Eq("Austen"), year.Gt(1816)).Count(tx)
		if err != nil {
			return err
		}
		fmt.Println("books of Austen after 1816:", n)
		return nil
	})
	if err != nil {
		panic(err)
	}

}

func mustExplain[K, V any](p *query.Projection[K, V]) string {
	plan, err := p.Explain()
	if err != nil {
		panic(err)
	}
	return plan
}
Output:
IndexOnlyScan by_author_year (in order of Year desc): 1 range
5 1977 The Dosadi Experiment THE DOSADI EXPERIMENT author selected: false
3 1976 Children of Dune CHILDREN OF DUNE author selected: false
1 1965 Dune DUNE author selected: false
the latest: The Dosadi Experiment 1977
IndexOnlyScan by_author_year (in order of Year desc): 1 range
IndexOnlyScan by_author_year: 1 range, then check [Year < 1900]
books of Herbert: 3
books of Austen after 1816: 1

func (*Query[K, V]) Using

func (q *Query[K, V]) Using(index string) *Query[K, V]

Using returns the query with a hint to read the index of that name. It is an error, when the query is run or explained, if the store has no such index or if the index cannot serve the query: it has some of the records only and the conditions of the query do not imply that they are among them, or it may not have an entry for a record that the query asks for (see the package documentation). It replaces the hint that the query had: FullScan or UsingAll. The name of the index of a Nearness is the hint to have its search check the conditions; see Nearest.

func (*Query[K, V]) UsingAll

func (q *Query[K, V]) UsingAll(indexes ...string) *Query[K, V]

UsingAll returns the query with a hint to read all of these indexes, each for a part of the query: an intersection of them if they serve different conditions of the query, or a union of them if a disjunction of the query has branches that each is served by one of them, and all of them are used. It is an error, when the query is run or explained, if the store lacks one of the indexes or if neither can be done with exactly these indexes, or if the plan would hold more keys than MaxKeys allows. The last of Using, UsingAll and FullScan is the hint. It is an error for a query with Nearest.

func (*Query[K, V]) Where

func (q *Query[K, V]) Where(conds ...cond.Cond[V]) *Query[K, V]

Where returns the query with more conditions, which the records must satisfy as well as the ones that the query has. Conditions of the same field that are given together are merged when the query is planned, and the ones that an index can serve are served by it.

type Row

type Row[K, V any] struct {
	// contains filtered or unexported fields
}

Row is a row of a projection: the key of a record, the values of the items that were selected, and the record, which is only read if it is asked for and the plan did not read it in full. A row stays valid while the transaction it was made in is.

func (*Row[K, V]) Distance

func (r *Row[K, V]) Distance() (float32, bool)

Distance returns the distance of the record of the row from what the query is ordered by (see Nearest), and false for a row of a query without one.

func (*Row[K, V]) Get

func (r *Row[K, V]) Get[F any](s field.Selectable[V, F]) (F, bool)

Get returns the first value that the record has for an item that was selected. It reports false if the item was not selected, or if the record has no value for it.

func (*Row[K, V]) GetAll

func (r *Row[K, V]) GetAll[F any](s field.Selectable[V, F]) ([]F, bool)

GetAll returns all the values that the record has for an item that was selected, which are several for an item that may have several. It reports false if the item was not selected, or if the record has no value for it.

func (*Row[K, V]) Key

func (r *Row[K, V]) Key() K

Key returns the key of the record of the row.

func (*Row[K, V]) Record

func (r *Row[K, V]) Record() (*V, error)

Record returns the record of the row. If the plan did not read it, it is got from the store when it is first asked for, in the transaction the query is run in; the same record is returned the next time.

type Store

type Store[K, V any] interface {
	ext.Extensible[K, V]
	// Extensions returns the extensions of the store, which the indexes are among.
	Extensions() []any
}

Store is a store whose records can be queried: one that indexes can be defined on. It is implemented by the stores of the packages ext and record.

Directories

Path Synopsis
Package sql turns the WHERE clause of a query, in the SQL of SQLite, into a condition on the records of a store, and runs it.
Package sql turns the WHERE clause of a query, in the SQL of SQLite, into a condition on the records of a store, and runs it.

Jump to

Keyboard shortcuts

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