Documentation ¶
Index ¶
Constants ¶
const ( EQ = Op("eq") // = NEQ = Op("neq") // <> LT = Op("lt") // < GT = Op("gt") // > LTE = Op("lte") // <= GTE = Op("gte") // >= IN = Op("in") // IN "PATTERN" LIKE = Op("like") // LIKE "PATTERN" (case sensitive LIKE) ILIKE = Op("ilike") // ILIKE "PATTERN" (case insensitive LIKE) ISNULL = Op("isnull") // IS NULL ISNOTNULL = Op("isnotnull") // IS NOT NULL NOT = Op("not") // disjunction OR = Op("or") // disjunction AND = Op("and") // conjunction COUNT = Op("count") // aggregation SUM = Op("sum") // aggregation AVG = Op("avg") // aggregation MIN = Op("min") // aggregation MAX = Op("max") // aggregation BALANCE = Op("balance") // aggregation TRUNC = Op("trunc") // aggregation EXTRACT = Op("extract") // aggregation ROUND = Op("round") // aggregation )
Operators that support by rql.
const ( DefaultTagName = "rql" DefaultOpPrefix = "$" DefaultFieldSep = "_" DefaultJsonbSep = "->" DefaultJsonbLastSep = "->>" DefaultLimit = 25 DefaultMaxLimit = 100 Offset = "offset" Limit = "limit" )
Default values for configuration.
Variables ¶
This section is empty.
Functions ¶
func CamelCaseToSnakeCase ¶
camelCaseToSnakeCase converts a camelCase string to snake_case.
func Column ¶
Column is the default function that converts field name into a database column. It used to convert the struct fields into their database names. For example:
Username => username FullName => full_name HTTPCode => http_code
func PascalToCamelCase ¶
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 // JsonbSep replaces the field Separator with JsonbSep to access nested jsonb objects in postgres JsonbSep string // replaces the last jsonbSep with JsonbLastSep to access nested jsonb objects in postgres without quotes JsonbLastSep string // InterpretFieldSepAsNestedJsonbObject replaces the fieldSep with -> to access nested jsonb objects in postgres InterpretFieldSepAsNestedJsonbObject bool // 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" // CreatedAt => "createdAt" // // 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 // ColumnFnDB 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" ColumnNameFn func(string) string // add table prefix to all column // createdAt => table.createdAt Table string // createdAt => users.createdAt MapColumnName map[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 // If true logs won't be printed to stdout DoNotLog bool }
Config is the configuration for the parser.
type ExpString ¶
type ExpString string
func (ExpString) PostgresString ¶
for i, v := range params.FilterArgs { b.WriteString(split[i]) b.Arg(v) } b.WriteString(split[len(split)-1]) }),
)
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. If group is not empty, values are automatically replaced by the group string and the aggregate string. Select []string // Aggregate contains additional aggregated `SELECT` expressions that can be optionally appended to the select statement. Aggregate []string // Update contains the expression for the `UPDATE` clause defined in the Query. Update []string // 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 ExpString FilterArgs []interface{} // GroupBy contains the expression for the `GROUP BY` clause defined in the Query. Values are automatically added to select string. Group []string }
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"` // Select contains the list of expressions define the value for the `UPDATE` clause. // For example: // // params, err := p.Parse([]byte(`{ // "update": ["name", "age"] // }`)) // Update []string `json:"update,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"` // ## in development // Aggregate is the query object for building the value for the `SELECT` clause when grouped. // An example for filter object: // // params, err := p.Parse([]byte(`{ // "aggregate": { // "gold": { "$sum": "gold_fieldname" }, // returns SUM(gold_fieldname) AS gold // "silver": { "$avg": "silver_fieldname" }, // returns AVG(silver_fieldname) AS silver // "bronze": { "$min": "bronze_fieldname" }, // returns MIN(bronze_fieldname) AS bronze // "bronze": { "$max": "bronze_fieldname" }, // returns MAX(bronze_fieldname) AS bronze // "bronze": { "$count": "bronze_fieldname" }, // returns COUNT(bronze_fieldname) AS bronze // } // }`)) // Aggregate map[string]interface{} `json:"aggregate,omitempty"` // ## in development // Group is the query object for building the value for the `GROUP` clause and will be appended to the `SELECT` clause. // An example for filter object: // // params, err := p.Parse([]byte(`{ // "group": ["name", "age"] // }`)) // Group []string `json:"group,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