better_structure_sql 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +77 -0
  3. data/README.md +218 -686
  4. data/app/CLAUDE.md +12 -0
  5. data/app/controllers/better_structure_sql/application_controller.rb +71 -31
  6. data/app/controllers/better_structure_sql/schema_versions_controller.rb +93 -177
  7. data/app/helpers/better_structure_sql/schema_versions_helper.rb +48 -24
  8. data/app/views/better_structure_sql/schema_versions/index.html.erb +46 -49
  9. data/app/views/better_structure_sql/schema_versions/show.html.erb +80 -126
  10. data/app/views/layouts/better_structure_sql/application.html.erb +27 -18
  11. data/config/routes.rb +1 -1
  12. data/lib/CLAUDE.md +73 -0
  13. data/lib/better_structure_sql/adapters/base_adapter.rb +16 -1
  14. data/lib/better_structure_sql/adapters/mysql_adapter.rb +396 -364
  15. data/lib/better_structure_sql/adapters/postgresql_adapter.rb +574 -478
  16. data/lib/better_structure_sql/adapters/registry.rb +18 -15
  17. data/lib/better_structure_sql/adapters/sqlite_adapter.rb +221 -474
  18. data/lib/better_structure_sql/configuration.rb +9 -2
  19. data/lib/better_structure_sql/creation_order.rb +157 -0
  20. data/lib/better_structure_sql/dependency_resolver.rb +4 -2
  21. data/lib/better_structure_sql/dumper.rb +173 -315
  22. data/lib/better_structure_sql/engine.rb +50 -4
  23. data/lib/better_structure_sql/file_writer.rb +108 -97
  24. data/lib/better_structure_sql/generators/base.rb +31 -4
  25. data/lib/better_structure_sql/generators/comment_generator.rb +16 -12
  26. data/lib/better_structure_sql/generators/domain_generator.rb +8 -6
  27. data/lib/better_structure_sql/generators/extension_generator.rb +7 -2
  28. data/lib/better_structure_sql/generators/foreign_key_generator.rb +14 -4
  29. data/lib/better_structure_sql/generators/index_generator.rb +0 -20
  30. data/lib/better_structure_sql/generators/materialized_view_generator.rb +17 -2
  31. data/lib/better_structure_sql/generators/sequence_generator.rb +13 -5
  32. data/lib/better_structure_sql/generators/table_generator.rb +164 -47
  33. data/lib/better_structure_sql/generators/type_generator.rb +25 -14
  34. data/lib/better_structure_sql/generators/view_generator.rb +12 -8
  35. data/lib/better_structure_sql/introspection/extensions.rb +1 -14
  36. data/lib/better_structure_sql/introspection/foreign_keys.rb +1 -14
  37. data/lib/better_structure_sql/introspection/functions.rb +1 -14
  38. data/lib/better_structure_sql/introspection/indexes.rb +1 -14
  39. data/lib/better_structure_sql/introspection/sequences.rb +1 -14
  40. data/lib/better_structure_sql/introspection/tables.rb +1 -14
  41. data/lib/better_structure_sql/introspection/triggers.rb +1 -14
  42. data/lib/better_structure_sql/introspection/types.rb +1 -14
  43. data/lib/better_structure_sql/introspection/views.rb +2 -19
  44. data/lib/better_structure_sql/introspection.rb +12 -1
  45. data/lib/better_structure_sql/migration_patch.rb +39 -139
  46. data/lib/better_structure_sql/railtie.rb +53 -56
  47. data/lib/better_structure_sql/schema_loader.rb +107 -86
  48. data/lib/better_structure_sql/schema_version.rb +3 -2
  49. data/lib/better_structure_sql/schema_versions.rb +70 -71
  50. data/lib/better_structure_sql/version.rb +1 -1
  51. data/lib/better_structure_sql/zip_generator.rb +43 -6
  52. data/lib/better_structure_sql.rb +2 -1
  53. data/lib/generators/better_structure_sql/migration_generator.rb +1 -1
  54. data/lib/generators/better_structure_sql/templates/README +17 -34
  55. data/lib/tasks/better_structure_sql.rake +19 -40
  56. metadata +10 -148
  57. data/config/database.yml +0 -3
@@ -15,51 +15,39 @@ module BetterStructureSql
15
15
  #
16
16
  # Calculates content hash and compares with latest version.
17
17
  # Skips storage if hash matches (no schema changes).
18
- # Cleans up filesystem directory after storing ZIP (multi-file mode only).
18
+ # The schema file or directory on disk is never modified.
19
19
  #
