sqlw.go 1.8 KB

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