tx.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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) QueryRowByID(ctx context.Context, id int64, row any) error {
  49. query := queryRowByIDString(row)
  50. return t.QueryRow(ctx, query, id).Scans(row)
  51. }
  52. func (t *Tx) RowExists(ctx context.Context, id int64, row any) bool {
  53. var exists int
  54. query := rowExistsString(row)
  55. if err := t.QueryRow(ctx, query, id).Scan(&exists); err == nil && exists == 1 {
  56. return true
  57. }
  58. return false
  59. }
  60. func (t *Tx) Rollback() error {
  61. err := t.tx.Rollback()
  62. t.log("Rollback", t.start, err, true, "")
  63. return err
  64. }