-
Notifications
You must be signed in to change notification settings - Fork 0
Quick start
Derevtsov Konstantin edited this page Jul 23, 2020
·
10 revisions
Here is a simple example of usage:
- Install d3
go get -u github.com/godzie44/d3/...
- Create entity, and generate code with d3 command (d3 < file >.go or d3 < directory >).
import (
"context"
"database/sql"
d3pgx "github.com/godzie44/d3/adapter/pgx"
"github.com/godzie44/d3/orm"
"github.com/jackc/pgx/v4/pgxpool"
)
//d3:entity
//d3_table:user
type user struct {
id sql.NullInt32 `d3:"pk:auto"`
name string
}
- Create db connection, orm instance, register entities.
cfg, err := pgxpool.ParseConfig(os.Getenv("DB"))
if err != nil {
log.Fatal(err.Error())
}
driver, err := d3pgx.NewPgxPoolDriver(cfg)
if err != nil {
log.Fatal(err.Error())
}
defer driver.Close()
d3orm := orm.New(driver)
if err = d3orm.Register((*user)(nil)); err != nil {
log.Fatal(err)
}
- Create a session and repository.
ctx := d3orm.CtxWithSession(context.Background())
userRepository, err := d3orm.MakeRepository((*user)(nil))
if err != nil {
log.Fatal(err)
}
- Find an existing user by id.
query := userRepository.Select().AndWhere("id", "=", 1)
existingUser, err := userRepository.FindOne(ctx, query)
if err != nil {
log.Fatal(err)
}
- Update entity. Create a new entity after.
existingUser.name = "new name"
newUser := &user{name: "new user"}
userRepository.Persists(ctx, newUser)
- Flush all changes to the database.
if err = orm.Session(ctx).Flush(); err != nil {
log.Fatal(err)
}