andybeak

Gorm test

Jun 13th, 2022 (edited)
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.73 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "database/sql"
  5.     "fmt"
  6.     "github.com/google/uuid"
  7.     "gorm.io/driver/mysql"
  8.     "gorm.io/gorm"
  9.     "gorm.io/gorm/clause"
  10.     "log"
  11.     "time"
  12. )
  13.  
  14. type Model struct {
  15.     ID        uuid.UUID `gorm:"type:char(36);primary_key"`
  16. }
  17.  
  18. // BeforeCreate will set a UUID rather than numeric ID.
  19. func (m *Model) BeforeCreate(tx *gorm.DB) (err error) {
  20.     m.ID = uuid.New()
  21.     return
  22. }
  23.  
  24. type Foo struct {
  25.     Model
  26.     Name string `gorm:"type:varchar(45)"`
  27.     Bars []*Bar `gorm:"many2many:foo_bar;"`
  28. }
  29.  
  30. type Bar struct {
  31.     Model
  32.     Name string `gorm:"type:varchar(45)"`
  33.     Foos []*Foo `gorm:"many2many:foo_bar;"`
  34. }
  35.  
  36. func main() {
  37.     db := provideDatabase()
  38.     foos := map[string]*Foo{}
  39.     for _, f := range []string{"a", "b", "c", "d", "e"} {
  40.         id := uuid.New()
  41.         foo := Foo{Model: Model{ID: id}, Name: f}
  42.         db.Omit(clause.Associations).Create(&foo)
  43.         foos[f] = &foo
  44.     }
  45.     for _, b := range []string{"z", "y", "x", "w", "v"} {
  46.         bar := Bar{
  47.             Model: Model{ID: uuid.New()},
  48.             Name:  b,
  49.             Foos: []*Foo{
  50.                 foos["a"],
  51.                 foos["e"],
  52.             },
  53.         }
  54.         db.Create(&bar)
  55.     }
  56. }
  57.  
  58. // create the database and truncate the tables
  59. func provideDatabase() *gorm.DB {
  60.     log.Println("Connecting to database...")
  61.     connectionString :=
  62.         fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true",
  63.             "root", "letmein", "127.0.0.1", 33070, "test")
  64.     var err error
  65.     sqlDB, err := sql.Open("mysql", connectionString)
  66.     if err != nil {
  67.         panic("Could not connect to database")
  68.     }
  69.     db, err := gorm.Open(mysql.New(mysql.Config{
  70.         Conn: sqlDB,
  71.     }), &gorm.Config{})
  72.     db.AutoMigrate(Foo{}, Bar{})
  73.     db.Exec("SET FOREIGN_KEY_CHECKS=0")
  74.     tables := []string{"foos", "bars", "foo_bar"}
  75.     for _, table := range tables {
  76.         db.Exec("TRUNCATE TABLE " + table)
  77.     }
  78.     return db
  79. }
  80.  
Add Comment
Please, Sign In to add comment