common.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package common
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "io"
  7. "net/url"
  8. "regexp"
  9. "strings"
  10. "time"
  11. "github.com/amacneil/dbmate/pkg/dbmate"
  12. _ "github.com/amacneil/dbmate/pkg/driver/mysql"
  13. _ "github.com/amacneil/dbmate/pkg/driver/postgres"
  14. _ "github.com/amacneil/dbmate/pkg/driver/sqlite"
  15. "golang.org/x/exp/slices"
  16. )
  17. type Engine interface {
  18. Begin(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
  19. Close() error
  20. Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
  21. Ping(context.Context) error
  22. Prepare(ctx context.Context, query string) (*sql.Stmt, error)
  23. Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
  24. QueryRow(ctx context.Context, query string, args ...any) *sql.Row
  25. Transaction(ctx context.Context, queries func(ctx context.Context, tx *Tx) error) error
  26. }
  27. var rLogSpacesAll = regexp.MustCompile(`[\s\t]+`)
  28. var rLogSpacesEnd = regexp.MustCompile(`[\s\t]+;$`)
  29. var rSqlParam = regexp.MustCompile(`\$\d+`)
  30. func log(w io.Writer, m string, s time.Time, e error, tx bool, query string, args ...any) string {
  31. var tmsg string
  32. if tx {
  33. tmsg = " [TX]"
  34. }
  35. if m != "" {
  36. tmsg = tmsg + " " + m
  37. }
  38. qmsg := query
  39. if qmsg != "" {
  40. qmsg = strings.Trim(rLogSpacesAll.ReplaceAllString(qmsg, " "), " ")
  41. qmsg = rLogSpacesEnd.ReplaceAllString(qmsg, ";")
  42. qmsg = " " + qmsg
  43. }
  44. astr := " (empty)"
  45. if len(args) > 0 {
  46. astr = fmt.Sprintf(" (%v)", args)
  47. }
  48. bold := "0"
  49. color := "33"
  50. estr := " (nil)"
  51. if e != nil {
  52. color = "31"
  53. estr = " (" + e.Error() + ")"
  54. }
  55. if tx {
  56. bold = "1"
  57. }
  58. res := fmt.Sprintln("\033[" + bold + ";" + color + "m[SQL]" + tmsg + qmsg + astr + estr + fmt.Sprintf(" %.3f ms", time.Since(s).Seconds()) + "\033[0m")
  59. fmt.Fprint(w, res)
  60. return res
  61. }
  62. func fixQuery(query string) string {
  63. return rSqlParam.ReplaceAllString(query, "?")
  64. }
  65. func ParseUrl(dbURL string) (*url.URL, error) {
  66. databaseURL, err := url.Parse(dbURL)
  67. if err != nil {
  68. return nil, fmt.Errorf("unable to parse URL: %w", err)
  69. }
  70. if databaseURL.Scheme == "" {
  71. return nil, fmt.Errorf("protocol scheme is not defined")
  72. }
  73. protocols := []string{"mysql", "postgres", "postgresql", "sqlite", "sqlite3"}
  74. if !slices.Contains(protocols, databaseURL.Scheme) {
  75. return nil, fmt.Errorf("unsupported protocol scheme: %s", databaseURL.Scheme)
  76. }
  77. return databaseURL, nil
  78. }
  79. func OpenDB(databaseURL *url.URL, migrationsDir string) (*sql.DB, error) {
  80. mate := dbmate.New(databaseURL)
  81. mate.AutoDumpSchema = false
  82. mate.Log = io.Discard
  83. if migrationsDir != "" {
  84. mate.MigrationsDir = migrationsDir
  85. }
  86. driver, err := mate.GetDriver()
  87. if err != nil {
  88. return nil, fmt.Errorf("DB get driver error: %w", err)
  89. }
  90. if err := mate.CreateAndMigrate(); err != nil {
  91. return nil, fmt.Errorf("DB migration error: %w", err)
  92. }
  93. db, err := driver.Open()
  94. if err != nil {
  95. return nil, fmt.Errorf("DB open error: %w", err)
  96. }
  97. return db, nil
  98. }