20
20
  # @param connection [ActiveRecord::Connection] Database connection
21
+ # @param config [Configuration] Configuration naming the schema output path
21
22
  # @return [StoreResult] Result indicating stored or skipped
22
- def store_current(connection = ActiveRecord::Base.connection)
23
- config = BetterStructureSql.configuration
24
- pg_version = PgVersion.detect(connection)
25
-
26
- # Determine format and output mode
27
- format_type = deduce_format_type(config.output_path)
23
+ # @raise [SchemaVersionError] If there is no schema file or directory to store
24
+ def store_current(connection = ActiveRecord::Base.connection, config: BetterStructureSql.configuration)
28
25
  output_mode = detect_output_mode(config.output_path)
29
-
30
- # Read content and calculate hash
31
26
  content, zip_archive, file_count = read_schema_content(config.output_path, output_mode)
32
- return build_skip_result(nil, count) unless content
27
+ raise SchemaVersionError, missing_schema_message(config.output_path) unless content
33
28
 
34
29
  content_hash = calculate_hash(content)
35
30
 
36
31
  # Compare with latest version's hash
37
32
  ensure_table_exists!(connection)
38
33
  latest_version = latest
39
- if latest_version && latest_version.content_hash == content_hash
40
- # Skip storage - no changes detected (directory remains for re-use)
41
- return build_skip_result(latest_version, count)
42
- end
34
+ # Skip storage - no changes detected
35
+ return build_skip_result(latest_version, count) if latest_version&.hash_matches?(content_hash)
43
36
 
44
- # Proceed with storage - hash differs or no previous versions
45
37
  version = store(
46
- content: content,
47
- content_hash: content_hash,
48
- zip_archive: zip_archive,
49
- format_type: format_type,
50
- output_mode: output_mode,
51
- pg_version: pg_version,
52
- file_count: file_count,
53
- connection: connection
38
+ content:,
39
+ content_hash:,
40
+ zip_archive:,
41
+ format_type: deduce_format_type(config.output_path),
42
+ output_mode:,
43
+ pg_version: PgVersion.detect(connection),
44
+ file_count:,
45
+ connection:
54
46
  )
55
47
 
56
- # Cleanup filesystem directory after ZIP stored (multi-file mode only)
57
- cleanup_filesystem_directory(config.output_path, output_mode)
58
-
59
48
  # Cleanup old versions (retention management)
60
49
  cleanup!(connection)
61
50
 
62
- # Return stored result
63
51
  build_stored_result(version)
64
52
  end
65
53
 
@@ -80,19 +68,38 @@ module BetterStructureSql
80
68
  ensure_table_exists!(connection)
81
69
 
82
70
  SchemaVersion.create!(
83
- content: content,
84
- content_hash: content_hash,
71
+ content:,
72
+ content_hash:,
85
73
  content_size: content.bytesize,
86
74
  line_count: content.count("\n"),
87
- zip_archive: zip_archive,
88
- format_type: format_type,
89
- output_mode: output_mode,
90
- pg_version: pg_version,
91
- file_count: file_count,
75
+ zip_archive:,
76
+ format_type:,
77
+ output_mode:,
78
+ pg_version:,
79
+ file_count:,
92
80
  created_at: Time.current
93
81
  )
94
82
  end
95
83
 
84
+ # Replaces the schema of a database with a stored version
85
+ #
86
+ # The database is purged first (every table and all data are dropped, the
87
+ # stored schema versions included), so the stored schema loads into an empty
88
+ # database. A schema that fails to load leaves the database purged.
89
+ #
90
+ # @param version [SchemaVersion] Version to restore, already read from the database
91
+ # @param db_config [ActiveRecord::DatabaseConfigurations::DatabaseConfig] Database to replace
92
+ # @return [void]
93
+ def restore(version, db_config: ActiveRecord::Base.connection_db_config)
94
+ Dir.mktmpdir('schema_restore') do |directory|
95
+ path = write_version_files(version, directory)
96
+
97
+ ActiveRecord::Tasks::DatabaseTasks.purge(db_config)
98
+ ActiveRecord::Base.establish_connection(db_config)
99
+ SchemaLoader.new.load_and_record(path)
100
+ end
101
+ end
102
+
96
103
  # Retrieval methods
97
104
  def latest
98
105
  return nil unless table_exists?
@@ -116,7 +123,7 @@ module BetterStructureSql
116
123
  def find(id)
