dbmethods.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package common
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "regexp"
  7. "github.com/pkg/errors"
  8. )
  9. type DBMethods struct {
  10. DB *sql.DB
  11. Debug bool
  12. Driver string
  13. }
  14. type qFunc func(ctx context.Context, tx *sql.Tx) error
  15. var r = regexp.MustCompile(`\$\d+`)
  16. func (db *DBMethods) fixQuery(query string) string {
  17. if db.Driver == "mysql" {
  18. return r.ReplaceAllString(query, "?")
  19. }
  20. return query
  21. }
  22. func (db *DBMethods) Begin(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) {
  23. return db.DB.BeginTx(ctx, opts)
  24. }
  25. func (db *DBMethods) Close() error {
  26. return db.DB.Close()
  27. }
  28. func (db *DBMethods) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
  29. return db.DB.ExecContext(ctx, db.fixQuery(query), args...)
  30. }
  31. func (db *DBMethods) Ping(ctx context.Context) error {
  32. return db.DB.PingContext(ctx)
  33. }
  34. func (db *DBMethods) Prepare(ctx context.Context, query string) (*sql.Stmt, error) {
  35. return db.DB.PrepareContext(ctx, db.fixQuery(query))
  36. }
  37. func (db *DBMethods) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
  38. return db.DB.QueryContext(ctx, db.fixQuery(query), args...)
  39. }
  40. func (db *DBMethods) QueryRow(ctx context.Context, query string, args ...any) *sql.Row {
  41. return db.DB.QueryRowContext(ctx, db.fixQuery(query), args...)
  42. }
  43. func (db *DBMethods) Transaction(ctx context.Context, queries qFunc) error {
  44. if queries == nil {
  45. return fmt.Errorf("queries is not set for transaction")
  46. }
  47. tx, err := db.Begin(ctx, nil)
  48. if err != nil {
  49. return err
  50. }
  51. if err := queries(ctx, tx); err != nil {
  52. return errors.Wrap(err, tx.Rollback().Error())
  53. }
  54. return tx.Commit()
  55. }