You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sql_postgres_with_schema.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "database/sql"
  7. "database/sql/driver"
  8. "sync"
  9. "code.gitea.io/gitea/modules/setting"
  10. "github.com/lib/pq"
  11. "xorm.io/xorm/dialects"
  12. )
  13. var registerOnce sync.Once
  14. func registerPostgresSchemaDriver() {
  15. registerOnce.Do(func() {
  16. sql.Register("postgresschema", &postgresSchemaDriver{})
  17. dialects.RegisterDriver("postgresschema", dialects.QueryDriver("postgres"))
  18. })
  19. }
  20. type postgresSchemaDriver struct {
  21. pq.Driver
  22. }
  23. // Open opens a new connection to the database. name is a connection string.
  24. // This function opens the postgres connection in the default manner but immediately
  25. // runs set_config to set the search_path appropriately
  26. func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
  27. conn, err := d.Driver.Open(name)
  28. if err != nil {
  29. return conn, err
  30. }
  31. schemaValue, _ := driver.String.ConvertValue(setting.Database.Schema)
  32. // golangci lint is incorrect here - there is no benefit to using driver.ExecerContext here
  33. // and in any case pq does not implement it
  34. if execer, ok := conn.(driver.Execer); ok { //nolint
  35. _, err := execer.Exec(`SELECT set_config(
  36. 'search_path',
  37. $1 || ',' || current_setting('search_path'),
  38. false)`, []driver.Value{schemaValue}) //nolint
  39. if err != nil {
  40. _ = conn.Close()
  41. return nil, err
  42. }
  43. return conn, nil
  44. }
  45. stmt, err := conn.Prepare(`SELECT set_config(
  46. 'search_path',
  47. $1 || ',' || current_setting('search_path'),
  48. false)`)
  49. if err != nil {
  50. _ = conn.Close()
  51. return nil, err
  52. }
  53. defer stmt.Close()
  54. // driver.String.ConvertValue will never return err for string
  55. // golangci lint is incorrect here - there is no benefit to using stmt.ExecWithContext here
  56. _, err = stmt.Exec([]driver.Value{schemaValue}) //nolint
  57. if err != nil {
  58. _ = conn.Close()
  59. return nil, err
  60. }
  61. return conn, nil
  62. }