migration_history.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package mysql
  2. import (
  3. "context"
  4. "strings"
  5. )
  6. type MigrationHistory struct {
  7. Version string
  8. CreatedTs int64
  9. }
  10. type MigrationHistoryUpsert struct {
  11. Version string
  12. }
  13. type MigrationHistoryFind struct {
  14. Version *string
  15. }
  16. func (d *DB) FindMigrationHistoryList(ctx context.Context, find *MigrationHistoryFind) ([]*MigrationHistory, error) {
  17. where, args := []string{"1 = 1"}, []any{}
  18. if v := find.Version; v != nil {
  19. where, args = append(where, "`version` = ?"), append(args, *v)
  20. }
  21. query := "SELECT `version`, UNIX_TIMESTAMP(`created_ts`) FROM `migration_history` WHERE " + strings.Join(where, " AND ") + " ORDER BY `created_ts` DESC"
  22. rows, err := d.db.QueryContext(ctx, query, args...)
  23. if err != nil {
  24. return nil, err
  25. }
  26. defer rows.Close()
  27. list := make([]*MigrationHistory, 0)
  28. for rows.Next() {
  29. var migrationHistory MigrationHistory
  30. if err := rows.Scan(
  31. &migrationHistory.Version,
  32. &migrationHistory.CreatedTs,
  33. ); err != nil {
  34. return nil, err
  35. }
  36. list = append(list, &migrationHistory)
  37. }
  38. if err := rows.Err(); err != nil {
  39. return nil, err
  40. }
  41. return list, nil
  42. }
  43. func (d *DB) UpsertMigrationHistory(ctx context.Context, upsert *MigrationHistoryUpsert) (*MigrationHistory, error) {
  44. stmt := "INSERT INTO `migration_history` (`version`) VALUES (?) ON DUPLICATE KEY UPDATE `version` = ?"
  45. _, err := d.db.ExecContext(ctx, stmt, upsert.Version, upsert.Version)
  46. if err != nil {
  47. return nil, err
  48. }
  49. var migrationHistory MigrationHistory
  50. stmt = "SELECT `version`, UNIX_TIMESTAMP(`created_ts`) FROM `migration_history` WHERE `version` = ?"
  51. if err := d.db.QueryRowContext(ctx, stmt, upsert.Version).Scan(
  52. &migrationHistory.Version,
  53. &migrationHistory.CreatedTs,
  54. ); err != nil {
  55. return nil, err
  56. }
  57. return &migrationHistory, nil
  58. }