117
124
  return nil unless table_exists?
118
125
 
119
- SchemaVersion.find_by(id: id)
126
+ SchemaVersion.find_by(id:)
120
127
  end
121
128
 
122
129
  # Returns total count of stored versions
@@ -194,9 +201,9 @@ module BetterStructureSql
194
201
  header_path = full_path.join('_header.sql')
195
202
  stream_file_to_digest(digest, header_path) if File.exist?(header_path)
196
203
 
197
- # Stream all .sql files from numbered directories in order (01_ through 10_)
204
+ # Stream all .sql files from numbered directories in order (01_extensions through 20_migrations)
198
205
  Dir.glob(File.join(full_path, '*_*')).select { |f| File.directory?(f) }.sort.each do |dir|
199
- Dir.glob(File.join(dir, '*.sql')).sort.each do |file|
206
+ Dir.glob(File.join(dir, '*.sql')).each do |file|
200
207
  stream_file_to_digest(digest, file)
201
208
  end
202
209
  end
@@ -263,20 +270,12 @@ module BetterStructureSql
263
270
  # Skip cleanup if unlimited (0)
264
271
  return 0 if limit.zero?
265
272
 
266
- # Delete oldest versions beyond limit
267
- total_count = SchemaVersion.count
268
- return 0 if total_count <= limit
269
-
270
- versions_to_delete = total_count - limit
271
- oldest_versions = SchemaVersion.oldest_first.limit(versions_to_delete)
273
+ # Delete oldest versions beyond limit without loading their content into memory
274
+ excess = SchemaVersion.count - limit
275
+ return 0 unless excess.positive?
272
276
 
273
- deleted_count = 0
274
- oldest_versions.each do |version|
275
- version.destroy
276
- deleted_count += 1
277
- end
278
-
279
- deleted_count
277
+ excess_ids = SchemaVersion.oldest_first.limit(excess).pluck(:id)
278
+ SchemaVersion.where(id: excess_ids).delete_all
280
279
  end
281
280
 
282
281
  private
@@ -291,10 +290,14 @@ module BetterStructureSql
291
290
  skipped: true,
292
291
  version_id: version&.id,
293
292
  hash: version&.content_hash,
294
- total_count: total_count
293
+ total_count:
295
294
  )
296
295
  end
297
296
 
297
+ def missing_schema_message(output_path)
298
+ "No schema found at #{output_path}. Dump it first with: rails db:schema:dump_better"
299
+ end
300
+
298
301
  # Builds a stored result when new version was created
299
302
  #
300
303
  # @param version [SchemaVersion] Newly created version
@@ -302,29 +305,25 @@ module BetterStructureSql
302
305
  def build_stored_result(version)
303
306
  StoreResult.new(
304
307
  skipped: false,
305
- version: version,
308
+ version:,
306
309
  total_count: count
307
310
  )
308
311
  end
309
312
 
310
- # Cleanup filesystem directory after ZIP archive stored
311
- #
312
- # Only removes multi-file directories (single files remain).
313
- # Gracefully handles errors without failing the storage operation.
313
+ # Writes a stored version to disk in the form SchemaLoader loads
314
314
  #
315
- # @param output_path [String, Pathname] Path to directory
316
- # @param output_mode [String] Output mode ('single_file' or 'multi_file')
317
- def cleanup_filesystem_directory(output_path, output_mode)
318
- # Only cleanup multi-file directories (single files remain)
319
- return unless output_mode == 'multi_file'
320
-
321
- full_path = Rails.root.join(output_path)
322
- return unless Dir.exist?(full_path)
323
-
324
- FileUtils.rm_rf(full_path)
325
- rescue StandardError => e
326
- warn "Warning: Failed to cleanup directory #{output_path}: #{e.message}"
327
- # Continue despite cleanup failure - version already stored
315
+ # @param version [SchemaVersion] Stored version
316
+ # @param directory [String] Directory to write into
317
+ # @return [String] Path of the schema file or directory
318
+ def write_version_files(version, directory)
319
+ if version.multi_file?
320
+ path = File.join(directory, 'schema')
321
+ ZipGenerator.extract_to_directory(version.zip_archive, path)
322
+ else
323
+ path = File.join(directory, "schema.#{version.format_type}")
324
+ File.write(path, version.content)
325
+ end
326
+ path
328
327
  end
329
328
 
330
329
  # Streams a file to digest using STREAM_CHUNK_SIZE chunks
