Skip to content

Quick start

Derevtsov Konstantin edited this page Jul 23, 2020 · 10 revisions

Here is a simple example of usage:

  1. Install d3
    go get -u github.com/godzie44/d3/...
  1. 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 
}
  1. 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)
}
  1. Create a session and repository.
ctx := d3orm.CtxWithSession(context.Background())
userRepository, err := d3orm.MakeRepository((*user)(nil))
if err != nil {
    log.Fatal(err)
}
  1. Find an existing user by id.
query := userRepository.Select().AndWhere("id", "=", 1)
existingUser, err := userRepository.FindOne(ctx, query)
if err != nil {
    log.Fatal(err)
}
  1. Update entity. Create a new entity after.
existingUser.name = "new name"

newUser := &user{name: "new user"}
userRepository.Persists(ctx, newUser)
  1. Flush all changes to the database.
if err = orm.Session(ctx).Flush(); err != nil {
    log.Fatal(err)
}
Clone this wiki locally