tx.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package common
  2. import (
  3. "context"
  4. "database/sql"
  5. "os"
  6. "time"
  7. )
  8. type Tx struct {
  9. tx *sql.Tx
  10. Debug bool
  11. Driver string
  12. t time.Time
  13. }
  14. func (db *Tx) fixQuery(query string) string {
  15. if db.Driver == "mysql" {
  16. return fixQuery(query)
  17. }
  18. return query
  19. }
  20. func (db *Tx) Commit() error {
  21. if db.Debug {
  22. err := db.tx.Commit()
  23. log(os.Stdout, "[func Commit]", db.t, err, true, "")
  24. return err
  25. }
  26. return db.tx.Commit()
  27. }
  28. func (db *Tx) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
  29. if db.Debug {
  30. t := time.Now()
  31. res, err := db.tx.ExecContext(ctx, db.fixQuery(query), args...)
  32. log(os.Stdout, "[func Exec]", t, err, true, db.fixQuery(query), args...)
  33. return res, err
  34. }
  35. return db.tx.ExecContext(ctx, db.fixQuery(query), args...)
  36. }
  37. func (db *Tx) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
  38. if db.Debug {
  39. t := time.Now()
  40. rows, err := db.tx.QueryContext(ctx, db.fixQuery(query), args...)
  41. log(os.Stdout, "[func Query]", t, err, true, db.fixQuery(query), args...)
  42. return rows, err
  43. }
  44. return db.tx.QueryContext(ctx, db.fixQuery(query), args...)
  45. }
  46. func (db *Tx) QueryRow(ctx context.Context, query string, args ...any) *sql.Row {
  47. if db.Debug {
  48. t := time.Now()
  49. row := db.tx.QueryRowContext(ctx, db.fixQuery(query), args...)
  50. log(os.Stdout, "[func QueryRow]", t, nil, true, db.fixQuery(query), args...)
  51. return row
  52. }
  53. return db.tx.QueryRowContext(ctx, db.fixQuery(query), args...)
  54. }
  55. func (db *Tx) Rollback() error {
  56. if db.Debug {
  57. err := db.tx.Rollback()
  58. log(os.Stdout, "[func Rollback]", db.t, err, true, "")
  59. return err
  60. }
  61. return db.tx.Rollback()
  62. }