@@ -372,10 +371,10 @@ module BetterStructureSql
372
371
  header_path = base_path.join('_header.sql')
373
372
  content_parts << File.read(header_path) if File.exist?(header_path)
374
373
 
375
- # Read all .sql files from numbered directories in order (01_ through 10_)
374
+ # Read all .sql files from numbered directories in order (01_extensions through 20_migrations)
376
375
  # Note: Manifest JSON is excluded as it's metadata, not schema content
377
376
  Dir.glob(File.join(base_path, '*_*')).select { |f| File.directory?(f) }.sort.each do |dir|
378
- Dir.glob(File.join(dir, '*.sql')).sort.each do |file|
377
+ Dir.glob(File.join(dir, '*.sql')).each do |file|
379
378
  content_parts << File.read(file)
380
379
  end
381
380
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module BetterStructureSql
4
- VERSION = '0.2.1'
4
+ VERSION = '0.3.0'
5
5
  end
@@ -8,6 +8,7 @@ module BetterStructureSql
8
8
  class ZipGenerator
9
9
  MAX_FILES_IN_ZIP = 300_000
10
10
  MAX_UNCOMPRESSED_SIZE = 800.megabytes
11
+ EXTRACT_CHUNK_SIZE = 1.megabyte
11
12
 
12
13
  class ZipError < StandardError; end
13
14
 
@@ -16,7 +17,7 @@ module BetterStructureSql
16
17
  # @return [String] ZIP file binary data
17
18
  def self.create_from_directory(dir_path)
18
19
  buffer = Zip::OutputStream.write_buffer do |zip|
19
- Dir.glob("#{dir_path}/**/*").sort.each do |file_path|
20
+ Dir.glob("#{dir_path}/**/*").each do |file_path|
20
21
  next if File.directory?(file_path)
21
22
 
22
23
  relative_path = file_path.sub("#{dir_path}/", '')
@@ -43,19 +44,22 @@ module BetterStructureSql
43
44
  end
44
45
 
45
46
  # Extract ZIP to directory
47
+ #
48
+ # Enforces the safety limits and refuses entries that would land outside the target.
49
+ #
46
50
  # @param zip_binary [String] ZIP file binary data
47
51
  # @param target_dir [String, Pathname] Target directory path
52
+ # @raise [ZipError] if the ZIP exceeds safety limits or contains an unsafe path
48
53
  def self.extract_to_directory(zip_binary, target_dir)
54
+ validate_zip!(zip_binary)
49
55
  FileUtils.mkdir_p(target_dir)
56
+ remaining_bytes = MAX_UNCOMPRESSED_SIZE
50
57
 
51
58
  Zip::File.open_buffer(StringIO.new(zip_binary)) do |zip_file|
52
59
  zip_file.each do |entry|
53
- # Security: rubyzip already prevents path traversal, but verify anyway
54
- next if entry.name.include?('..')
60
+ next if entry.directory?
55
61
 
56
- path = File.join(target_dir, entry.name)
57
- FileUtils.mkdir_p(File.dirname(path))
58
- entry.extract(path) unless File.exist?(path)
62
+ remaining_bytes -= extract_entry(entry, safe_entry_path(entry.name, target_dir), remaining_bytes)
59
63
  end
60
64
  end
61
65
  end
@@ -77,5 +81,38 @@ module BetterStructureSql
77
81
  end
78
82
  end
79
83
  end
84
+
85
+ # Resolve an entry name inside the target directory
86
+ # @raise [ZipError] if the entry would be written outside the target directory
87
+ def self.safe_entry_path(entry_name, target_dir)
88
+ root = File.expand_path(target_dir)
89
+ path = File.expand_path(File.join(root, entry_name))
90
+ return path if path.start_with?("#{root}#{File::SEPARATOR}")
91
+
92
+ raise ZipError, "Unsafe path in ZIP: #{entry_name}"
93
+ end
94
+ private_class_method :safe_entry_path
95
+
96
+ # Write one entry, trusting the bytes actually decompressed rather than the declared size
97
+ # @return [Integer] Bytes written
98
+ # @raise [ZipError] if the entry inflates past the remaining byte budget
99
+ def self.extract_entry(entry, path, remaining_bytes)
100
+ FileUtils.mkdir_p(File.dirname(path))
101
+ written = 0
102
+
103
+ File.open(path, 'wb') do |file|
104
+ entry.get_input_stream do |stream|
105
+ while (chunk = stream.read(EXTRACT_CHUNK_SIZE))
106
+ written += chunk.bytesize
107
+ raise ZipError, "ZIP content too large (max #{MAX_UNCOMPRESSED_SIZE} bytes)" if written > remaining_bytes
108
+
109
+ file.write(chunk)
110
+ end
111
+ end
112
+ end
113
+
114
+ written
115
+ end
116
+ private_class_method :extract_entry
80
117
  end
