sqlw.go 1.7 KB

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