This package is only for creating sql text. To run the created sql text, you must create a database connection. (Ex: mysql, postgresql).
import "github.com/mstgnz/gobuilder"
var gb GoBuilder
// all columns
gb.Table("users").Select().Where("id","=","1").ToSql()
// filter columns
gb.Table("users").Select("firstname", "lastname", "created_at").
Where("id", "=", 1).
ToSql()
Result: SELECT * FROM users WHERE id = '1'
Result: SELECT firstname,lastname,created_at FROM users WHERE id = 1
gb.Table("users").Select().
Where("id", "=", "1").
OrWhere("email", "=", "[email protected]").
ToSql()
Result: SELECT * FROM users WHERE id='1' OR email='[email protected]'
gb.Table("users as u").Select("u.firstname", "u.lastname", "a.address").
Join("INNER", "address as a", "a.user_id=u.id").
Where("u.email", "=", "[email protected]").
ToSql()
Result: SELECT u.firstname,u.lastname,a.address FROM users as u INNER JOIN address as a ON a.user_id=u.id WHERE u.email='[email protected]'
gb.Table("users").Select().
Where("id", "=", "1").
Between("created_at", "2021-01-01", "2021-03-16").
ToSql()
Result: SELECT * FROM users WHERE id='1' AND created_at BETWEEN '2021-01-01' AND '2021-03-16'
gb.Table("users").Select().
Where("id", "=", "1").
Between("created_at", "2021-01-01", "2021-03-16").
Limit(1, 5).
ToSql()
Result: SELECT * FROM users WHERE id='1' AND created_at BETWEEN '2021-01-01' AND '2021-03-16' LIMIT 1,5
gb.Table("users").Select().
Where("id", "=", "1").
Between("created_at", "2021-01-01", "2021-03-16").
GroupBy("lastname").
ToSql()
Result: SELECT * FROM users WHERE id='1' AND created_at BETWEEN '2021-01-01' AND '2021-03-16' GROUP BY lastname
gb.Table("users").Select().
Where("id", "=", "1").
Between("created_at", "2021-01-01", "2021-03-16").
GroupBy("lastname").
OrderBy("id", "DESC").
ToSql()
Result: SELECT * FROM users WHERE id='1' AND created_at BETWEEN '2021-01-01' AND '2021-03-16' GROUP BY lastname ORDER BY id DESC
s1 := gb.Table("users").Select().Where("lastname", "=", "lorem").ToSql()
s2 := gb.Table("users").Select().Where("lastname", "=", "ipsum").Union(s1).ToSql()
Result: SELECT * FROM users WHERE lastname='ipsum' UNION SELECT * FROM users WHERE lastname='lorem'
args := map[string]string{
"firstname": "Lorem",
"lastname": "IPSUM",
}
gb.Table("users").Insert(args).ToSql()
Result : INSERT INTO users (lastname,firstname) VALUES ('Lorem','IPSUM')
args := map[string]string{
"firstname": "Lorem",
"lastname": "IPSUM",
}
gb.Table("users").Update(args).Where("email", "=", "[email protected]").ToSql()
Result: UPDATE users SET firstname='Lorem', lastname='IPSUM' WHERE email='[email protected]'
gb.Table("users").Delete().Where("email", "=", "[email protected]").ToSql()
Result: DELETE FROM users WHERE email='[email protected]'