migration_history.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package sqlite
  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 := `
  22. SELECT
  23. version,
  24. created_ts
  25. FROM
  26. migration_history
  27. WHERE ` + strings.Join(where, " AND ") + `
  28. ORDER BY created_ts DESC
  29. `
  30. rows, err := d.db.QueryContext(ctx, query, args...)
  31. if err != nil {
  32. return nil, err
  33. }
  34. defer rows.Close()
  35. list := make([]*MigrationHistory, 0)
  36. for rows.Next() {
  37. var migrationHistory MigrationHistory
  38. if err := rows.Scan(
  39. &migrationHistory.Version,
  40. &migrationHistory.CreatedTs,
  41. ); err != nil {
  42. return nil, err
  43. }
  44. list = append(list, &migrationHistory)
  45. }
  46. if err := rows.Err(); err != nil {
  47. return nil, err
  48. }
  49. return list, nil
  50. }
  51. func (d *DB) UpsertMigrationHistory(ctx context.Context, upsert *MigrationHistoryUpsert) (*MigrationHistory, error) {
  52. stmt := `
  53. INSERT INTO migration_history (
  54. version
  55. )
  56. VALUES (?)
  57. ON CONFLICT(version) DO UPDATE
  58. SET
  59. version=EXCLUDED.version
  60. RETURNING version, created_ts
  61. `
  62. var migrationHistory MigrationHistory
  63. if err := d.db.QueryRowContext(ctx, stmt, upsert.Version).Scan(
  64. &migrationHistory.Version,
  65. &migrationHistory.CreatedTs,
  66. ); err != nil {
  67. return nil, err
  68. }
  69. return &migrationHistory, nil
  70. }