Gatsby SQLUtils package helps you build SQL through the struct object.
Import from GitHub:
import sqlutils "github.com/c9s/go-sqlutils"
Define your struct with json spec or with field tag:
type Staff struct {
Id int64 `field:",primary,serial"`
Name string `field:",required"`
Gender string `field:"gender"`
StaffType string `field:"staff_type"`
Phone string `field:"phone"`
}
// to use with json tag
type Staff struct {
Id int64 `json:"id" field:",primary,serial"`
Name string `json:"name" field:",required"`
Gender string `json:"gender"`
StaffType string `json:"staff_type"`
Phone string `json:"phone"`
}
Implement the PrimaryKey interface
func (self *Staff) GetPkId() int64 {
return self.Id
}
func (self *Staff) SetPkId(id int64) {
self.Id = id
}
To build select clause depends on the struct fields:
sql := sqlutils.BuildSelectClause(&Staff{})
Which returns:
SELECT id, name, gender, staff_type, phone FROM staffs
sql := sqlutils.BuildSelectColumnClause(&Staff{})
Which returns:
id, name, gender, staff_type, phone
sql, args := sqlutils.BuildUpdateClause(&Staff{})
Which returns:
UPDATE staffs SET name = $1, phone = $2, cellphone = $3
sql, args := sqlutils.BuildUpdateColumns(&Staff{})
Which returns:
name = $1, phone = $2, cellphone = $3
To build where clause from map:
sql, args := sqlutils.BuildWhereClauseWithAndOp(map[string]interface{} {
"name": "John"
})
which outputs:
WHERE name = $1
Which returns:
WHERE name = $1
To create new record:
staff := Staff{Name:"Mary"}
result := sqlutils.Create(db,&staff, sqlutils.DriverPg)
if result.Error {
// handle error
}
if result.Id != 0 {
// handle primary key id
}
To update struct object:
staff.Name = "NewName"
rows, err := sqlutils.Update(db,&staff)