81
118
  end
@@ -7,7 +7,8 @@ require_relative 'better_structure_sql/adapters/base_adapter'
7
7
  require_relative 'better_structure_sql/adapters/postgresql_config'
8
8
  require_relative 'better_structure_sql/adapters/registry'
9
9
  require_relative 'better_structure_sql/configuration'
10
- # require_relative 'better_structure_sql/dependency_resolver' # TODO: Not yet integrated, implement in future phase
10
+ require_relative 'better_structure_sql/dependency_resolver'
11
+ require_relative 'better_structure_sql/creation_order'
11
12
  require_relative 'better_structure_sql/introspection'
12
13
  require_relative 'better_structure_sql/formatter'
13
14
  require_relative 'better_structure_sql/generators/base'
@@ -20,7 +20,7 @@ module BetterStructureSql
20
20
  migration_template(
21
21
  'migration.rb.erb',
22
22
  'db/migrate/create_better_structure_sql_schema_versions.rb',
23
- migration_version: migration_version
23
+ migration_version:
24
24
  )
25
25
  end
26
26
 
@@ -5,45 +5,28 @@ BetterStructureSql has been installed!
5
5
  Configuration file created at:
6
6
  config/initializers/better_structure_sql.rb
7
7
 
8
- To generate a clean schema dump, run:
8
+ Generate a clean schema dump:
9
9
  rails db:schema:dump_better
10
10
 
11
- To replace Rails' default schema dump task, set in the initializer:
11
+ To replace Rails' default dump and load tasks, set in the initializer:
12
12
  config.replace_default_dump = true
13
+ config.replace_default_load = true
13
14
 
14
- Then you can use the standard command:
15
+ Then the standard commands use BetterStructureSql:
15
16
  rails db:schema:dump
17
+ rails db:schema:load
16
18
 
17
- Phase 1 features available:
18
- ✓ Tables with columns, primary keys, and constraints
19
- ✓ Indexes (including unique and partial)
20
- ✓ Foreign keys with CASCADE/RESTRICT/SET NULL
21
- ✓ PostgreSQL extensions
22
- ✓ Clean, deterministic output
23
-
24
- Phase 2 features available:
25
- ✓ Schema version storage
26
- ✓ Version retention management
27
- ✓ PostgreSQL version tracking
28
-
29
- To enable schema versioning:
30
- 1. Enable in config/initializers/better_structure_sql.rb:
31
- config.enable_schema_versions = true
32
- 2. Run the migration (if not already generated):
33
- rails db:migrate
34
- 3. Store current schema:
35
- rails db:schema:store
36
- 4. List versions:
37
- rails db:schema:versions
38
- 5. Cleanup old versions:
39
- rails db:schema:cleanup
40
-
41
- Coming in Phase 3:
42
- - Views and materialized views
43
- - Functions and triggers
44
- - Advanced PostgreSQL features
45
-
46
- For more information, visit:
47
- https://github.com/sebyx07/better_structure_sql
19
+ Schema versioning (optional):
20
+ 1. Set config.enable_schema_versions = true in the initializer
21
+ 2. rails db:migrate # creates the schema versions table
22
+ 3. rails db:schema:store # store the current dump
23
+ 4. rails db:schema:versions # list stored versions
24
+ 5. rails db:schema:cleanup # apply the retention limit
25
+
26
+ The web UI for stored versions fails closed outside development and test:
27
+ configure access with BetterStructureSql::Engine.authenticate_with { ... }
28
+ or BetterStructureSql::Engine.authentication_handled_by_routes!
29
+
30
+ Documentation: https://github.com/sebyx07/better_structure_sql
48
31
 
49
32
  ===============================================================================
@@ -62,10 +62,9 @@ namespace :db do
62
62
  loader = BetterStructureSql::SchemaLoader.new(config)
63
63
 
64
64
  begin
65
- loader.load
65
+ loader.load_and_record
66
66
  rescue BetterStructureSql::SchemaLoader::LoadError => e
67
- puts "Error loading schema: #{e.message}"
68
- exit 1
67
+ abort "Error loading schema: #{e.message}"
69
68
  end
70
69
  end
71
70
 
