sqlw.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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, 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. return nil, err
  49. }
  50. if consts.ParamDebug {
  51. s := time.Now()
  52. log("[TX] TRANSACTION START", s, true)
  53. return &Tx{tx, s}, err
  54. }
  55. return &Tx{tx, time.Now()}, err
  56. }
  57. func (this *DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
  58. if consts.ParamDebug {
  59. s := time.Now()
  60. r, e := this.db.Query(query, args...)
  61. log(query, s, false)
  62. return r, e
  63. }
  64. return this.db.Query(query, args...)
  65. }
  66. func (this *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
  67. if consts.ParamDebug {
  68. s := time.Now()
  69. r, e := this.db.Exec(query, args...)
  70. log(query, s, false)
  71. return r, e
  72. }
  73. return this.db.Exec(query, args...)
  74. }
  75. func (this *DB) Transaction(queries func(tx *Tx) error) error {
  76. if queries == nil {
  77. return errors.New("queries is not set for transaction")
  78. }
  79. tx, err := this.Begin()
  80. if err != nil {
  81. return err
  82. }
  83. err = queries(tx)
  84. if err != nil {
  85. tx.Rollback()
  86. return err
  87. }
  88. return tx.Commit()
  89. }