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

database.go 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 *DBInfo
  23. DatabaseStatistic *DBInfo
  24. )
  25. type DBInfo struct {
  26. Type string
  27. Host string
  28. Name string
  29. User string
  30. Passwd string
  31. Schema string
  32. SSLMode string
  33. Path string
  34. LogSQL bool
  35. Charset string
  36. Timeout int // seconds
  37. UseSQLite3 bool
  38. UseMySQL bool
  39. UseMSSQL bool
  40. UsePostgreSQL bool
  41. DBConnectRetries int
  42. DBConnectBackoff time.Duration
  43. MaxIdleConns int
  44. MaxOpenConns int
  45. ConnMaxLifetime time.Duration
  46. IterateBufferSize int
  47. }
  48. // GetDBTypeByName returns the dataase 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(section string, database *DBInfo) {
  54. sec := Cfg.Section(section)
  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. func InitDBConfig() {
  90. Database = new(DBInfo)
  91. DatabaseStatistic = new(DBInfo)
  92. initDBConfig("database", Database)
  93. initDBConfig("database_statistic", DatabaseStatistic)
  94. }
  95. // DBConnStr returns database connection string
  96. func DBConnStr(database *DBInfo) (string, error) {
  97. connStr := ""
  98. var Param = "?"
  99. if strings.Contains(database.Name, Param) {
  100. Param = "&"
  101. }
  102. switch database.Type {
  103. case "mysql":
  104. connType := "tcp"
  105. if database.Host[0] == '/' { // looks like a unix socket
  106. connType = "unix"
  107. }
  108. tls := database.SSLMode
  109. if tls == "disable" { // allow (Postgres-inspired) default value to work in MySQL
  110. tls = "false"
  111. }
  112. connStr = fmt.Sprintf("%s:%s@%s(%s)/%s%scharset=%s&parseTime=true&tls=%s",
  113. database.User, database.Passwd, connType, database.Host, database.Name, Param, database.Charset, tls)
  114. case "postgres":
  115. connStr = getPostgreSQLConnectionString(database.Host, database.User, database.Passwd, database.Name, Param, database.SSLMode)
  116. case "mssql":
  117. host, port := ParseMSSQLHostPort(database.Host)
  118. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, database.Name, database.User, database.Passwd)
  119. case "sqlite3":
  120. if !EnableSQLite3 {
  121. return "", errors.New("this binary version does not build support for SQLite3")
  122. }
  123. if err := os.MkdirAll(path.Dir(database.Path), os.ModePerm); err != nil {
  124. return "", fmt.Errorf("Failed to create directories: %v", err)
  125. }
  126. connStr = fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d&_txlock=immediate", database.Path, database.Timeout)
  127. default:
  128. return "", fmt.Errorf("Unknown database type: %s", database.Type)
  129. }
  130. return connStr, nil
  131. }
  132. // parsePostgreSQLHostPort parses given input in various forms defined in
  133. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  134. // and returns proper host and port number.
  135. func parsePostgreSQLHostPort(info string) (string, string) {
  136. host, port := "127.0.0.1", "5432"
  137. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  138. idx := strings.LastIndex(info, ":")
  139. host = info[:idx]
  140. port = info[idx+1:]
  141. } else if len(info) > 0 {
  142. host = info
  143. }
  144. return host, port
  145. }
  146. func getPostgreSQLConnectionString(dbHost, dbUser, dbPasswd, dbName, dbParam, dbsslMode string) (connStr string) {
  147. host, port := parsePostgreSQLHostPort(dbHost)
  148. if host[0] == '/' { // looks like a unix socket
  149. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  150. url.PathEscape(dbUser), url.PathEscape(dbPasswd), port, dbName, dbParam, dbsslMode, host)
  151. } else {
  152. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  153. url.PathEscape(dbUser), url.PathEscape(dbPasswd), host, port, dbName, dbParam, dbsslMode)
  154. }
  155. return
  156. }
  157. // ParseMSSQLHostPort splits the host into host and port
  158. func ParseMSSQLHostPort(info string) (string, string) {
  159. host, port := "127.0.0.1", "1433"
  160. if strings.Contains(info, ":") {
  161. host = strings.Split(info, ":")[0]
  162. port = strings.Split(info, ":")[1]
  163. } else if strings.Contains(info, ",") {
  164. host = strings.Split(info, ",")[0]
  165. port = strings.TrimSpace(strings.Split(info, ",")[1])
  166. } else if len(info) > 0 {
  167. host = info
  168. }
  169. return host, port
  170. }