Your Question

Hi guys,

Now, gorm use database/sql, every command with a connection.

In my situation, I want run multiple commands in a single connection(no use transaction). How can I do this?

// I want these commands use the same connection(single).
db.Create()
db.Update()
db.Query()

Comment From: ghost

  • 估计不行,底层用的连接池 :new_moon_with_face:
  • 这样估计可以 , 但不是用 gorm 了.
    d,_ := gormDB.DB()
    conn,_:= d.Conn(context.Background())

    defer conn.Close()

    conn.ExecContext(context.Background(),"show tables")

Comment From: haijianyang

@longlihale

嗯呢,我的实际需求是在执行 SQL 之前,在 connection 设置一下 PG 变量(实现多租户)

// 以下多个 SQL 使用的是同一个数据库连接

// 设置 PG 变量 
"SET app.current_tenant=123456;"

// 执行 SQL
"SELECT * From user;"

// 其他 SQL

除了 database/sql 直接获取 connection,还有其他办法吗,比如同时执行多条 SQL :

"SET app.current_tenant=123456; SELECT * From user;"

Comment From: ghost

@longlihale

嗯呢,我的实际需求是在执行 SQL 之前,在 connection 设置一下 PG 变量(实现多租户)

```go // 设置 PG 变量 "SET app.current_tenant=123456;"

// 执行 SQL "SELECT * From user;"

// 其他 SQL ```

除了 database/sql 直接获取 connection,还有其他办法吗,比如同时执行多条 SQL :

go "SET app.current_tenant=123456; SELECT * From user;"

可以这样试一下,参考一下 Begin 的写法.

d, _ := DB.DB()
    // 获取 一个连接
conn, _ := d.Conn(context.Background())
    // 
newDB := DB.WithContext(context.Background())

newDB.Statement.ConnPooll = conn

// use newDB

Comment From: ghost

可以支持一下这个功能, 添加一个类似 Transaction 的方法 , 保证用的都是同一个 conn

Comment From: haijianyang

好的,那这个功能的大概计划是?

Comment From: ccdd4ever

好的,那这个功能的大概计划是?

你好,请问下最后你是怎么实现的?

Comment From: haijianyang

你好,请问下最后你是怎么实现的?

https://github.com/go-gorm/gorm/pull/4982

Comment From: ccdd4ever

你好,请问下最后你是怎么实现的?

4982

这种方式是不是略麻烦,而且必须在事务里面才行。 我测试了下面这种方式好像可以,不知道会不会有坑

`func GetDB(ctx context.Context) (*gorm.DB, error) { session := GVA_DB.WithContext(ctx) var tenantID int64 tenantID, ok := ctx.Value("x-global-tid").(int64) if !ok { return nil, errors.New("no tenantID fund in context to init DB session") }

preSql := fmt.Sprintf("SET app.current_tenant = %d", tenantID)
session.Exec(preSql)
return session, nil

} `