Documentation
¶
Index ¶
Constants ¶
const ( EQ = Op("eq") // = NEQ = Op("neq") // <> LT = Op("lt") // < GT = Op("gt") // > LTE = Op("lte") // <= GTE = Op("gte") // >= LIKE = Op("like") // LIKE "PATTERN" NLIKE = Op("nlike") // NOT LIKE "PATTERN" ILIKE = Op("ilike") // ILIKE "PATTERN" (case-insensitive, PostgreSQL) NILIKE = Op("nilike") // NOT ILIKE "PATTERN" (case-insensitive, PostgreSQL) REGEX = Op("regex") // REGEXP "PATTERN" (MySQL/PostgreSQL/SQLite with extension) IN = Op("in") // IN (v1, v2, ...) NIN = Op("nin") // NOT IN (v1, v2, ...) BETWEEN = Op("between") // BETWEEN v1 AND v2 NBETWEEN = Op("nbetween") // NOT BETWEEN v1 AND v2 ISNULL = Op("isnull") // IS NULL ISNOTNULL = Op("isnotnull") // IS NOT NULL OR = Op("or") // disjunction AND = Op("and") // conjunction NOR = Op("nor") // negated disjunction (NOT (... OR ...)) NOT = Op("not") // negation of a sub-condition )
Operators that support by rql.
const ( DefaultTagName = "rql" DefaultOpPrefix = "$" DefaultFieldSep = "_" DefaultLimit = 25 DefaultMaxLimit = 100 Offset = "offset" Limit = "limit" )
Default values for configuration.
const ( // DialectMySQL targets MySQL. ILIKE/NILIKE are translated to // `LOWER(col) LIKE LOWER(?)` / `LOWER(col) NOT LIKE LOWER(?)`. // REGEX uses the `REGEXP` keyword. DialectMySQL = "mysql" // DialectPostgreSQL targets PostgreSQL. ILIKE/NILIKE are emitted natively. // REGEX is translated to the `~` operator. DialectPostgreSQL = "postgres" // DialectSQLite targets SQLite. Same as MySQL for ILIKE/NILIKE/REGEX, // but REGEX requires the `regexp` extension to be loaded. DialectSQLite = "sqlite" )
Database dialects supported by rql. The dialect controls which operators are registered for each field type and how dialect-specific operators (ILIKE/NILIKE/REGEX) are translated to SQL.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Config ¶
type Config struct {
// TagName is an optional tag name for configuration. t defaults to "rql".
TagName string
// Model is the resource definition. The parser is configured based on the its definition.
// For example, given the following struct definition:
//
// type User struct {
// Age int `rql:"filter,sort"`
// Name string `rql:"filter"`
// }
//
// In order to create a parser for the given resource, you will do it like so:
//
// var QueryParser = rql.MustNewParser(
// Model: User{},
// })
//
Model interface{}
// OpPrefix is the prefix for operators. it defaults to "$". for example, in order
// to use the "gt" (greater-than) operator, you need to prefix it with "$".
// It similar to the MongoDB query language.
OpPrefix string
// FieldSep is the separator for nested fields in a struct. For example, given the following struct:
//
// type User struct {
// Name string `rql:"filter"`
// Address struct {
// City string `rql:"filter"“
// }
// }
//
// We assume the schema for this struct contains a column named "address_city". Therefore, the default
// separator is underscore ("_"). But, you can change it to "." for convenience or readability reasons.
// Then you will be able to query your resource like this:
//
// {
// "filter": {
// "address.city": "DC"
// }
// }
//
// The parser will automatically convert it to underscore ("_"). If you want to control the name of
// the column, use the "column" option in the struct definition. For example:
//
// type User struct {
// Name string `rql:"filter,column=full_name"`
// }
//
FieldSep string
// ColumnFn is the function that translate the struct field string into a table column.
// For example, given the following fields and their column names:
//
// FullName => "full_name"
// HTTPPort => "http_port"
//
// It is preferred that you will follow the same convention that your ORM or other DB helper use.
// For example, If you are using `gorm` you want to se this option like this:
//
// var QueryParser = rql.MustNewParser(
// ColumnFn: gorm.ToDBName,
// })
//
ColumnFn func(string) string
// Log the the logging function used to log debug information in the initialization of the parser.
// It defaults `to log.Printf`.
Log func(string, ...interface{})
// DefaultLimit is the default value for the `Limit` field that returns when no limit supplied by the caller.
// It defaults to 25.
DefaultLimit int
// LimitMaxValue is the upper boundary for the limit field. User will get an error if the given value is greater
// than this value. It defaults to 100.
LimitMaxValue int
// DefaultSort is the default value for the 'Sort' field that returns when no sort expression is supplied by the caller.
// It defaults to an empty string slice.
DefaultSort []string
// Dialect controls how dialect-specific operators (ILIKE/NILIKE/REGEX) are
// translated to SQL. Supported values: DialectMySQL, DialectPostgreSQL,
// DialectSQLite. When empty, rql emits the raw SQL keyword (ILIKE/REGEXP)
// and lets the underlying database reject it if unsupported.
//
// Recommended: set it explicitly to match your production database.
Dialect string
}
Config is the configuration for the parser.
type Params ¶
type Params struct {
// Limit represents the number of rows returned by the SELECT statement.
Limit int
// Offset specifies the offset of the first row to return. Useful for pagination.
Offset int
// Select contains the expression for the `SELECT` clause defined in the Query.
Select string
// Distinct, when true, indicates the caller should emit `SELECT DISTINCT`.
Distinct bool
// Sort used as a parameter for the `ORDER BY` clause. For example, "age desc, name".
Sort string
// FilterExp and FilterArgs come together and used as a parameters for the `WHERE` clause.
//
// examples:
// 1. Exp: "name = ?"
// Args: "a8m"
//
// 2. Exp: "name = ? AND age >= ?"
// Args: "a8m", 22
FilterExp string
FilterArgs []interface{}
// GroupExp contains the comma-separated field list for the `GROUP BY` clause.
// Empty string means no grouping. Example: "city, country".
GroupExp string
// HavingExp and HavingArgs come together and are used as parameters for the `HAVING` clause.
// They follow the same structure as FilterExp/FilterArgs.
HavingExp string
HavingArgs []interface{}
}
Params is the parser output after calling to `Parse`. You should pass its field values to your query tool. For example, Suppose you use `gorm`:
params, err := p.Parse(b)
if err != nil {
return nil, err
}
var users []User
err := db.Where(params.FilterExp, params.FilterArgs...).
Order(params.Sort).
Find(&users).
Error
if err != nil {
return nil, err
}
return users, nil
type ParseError ¶
type ParseError struct {
// contains filtered or unexported fields
}
ParseError is type of error returned when there is a parsing problem.
func (ParseError) Error ¶
func (p ParseError) Error() string
type Parser ¶
type Parser struct {
Config
// contains filtered or unexported fields
}
A Parser parses various types. The result from the Parse method is a Param object. It is safe for concurrent use by multiple goroutines except for configuration changes.
func MustNewParser ¶
MustNewParser is like NewParser but panics if the configuration is invalid. It simplifies safe initialization of global variables holding a resource parser.
type Query ¶
type Query struct {
// Limit must be > 0 and <= to `LimitMaxValue`.
Limit int `json:"limit,omitempty"`
// Offset must be >= 0.
Offset int `json:"offset,omitempty"`
// Select contains the list of expressions define the value for the `SELECT` clause.
// For example:
//
// params, err := p.Parse([]byte(`{
// "select": ["name", "age"]
// }`))
//
Select []string `json:"select,omitempty"`
// Sort contains list of expressions define the value for the `ORDER BY` clause.
// In order to return the rows in descending order you can prefix your field with `-`.
// For example:
//
// params, err := p.Parse([]byte(`{
// "sort": ["name", "-age", "+redundant"]
// }`))
//
Sort []string `json:"sort,omitempty"`
// Filter is the query object for building the value for the `WHERE` clause.
// The full documentation of the supported operators is writtern in the README.
// An example for filter object:
//
// params, err := p.Parse([]byte(`{
// "filter": {
// "account": { "$like": "%github%" },
// "$or": [
// { "city": "TLV" },
// { "city": "NYC" }
// ]
// }
// }`))
//
Filter map[string]interface{} `json:"filter,omitempty"`
// Group contains the list of fields for the `GROUP BY` clause. Each name must
// be a registered, filterable field. Example:
//
// params, err := p.Parse([]byte(`{
// "group": ["city", "country"]
// }`))
//
// Emits `GROUP BY city, country`.
Group []string `json:"group,omitempty"`
// Having is a query object for building the `HAVING` clause. It uses the same
// operator syntax as Filter, but the referenced fields should be aggregate
// expressions written via the `column=` tag option on dedicated fields
// (e.g. `Count int \`rql:"filter,column=COUNT(*)"\“).
//
// Example:
//
// params, err := p.Parse([]byte(`{
// "having": { "count": { "$gt": 10 } }
// }`))
//
Having map[string]interface{} `json:"having,omitempty"`
// Distinct, when true, emits `SELECT DISTINCT` instead of `SELECT`.
// It is ignored if `Select` is empty.
Distinct bool `json:"distinct,omitempty"`
}
Query is the decoded result of the user input.
func (Query) MarshalEasyJSON ¶
MarshalEasyJSON supports easyjson.Marshaler interface
func (Query) MarshalJSON ¶
MarshalJSON supports json.Marshaler interface
func (*Query) UnmarshalEasyJSON ¶
UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (*Query) UnmarshalJSON ¶
UnmarshalJSON supports json.Unmarshaler interface