sqlw.go 2.1 KB

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