migrate.rb 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # lib/migrate.rb
  2. # Lightweight sequential schema migration runner.
  3. #
  4. # Tracks applied migrations in a `schema_migrations` table (single source of
  5. # truth). Every migration is idempotent — it uses ADD COLUMN IF NOT EXISTS and
  6. # CREATE TABLE IF NOT EXISTS so re-running a partially-applied version is safe.
  7. #
  8. # Usage — call once at container/process startup, before any scrapers run:
  9. #
  10. # require_relative "lib/migrate"
  11. # Migrate.run!
  12. #
  13. # Or run as a standalone script:
  14. #
  15. # ruby /app/lib/migrate.rb
  16. require_relative "./db"
  17. require_relative "./log"
  18. module Migrate
  19. # -------------------------------------------------------------------------
  20. # Migration definitions — add new ones at the END of this array only.
  21. # Never edit or reorder existing entries; create a new version instead.
  22. # -------------------------------------------------------------------------
  23. MIGRATIONS = [
  24. {
  25. version: 1,
  26. description: "Add enrichment and geocode columns to all existing da_* tables",
  27. up: -> {
  28. # These are the columns every da_* table should have. New tables already
  29. # get all of them via DB.ensure_table!; this migration adds them to tables
  30. # that were created before these columns were introduced.
  31. cols = {
  32. "on_notice_to" => "DATE NULL",
  33. "on_notice_to_raw" => "VARCHAR(80) NULL",
  34. "title_reference" => "TEXT NULL",
  35. "property_id" => "TEXT NULL",
  36. "area_sqm" => "DOUBLE NULL",
  37. "area_ha" => "DOUBLE NULL",
  38. "address_std" => "VARCHAR(255) NULL",
  39. "street" => "VARCHAR(120) NULL",
  40. "locality" => "VARCHAR(120) NULL",
  41. "state" => "VARCHAR(10) NULL",
  42. "postcode" => "VARCHAR(10) NULL",
  43. "document_url" => "TEXT NULL",
  44. "local_document_url" => "TEXT NULL",
  45. "lat" => "DECIMAL(10,7) NULL",
  46. "lng" => "DECIMAL(10,7) NULL"
  47. }
  48. Migrate.da_tables.each do |table|
  49. esc = DB.client.escape(table)
  50. cols.each do |col, defn|
  51. DB.client.query(
  52. "ALTER TABLE `#{esc}` ADD COLUMN IF NOT EXISTS `#{col}` #{defn}"
  53. )
  54. rescue Mysql2::Error => e
  55. Log.warn "migrate", "skipped #{table}.#{col}: #{e.message}"
  56. end
  57. end
  58. }
  59. },
  60. {
  61. version: 2,
  62. description: "Create geo_cache table",
  63. up: -> {
  64. DB.client.query(<<~SQL)
  65. CREATE TABLE IF NOT EXISTS geo_cache (
  66. id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  67. q_hash CHAR(40) NOT NULL UNIQUE,
  68. query_text VARCHAR(255) NOT NULL,
  69. formatted VARCHAR(255),
  70. street VARCHAR(255),
  71. locality VARCHAR(120),
  72. state VARCHAR(10),
  73. postcode VARCHAR(10),
  74. lat DECIMAL(10,7),
  75. lng DECIMAL(10,7),
  76. raw_json MEDIUMTEXT,
  77. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  78. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  79. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  80. SQL
  81. }
  82. }
  83. ].freeze
  84. # -------------------------------------------------------------------------
  85. # Public API
  86. # -------------------------------------------------------------------------
  87. # Apply all pending migrations and record them in schema_migrations.
  88. # Raises on unexpected errors so the caller (run_all.sh) aborts early.
  89. def self.run!
  90. ensure_migrations_table!
  91. applied = applied_versions
  92. pending = MIGRATIONS.reject { |m| applied.include?(m[:version]) }
  93. if pending.empty?
  94. Log.info "migrate", "schema up to date (#{MIGRATIONS.size} migration(s) applied)"
  95. return
  96. end
  97. pending.each do |m|
  98. Log.info "migrate", "applying v#{m[:version]}: #{m[:description]}"
  99. m[:up].call
  100. stmt = DB.client.prepare(
  101. "INSERT INTO schema_migrations (version, description) VALUES (?, ?)"
  102. )
  103. stmt.execute(m[:version], m[:description])
  104. Log.info "migrate", "v#{m[:version]} done"
  105. end
  106. end
  107. # -------------------------------------------------------------------------
  108. # Helpers (private to module)
  109. # -------------------------------------------------------------------------
  110. def self.ensure_migrations_table!
  111. DB.client.query(<<~SQL)
  112. CREATE TABLE IF NOT EXISTS schema_migrations (
  113. version INT UNSIGNED NOT NULL,
  114. description VARCHAR(255) NOT NULL,
  115. applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  116. PRIMARY KEY (version)
  117. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  118. SQL
  119. end
  120. def self.applied_versions
  121. rs = DB.client.query("SELECT version FROM schema_migrations ORDER BY version")
  122. rs.map { |r| r["version"] }.to_set
  123. end
  124. # All da_* tables currently in the database.
  125. def self.da_tables
  126. # The backslash escapes _ (a LIKE wildcard) so only genuine da_ prefixes match.
  127. rs = DB.client.query("SHOW TABLES LIKE 'da\\_%'")
  128. rs.map { |r| r.values.first }
  129. end
  130. private_class_method :ensure_migrations_table!, :applied_versions, :da_tables
  131. end
  132. # Allow running as a standalone script: ruby /app/lib/migrate.rb
  133. if __FILE__ == $0
  134. Migrate.run!
  135. end