douyinglan2599 2019-05-29 19:10
浏览 195
已采纳

使用GORM和Postgresql如何设置search_path?

How can I get the current schema from gorm? Normally it is "SHOW search_path" and is an exec. Same with setting the current search_path normally "set search_path to newschema". where new schema can be a single schema name of a series of names.

I attempted db.Exec("show search_path").Find(&result) where result is a []string and I get an empty array.

  • 写回答

2条回答 默认 最新

  • 普通网友 2019-05-29 19:35
    关注

    FOUND how to display current schema by experimenting and a hint about Raw and Scan in PluralSite's GORM class.

    var currentSchema string
    rows, err := db.Debug().Raw("show search_path").Rows()
    rows.Next()  // to get the first and only result
    rows.Scan(&currentSchema)
    fmt.Printf("Search Path: %v
    ", currentSchema)
    

    returns: Search Path: "$user", public

    Taking @PavloStrokov point about transactions (which are basically threads and a transaction) into account, I was able to get the schema to stay during the current process. In the handler, I use the existing DB connection and create a transaction. It gets passed to every method that is called that touches the Database. I change the call to the gorm method to be the passed tx instead of the normal db variable that was stored and made available to any method that needed it.

    The call I make to start it all of is:

    tx := db.Begin()

    tx.Exec("set search_path to schema_name")

    The string is generated to use the proper Facility schema name.

    The tx is the last param in the signature of all methods that touch the DB. For example func methiodUsingDBSchema(val1 string, val2 string, tx *gorm.DB){}

    Then the last thing I do is tx.Commit() Even though these are all reads.

    I have run all test and works well.

    I use the Postgres schemas to separate Facilities in my application and need to change based upon the user logged in. All User and Facility information is in public.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码