tx.go 2.0 KB

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