dbmethods.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package common
  2. import (
  3. "context"
  4. "database/sql"
  5. "regexp"
  6. )
  7. type DBMethods struct {
  8. DB *sql.DB
  9. Driver string
  10. }
  11. var r = regexp.MustCompile(`\$\d+`)
  12. func (db *DBMethods) fixQuery(query string) string {
  13. if db.Driver == "mysql" {
  14. return r.ReplaceAllString(query, "?")
  15. }
  16. return query
  17. }
  18. func (db *DBMethods) Close() error {
  19. return db.DB.Close()
  20. }
  21. func (db *DBMethods) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
  22. return db.DB.ExecContext(ctx, db.fixQuery(query), args...)
  23. }
  24. func (db *DBMethods) Ping(ctx context.Context) error {
  25. return db.DB.PingContext(ctx)
  26. }
  27. func (db *DBMethods) Prepare(ctx context.Context, query string) (*sql.Stmt, error) {
  28. return db.DB.PrepareContext(ctx, db.fixQuery(query))
  29. }
  30. func (db *DBMethods) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
  31. return db.DB.QueryContext(ctx, db.fixQuery(query), args...)
  32. }
  33. func (db *DBMethods) QueryRow(ctx context.Context, query string, args ...any) *sql.Row {
  34. return db.DB.QueryRowContext(ctx, db.fixQuery(query), args...)
  35. }