本站源代码
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.

176 lines
5.7KB

  1. // Copyright 2019 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 setting
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. )
  15. var (
  16. // SupportedDatabases includes all supported databases type
  17. SupportedDatabases = []string{"MySQL", "PostgreSQL", "MSSQL"}
  18. dbTypes = map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "MSSQL": "mssql", "SQLite3": "sqlite3"}
  19. // EnableSQLite3 use SQLite3, set by build flag
  20. EnableSQLite3 bool
  21. // Database holds the database settings
  22. Database = struct {
  23. Type string
  24. Host string
  25. Name string
  26. User string
  27. Passwd string
  28. SSLMode string
  29. Path string
  30. LogSQL bool
  31. Charset string
  32. Timeout int // seconds
  33. UseSQLite3 bool
  34. UseMySQL bool
  35. UseMSSQL bool
  36. UsePostgreSQL bool
  37. DBConnectRetries int
  38. DBConnectBackoff time.Duration
  39. MaxIdleConns int
  40. MaxOpenConns int
  41. ConnMaxLifetime time.Duration
  42. IterateBufferSize int
  43. }{
  44. Timeout: 500,
  45. }
  46. )
  47. // GetDBTypeByName returns the dataase type as it defined on XORM according the given name
  48. func GetDBTypeByName(name string) string {
  49. return dbTypes[name]
  50. }
  51. // InitDBConfig loads the database settings
  52. func InitDBConfig() {
  53. sec := Cfg.Section("database")
  54. Database.Type = sec.Key("DB_TYPE").String()
  55. switch Database.Type {
  56. case "sqlite3":
  57. Database.UseSQLite3 = true
  58. case "mysql":
  59. Database.UseMySQL = true
  60. case "postgres":
  61. Database.UsePostgreSQL = true
  62. case "mssql":
  63. Database.UseMSSQL = true
  64. }
  65. Database.Host = sec.Key("HOST").String()
  66. Database.Name = sec.Key("NAME").String()
  67. Database.User = sec.Key("USER").String()
  68. if len(Database.Passwd) == 0 {
  69. Database.Passwd = sec.Key("PASSWD").String()
  70. }
  71. Database.SSLMode = sec.Key("SSL_MODE").MustString("disable")
  72. Database.Charset = sec.Key("CHARSET").In("utf8", []string{"utf8", "utf8mb4"})
  73. Database.Path = sec.Key("PATH").MustString(filepath.Join(AppDataPath, "gitea.db"))
  74. Database.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500)
  75. Database.MaxIdleConns = sec.Key("MAX_IDLE_CONNS").MustInt(2)
  76. if Database.UseMySQL {
  77. Database.ConnMaxLifetime = sec.Key("CONN_MAX_LIFE_TIME").MustDuration(3 * time.Second)
  78. } else {
  79. Database.ConnMaxLifetime = sec.Key("CONN_MAX_LIFE_TIME").MustDuration(0)
  80. }
  81. Database.MaxOpenConns = sec.Key("MAX_OPEN_CONNS").MustInt(0)
  82. Database.IterateBufferSize = sec.Key("ITERATE_BUFFER_SIZE").MustInt(50)
  83. Database.LogSQL = sec.Key("LOG_SQL").MustBool(true)
  84. Database.DBConnectRetries = sec.Key("DB_RETRIES").MustInt(10)
  85. Database.DBConnectBackoff = sec.Key("DB_RETRY_BACKOFF").MustDuration(3 * time.Second)
  86. }
  87. // DBConnStr returns database connection string
  88. func DBConnStr() (string, error) {
  89. connStr := ""
  90. var Param = "?"
  91. if strings.Contains(Database.Name, Param) {
  92. Param = "&"
  93. }
  94. switch Database.Type {
  95. case "mysql":
  96. connType := "tcp"
  97. if Database.Host[0] == '/' { // looks like a unix socket
  98. connType = "unix"
  99. }
  100. tls := Database.SSLMode
  101. if tls == "disable" { // allow (Postgres-inspired) default value to work in MySQL
  102. tls = "false"
  103. }
  104. connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%scharset=%s&parseTime=true&tls=%s",
  105. Database.User, Database.Passwd, connType, Database.Host, Database.Name, Param, Database.Charset, tls)
  106. case "postgres":
  107. connStr = getPostgreSQLConnectionString(Database.Host, Database.User, Database.Passwd, Database.Name, Param, Database.SSLMode)
  108. case "mssql":
  109. host, port := ParseMSSQLHostPort(Database.Host)
  110. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, Database.Name, Database.User, Database.Passwd)
  111. case "sqlite3":
  112. if !EnableSQLite3 {
  113. return "", errors.New("this binary version does not build support for SQLite3")
  114. }
  115. if err := os.MkdirAll(path.Dir(Database.Path), os.ModePerm); err != nil {
  116. return "", fmt.Errorf("Failed to create directories: %v", err)
  117. }
  118. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d", Database.Path, Database.Timeout)
  119. default:
  120. return "", fmt.Errorf("Unknown database type: %s", Database.Type)
  121. }
  122. return connStr, nil
  123. }
  124. // parsePostgreSQLHostPort parses given input in various forms defined in
  125. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  126. // and returns proper host and port number.
  127. func parsePostgreSQLHostPort(info string) (string, string) {
  128. host, port := "127.0.0.1", "5432"
  129. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  130. idx := strings.LastIndex(info, ":")
  131. host = info[:idx]
  132. port = info[idx+1:]
  133. } else if len(info) > 0 {
  134. host = info
  135. }
  136. return host, port
  137. }
  138. func getPostgreSQLConnectionString(dbHost, dbUser, dbPasswd, dbName, dbParam, dbsslMode string) (connStr string) {
  139. host, port := parsePostgreSQLHostPort(dbHost)
  140. if host[0] == '/' { // looks like a unix socket
  141. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  142. url.PathEscape(dbUser), url.PathEscape(dbPasswd), port, dbName, dbParam, dbsslMode, host)
  143. } else {
  144. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  145. url.PathEscape(dbUser), url.PathEscape(dbPasswd), host, port, dbName, dbParam, dbsslMode)
  146. }
  147. return
  148. }
  149. // ParseMSSQLHostPort splits the host into host and port
  150. func ParseMSSQLHostPort(info string) (string, string) {
  151. host, port := "127.0.0.1", "1433"
  152. if strings.Contains(info, ":") {
  153. host = strings.Split(info, ":")[0]
  154. port = strings.Split(info, ":")[1]
  155. } else if strings.Contains(info, ",") {
  156. host = strings.Split(info, ",")[0]
  157. port = strings.TrimSpace(strings.Split(info, ",")[1])
  158. } else if len(info) > 0 {
  159. host = info
  160. }
  161. return host, port
  162. }
上海开阖软件有限公司 沪ICP备12045867号-1