common.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package common
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "io"
  7. "net/url"
  8. "github.com/amacneil/dbmate/pkg/dbmate"
  9. _ "github.com/amacneil/dbmate/pkg/driver/mysql"
  10. _ "github.com/amacneil/dbmate/pkg/driver/postgres"
  11. _ "github.com/amacneil/dbmate/pkg/driver/sqlite"
  12. "golang.org/x/exp/slices"
  13. )
  14. type Engine interface {
  15. Begin(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
  16. Close() error
  17. Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
  18. Ping(context.Context) error
  19. Prepare(ctx context.Context, query string) (*sql.Stmt, error)
  20. Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
  21. QueryRow(ctx context.Context, query string, args ...any) *sql.Row
  22. }
  23. func ParseUrl(dbURL string) (*url.URL, error) {
  24. databaseURL, err := url.Parse(dbURL)
  25. if err != nil {
  26. return nil, fmt.Errorf("unable to parse URL: %w", err)
  27. }
  28. if databaseURL.Scheme == "" {
  29. return nil, fmt.Errorf("protocol scheme is not defined")
  30. }
  31. protocols := []string{"mysql", "postgres", "postgresql", "sqlite", "sqlite3"}
  32. if !slices.Contains(protocols, databaseURL.Scheme) {
  33. return nil, fmt.Errorf("unsupported protocol scheme: %s", databaseURL.Scheme)
  34. }
  35. return databaseURL, nil
  36. }
  37. func OpenDB(databaseURL *url.URL, migrationsDir string) (*sql.DB, error) {
  38. mate := dbmate.New(databaseURL)
  39. mate.AutoDumpSchema = false
  40. mate.Log = io.Discard
  41. if migrationsDir != "" {
  42. mate.MigrationsDir = migrationsDir
  43. }
  44. driver, err := mate.GetDriver()
  45. if err != nil {
  46. return nil, fmt.Errorf("DB get driver error: %w", err)
  47. }
  48. if err := mate.CreateAndMigrate(); err != nil {
  49. return nil, fmt.Errorf("DB migration error: %w", err)
  50. }
  51. db, err := driver.Open()
  52. if err != nil {
  53. return nil, fmt.Errorf("DB open error: %w", err)
  54. }
  55. return db, nil
  56. }