github.com/zooyer/miskit@v1.0.71/micro/gorm_test.go (about)

     1  package micro
     2  
     3  import (
     4  	"encoding/json"
     5  	"testing"
     6  
     7  	"gorm.io/gorm"
     8  )
     9  
    10  type People struct {
    11  	gorm.Model
    12  	Name string
    13  	Age  int
    14  }
    15  
    16  func (People) TableName() string {
    17  	return "people"
    18  }
    19  
    20  func TestOpen(t *testing.T) {
    21  	db, err := OpenDB("sqlite", ":memory:", nil)
    22  	if err != nil {
    23  		t.Fatal(err)
    24  	}
    25  
    26  	// gorm v2 不用Close了吗?
    27  	// defer db.Close()
    28  
    29  	db = db.Debug()
    30  
    31  	if err = db.AutoMigrate(new(People)); err != nil {
    32  		t.Fatal(err)
    33  	}
    34  
    35  	var p = People{
    36  		Name: "zs",
    37  		Age:  24,
    38  	}
    39  
    40  	if err = db.Create(&p).Error; err != nil {
    41  		t.Fatal(err)
    42  	}
    43  
    44  	var ps []People
    45  	if err = db.Find(&ps).Error; err != nil {
    46  		t.Fatal(err)
    47  	}
    48  
    49  	data, _ := json.Marshal(ps)
    50  	t.Log(string(data))
    51  }