gdb_transaction.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gdb
  7. import (
  8. "database/sql"
  9. "fmt"
  10. "reflect"
  11. "github.com/gogf/gf/text/gregex"
  12. )
  13. // TX is the struct for transaction management.
  14. type TX struct {
  15. db DB
  16. tx *sql.Tx
  17. master *sql.DB
  18. }
  19. // Commit commits the transaction.
  20. func (tx *TX) Commit() error {
  21. return tx.tx.Commit()
  22. }
  23. // Rollback aborts the transaction.
  24. func (tx *TX) Rollback() error {
  25. return tx.tx.Rollback()
  26. }
  27. // Query does query operation on transaction.
  28. // See Core.Query.
  29. func (tx *TX) Query(sql string, args ...interface{}) (rows *sql.Rows, err error) {
  30. return tx.db.DoQuery(tx.tx, sql, args...)
  31. }
  32. // Exec does none query operation on transaction.
  33. // See Core.Exec.
  34. func (tx *TX) Exec(sql string, args ...interface{}) (sql.Result, error) {
  35. return tx.db.DoExec(tx.tx, sql, args...)
  36. }
  37. // Prepare creates a prepared statement for later queries or executions.
  38. // Multiple queries or executions may be run concurrently from the
  39. // returned statement.
  40. // The caller must call the statement's Close method
  41. // when the statement is no longer needed.
  42. func (tx *TX) Prepare(sql string) (*sql.Stmt, error) {
  43. return tx.db.DoPrepare(tx.tx, sql)
  44. }
  45. // GetAll queries and returns data records from database.
  46. func (tx *TX) GetAll(sql string, args ...interface{}) (Result, error) {
  47. rows, err := tx.Query(sql, args...)
  48. if err != nil || rows == nil {
  49. return nil, err
  50. }
  51. defer rows.Close()
  52. return tx.db.convertRowsToResult(rows)
  53. }
  54. // GetOne queries and returns one record from database.
  55. func (tx *TX) GetOne(sql string, args ...interface{}) (Record, error) {
  56. list, err := tx.GetAll(sql, args...)
  57. if err != nil {
  58. return nil, err
  59. }
  60. if len(list) > 0 {
  61. return list[0], nil
  62. }
  63. return nil, nil
  64. }
  65. // GetStruct queries one record from database and converts it to given struct.
  66. // The parameter <pointer> should be a pointer to struct.
  67. func (tx *TX) GetStruct(obj interface{}, sql string, args ...interface{}) error {
  68. one, err := tx.GetOne(sql, args...)
  69. if err != nil {
  70. return err
  71. }
  72. return one.Struct(obj)
  73. }
  74. // GetStructs queries records from database and converts them to given struct.
  75. // The parameter <pointer> should be type of struct slice: []struct/[]*struct.
  76. func (tx *TX) GetStructs(objPointerSlice interface{}, sql string, args ...interface{}) error {
  77. all, err := tx.GetAll(sql, args...)
  78. if err != nil {
  79. return err
  80. }
  81. return all.Structs(objPointerSlice)
  82. }
  83. // GetScan queries one or more records from database and converts them to given struct or
  84. // struct array.
  85. //
  86. // If parameter <pointer> is type of struct pointer, it calls GetStruct internally for
  87. // the conversion. If parameter <pointer> is type of slice, it calls GetStructs internally
  88. // for conversion.
  89. func (tx *TX) GetScan(objPointer interface{}, sql string, args ...interface{}) error {
  90. t := reflect.TypeOf(objPointer)
  91. k := t.Kind()
  92. if k != reflect.Ptr {
  93. return fmt.Errorf("params should be type of pointer, but got: %v", k)
  94. }
  95. k = t.Elem().Kind()
  96. switch k {
  97. case reflect.Array, reflect.Slice:
  98. return tx.db.GetStructs(objPointer, sql, args...)
  99. case reflect.Struct:
  100. return tx.db.GetStruct(objPointer, sql, args...)
  101. default:
  102. return fmt.Errorf("element type should be type of struct/slice, unsupported: %v", k)
  103. }
  104. }
  105. // GetValue queries and returns the field value from database.
  106. // The sql should queries only one field from database, or else it returns only one
  107. // field of the result.
  108. func (tx *TX) GetValue(sql string, args ...interface{}) (Value, error) {
  109. one, err := tx.GetOne(sql, args...)
  110. if err != nil {
  111. return nil, err
  112. }
  113. for _, v := range one {
  114. return v, nil
  115. }
  116. return nil, nil
  117. }
  118. // GetCount queries and returns the count from database.
  119. func (tx *TX) GetCount(sql string, args ...interface{}) (int, error) {
  120. if !gregex.IsMatchString(`(?i)SELECT\s+COUNT\(.+\)\s+FROM`, sql) {
  121. sql, _ = gregex.ReplaceString(`(?i)(SELECT)\s+(.+)\s+(FROM)`, `$1 COUNT($2) $3`, sql)
  122. }
  123. value, err := tx.GetValue(sql, args...)
  124. if err != nil {
  125. return 0, err
  126. }
  127. return value.Int(), nil
  128. }
  129. // Insert does "INSERT INTO ..." statement for the table.
  130. // If there's already one unique record of the data in the table, it returns error.
  131. //
  132. // The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc.
  133. // Eg:
  134. // Data(g.Map{"uid": 10000, "name":"john"})
  135. // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
  136. //
  137. // The parameter <batch> specifies the batch operation count when given data is slice.
  138. func (tx *TX) Insert(table string, data interface{}, batch ...int) (sql.Result, error) {
  139. if len(batch) > 0 {
  140. return tx.Model(table).Data(data).Batch(batch[0]).Insert()
  141. }
  142. return tx.Model(table).Data(data).Insert()
  143. }
  144. // InsertIgnore does "INSERT IGNORE INTO ..." statement for the table.
  145. // If there's already one unique record of the data in the table, it ignores the inserting.
  146. //
  147. // The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc.
  148. // Eg:
  149. // Data(g.Map{"uid": 10000, "name":"john"})
  150. // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
  151. //
  152. // The parameter <batch> specifies the batch operation count when given data is slice.
  153. func (tx *TX) InsertIgnore(table string, data interface{}, batch ...int) (sql.Result, error) {
  154. if len(batch) > 0 {
  155. return tx.Model(table).Data(data).Batch(batch[0]).InsertIgnore()
  156. }
  157. return tx.Model(table).Data(data).InsertIgnore()
  158. }
  159. // Replace does "REPLACE INTO ..." statement for the table.
  160. // If there's already one unique record of the data in the table, it deletes the record
  161. // and inserts a new one.
  162. //
  163. // The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc.
  164. // Eg:
  165. // Data(g.Map{"uid": 10000, "name":"john"})
  166. // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
  167. //
  168. // The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc.
  169. // If given data is type of slice, it then does batch replacing, and the optional parameter
  170. // <batch> specifies the batch operation count.
  171. func (tx *TX) Replace(table string, data interface{}, batch ...int) (sql.Result, error) {
  172. if len(batch) > 0 {
  173. return tx.Model(table).Data(data).Batch(batch[0]).Replace()
  174. }
  175. return tx.Model(table).Data(data).Replace()
  176. }
  177. // Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the table.
  178. // It updates the record if there's primary or unique index in the saving data,
  179. // or else it inserts a new record into the table.
  180. //
  181. // The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc.
  182. // Eg:
  183. // Data(g.Map{"uid": 10000, "name":"john"})
  184. // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
  185. //
  186. // If given data is type of slice, it then does batch saving, and the optional parameter
  187. // <batch> specifies the batch operation count.
  188. func (tx *TX) Save(table string, data interface{}, batch ...int) (sql.Result, error) {
  189. if len(batch) > 0 {
  190. return tx.Model(table).Data(data).Batch(batch[0]).Save()
  191. }
  192. return tx.Model(table).Data(data).Save()
  193. }
  194. // BatchInsert batch inserts data.
  195. // The parameter <list> must be type of slice of map or struct.
  196. func (tx *TX) BatchInsert(table string, list interface{}, batch ...int) (sql.Result, error) {
  197. if len(batch) > 0 {
  198. return tx.Model(table).Data(list).Batch(batch[0]).Insert()
  199. }
  200. return tx.Model(table).Data(list).Insert()
  201. }
  202. // BatchInsert batch inserts data with ignore option.
  203. // The parameter <list> must be type of slice of map or struct.
  204. func (tx *TX) BatchInsertIgnore(table string, list interface{}, batch ...int) (sql.Result, error) {
  205. if len(batch) > 0 {
  206. return tx.Model(table).Data(list).Batch(batch[0]).InsertIgnore()
  207. }
  208. return tx.Model(table).Data(list).InsertIgnore()
  209. }
  210. // BatchReplace batch replaces data.
  211. // The parameter <list> must be type of slice of map or struct.
  212. func (tx *TX) BatchReplace(table string, list interface{}, batch ...int) (sql.Result, error) {
  213. if len(batch) > 0 {
  214. return tx.Model(table).Data(list).Batch(batch[0]).Replace()
  215. }
  216. return tx.Model(table).Data(list).Replace()
  217. }
  218. // BatchSave batch replaces data.
  219. // The parameter <list> must be type of slice of map or struct.
  220. func (tx *TX) BatchSave(table string, list interface{}, batch ...int) (sql.Result, error) {
  221. if len(batch) > 0 {
  222. return tx.Model(table).Data(list).Batch(batch[0]).Save()
  223. }
  224. return tx.Model(table).Data(list).Save()
  225. }
  226. // Update does "UPDATE ... " statement for the table.
  227. //
  228. // The parameter <data> can be type of string/map/gmap/struct/*struct, etc.
  229. // Eg: "uid=10000", "uid", 10000, g.Map{"uid": 10000, "name":"john"}
  230. //
  231. // The parameter <condition> can be type of string/map/gmap/slice/struct/*struct, etc.
  232. // It is commonly used with parameter <args>.
  233. // Eg:
  234. // "uid=10000",
  235. // "uid", 10000
  236. // "money>? AND name like ?", 99999, "vip_%"
  237. // "status IN (?)", g.Slice{1,2,3}
  238. // "age IN(?,?)", 18, 50
  239. // User{ Id : 1, UserName : "john"}
  240. func (tx *TX) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) {
  241. return tx.Model(table).Data(data).Where(condition, args...).Update()
  242. }
  243. // Delete does "DELETE FROM ... " statement for the table.
  244. //
  245. // The parameter <condition> can be type of string/map/gmap/slice/struct/*struct, etc.
  246. // It is commonly used with parameter <args>.
  247. // Eg:
  248. // "uid=10000",
  249. // "uid", 10000
  250. // "money>? AND name like ?", 99999, "vip_%"
  251. // "status IN (?)", g.Slice{1,2,3}
  252. // "age IN(?,?)", 18, 50
  253. // User{ Id : 1, UserName : "john"}
  254. func (tx *TX) Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error) {
  255. return tx.Model(table).Where(condition, args...).Delete()
  256. }