Gorm遇到的錯誤整理

1#signal SIGSEGV: segmentation violation

錯誤信息mysql

vagrant@homestead:/var/go/src/gin$ go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0xb0 pc=0x9cf1a6]

goroutine 1 [running]:
github.com/jinzhu/gorm.(*DB).clone(0x0, 0x40dd08)
        /var/go/pkg/mod/github.com/jinzhu/gorm@v1.9.10/main.go:821 +0x26
github.com/jinzhu/gorm.(*DB).Unscoped(...)
        /var/go/pkg/mod/github.com/jinzhu/gorm@v1.9.10/main.go:312
github.com/jinzhu/gorm.(*DB).AutoMigrate(0x0, 0xc000193f18, 0x1, 0x1, 0x1)
        /var/go/pkg/mod/github.com/jinzhu/gorm@v1.9.10/main.go:655 +0x30
github.com/tqsq2005/go-newbird/gin/models.migration(...)
        /var/go/src/gin/models/models.go:44
github.com/tqsq2005/go-newbird/gin/models.Setup()
        /var/go/src/gin/models/models.go:30 +0x2c1
main.init.0()
        /var/go/src/gin/main.go:12 +0x25
exit status 2
複製代碼

錯誤定位git

package models

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/tqsq2005/go-newbird/gin/pkg/setting"
	"log"
	"time"
)

var db *gorm.DB

func Setup() {
	var err error
	db, err := gorm.Open(setting.DatabaseSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		setting.DatabaseSetting.User,
		setting.DatabaseSetting.Password,
		setting.DatabaseSetting.Host,
		setting.DatabaseSetting.Name))

	if err != nil {
		log.Fatalf("models.Setup err:%v", err)
	}

	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return setting.DatabaseSetting.TablePrefix + defaultTableName
	}

	migration()

	// 關閉複數表名,若是設置爲true,`User`表的表名就會是`user`,而不是`users`
	//db.SingularTable(true)

	// SetMaxIdleCons 設置鏈接池中的最大閒置鏈接數。
	db.DB().SetMaxIdleConns(10)
	// SetMaxOpenCons 設置數據庫的最大鏈接數量
	db.DB().SetMaxOpenConns(100)
	// SetConnMaxLifetiment 設置鏈接的最大可複用時間。
	db.DB().SetConnMaxLifetime(time.Hour)
}

func migration() {
	db.AutoMigrate(&User{}, &Article{})
}

func CloseDB() {
	defer db.Close()
}
複製代碼

go報的定位到migration()這邊,推斷出應該是db這個變量有問題,找到db賦值的地方,db, err := gorm.Open(...),這邊的db由於:的操做符實際上是函數內部的局部變量,而不是外面的全局變量,代碼改成db, err = gorm.Open(...),錯誤解決!github

#2定義模型中的gorm:"size:length"註釋的時候size:length之間不能有空格

下面的代碼生成的passwordremember_token表結果是varcharsql

type User struct {
	gorm.Model
	UserName        string     `gorm:"type: varchar(30); not null" json:"user_name"`
	Email           string     `gorm:"type: varchar(50); unique_index; not null" json:"email"`
	EmailVerifiedAt *time.Time `json:"email_verified_at"`
	Tel             string     `gorm:"type: varchar(20); unique_index; not null" json:"tel"`
	Password        string     `gorm:"size:60; not null" json:"password"`
	RememberToken   string     `gorm:"size:60" json:"remember_token"`
}
複製代碼

下面的代碼生成的passwordremember_token表結果是longtext,僅僅是由於size: 60;: size:60之間有空格!數據庫

type User struct {
	gorm.Model
	UserName        string     `gorm:"type: varchar(30); not null" json:"user_name"`
	Email           string     `gorm:"type: varchar(50); unique_index; not null" json:"email"`
	EmailVerifiedAt *time.Time `json:"email_verified_at"`
	Tel             string     `gorm:"type: varchar(20); unique_index; not null" json:"tel"`
	Password        string     `gorm:"size: 60; not null" json:"password"`
	RememberToken   string     `gorm:"size: 60" json:"remember_token"`
}
複製代碼

#其餘

  • 一、gorm設置varchar(100)和size:100有什麼區別?

區別在於,type後的定義將會直接做用到create table語句中,你還能夠設置 type:"int(11) unsigned auto_increment;",且type有最高優先級 size只做用於類型爲stringarrayslice的字段,爲string類型時判斷size0到65532之間時自動設置爲varchar大於65532時設置爲longtext,不然自動設置爲varbinary或longblob類型 詳見:dialect_mysql.go#L31(僅針對mysql)json

  • 二、sql.NullInt64是什麼意思?

容許db中值爲NULL的bigint類型bash

  • 三、MemberNumber字段的類型是*string,和string有什麼不一樣,何時使用指針類型?

*string容許爲空,也就是說容許設置爲NULL,string默認值是空字符串,保存時前者設置爲NULL,後者爲空字符串tcp

  • 四、IgnoreMe字段後面的gorm:"-" // 忽略本字段,這個**「忽略本字段」**是什麼意思?

本字段不做爲數據庫的映射字段函數

  • 五、type:"int(11) unsigned auto_increment;"能夠改爲中間加分號嗎?像這樣:type:"int(11);unsigned;auto_increment;"

不行,type是有最高優先級的,直接做用到create table語句中,加分號的話,語句錯誤ui

  • 六、 uniqueunique_index的區別

unique means "has to be unique value", it's an equivalent of setting a UNIQUE constraint on a database table field. unique_index means "index database on this value, which is unique", it's an equivalent of creating a unique index in the database — you can specify a name of such index and use the annotation with the same name on multiple struct fields:

// just an exampe
type Example struct {
    // two people can have the same name
    Name string `gorm:"primary_key;unique_index:exampleindex"`
    // but usernames have to be unique
    Username string `gorm:"unique;"`
    // colors can be repeating too
    FavoriteColor string `gorm:"unique_index:exampleindex"` 
    // But combinations of User + FavoriteColor have to be UNIQUE
}
複製代碼
  • 7
  • 8
  • 9
  • 10
相關文章
相關標籤/搜索