migrate.rb 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. {
  84. version: 3,
  85. description: "Add documents_json column to all existing da_* tables",
  86. up: -> {
  87. Migrate.da_tables.each do |table|
  88. esc = DB.client.escape(table)
  89. DB.client.query(
  90. "ALTER TABLE `#{esc}` ADD COLUMN IF NOT EXISTS `documents_json` MEDIUMTEXT NULL"
  91. )
  92. rescue Mysql2::Error => e
  93. Log.warn "migrate", "skipped #{table}.documents_json: #{e.message}"
  94. end
  95. }
  96. },
  97. {
  98. version: 4,
  99. description: "Add application detail columns (status, assigned_officer, group, category, application_valid, advertised_on, property_legal_description)",
  100. up: -> {
  101. cols = {
  102. "status" => "VARCHAR(100) NULL",
  103. "assigned_officer" => "VARCHAR(255) NULL",
  104. "`group`" => "VARCHAR(100) NULL",
  105. "category" => "VARCHAR(100) NULL",
  106. "application_valid" => "DATE NULL",
  107. "application_valid_raw" => "VARCHAR(80) NULL",
  108. "advertised_on" => "DATE NULL",
  109. "advertised_on_raw" => "VARCHAR(80) NULL",
  110. "property_legal_description" => "TEXT NULL"
  111. }
  112. Migrate.da_tables.each do |table|
  113. esc = DB.client.escape(table)
  114. cols.each do |col, defn|
  115. DB.client.query(
  116. "ALTER TABLE `#{esc}` ADD COLUMN IF NOT EXISTS #{col} #{defn}"
  117. )
  118. rescue Mysql2::Error => e
  119. Log.warn "migrate", "skipped #{table}.#{col}: #{e.message}"
  120. end
  121. end
  122. }
  123. }
  124. ].freeze
  125. # -------------------------------------------------------------------------
  126. # Public API
  127. # -------------------------------------------------------------------------
  128. # Apply all pending migrations and record them in schema_migrations.
  129. # Raises on unexpected errors so the caller (run_all.sh) aborts early.
  130. def self.run!
  131. ensure_migrations_table!
  132. applied = applied_versions
  133. pending = MIGRATIONS.reject { |m| applied.include?(m[:version]) }
  134. if pending.empty?
  135. Log.info "migrate", "schema up to date (#{MIGRATIONS.size} migration(s) applied)"
  136. return
  137. end
  138. pending.each do |m|
  139. Log.info "migrate", "applying v#{m[:version]}: #{m[:description]}"
  140. m[:up].call
  141. stmt = DB.client.prepare(
  142. "INSERT INTO schema_migrations (version, description) VALUES (?, ?)"
  143. )
  144. stmt.execute(m[:version], m[:description])
  145. Log.info "migrate", "v#{m[:version]} done"
  146. end
  147. end
  148. # -------------------------------------------------------------------------
  149. # Helpers (private to module)
  150. # -------------------------------------------------------------------------
  151. def self.ensure_migrations_table!
  152. DB.client.query(<<~SQL)
  153. CREATE TABLE IF NOT EXISTS schema_migrations (
  154. version INT UNSIGNED NOT NULL,
  155. description VARCHAR(255) NOT NULL,
  156. applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  157. PRIMARY KEY (version)
  158. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  159. SQL
  160. end
  161. def self.applied_versions
  162. rs = DB.client.query("SELECT version FROM schema_migrations ORDER BY version")
  163. rs.map { |r| r["version"] }.to_set
  164. end
  165. # All da_* tables currently in the database.
  166. def self.da_tables
  167. # The backslash escapes _ (a LIKE wildcard) so only genuine da_ prefixes match.
  168. rs = DB.client.query("SHOW TABLES LIKE 'da\\_%'")
  169. rs.map { |r| r.values.first }
  170. end
  171. private_class_method :ensure_migrations_table!, :applied_versions
  172. end
  173. # Allow running as a standalone script: ruby /app/lib/migrate.rb
  174. if __FILE__ == $0
  175. Migrate.run!
  176. end