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

使用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条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答