go-gorm / dbresolver

Multiple databases, read-write splitting FOR GORM

Home Page:https://gorm.io/docs/dbresolver.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

如何对slover设置gorm.Config

anerg2046 opened this issue · comments

我目前的情况

有两个mysql数据库需要同时连接使用,然后我想设置DisableForeignKeyConstraintWhenMigrating
目前的情况是只有主连接会赋予该配置,而*dbresolver.DBResolver貌似不可以

var Conn *gorm.DB

func init() {
	InitMultiDatabase()

	// 设置一些gorm配置
	Conn.Config.Apply(&gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		PrepareStmt:                              true,
	})

	Conn.Logger = logger.NewGormLogger()

	// 创建表
	Conn.AutoMigrate(
	 	&model.Customer{},
	 	&model.CustomerBrand{},
		&model.FlowNode{},
		&model.FlowCurrent{},
		&model.FlowUnknown{},
	)
	if !Conn.Migrator().HasTable(model.FlowUnknown{}) {
		Conn.Migrator().CreateTable(&model.FlowUnknown{})
	}
}

func InitMultiDatabase() {
	var err error
	Conn, err = gorm.Open(mysql.Open(config.DB_APP.DSN), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	// 设置主库的线程池
	sqlDB, err := Conn.DB()
	sqlDB.SetMaxIdleConns(config.Pool.MaxIdleConns)
	sqlDB.SetMaxOpenConns(config.Pool.MaxOpenConns)
	sqlDB.SetConnMaxIdleTime(config.Pool.ConnMaxIdleTime)
	sqlDB.SetConnMaxLifetime(config.Pool.ConnMaxLifetime)
	if err != nil {
		panic(err)
	}

	// 这里指定特定的表去特定的数据库
	slover := dbresolver.Register(
		dbresolver.Config{
			Sources: []gorm.Dialector{mysql.Open(config.DB_DATA.DSN)},
		},
		&model.Agent{},
		&model.Flow{},
		&model.Global{},
		&model.Item{},
	)

	// 设置连接池信息
	slover.SetConnMaxIdleTime(config.Pool.ConnMaxIdleTime).
		SetConnMaxLifetime(config.Pool.ConnMaxLifetime).
		SetMaxIdleConns(config.Pool.MaxIdleConns).
		SetMaxOpenConns(config.Pool.MaxOpenConns)

	// 这里这么写会报错空指针
	slover.Apply(&gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		PrepareStmt:                              true,
	})

	Conn.Use(slover)
}

当有跨数据库的表存在关联字段的时候会报错

db/mysql.go:34  Database Error  {"sql": "ALTER TABLE `customer_brand` ADD CONSTRAINT `fk_flow_current_customer_brand` FOREIGN KEY (`b_id`) REFERENCES `flow_current`(`b_id`)", "time": "758.326ms", "rows": 0, "error": "Error 1452: Cannot add or update a child row: a foreign key constraint fails (`brand_alpha`.`#sql-1_5d59b4`, CONSTRAINT `fk_flow_current_customer_brand` FOREIGN KEY (`b_id`) REFERENCES `flow_current` (`b_id`))"}

Change

Conn, err = gorm.Open(mysql.Open(config.DB_APP.DSN), &gorm.Config{})

to

Conn, err = gorm.Open(mysql.Open(config.DB_APP.DSN),&gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		PrepareStmt:                              true,
	})