### rql Filter: Integration with Database Connectors Source: https://github.com/a8m/rql/blob/master/README.md Provides examples of how to use the parsed rql parameters (FilterExp, FilterArgs, Limit, Offset, Sort) with various Go database connectors like entgo.io, gorm, xorm, and go-pg/pg. ```go var users []*User // entgo.io (A type-safe entity framework) users, err = client.User.Query(). Where(func(s *sql.Selector) { s.Where(sql.ExprP(p.FilterExp, p.FilterArgs...)) }). Limit(p.Limit). Offset(p.Offset). All(ctx) must(err, "failed to query ent") // gorm err = db.Where(p.FilterExp, p.FilterArgs). Offset(p.Offset). Limit(p.Limit). Order(p.Sort). Find(&users).Error must(err, "failed to query gorm") // xorm err = engine.Where(p.FilterExp, p.FilterArgs...). Limit(p.Limit, p.Offset). OrderBy(p.Sort). Find(&users) must(err, "failed to query xorm") // go-pg/pg err = db.Model(&users). Where(p.FilterExp, p.FilterArgs). Offset(p.Offest). Limit(p.Limit). Order(p.Sort). Select() must(err, "failed to query pg/orm") ``` -------------------------------- ### Configure RQL Parser with Go Source: https://github.com/a8m/rql/blob/master/README.md Demonstrates how to initialize and configure the RQL parser using `rql.MustNew` with custom settings for model, column function, logger, default limit, and maximum limit value. ```Go var Parser = rql.MustNew(rql.Config{ // User if the resource we want to query. Model: User{}, // Since we work with gorm, we want to use its column-function, and not rql default. // although, they are pretty the same. ColumnFn: gorm.ToDBName, // Use your own custom logger. This logger is used only in the building stage. Log: logrus.Printf, // Default limit returned by the `Parse` function if no limit provided by the user. DefaultLimit: 100, // Accept only requests that pass limit value that is greater than or equal to 200. LimitMaxValue: 200, }) ``` -------------------------------- ### rql Filter: Simple Field Equality Source: https://github.com/a8m/rql/blob/master/README.md Demonstrates how a simple field-value pair in the filter object translates to an SQL WHERE clause with an equality predicate. It shows the generated SQL expression and arguments. ```go var QueryParser = rql.MustNewParser(rql.Config{ Model: User{}, FieldSep: ".", LimitMaxValue: 25, }) type User struct { ID uint `gorm:"primary_key" rql:"filter,sort" Admin bool `rql:"filter" Name string `rql:"filter" Address string `rql:"filter" CreatedAt time.Time `rql:"filter,sort" } params, err := QueryParser.Parse([]byte(`{ "limit": 25, "offset": 0, "filter": { "admin": false } "sort": ["+name"] }`)) must(err, "parse should pass") fmt.Println(params.Limit) // 25 fmt.Println(params.Offset) // 0 fmt.Println(params.Sort) // "name ASC" fmt.Println(params.FilterExp) // "admin = ?" fmt.Println(params.FilterArgs) // [true] ``` -------------------------------- ### Go HTTP Handler with RQL for GORM Source: https://github.com/a8m/rql/blob/master/README.md Demonstrates an HTTP handler in Go that uses RQL with GORM to process database queries. It accepts user queries from the request body or URL query string, parses them using RQL, and applies filters, limits, and sorting to a GORM database query. ```go package main import ( "encoding/json" "io" "io/ioutil" "net/http" "time" "github.com/a8m/rql" "github.com/jinzhu/gorm" "encoding/base64" ) var ( db *gorm.DB // QueryParam is the name of the query string key. QueryParam = "query" // MustNewParser panics if the configuration is invalid. QueryParser = rql.MustNewParser(rql.Config{ Model: User{}, FieldSep: ".", }) ) // User is the model in gorm's terminology. type User struct { ID uint `gorm:"primary_key" rql:"filter,sort" Admin bool `rql:"filter" Name string `rql:"filter" AddressName string `rql:"filter" CreatedAt time.Time `rql:"filter,sort" } // GetUsers is an http.Handler that accepts a db query in either the body or the query string. func GetUsers(w http.ResponseWriter, r *http.Request) { var users []User p, err := getDBQuery(r) if err != nil { io.WriteString(w, err.Error()) w.WriteHeader(http.StatusBadRequest) return } err = db.Where(p.FilterExp, p.FilterArgs). Offset(p.Offset). Limit(p.Limit). Order(p.Sort). Find(&users).Error if err != nil { w.WriteHeader(http.StatusInternalServerError) return } if err := json.NewEncoder(w).Encode(users); err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") } // getDBQuery extract the query blob from either the body or the query string // and execute the parser. func getDBQuery(r *http.Request) (*rql.Params, error) { var ( b []byte err error ) if v := r.URL.Query().Get(QueryParam); v != "" { b, err = base64.StdEncoding.DecodeString(v) } else { b, err = ioutil.ReadAll(io.LimitReader(r.Body, 1<<12)) } if err != nil { return nil, err } return QueryParser.Parse(b) } ``` -------------------------------- ### Customize time.Time Layout in RQL Source: https://github.com/a8m/rql/blob/master/README.md Illustrates how to specify custom time layouts for `time.Time` fields within a struct using RQL tags, overriding the default RFC3339 format. ```Go type User struct { T1 time.Time `rql:"filter"` // time.RFC3339 T2 time.Time `rql:"filter,layout=UnixDate"` // time.UnixDate T3 time.Time `rql:"filter,layout=2006-01-02 15:04"` // 2006-01-02 15:04 (custom) } ``` -------------------------------- ### rql Filter: Unsupported Predicate Error Handling Source: https://github.com/a8m/rql/blob/master/README.md Demonstrates the error handling when an unsupported predicate (e.g., $like on a non-string field) is applied. It shows the informative error message returned by the system. ```go For input: { "age": { "$like": "%0" } } Result is: can not apply op "$like" on field "age" ``` -------------------------------- ### rql Filter: Predicate Usage (e.g., $gt, $lt) Source: https://github.com/a8m/rql/blob/master/README.md Illustrates how to use predicates like $gt (greater than) and $lt (less than) within the filter object to create range conditions in the SQL WHERE clause. It shows the resulting SQL expression with multiple conditions combined by AND. ```go var QueryParser = rql.MustNewParser(rql.Config{ Model: User{}, FieldSep: ".", LimitMaxValue: 25, }) type User struct { ID uint `gorm:"primary_key" rql:"filter,sort" Admin bool `rql:"filter" Name string `rql:"filter" Address string `rql:"filter" CreatedAt time.Time `rql:"filter,sort" } params, err := QueryParser.Parse([]byte(`{ "limit": 25, "filter": { "admin": false, "created_at": { "$gt": "2018-01-01T16:00:00.000Z", "$lt": "2018-04-01T16:00:00.000Z" } "$or": [ { "address": "TLV" }, { "address": "NYC" } ] } "sort": ["-created_at"] }`)) must(err, "parse should pass") fmt.Println(params.Limit) // 25 fmt.Println(params.Offset) // 0 fmt.Println(params.Sort) // "created_at DESC" fmt.Println(params.FilterExp) // "admin = ? AND created_at > ? AND created_at < ? AND (address = ? OR address = ?)" fmt.Println(params.FilterArgs) // [true, Time(2018-01-01T16:00:00.000Z), Time(2018-04-01T16:00:00.000Z), "TLV", "NYC"] ``` -------------------------------- ### rql Filter: $or Operator Usage Source: https://github.com/a8m/rql/blob/master/README.md Demonstrates the usage of the $or operator to combine multiple filter conditions with a logical OR. It shows how an array of condition objects is translated into an OR clause in the SQL WHERE statement. ```go { "$or": [ { "city": "TLV" }, { "zip": { "$gte": 49800, "$lte": 57080 } } ] } Result is: city = ? OR (zip >= ? AND zip <= ?) ``` -------------------------------- ### Go Struct for Nested Fields in RQL Source: https://github.com/a8m/rql/blob/master/README.md This Go struct demonstrates how RQL handles nested fields. It assumes a flattened database structure where nested fields are represented by concatenated names (e.g., 'address_name'). Future plans include adding a 'table=' option to support actual nested queries. ```go type User struct { Address struct { Name string `rql:"filter"` } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.