tx.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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) DeleteRowByID(ctx context.Context, id int64, row any) error {
  31. query := deleteRowByIDString(row)
  32. _, err := t.Exec(ctx, query, id)
  33. return err
  34. }
  35. func (t *Tx) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
  36. start := time.Now()
  37. res, err := t.tx.ExecContext(ctx, t.fixQuery(query), args...)
  38. t.log("Exec", start, err, true, t.fixQuery(query), args...)
  39. return res, err
  40. }
  41. func (t *Tx) Query(ctx context.Context, query string, args ...any) (*Rows, error) {
  42. start := time.Now()
  43. rows, err := t.tx.QueryContext(ctx, t.fixQuery(query), args...)
  44. t.log("Query", start, err, true, t.fixQuery(query), args...)
  45. return &Rows{Rows: rows}, err
  46. }
  47. func (t *Tx) QueryRow(ctx context.Context, query string, args ...any) *Row {
  48. start := time.Now()
  49. row := t.tx.QueryRowContext(ctx, t.fixQuery(query), args...)
  50. t.log("QueryRow", start, nil, true, t.fixQuery(query), args...)
  51. return &Row{Row: row}
  52. }
  53. func (t *Tx) QueryRowByID(ctx context.Context, id int64, row any) error {
  54. query := queryRowByIDString(row)
  55. return t.QueryRow(ctx, query, id).Scans(row)
  56. }
  57. func (t *Tx) RowExists(ctx context.Context, id int64, row any) bool {
  58. var exists int
  59. query := rowExistsString(row)
  60. if err := t.QueryRow(ctx, query, id).Scan(&exists); err == nil && exists == 1 {
  61. return true
  62. }
  63. return false
  64. }
  65. func (t *Tx) Rollback() error {
  66. err := t.tx.Rollback()
  67. t.log("Rollback", t.start, err, true, "")
  68. return err
  69. }