dsn.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. // Copyright 2020 The Gogs 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 dbutil
  5. import (
  6. "fmt"
  7. "strings"
  8. "github.com/pkg/errors"
  9. "gorm.io/driver/mysql"
  10. "gorm.io/driver/postgres"
  11. "gorm.io/driver/sqlite"
  12. "gorm.io/driver/sqlserver"
  13. "gorm.io/gorm"
  14. "gogs.io/gogs/internal/conf"
  15. )
  16. // ParsePostgreSQLHostPort parses given input in various forms defined in
  17. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  18. // and returns proper host and port number.
  19. func ParsePostgreSQLHostPort(info string) (host, port string) {
  20. host, port = "127.0.0.1", "5432"
  21. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  22. idx := strings.LastIndex(info, ":")
  23. host = info[:idx]
  24. port = info[idx+1:]
  25. } else if len(info) > 0 {
  26. host = info
  27. }
  28. return host, port
  29. }
  30. // ParseMSSQLHostPort parses given input in various forms for MSSQL and returns
  31. // proper host and port number.
  32. func ParseMSSQLHostPort(info string) (host, port string) {
  33. host, port = "127.0.0.1", "1433"
  34. if strings.Contains(info, ":") {
  35. host = strings.Split(info, ":")[0]
  36. port = strings.Split(info, ":")[1]
  37. } else if strings.Contains(info, ",") {
  38. host = strings.Split(info, ",")[0]
  39. port = strings.TrimSpace(strings.Split(info, ",")[1])
  40. } else if len(info) > 0 {
  41. host = info
  42. }
  43. return host, port
  44. }
  45. // NewDSN takes given database options and returns parsed DSN.
  46. func NewDSN(opts conf.DatabaseOpts) (dsn string, err error) {
  47. // In case the database name contains "?" with some parameters
  48. concate := "?"
  49. if strings.Contains(opts.Name, concate) {
  50. concate = "&"
  51. }
  52. switch opts.Type {
  53. case "mysql":
  54. if opts.Host[0] == '/' { // Looks like a unix socket
  55. dsn = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
  56. opts.User, opts.Password, opts.Host, opts.Name, concate)
  57. } else {
  58. dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
  59. opts.User, opts.Password, opts.Host, opts.Name, concate)
  60. }
  61. case "postgres":
  62. host, port := ParsePostgreSQLHostPort(opts.Host)
  63. dsn = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s' application_name='gogs'",
  64. opts.User, opts.Password, host, port, opts.Name, opts.SSLMode, opts.Schema)
  65. case "mssql":
  66. host, port := ParseMSSQLHostPort(opts.Host)
  67. dsn = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  68. host, port, opts.Name, opts.User, opts.Password)
  69. case "sqlite3", "sqlite":
  70. dsn = "file:" + opts.Path + "?cache=shared&mode=rwc"
  71. default:
  72. return "", errors.Errorf("unrecognized dialect: %s", opts.Type)
  73. }
  74. return dsn, nil
  75. }
  76. // OpenDB opens a new database connection encapsulated as gorm.DB using given
  77. // database options and GORM config.
  78. func OpenDB(opts conf.DatabaseOpts, cfg *gorm.Config) (*gorm.DB, error) {
  79. dsn, err := NewDSN(opts)
  80. if err != nil {
  81. return nil, errors.Wrap(err, "parse DSN")
  82. }
  83. var dialector gorm.Dialector
  84. switch opts.Type {
  85. case "mysql":
  86. dialector = mysql.Open(dsn)
  87. case "postgres":
  88. dialector = postgres.Open(dsn)
  89. case "mssql":
  90. dialector = sqlserver.Open(dsn)
  91. case "sqlite3":
  92. dialector = sqlite.Open(dsn)
  93. case "sqlite":
  94. dialector = sqlite.Open(dsn)
  95. dialector.(*sqlite.Dialector).DriverName = "sqlite"
  96. default:
  97. panic("unreachable")
  98. }
  99. return gorm.Open(dialector, cfg)
  100. }