https://github.com/roberth-k/qb
SQL query builder for Go
https://github.com/roberth-k/qb
golang sql
Last synced: 3 months ago
JSON representation
SQL query builder for Go
- Host: GitHub
- URL: https://github.com/roberth-k/qb
- Owner: roberth-k
- License: mit
- Created: 2019-06-03T19:15:36.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2020-05-21T22:09:27.000Z (almost 6 years ago)
- Last Synced: 2025-08-14T00:34:48.435Z (8 months ago)
- Topics: golang, sql
- Language: Go
- Homepage:
- Size: 142 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
github.com/tetratom/qb
qb is a simple SQL query builder for Go
# highlights
- `go get -u github.com/tetratom/qb`
- [GoDoc](https://godoc.org/github.com/tetratom/qb)
- More examples can be found in [qb_test.go](./qb_test.go).
- All methods take value receivers and return values.
- Select the placeholder dialect with the `DialectOption(Dialect)` method.
# example
```go
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:
```go
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:
```go
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
}
```