dataservicex
is a go library that wrapup common CRUD functions of the data service layer to access a database. As a common application, it frequently re-implements the following functions with its data model:
- Create model
- Update full model
- Update specific columns
- Get a model by ID
- Get list model
- Delete by ID
The dataservicex
uses generic, goqu, and sqlx to implement the common functions.
Import library to your project
go get -u github.com/vnteamopen/dataservicex
import (
"github.com/jmoiron/sqlx"
_ "github.com/go-sql-driver/mysql"
)
type Person struct {
ID int64 `db:"person_id" goqu:"skipupdate"`
Name string `db:"name"`
Age int64 `db:"age"`
}
func (Person) TableName() string {
return "person"
}
func (Person) IDColumnName() string {
return "person_id"
}
func main() {
db, _ := sqlx.Connect("mysql", connStr)
dataService := dataservicex.NewDataServices[Person](db)
}
You can specific Dialect of database query generating
dialect := goqu.Dialect("mysql")
dataService = dataservicex.NewDataServices(db, dataservicex.WithDialect[Person](dialect))
func main() {
dataService := dataservicex.NewDataServices[Person](...)
createdPerson, err := dataService.Create(context.Background(), Person{
Name: "Thuc Le",
Age: 25,
})
}
func main() {
dataService := dataservicex.NewDataServices[Person](...)
updatingID := 1
updatedPerson, err := dataService.Update(context.Background(), updatingID, Person{
Name: "Thuc Le",
Age: 25,
})
}
func main() {
dataService := dataservicex.NewDataServices[Person](...)
updatingID := 1
updatedPerson, err := dataService.UpdateColumns(context.Background(),
updatingID,
goqu.Record{
"name": "Thuc Le",
})
}
func main() {
dataService := dataservicex.NewDataServices[Person](...)
person, err := dataService.GetByID(context.Background(), 1)
}
func main() {
dataService := dataservicex.NewDataServices[Person](...)
personList, err := dataService.GetList(context.Background())
}
func main() {
dataService := dataservicex.NewDataServices[Person](...)
err := dataService.Delete(context.Background(), 1)
}
MIT
All your contributions to project and make it better, they are welcome. Feel free to start an issue.
- Viet Nam We Build group https://webuild.community for discussion.