Documentation
¶
Overview ¶
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.
Author = 'Herbert' AND Year >= 1970 AND Title LIKE '%Dune%'
What compares a field with values becomes a comparison of package cond, which an index can look records up by: =, ==, !=, <>, <, <=, >, >=, IN and BETWEEN with values, joined by AND, OR and NOT. A field that is true or false is a condition by itself, and IS NULL and IS NOT NULL tell whether a record has a value for a field. Everything else that is true or false, like LIKE and GLOB, a function, arithmetic or a comparison of two fields, is evaluated on each record by an evaluator of this package. Which of the two a part of the text becomes only depends on how it is written, never on the indexes that there are.
Quotes ¶
In the SQL of SQLite single quotes make a string and double quotes make a name:
Author = 'Herbert' // the field Author is equal to the text Herbert Author = "Herbert" // the field Author is equal to the field Herbert
so the second is an unknown field when the records have no field Herbert. Backquotes and brackets make a name too. The text is parsed by github.com/rqlite/sql, which is the only package of the module that needs it.
Fields ¶
The fields are named as they are in Go, with the case that they have, and with dots for the fields of fields: Publisher.City, "Publisher"."City" and "Publisher.City" are the same. The parser reads at most three names joined by dots, but a name in quotes may have any number of dots in it: "A.B.C.D". A name that SQL reserves, like "Order" or "Index", goes in quotes. Where a name is looked for, the first of these has it:
- the fields given with WithFields;
- the fields of the indexes of the store, if the parser is of a store, which may be computed by a function; the first index that has a field gives it;
- the fields of the struct, found by reflection as field.Reflect does.
The fields of the indexes are the ones that the store has when the first text is parsed. A field of a type that has no key codec, like a map or a struct, can be used in what is evaluated, but it cannot be compared with a value of the text.
Values ¶
A value of the text is a string in single quotes, a number (an integer is read from its digits, so it keeps its value up to 18446744073709551615), TRUE, FALSE or, for a field that is compared with it, a blob like x'ab12'. It is converted to the type of the field it is compared with as field.Convert does, so Year = '1965' and Year = 1965.0 are fine for an int, and Year = 'abc', Year = 1965.5 and a Rating of 300 for a uint8 are errors of the text. Nothing is equal to NULL, so Author = NULL is an error that says to use IS NULL.
Two values ¶
Conditions are true or false, like the ones of package cond, and not true, false or unknown like in SQL: a comparison with a value that a record does not have is false, and NOT makes it true. So Subtitle != 'x' is satisfied by a record that has no Subtitle, as NOT (Subtitle = 'x') is; the same goes for NOT IN, NOT BETWEEN, NOT LIKE and NOT GLOB. A field of several values satisfies a comparison, LIKE, GLOB, IN or BETWEEN if one of its values does, and a function or an operator of numbers or text that is given one is applied to each of its values.
Evaluated ¶
The evaluator works with numbers (integers stay integers, and a division by zero has no value), text, true and false, bytes, times, and no value. It has the operators + - * / % and || (text), the comparisons, IS and IS NOT, IN with a list or with a field of several values, BETWEEN, LIKE with % and _ (ASCII letters in either case, with ESCAPE), GLOB with * and ?, CASE, and the functions lower, upper, length, abs, substr, instr, trim, ltrim, rtrim, round, coalesce and ifnull, with the meanings that they have in SQLite, but for lower and upper, which change all letters and not only those of ASCII. The length of a field of several values is the number of its values. A function that is given the name of a function there is not is ErrUnknownFunction, and one that is given the wrong number or kinds of arguments is ErrType. What it does not have, like subqueries, CAST, COLLATE, MATCH, REGEXP, bit operators and parameters, is a syntax error. The names of functions are not case sensitive, and the text that the parser prints for a call, which is what a condition is shown as, has them in lower case.
The types of what is evaluated are checked when the text is parsed: the ones that a text can be known to have, which are bool, number, text, bytes and time, and any for a field of an interface type. A text that has something that is not true or false where a condition is expected (Author, 5, Year + 1, lower(Author)), or that does arithmetic on text, is an error then. What can only be known on a record, like a field of an interface type that is not true or false where it is expected to be, is not true for it, or is ErrEvaluation from Match if it is the whole of a condition.
Functions of your own ¶
A parser can be given functions that a text calls like the ones above, with WithFunctions. A function is made from a Go function with Func1, Func2 or Func3, or from the types of its arguments with FuncN, and the functions are put in a set:
functions := sql.Functions{}.
Add(sql.Func1("initial", func(s string) string { return s[:1] })).
Add(sql.Func2("age", func(year, now int) int { return now - year }))
parser := sql.For(books, sql.WithFunctions(functions))
parser.Query(tx, `initial(Author) = 'H' AND age(Year, 2000) > 30`)
A call is checked when the text is parsed, as the calls of the functions above are: the name (ErrUnknownFunction), the number of arguments and their kinds (ErrType), and, where the call stands for a condition, that its result is true or false (ErrType). A function that fails fails the evaluation with its error, wrapped in ErrEvaluation, as Match returns it and as the iterator of a query does. A function is applied to each value of a field of several values. The functions of a parser are not seen by any other.
A function must be deterministic: it must return the same for the same arguments, always. The entries of an index that is defined on an expression or on a condition that calls it are computed again to be removed, and the records are found by them. If what a function computes changes, give it a new version (Function.WithVersion), and the indexes that call it are built again by the migration.
Indexes of expressions and of conditions ¶
Expr defines a field whose values are those of an expression of the record, to index by:
index.On(books, "by_author", sql.Expr[Book, string](`lower(Author)`))
and a query that compares the same expression with values reads the index, as it does for a field that is named: lower(Author) = 'herbert', and the other comparisons of the first section above, whatever the spelling of the expression is, so LOWER( "Author" ) is the same. A parser finds the field in the indexes of the store, or is given it with WithFields. An expression that no field is of is evaluated on the records, as it is without an index.
Where is the option of an index to have the records that satisfy a condition only:
index.On(books, "in_print_by_year", year, sql.Where[Book](`InPrint AND Year >= 1900`))
A query reads such an index if its conditions imply the condition of the index, which package query decides conservatively: InPrint AND Year > 1950 does, and InPrint OR Year > 1950 does not. A condition that is not a comparison is implied by the identical text only, in the form the parser prints it (lower case for the functions, and the same as the parser prints everywhere).
Example ¶
Example parses the WHERE clauses of queries on a store, and runs them with an index and without one.
package main
import (
"errors"
"fmt"
"strings"
"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/sql"
extstore "github.com/ehsanranjbar/kvutil/store/ext"
)
type Novel struct {
Title string
Author string
Year int
Tags []string
InPrint bool
}
func main() {
novels := extstore.New[int64, Novel]("novels")
title := field.Path[Novel, string]("Title")
// The title is kept with the entries, so a query can select it without reading the novels.
index.Composite(novels, "by_author_year", field.List(
field.Path[Novel, string]("Author"),
field.Path[Novel, int]("Year"),
), index.Including(title))
// A field that is computed is known to the parser by the index that is defined on it.
index.On(novels, "by_decade", field.Of("Decade", func(n *Novel) int { return n.Year / 10 * 10 }))
db := memkv.New()
if err := novels.Check(db); err != nil {
panic(err)
}
err := db.Update(func(tx kv.Tx) error {
store := novels.Instantiate(tx)
for id, novel := range []Novel{
{Title: "Dune", Author: "Herbert", Year: 1965, Tags: []string{"scifi", "classic"}, InPrint: true},
{Title: "Emma", Author: "Austen", Year: 1815, Tags: []string{"classic"}, InPrint: true},
{Title: "Children of Dune", Author: "Herbert", Year: 1976, Tags: []string{"scifi"}},
{Title: "The Dosadi Experiment", Author: "Herbert", Year: 1977, InPrint: true},
} {
if err := store.Set(int64(id+1), &novel); err != nil {
return err
}
}
return nil
})
if err != nil {
panic(err)
}
// The fields are the ones of the indexes of the store and the ones of the struct.
parser := sql.For(novels)
err = db.View(func(tx kv.Tx) error {
query := func(where string) {
explain, err := parser.Explain(where)
if err != nil {
panic(err)
}
it, err := parser.Query(tx, where)
if err != nil {
panic(err)
}
titles, err := iterutil.Of(it).
Map(func(_ int64, n *Novel) (string, error) { return n.Title, nil }).
Values()
if err != nil {
panic(err)
}
fmt.Printf("%s\n %s\n %v\n", where, strings.ReplaceAll(explain, "\n", "\n "), titles)
}
// The comparisons of the fields of an index are served by it, and the rest of the
// text is checked on the novels that it finds.
query(`Author = 'Herbert' AND Year >= 1970 AND Title LIKE '%dune'`)
// Nothing serves a condition that is about a part of a field alone, so the store is scanned.
query(`Decade = 1970 OR ('classic' IN Tags AND NOT Year >= 1900)`)
query(`length(Title) > 10 AND InPrint`)
// The condition itself is a filter of anything that has records.
c, err := parser.Parse(`Author = 'Herbert' AND Year >= 1970 AND Title LIKE '%dune'`)
if err != nil {
return err
}
fmt.Println("condition:", c)
// Where returns a query, so it can select values and count like any other: the titles
// come from the index alone here.
q, err := parser.Where(`Author = 'Herbert' AND Year >= 1970`)
if err != nil {
return err
}
selection := q.Select(title)
plan, err := selection.Explain()
if err != nil {
return err
}
fmt.Println("selected:", plan)
rows := selection.Run(tx)
defer rows.Close()
for ; rows.Valid(); rows.Next() {
row, err := rows.Value()
if err != nil {
return err
}
t, _ := row.Get(title)
fmt.Println(" ", row.Key(), t)
}
if err := rows.Err(); err != nil {
return err
}
n, err := q.Count(tx)
if err != nil {
return err
}
fmt.Println("count:", n)
return nil
})
if err != nil {
panic(err)
}
// What cannot be right for any novel is an error of the text. Double quotes make a name.
for _, where := range []string{
`Athor = 'Herbert'`,
`Author = "Herbert"`,
`Year = 'soon'`,
`contains(Title, 'Dune')`,
`Year = 1965 AND`,
`Year + 1`,
} {
_, err := parser.Parse(where)
fmt.Printf("%s: %v %v\n", where,
errors.Is(err, sql.ErrUnknownField) || errors.Is(err, sql.ErrType) ||
errors.Is(err, sql.ErrUnknownFunction) || errors.Is(err, sql.ErrSyntax), err == nil)
}
_, err = parser.Parse(`Year = 'soon'`)
fmt.Println(err)
}
Output: Author = 'Herbert' AND Year >= 1970 AND Title LIKE '%dune' IndexLookup by_author_year: 1 range, then check ["Title" LIKE '%dune'] [Children of Dune] Decade = 1970 OR ('classic' IN Tags AND NOT Year >= 1900) StoreScan, then check [(Decade = 1970) or ((Tags = "classic") and (not (Year >= 1900)))] [Emma Children of Dune The Dosadi Experiment] length(Title) > 10 AND InPrint StoreScan, then check [length("Title") > 10; InPrint = true] [The Dosadi Experiment] condition: (Author = "Herbert") and (Year >= 1970) and ("Title" LIKE '%dune') selected: IndexOnlyScan by_author_year: 1 range 3 Children of Dune 4 The Dosadi Experiment count: 2 Athor = 'Herbert': true false Author = "Herbert": true false Year = 'soon': true false contains(Title, 'Dune'): true false Year = 1965 AND: true false Year + 1: true false sql: type mismatch: field Year: cannot use "soon" as a value of the type int: it is not a whole number that the type has
Example (Functions) ¶
Example_functions gives a parser functions of its own, which the texts of its queries call as they call the ones that there always are.
package main
import (
"fmt"
"strings"
"github.com/ehsanranjbar/kvutil/iterutil"
"github.com/ehsanranjbar/kvutil/kv"
"github.com/ehsanranjbar/kvutil/kv/memkv"
"github.com/ehsanranjbar/kvutil/query/sql"
extstore "github.com/ehsanranjbar/kvutil/store/ext"
)
type Novel struct {
Title string
Author string
Year int
Tags []string
InPrint bool
}
func main() {
novels := extstore.New[int64, Novel]("novels")
// A function is made from a Go function: its types are the ones of the Go function. It
// must be deterministic. Its version says what it computes, and is a part of what an index
// that calls it is identified by.
functions := sql.Functions{}.
Add(sql.Func1("initial", func(s string) string { return strings.ToUpper(s[:1]) }).WithVersion("1")).
Add(sql.Func2("age", func(year, now int) int { return now - year })).
// FuncN is for the types that Go has no type for, and for functions that fail.
Add(sql.FuncN("century", []sql.Type{sql.Number}, false, sql.Integer, func(args []any) (any, error) {
year, ok := args[0].(int64)
if !ok {
return nil, fmt.Errorf("%v is not a year", args[0])
}
return (year-1)/100 + 1, nil
}))
parser := sql.For(novels, sql.WithFunctions(functions))
db := memkv.New()
if err := novels.Check(db); err != nil {
panic(err)
}
err := db.Update(func(tx kv.Tx) error {
store := novels.Instantiate(tx)
for id, novel := range []Novel{
{Title: "Dune", Author: "Herbert", Year: 1965},
{Title: "Emma", Author: "Austen", Year: 1815},
{Title: "Persuasion", Author: "Austen", Year: 1817},
} {
if err := store.Set(int64(id+1), &novel); err != nil {
return err
}
}
return nil
})
if err != nil {
panic(err)
}
err = db.View(func(tx kv.Tx) error {
for _, where := range []string{
`initial(Author) = 'A' AND age(Year, 2000) > 180`,
`INITIAL(Title) IN ('D', 'E') AND century(Year) = 20`,
`century(Year) = 19 OR century(Year) = 21`,
} {
it, err := parser.Query(tx, where)
if err != nil {
return err
}
titles, err := iterutil.Of(it).
Map(func(_ int64, n *Novel) (string, error) { return n.Title, nil }).
Values()
if err != nil {
return err
}
fmt.Printf("%s\n %v\n", where, titles)
}
// A function is checked when the text is parsed, as the ones that always are.
for _, where := range []string{`initial(Year) = 'A'`, `age(Year) > 1`, `initial(Author)`, `shout(Author) = 'A'`} {
_, err := parser.Parse(where)
fmt.Printf("%s: %v\n", where, err)
}
// A function that fails fails the query, with its error.
it, err := parser.Query(tx, `century(Year) = 1 OR century(NULL) = 1`)
if err != nil {
return err
}
defer it.Close()
for ; it.Valid(); it.Next() {
}
fmt.Println(it.Err())
return nil
})
if err != nil {
panic(err)
}
}
Output: initial(Author) = 'A' AND age(Year, 2000) > 180 [Emma Persuasion] INITIAL(Title) IN ('D', 'E') AND century(Year) = 20 [Dune] century(Year) = 19 OR century(Year) = 21 [Emma Persuasion] initial(Year) = 'A': sql: type mismatch: argument 1 of initial is a number, which it does not take: initial("Year") age(Year) > 1: sql: type mismatch: age takes 2 arguments, not 1 initial(Author): sql: type mismatch: initial("Author") is a string, not true or false shout(Author) = 'A': sql: unknown function "shout" failed to check (century("Year") = 1) or (century(NULL) = 1): sql: evaluation failed: function century: <nil> is not a year
Example (Indexes) ¶
Example_indexes defines indexes on an SQL expression and on an SQL condition. A query reads them when it compares the same expression with values, and when its conditions imply the condition of the index.
package main
import (
"fmt"
"strings"
"github.com/ehsanranjbar/kvutil/field"
"github.com/ehsanranjbar/kvutil/index"
"github.com/ehsanranjbar/kvutil/query/sql"
extstore "github.com/ehsanranjbar/kvutil/store/ext"
)
type Novel struct {
Title string
Author string
Year int
Tags []string
InPrint bool
}
func main() {
novels := extstore.New[int64, Novel]("novels")
year := field.Path[Novel, int]("Year")
// The path of the field is the expression as the parser prints it.
lowerAuthor := sql.Expr[Novel, string](`LOWER(Author)`)
fmt.Println("field:", lowerAuthor.Path())
index.On(novels, "by_author", lowerAuthor)
// Only the novels that are in print and are not too old are in this index.
recent := index.On(novels, "recent_by_year", year, sql.Where[Novel](`InPrint AND Year >= 1900`))
fmt.Println("where:", recent.Descriptor().Where)
parser := sql.For(novels)
for _, where := range []string{
`lower(Author) = 'herbert'`,
`'austen' = LOWER( "Author" )`,
`lower(Author) != 'herbert'`,
`upper(Author) = 'HERBERT'`,
`InPrint AND Year >= 1970`,
`InPrint AND Year > 1800`,
`Year >= 1970`,
`InPrint OR Year >= 1970`,
} {
explain, err := parser.Explain(where)
if err != nil {
panic(err)
}
fmt.Printf("%s\n %s\n", where, strings.ReplaceAll(explain, "\n", "\n "))
}
// An index of some of the novels cannot be asked for by a query that is about others.
q, err := parser.Where(`Year >= 1970`)
if err != nil {
panic(err)
}
_, err = q.Using("recent_by_year").Explain()
fmt.Println(err)
}
Output: field: lower("Author") where: (InPrint = true) and (Year >= 1900) lower(Author) = 'herbert' IndexLookup by_author: 1 range 'austen' = LOWER( "Author" ) IndexLookup by_author: 1 range lower(Author) != 'herbert' StoreScan, then check [not (lower("Author") = "herbert")] upper(Author) = 'HERBERT' StoreScan, then check [upper("Author") = 'HERBERT'] InPrint AND Year >= 1970 IndexLookup recent_by_year: 1 range, then check [InPrint = true] InPrint AND Year > 1800 StoreScan, then check [InPrint = true; Year > 1800] Year >= 1970 StoreScan, then check [Year >= 1970] InPrint OR Year >= 1970 StoreScan, then check [(InPrint = true) or (Year >= 1970)] query: the hint cannot be followed: the index "recent_by_year" cannot serve the query: it has the records that satisfy (InPrint = true) and (Year >= 1900) only, which the conditions do not imply
Index ¶
- Variables
- func Expr[V, F any](text string, opts ...Option[V]) field.Field[V, F]
- func ParseWhere[V any](where string, opts ...Option[V]) (cond.Cond[V], error)
- func Where[V any](text string, opts ...Option[V]) index.Option[V]
- type Function
- type Functions
- type FunctionsOption
- type Option
- type Parser
- type Store
- type Type
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrSyntax is returned for a text that is not a condition as it is written, or that uses // what this package does not have. ErrSyntax = errors.New("sql: syntax error") // ErrUnknownField is returned for a text that names a field that the records do not have. ErrUnknownField = errors.New("sql: unknown field") // ErrUnknownFunction is returned for a text that calls a function that there is not. ErrUnknownFunction = errors.New("sql: unknown function") // ErrType is returned for a text that has something of a type that its place cannot have: // a value that the field that it is compared with cannot have, a function that is given // the wrong number or types of arguments, or something that is not true or false where a // condition is expected. ErrType = errors.New("sql: type mismatch") // ErrEvaluation is returned by the Match of a condition for a part of the text that is // evaluated and that is not true or false for a record, which can only be the case for a // field of an interface type. ErrEvaluation = errors.New("sql: evaluation failed") )
Functions ¶
func Expr ¶
Expr defines a field whose value is an SQL expression of a record, like lower(Author), to index records by. The path of the field is the expression in a canonical text: the one that the parser prints for it, with the names of the functions in lower case, so lower(Author), LOWER("Author") and lower( Author ) are all lower("Author"). A query that compares an expression of that text with values is served by an index on the field (see the package documentation), and the parsers of the stores that the index is defined on find the field.
byAuthor := sql.Expr[Book, string](`lower(Author)`) index.On(books, "by_author", byAuthor) sql.For(books).Explain(`LOWER(Author) = 'herbert'`) // IndexLookup by_author: 1 range
The values of the field are those of the expression: no value if it has none for a record (a field it names that is a nil pointer, NULL, a function that has no value for its arguments), one value, or several if it names a field of several values (then the field is Multi). They are converted to F as field.Convert does; the kinds of the expression and of F must agree (a number for a number, a text for a string, and so on). The field is not Always.
A record whose expression cannot be evaluated or converted is not left out of the index: setting it fails, with the error (see field.Computed). The functions that the expression calls must be deterministic; give the field functions with WithFunctions, and see Function for versions. An index on the field is identified by the canonical text, and by the versions of the functions that the expression calls, so it is built again when either changes.
It panics on a text that does not parse, that is not an expression of a type that F converts from, or that names a field or a function that there is not, as these are mistakes of the definition of the program.
func ParseWhere ¶
ParseWhere parses a WHERE clause, without the word WHERE, for records that are not in a store. The fields are found in the struct V by reflection, as field.Reflect does, and in the ones that WithFields gives.
func Where ¶
Where is the index option that keeps only the records that satisfy an SQL condition, as index.Where does for a condition written in Go:
index.On(books, "in_print_by_year", year, sql.Where[Book](`InPrint AND Year >= 1900`))
The text is translated as the text of a query is, to comparisons that queries can be matched against and to conditions that are evaluated. A query reads the index only if its conditions imply the condition of the index (see the package documentation of query): the comparisons by implication, anything else if the query has the identical text, which is the same canonical text that Expr has. The index is identified by that text, and by the versions of the functions that the text calls, so it is built again when either changes. The functions must be deterministic. An error while checking the condition for a record fails the setting of the record.
The fields of the text are the ones of the struct, found by reflection, and the ones that WithFields gives; functions come from WithFunctions. It panics on a text that does not parse, as that is a mistake of the definition of the program.
Types ¶
type Function ¶
type Function struct {
// contains filtered or unexported fields
}
Function is a function that a text can call, besides the ones that there always are: lower, upper, length, abs, substr, instr, trim, ltrim, rtrim, round, coalesce and ifnull. Functions are made with Func1, Func2, Func3 and FuncN, and given to a parser with WithFunctions.
A function must be deterministic: it must return the same for the same arguments, whenever it is called. An index that is defined on an expression or on a condition that calls it keeps the results in its entries, and finds the records by them, and they are computed again to be removed. The results must not depend on the time, on random numbers or on anything that changes. If what a function computes changes, give it another version with WithVersion, so that the indexes that depend on it are built again.
Like the functions that there always are, a function that is given a field of several values is applied to each of its values, and its results are the values of the result.
func Func1 ¶
Func1 makes a function of one argument. The types of the argument and of the result are those of A and of R: bool, the integers, the floats, string, []byte, time.Time, the types that are defined on them, and any (Any). It panics for a Go type that the evaluator has no Type for.
The value of an argument is converted to A as field.Convert does, so that a whole number that is written as 5.0 can be given to an int; one that cannot be converted, like 5.5 for an int, is an ErrEvaluation. A function that is given no value for an argument is not called, and has no value as its result, like the functions that there always are.
func FuncN ¶
func FuncN(name string, args []Type, variadic bool, result Type, f func(args []any) (any, error)) Function
FuncN makes a function from the types of its arguments, for one that takes more than three or a different number of them, or of the types that the Go ones do not have, like Number. If variadic is set the last type is the type of the last argument and of any number of arguments after it, so the function takes the number of types that there are or more. The function is given the values as the evaluator has them: nil for no value, an int64 or a float64 for a number, a string, a bool, a []byte, a time.Time. It returns one of those (or nil for no value) of the type that it is declared to return, or an error, which makes the evaluation of the text fail with ErrEvaluation.
The function is called when an argument has no value, unlike the ones that Func1, Func2 and Func3 make, so that it can tell what to do about it. It panics if there is no type for a variadic function, or if f is nil.
func (Function) Name ¶
Name returns the name of the function as it was given, which the text calls it by in any case.
func (Function) Version ¶
Version returns the version of the function, which is empty if it has none.
func (Function) WithVersion ¶
WithVersion returns the function with a version, which says what it computes. The version is a part of what an index on an expression or on a condition that calls the function is identified by, as name@version: the index is built again when the version changes.
type Functions ¶
type Functions struct {
// contains filtered or unexported fields
}
Functions is a set of functions that a text can call. It is a value that is not changed by what is done with it: Add returns another set. The zero value is the empty set.
func (Functions) Add ¶
Add returns the set with a function more. The names of functions are not case sensitive, like the names of the functions that there always are. It panics if the name is empty, if the set has a function of that name, or if it is the name of one of the functions that there always are: such mistakes are in the definition of the program.
type FunctionsOption ¶
type FunctionsOption struct {
// contains filtered or unexported fields
}
FunctionsOption is the option that WithFunctions returns. It is an Option of any type of records.
func WithFunctions ¶
func WithFunctions(fs Functions) FunctionsOption
WithFunctions gives the parser functions that its texts can call, besides the ones that there always are. The parser does not see the functions of any other parser. It replaces the functions that an option before it gave.
It does not depend on the type of the records, so it is a plain value that every parser takes.
type Option ¶
type Option[V any] interface { // contains filtered or unexported methods }
Option is an option of a parser of the records of type V. V is not used by the options that do not depend on it, like the one of WithFunctions, which are an Option of every V.
func WithFields ¶
WithFields gives the parser fields that it cannot find itself, which are the ones that are computed by a function and that no index is defined on. A field that is given is used instead of the one of the same path that the parser would find.
type Parser ¶
type Parser[K, V any] struct { // contains filtered or unexported fields }
Parser parses the WHERE clauses of queries on the records of a store, and runs them. It can be used from several goroutines.
func For ¶
For returns a parser of the WHERE clauses of queries on the records of a store.
A field that a text names is one of the fields that the indexes of the store are defined on, which a comparison must be written with for the index to serve it, and which may be computed by a function. If no index has the field, it is found in the struct V by reflection, as field.Reflect does. The indexes are the ones that the store has when a text is first parsed.
func (*Parser[K, V]) Explain ¶
Explain says how Query would run a WHERE clause, as query.Query.Explain does:
IndexLookup by_author_year: 1 range, then check ["Title" LIKE '%Dune']
func (*Parser[K, V]) Parse ¶
Parse parses a WHERE clause, without the word WHERE. It returns an error for a text that cannot be right for any record: one that is not written as a condition, that names a field or a function that there is not, or that compares a field with a value that it cannot have.
func (*Parser[K, V]) Query ¶
Query parses a WHERE clause and returns the records that satisfy it, in no order that is promised (the order of the index that serves it, or of the keys of a scan): it is Where and then Run, and an order is given to the query of Where. An error of the text is returned right away, and an error while iterating, like one of a condition that cannot be evaluated on a record, stops the iterator and is returned by its Err. The iterator must be closed.
func (*Parser[K, V]) Where ¶
Where parses a WHERE clause and returns the query of the records of the store that satisfy it. The ordering and the paging of the records are not a part of the text: they are set on the query with OrderBy, Offset and Limit, and the query is planned, with the indexes of the store that serve the condition, when it is run or explained.
type Store ¶
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.
type Type ¶
type Type int
Type is a type of the values that a text is evaluated with, which a function is declared to take and to return.
const ( // Bool is true or false. Bool Type = iota + 1 // Integer is a whole number. Integer // Real is a number that may have a fraction. Real // Number is an integer or a real: any number. A function can take it, and it is what the // evaluator calls the type of both. Number // Text is a string. Text // Bytes is a slice of bytes. Bytes // Time is a time.Time. Time // Any is a value of any type, which is only known when there is a record. Any )