roberth-k / qb

SQL query builder for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

github.com/tetratom/qb

GoDoc CircleCI Codecov

qb is a simple SQL query builder for Go

highlights

  • go get -u github.com/tetratom/qb
  • GoDoc
  • More examples can be found in qb_test.go.
  • All methods take value receivers and return values.
  • Select the placeholder dialect with the DialectOption(Dialect) method.

example

import "github.com/tetratom/qb"

q := qb.
    Select("*").From("my_table").
    Where(qb.
        And("id = ?", 1).
        Or("time < ?", qb.Lit("now()"))).
    OrderBy("time ASC").
    Limit(10)

// q.SQL() is "SELECT * FROM my_table WHERE id = ?".
// q.Args() is []interface{1}.
row := tx.QueryRow(q.SQL(), q.Args()...)

thread-safe and reusable builders

qb builders should be used the same as the append() built-in. The builders take and return values, and internally keep state such that one builder value can be re-used for different queries. For example:

qbase := qb.Select("col1", "col2")
q1 := qbase.From("t1") // q1 is: SELECT col1, col2 FROM t1
q2 := qbase.From("t2") // q2 is: SELECT col1, col2 FROM t2
// qbase is: SELECT col1, col2

Just like with append(), the return value of calling a builder method must be assigned back into a variable to be used. For example:

func Search(name string, ordered bool) qb.Query {
    q := qb.Select("*").From("members")

    if name != "" {
        q = q.Where(qb.And("name = ?", name))
    }
    
    if ordered {
        q = q.OrderBy("created_at DESC")
    }
    
    return q
}

About

SQL query builder for Go

License:MIT License


Languages

Language:Go 100.0%