sql.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sqlchemy
  15. import (
  16. "database/sql"
  17. "strings"
  18. "yunion.io/x/log"
  19. "yunion.io/x/pkg/errors"
  20. )
  21. // DBName is a type of string for name of database
  22. type DBName string
  23. // SDatabase represents a SQL database
  24. type SDatabase struct {
  25. db *sql.DB
  26. name DBName
  27. backend IBackend
  28. }
  29. // DefaultDB is the name for the default database instance
  30. const DefaultDB = DBName("__default__")
  31. // the global DB connection table
  32. var _db_tbl = make(map[DBName]*SDatabase)
  33. // Deprecated
  34. // SetDB sets global DB instance
  35. func SetDB(db *sql.DB) {
  36. SetDefaultDB(db)
  37. }
  38. // SetDefaultDB save default global DB instance
  39. func SetDefaultDB(db *sql.DB) {
  40. SetDBWithNameBackend(db, DefaultDB, MySQLBackend)
  41. }
  42. // SetDBWithName sets a DB instance with given name
  43. // param: name DBName
  44. func SetDBWithNameBackend(db *sql.DB, name DBName, backend DBBackendName) {
  45. _db_tbl[name] = &SDatabase{
  46. name: name,
  47. db: db,
  48. backend: getBackend(backend),
  49. }
  50. }
  51. // GetDB get DB instance
  52. // Deprecated
  53. func GetDB() *sql.DB {
  54. return GetDefaultDB().db
  55. }
  56. // GetDefaultDB get the DB instance set by default
  57. func GetDefaultDB() *SDatabase {
  58. return GetDBWithName(DefaultDB)
  59. }
  60. // GetDBWithName returns the db instance with given name
  61. func GetDBWithName(name DBName) *SDatabase {
  62. if name == DefaultDB && len(_db_tbl) == 1 {
  63. for _, db := range _db_tbl {
  64. return db
  65. }
  66. }
  67. if db, ok := _db_tbl[name]; ok {
  68. return db
  69. }
  70. // panic(fmt.Sprintf("no such database %s", name))
  71. return nil
  72. }
  73. type sDBReferer struct {
  74. dbName DBName
  75. _db_cache *SDatabase
  76. }
  77. func (r *sDBReferer) Database() *SDatabase {
  78. if r._db_cache == nil {
  79. r._db_cache = GetDBWithName(r.dbName)
  80. }
  81. return r._db_cache
  82. }
  83. func (r *sDBReferer) DBName() DBName {
  84. return r.dbName
  85. }
  86. // CloseDB close DB connection
  87. func CloseDB() {
  88. names := make([]DBName, 0)
  89. for n, db := range _db_tbl {
  90. names = append(names, n)
  91. db.db.Close()
  92. }
  93. for _, n := range names {
  94. delete(_db_tbl, n)
  95. }
  96. }
  97. type tableName struct {
  98. Name string
  99. }
  100. // GetTables get all tables' name in default database
  101. // Deprecated
  102. func GetTables() []string {
  103. return GetDefaultDB().GetTables()
  104. }
  105. // GetTables get all tables' name in database
  106. func (db *SDatabase) GetTables() []string {
  107. tables := make([]tableName, 0)
  108. q := db.NewRawQuery(db.backend.GetTableSQL(), "name")
  109. err := q.All(&tables)
  110. if err != nil {
  111. log.Errorf("show tables fail %s", err)
  112. return nil
  113. }
  114. ret := make([]string, len(tables))
  115. for i, t := range tables {
  116. ret[i] = strings.ToLower(t.Name)
  117. }
  118. return ret
  119. }
  120. // Exec execute a raw SQL query for the default db instance
  121. // Deprecated
  122. func Exec(sql string, args ...interface{}) (sql.Result, error) {
  123. return GetDefaultDB().Exec(sql, args...)
  124. }
  125. // Exec execute a raw SQL query for a db instance
  126. func (db *SDatabase) Exec(sql string, args ...interface{}) (sql.Result, error) {
  127. return db.db.Exec(sql, args...)
  128. }
  129. type SSqlResult struct {
  130. Result sql.Result
  131. Error error
  132. }
  133. func (db *SDatabase) TxBatchExec(sqlstr string, varsList [][]interface{}) ([]SSqlResult, error) {
  134. tx, err := db.db.Begin()
  135. if err != nil {
  136. return nil, errors.Wrap(err, "Begin transaction")
  137. }
  138. defer tx.Rollback()
  139. stmt, err := tx.Prepare(sqlstr)
  140. if err != nil {
  141. return nil, errors.Wrapf(err, "Prepare sql %s", SQLPrintf(sqlstr, varsList[0]))
  142. }
  143. defer stmt.Close()
  144. results := make([]SSqlResult, len(varsList))
  145. for i := range varsList {
  146. vars := varsList[i]
  147. result, err := stmt.Exec(vars...)
  148. results[i] = SSqlResult{
  149. Result: result,
  150. Error: err,
  151. }
  152. }
  153. err = tx.Commit()
  154. if err != nil {
  155. return nil, errors.Wrap(err, "Commit transaction")
  156. }
  157. return results, nil
  158. }
  159. func (db *SDatabase) TxExec(sqlstr string, vars ...interface{}) (sql.Result, error) {
  160. results, err := db.TxBatchExec(sqlstr, [][]interface{}{
  161. vars,
  162. })
  163. if err != nil {
  164. return nil, errors.Wrap(err, "db.TxBatchExec")
  165. }
  166. return results[0].Result, results[0].Error
  167. }
  168. func (db *SDatabase) DB() *sql.DB {
  169. return db.db
  170. }