andybeak icon

Gorm test

andybeak | PRO | 06/13/22 05:34:31 PM UTC (Edited) | 0 ⭐ | 501 👁️ | Never ⏰ | []
Go |

1.73 KB

|

None

|

0 👍

/

0 👎

package main
 
import (
    "database/sql"
    "fmt"
    "github.com/google/uuid"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/clause"
    "log"
    "time"
)
 
type Model struct {
    ID        uuid.UUID `gorm:"type:char(36);primary_key"`
}
 
// BeforeCreate will set a UUID rather than numeric ID.
func (m *Model) BeforeCreate(tx *gorm.DB) (err error) {
    m.ID = uuid.New()
    return
}
 
type Foo struct {
    Model
    Name string `gorm:"type:varchar(45)"`
    Bars []*Bar `gorm:"many2many:foo_bar;"`
}
 
type Bar struct {
    Model
    Name string `gorm:"type:varchar(45)"`
    Foos []*Foo `gorm:"many2many:foo_bar;"`
}
 
func main() {
    db := provideDatabase()
    foos := map[string]*Foo{}
    for _, f := range []string{"a", "b", "c", "d", "e"} {
        id := uuid.New()
        foo := Foo{Model: Model{ID: id}, Name: f}
        db.Omit(clause.Associations).Create(&foo)
        foos[f] = &foo
    }
    for _, b := range []string{"z", "y", "x", "w", "v"} {
        bar := Bar{
            Model: Model{ID: uuid.New()},
            Name:  b,
            Foos: []*Foo{
                foos["a"],
                foos["e"],
            },
        }
        db.Create(&bar)
    }
}
 
// create the database and truncate the tables
func provideDatabase() *gorm.DB {
    log.Println("Connecting to database...")
    connectionString :=
        fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true",
            "root", "letmein", "127.0.0.1", 33070, "test")
    var err error
    sqlDB, err := sql.Open("mysql", connectionString)
    if err != nil {
        panic("Could not connect to database")
    }
    db, err := gorm.Open(mysql.New(mysql.Config{
        Conn: sqlDB,
    }), &gorm.Config{})
    db.AutoMigrate(Foo{}, Bar{})
    db.Exec("SET FOREIGN_KEY_CHECKS=0")
    tables := []string{"foos", "bars", "foo_bar"}
    for _, table := range tables {
        db.Exec("TRUNCATE TABLE " + table)
    }
    return db
}
 

Comments