tx.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. start time.Time
  13. }
  14. func (t *Tx) fixQuery(query string) string {
  15. if t.Driver == "mysql" {
  16. return fixQuery(query)
  17. }
  18. return query
  19. }
  20. func (t *Tx) log(fname string, start time.Time, err error, tx bool, query string, args ...any) {
  21. if t.Debug {
  22. log(os.Stdout, fname, start, err, tx, query, args...)
  23. }
  24. }
  25. func (t *Tx) Commit() error {
  26. err := t.tx.Commit()
  27. t.log("Commit", t.start, err, true, "")
  28. return err
  29. }
  30. func (t *Tx) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
  31. start := time.Now()
  32. res, err := t.tx.ExecContext(ctx, t.fixQuery(query), args...)
  33. t.log("Exec", start, err, true, t.fixQuery(query), args...)
  34. return res, err
  35. }
  36. func (t *Tx) Query(ctx context.Context, query string, args ...any) (*Rows, error) {
  37. start := time.Now()
  38. rows, err := t.tx.QueryContext(ctx, t.fixQuery(query), args...)
  39. t.log("Query", start, err, true, t.fixQuery(query), args...)
  40. return &Rows{Rows: rows}, err
  41. }
  42. func (t *Tx) QueryRow(ctx context.Context, query string, args ...any) *Row {
  43. start := time.Now()
  44. row := t.tx.QueryRowContext(ctx, t.fixQuery(query), args...)
  45. t.log("QueryRow", start, nil, true, t.fixQuery(query), args...)
  46. return &Row{Row: row}
  47. }
  48. func (t *Tx) Rollback() error {
  49. err := t.tx.Rollback()
  50. t.log("Rollback", t.start, err, true, "")
  51. return err
  52. }