go-korm

Golang struct base orm model library

πŸ’‘ Concept

korm is an Sequrlize / Hibernate inspired ‘half’ object-relational mapping. ‘Half’ mean we do not control database connection for now.

There are many struct base orm library written in Go. Main difference in korm is that support .Create() .Get() .Insert() .Update() .Delete() from korm-model directly.

πŸ›  How to use

πŸ“– Pre steps

  • Step 1 : Create Database connection (for pass it to korm)
    db, _ := sql.Open("mysql", "root:[email protected](localhost:3306)/schema")
  • Step 2 : Define struct as database model (using korm tag)

    type Employee struct {
        Eid int32 `korm:"integer"`
        Name string `korm:"varchar(100)"`
        Team string `korm:"varchar(30)"`
    }
  • Step 3 : Create korm model based on step 2
    model := korm.NewModel[Employee]

πŸ“– Create Table

// korm use first struct field for primary key by default
// Second parameter : set primary key or not
model.CreateTable(db, true)

πŸ“– Insert into database

model.Data.Eid = 920809
model.Data.Name = "Abbie Oh"
model.Data.Team = "Dev Team 1"

model.Insert(db)

πŸ“– Get from database

model.Data.Eid = 920809

// Second parameter : index of struct field.
// It mean get data from database with filter eid = 920809
model.Get(db, 0)

πŸ“– Get all from database

//var result []Employee
result := model.GetAll(db)

πŸ“– Update to database

model.Data.Eid = 920809
model.Data.Team = "Dev Team 2"

// Second parameter : index of struct field which want to update.
// It mean just update team to database.
model.Update(db, 2)

πŸ“– Delete from database

model.Data.Eid = 920809

// Second parameter : index of struct field which use for delete operation.
model.Delete(db, 0)

GitHub

View Github