@@ -89,8 +88,7 @@ namespace :db do
89
88
  puts " Current schema matches version ##{result.version_id}"
90
89
  puts " Hash: #{result.hash}"
91
90
  puts ' No new version stored'
92
- puts " Total versions: #{result.total_count}"
93
- elsif result.stored?
91
+ else
94
92
  version = result.version
95
93
  puts "\nStored schema version ##{version.id}"
96
94
  puts " Format: #{version.format_type}"
@@ -99,15 +97,10 @@ namespace :db do
99
97
  puts " PostgreSQL: #{version.pg_version}"
100
98
  puts " Size: #{version.formatted_size}"
101
99
  puts " Hash: #{version.content_hash}"
102
- puts " Total versions: #{result.total_count}"
103
- else
104
- puts "\nNo schema file found to store"
105
- exit 1
106
100
  end
107
- rescue StandardError => e
108
- puts "\nError storing schema version: #{e.message}"
109
- puts e.backtrace.first(5).join("\n") if ENV['VERBOSE']
110
- exit 1
101
+ puts " Total versions: #{result.total_count}"
102
+ rescue BetterStructureSql::Error => e
103
+ abort "Error storing schema version: #{e.message}"
111
104
  end
112
105
 
113
106
  desc 'List all stored schema versions'
@@ -155,7 +148,7 @@ namespace :db do
155
148
  config = BetterStructureSql.configuration
156
149
  if config.schema_versions_limit.zero?
157
150
  puts 'Retention limit is set to unlimited (0). No cleanup needed.'
158
- exit 0
151
+ next
159
152
  end
160
153
 
161
154
  deleted_count = BetterStructureSql::SchemaVersions.cleanup!
@@ -164,41 +157,27 @@ namespace :db do
164
157
  puts "Retention limit: #{config.schema_versions_limit}"
165
158
  end
166
159
 
167
- desc 'Restore schema from stored version'
168
- task :restore, [:version_id] => :environment do |_t, args|
160
+ desc 'Replace the database schema with a stored version (drops all data; needs CONFIRM=1)'
161
+ task :restore, [:version_id] => %i[environment check_protected_environments] do |_t, args|
169
162
  require 'better_structure_sql'
170
163
 
171
164
  version_id = args[:version_id] || ENV.fetch('VERSION_ID', nil)
172
- raise 'Usage: rails db:schema:restore[VERSION_ID]' unless version_id
165
+ raise 'Usage: CONFIRM=1 rails db:schema:restore[VERSION_ID]' unless version_id
173
166
 
174
167
  version = BetterStructureSql::SchemaVersions.find(version_id)
175
168
  raise "Version #{version_id} not found" unless version
176
169
 
177
- connection = ActiveRecord::Base.connection
178
- connection.execute('SET client_min_messages TO warning')
179
-
180
- if version.multi_file?
181
- # Extract ZIP to temp directory
182
- temp_dir = Rails.root.join('tmp', "schema_restore_#{version.id}")
183
- FileUtils.rm_rf(temp_dir)
184
-
185
- BetterStructureSql::ZipGenerator.extract_to_directory(version.zip_archive, temp_dir)
186
-
187
- # Load from temp directory
188
- loader = BetterStructureSql::SchemaLoader.new
189
- loader.load(temp_dir)
190
-
191
- # Cleanup
192
- FileUtils.rm_rf(temp_dir)
193
-
194
- puts "Schema version #{version.id} restored from #{version.file_count} files"
195
- else
196
- # Single file - load from content
197
- connection.execute(version.content)
198
-
199
- puts "Schema version #{version.id} restored"
170
+ db_config = ActiveRecord::Base.connection_db_config
171
+ unless ENV['CONFIRM'] == '1'
172
+ abort "db:schema:restore replaces the schema of database #{db_config.database}: it drops every table and all data, " \
173
+ "the stored schema versions included, then loads version #{version.id}.\n" \
174
+ "Run it again with CONFIRM=1 to proceed: CONFIRM=1 rails db:schema:restore[#{version.id}]"
200
175
  end
201
176
 
177
+ BetterStructureSql::SchemaVersions.restore(version, db_config:)
178
+
179
+ puts "Schema version #{version.id} restored into #{db_config.database}"
180
+ puts " Files: #{version.file_count}" if version.multi_file?
202
181
  puts " Format: #{version.format_type}"
203
182
  puts " PostgreSQL: #{version.pg_version}"
204
183
  puts " Size: #{version.formatted_size}"