dbmethods.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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) Begin(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) {
  19. return db.DB.BeginTx(ctx, opts)
  20. }
  21. func (db *DBMethods) Close() error {
  22. return db.DB.Close()
  23. }
  24. func (db *DBMethods) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
  25. return db.DB.ExecContext(ctx, db.fixQuery(query), args...)
  26. }
  27. func (db *DBMethods) Ping(ctx context.Context) error {
  28. return db.DB.PingContext(ctx)
  29. }
  30. func (db *DBMethods) Prepare(ctx context.Context, query string) (*sql.Stmt, error) {
  31. return db.DB.PrepareContext(ctx, db.fixQuery(query))
  32. }
  33. func (db *DBMethods) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
  34. return db.DB.QueryContext(ctx, db.fixQuery(query), args...)
  35. }
  36. func (db *DBMethods) QueryRow(ctx context.Context, query string, args ...any) *sql.Row {
  37. return db.DB.QueryRowContext(ctx, db.fixQuery(query), args...)
  38. }