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.

database.go 5.8KB

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