sqlw.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package sqlw
  2. import (
  3. "database/sql"
  4. _ "github.com/go-sql-driver/mysql"
  5. "errors"
  6. "time"
  7. "golang-fave/consts"
  8. )
  9. type Rows = sql.Rows
  10. type DB struct {
  11. db *sql.DB
  12. }
  13. var ErrNoRows = sql.ErrNoRows
  14. func Open(driverName, dataSourceName string) (*DB, error) {
  15. db, err := sql.Open(driverName, dataSourceName)
  16. if err != nil {
  17. return nil, err
  18. }
  19. return &DB{db: db}, err
  20. }
  21. func (this *DB) Close() error {
  22. return this.db.Close()
  23. }
  24. func (this *DB) Ping() error {
  25. return this.db.Ping()
  26. }
  27. func (this *DB) SetConnMaxLifetime(d time.Duration) {
  28. this.db.SetConnMaxLifetime(d)
  29. }
  30. func (this *DB) SetMaxIdleConns(n int) {
  31. this.db.SetMaxIdleConns(n)
  32. }
  33. func (this *DB) SetMaxOpenConns(n int) {
  34. this.db.SetMaxOpenConns(n)
  35. }
  36. func (this *DB) QueryRow(query string, args ...interface{}) *sql.Row {
  37. if consts.ParamDebug {
  38. s := time.Now()
  39. r := this.db.QueryRow(query, args...)
  40. log(query, s, nil, false)
  41. return r
  42. }
  43. return this.db.QueryRow(query, args...)
  44. }
  45. func (this *DB) Begin() (*Tx, error) {
  46. tx, err := this.db.Begin()
  47. if err != nil {
  48. if consts.ParamDebug {
  49. log("[TX] TRANSACTION START", time.Now(), err, true)
  50. }
  51. return nil, err
  52. }
  53. if consts.ParamDebug {
  54. s := time.Now()
  55. log("[TX] TRANSACTION START", s, err, true)
  56. return &Tx{tx, s}, err
  57. }
  58. return &Tx{tx, time.Now()}, err
  59. }
  60. func (this *DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
  61. if consts.ParamDebug {
  62. s := time.Now()
  63. r, e := this.db.Query(query, args...)
  64. log(query, s, e, false)
  65. return r, e
  66. }
  67. return this.db.Query(query, args...)
  68. }
  69. func (this *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
  70. if consts.ParamDebug {
  71. s := time.Now()
  72. r, e := this.db.Exec(query, args...)
  73. log(query, s, e, false)
  74. return r, e
  75. }
  76. return this.db.Exec(query, args...)
  77. }
  78. func (this *DB) Transaction(queries func(tx *Tx) error) error {
  79. if queries == nil {
  80. return errors.New("queries is not set for transaction")
  81. }
  82. tx, err := this.Begin()
  83. if err != nil {
  84. return err
  85. }
  86. err = queries(tx)
  87. if err != nil {
  88. tx.Rollback()
  89. return err
  90. }
  91. return tx.Commit()
  92. }