common.go 1.7 KB

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