sqlbuilder
is a Go library for constructing SQL queries using a fluent API.
This project is now unmaintained and considered obsolete. Please choose an alternative: I recommend sqlgen2.
go get github.com/rickb777/sqlbuilder
SELECT
query, args, dest := sqlbuilder.Select().
From("customers").
Map("id", &customer.ID).
Map("name", &customer.Name).
Map("telephone", &customer.Phone).As("phone").
OrderBy("id DESC").
Limit(1).
Build()
err := db.QueryRow(query, args...).Scan(dest...)
Joins have a fluent style:
query, args, dest := sqlbuilder.Select().
From("customers").As("c").
Inner().Join("orders").As("o").On("o.customer_id", "c.id").
OrderBy("o.total_price").
Map("c.id", &cview.ID).
Map("c.name", &cview.Name).
Map("c.telephone", &cview.Phone).
Map("o.total_price", &cview.TotalPrice).
Build()
INSERT
query, args := sqlbuilder.Insert().
Into("customers").
Set("name", "John").
Set("phone", "555").
Build()
err := db.Exec(query, args...)
UPDATE
query, args := sqlbuilder.Update().
Table("customers").
Set("name", "John").
Set("phone", "555").
Where("id", "= ?", 1).
Build()
err := db.Exec(query, args...)
DELETE
query, args := sqlbuilder.Delete().
From("customers").
WhereEq("id", 1).
Build()
err := db.Exec(query, args...)
sqlbuilder
supports building queries for MySQL, SQLite, and Postgres databases. You
can set the default dialect with:
sqlbuilder.DefaultDialect = sqlbuilder.Postgres
sqlbuilder.Select().From("...")...
Or you can specify the dialect explicitly:
sqlbuilder.Select().Dialect(sqlbuilder.Postgres).From("...")...
Documentation is available at Godoc.
sqlbuilder
is licensed under the MIT License.