dbmethods.go 854 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package common
  2. import (
  3. "context"
  4. "database/sql"
  5. "regexp"
  6. )
  7. type DBMethods struct {
  8. *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) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
  19. return db.DB.ExecContext(ctx, db.fixQuery(query), args...)
  20. }
  21. func (db *DBMethods) Ping(ctx context.Context) error {
  22. return db.PingContext(ctx)
  23. }
  24. func (db *DBMethods) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
  25. return db.DB.QueryContext(ctx, db.fixQuery(query), args...)
  26. }
  27. func (db *DBMethods) QueryRow(ctx context.Context, query string, args ...any) *sql.Row {
  28. return db.DB.QueryRowContext(ctx, db.fixQuery(query), args...)
  29. }