common.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. Close() error
  16. Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
  17. Ping(context.Context) error
  18. Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
  19. QueryRow(ctx context.Context, query string, args ...any) *sql.Row
  20. }
  21. func ParseUrl(dbURL string) (*url.URL, error) {
  22. databaseURL, err := url.Parse(dbURL)
  23. if err != nil {
  24. return nil, fmt.Errorf("unable to parse URL: %w", err)
  25. }
  26. if databaseURL.Scheme == "" {
  27. return nil, fmt.Errorf("protocol scheme is not defined")
  28. }
  29. protocols := []string{"mysql", "postgres", "postgresql", "sqlite", "sqlite3"}
  30. if !slices.Contains(protocols, databaseURL.Scheme) {
  31. return nil, fmt.Errorf("unsupported protocol scheme: %s", databaseURL.Scheme)
  32. }
  33. return databaseURL, nil
  34. }
  35. func OpenDB(databaseURL *url.URL, migrationsDir string) (*sql.DB, error) {
  36. mate := dbmate.New(databaseURL)
  37. mate.AutoDumpSchema = false
  38. mate.Log = io.Discard
  39. if migrationsDir != "" {
  40. mate.MigrationsDir = migrationsDir
  41. }
  42. driver, err := mate.GetDriver()
  43. if err != nil {
  44. return nil, fmt.Errorf("DB get driver error: %w", err)
  45. }
  46. if err := mate.CreateAndMigrate(); err != nil {
  47. return nil, fmt.Errorf("DB migration error: %w", err)
  48. }
  49. db, err := driver.Open()
  50. if err != nil {
  51. return nil, fmt.Errorf("DB open error: %w", err)
  52. }
  53. return db, nil
  54. }