better_structure_sql 0.2.2 → 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 +69 -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 +94 -153
  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 +73 -120
  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 +9 -147
  57. data/config/database.yml +0 -3
@@ -1,144 +1,44 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module BetterStructureSql
4
- # Patches ActiveRecord::Migration to handle multi-file schema directories
5
- #
6
- # Rails' maintain_test_schema! calls purge_current_test_schema which tries to
7
- # read the schema file directly using File.read(), which fails when the schema
8
- # is a directory (multi-file mode).
9
- #
10
- # This patch intercepts that behavior and uses our SchemaLoader instead.
4
+ # Patches ActiveRecord so a multi-file schema directory works where Rails expects a file
11
5
  module MigrationPatch
12
- # Override schema_cache to handle directory-based schemas
13
- module SchemaCachePatch
14
- # Returns the schema cache, handling directory-based schemas
15
- # @return [ActiveRecord::ConnectionAdapters::SchemaCache] Schema cache
16
- def schema_cache
17
- return super unless multi_file_schema?
18
-
19
- # For multi-file schemas, we need to handle the cache differently
20
- # Check if cache exists as a file with the expected naming convention
21
- cache_path = derived_cache_path
22
-
23
- connection.schema_cache = ActiveRecord::ConnectionAdapters::SchemaCache.load_from(cache_path) if File.exist?(cache_path)
24
-
25
- super
26
- rescue Errno::EISDIR
27
- # If we get EISDIR, it means Rails is trying to read a directory
28
- # This is expected for multi-file schemas, just return the current cache
29
- connection.schema_cache
30
- end
31
-
32
- private
33
-
34
- def multi_file_schema?
35
- return false unless defined?(Rails) && Rails.application
36
-
37
- schema_path = if Rails.application.config.active_record.schema_format == :sql
38
- ENV.fetch('SCHEMA', 'db/structure.sql')
39
- else
40
- 'db/schema.rb'
41
- end
42
-
43
- full_path = Rails.root.join(schema_path)
44
- File.directory?(full_path)
45
- end
46
-
47
- def derived_cache_path
48
- # Check if using BetterStructureSql config
49
- base_path = if defined?(BetterStructureSql) && BetterStructureSql.configured?
50
- BetterStructureSql.configuration.output_path
51
- elsif Rails.application.config.active_record.schema_format == :sql
52
- ENV.fetch('SCHEMA', 'db/structure.sql')
53
- else
54
- 'db/schema.rb'
55
- end
56
-
57
- # For directory mode, use the directory path + _schema_cache.yml
58
- if Rails.root.join(base_path).directory?
59
- Rails.root.join(base_path, '_schema_cache.yml')
60
- else
61
- # For file mode, use the default Rails cache path
62
- Rails.root.join('db/schema_cache.yml')
63
- end
64
- end
65
- end
66
-
67
- # Patch for maintain_test_schema! to handle directory schemas
6
+ # Keeps the test schema current for a schema directory Rails does not know about
7
+ #
8
+ # With replace_default_dump or replace_default_load on, Rails resolves the
9
+ # directory itself (schema_dump_path) and its own maintain_test_schema! works
10
+ # unchanged. Otherwise Rails looks at db/structure.sql, so the directory at
11
+ # config.output_path is loaded here, through the same Rails calls.
68
12
  module MaintainTestSchemaPatch
69
- # Maintains test schema, handling directory-based schemas
13
+ # Reloads the test database when the schema directory changed, then fails on pending migrations
70
14
  # @return [void]
71
15
  def maintain_test_schema!
72
- return super unless should_use_better_structure_sql?
73
-
74
- # Check if we need to load or purge the schema
75
- if pending_migrations?
76
- # Purge the schema first
77
- purge_current_test_schema_with_directory_support
78
- # Load the schema using our loader
79
- load_schema_with_directory_support
80
- end
81
- rescue Errno::EISDIR
82
- # If we still get EISDIR, provide a helpful error message
83
- raise ActiveRecord::MigrationError,
84
- "Multi-file schema directory detected at #{schema_file_path}. " \
85
- 'Set config.replace_default_load = true in config/initializers/better_structure_sql.rb ' \
86
- 'to enable automatic multi-file schema loading, or run: rails db:schema:load_better'
16
+ return super unless ActiveRecord.maintain_test_schema && unmanaged_schema_directory?
17
+
18
+ db_config = ActiveRecord::Base.connection_db_config
19
+ tasks = ActiveRecord::Tasks::DatabaseTasks
20
+ load_schema_directory(tasks, db_config) unless tasks.schema_up_to_date?(db_config, :sql, schema_directory)
21
+ check_pending_migrations
87
22
  end
88
23
 
89
24
  private
90
25
 
91
- def should_use_better_structure_sql?
92
- return false unless defined?(BetterStructureSql) && defined?(Rails)
93
- return false unless Rails.application.config.active_record.schema_format == :sql
94
-
95
- # Check if schema path is a directory
96
- File.directory?(schema_file_path)
97
- end
98
-
99
- def schema_file_path
100
- if defined?(BetterStructureSql) && BetterStructureSql.configured?
101
- Rails.root.join(BetterStructureSql.configuration.output_path)
102
- else
103
- Rails.root.join(ENV.fetch('SCHEMA', 'db/structure.sql'))
104
- end
105
- end
26
+ def unmanaged_schema_directory?
27
+ config = BetterStructureSql.configuration
28
+ return false if config.replace_default_dump || config.replace_default_load
106
29
 
107
- def pending_migrations?
108
- # Use ActiveRecord::Base.connection_pool.migration_context for compatibility
109
- # Different Rails versions have migration_context in different places
110
- if ActiveRecord::Base.connection_pool.respond_to?(:migration_context)
111
- ActiveRecord::Base.connection_pool.migration_context.needs_migration?
112
- elsif ActiveRecord::Base.connection.respond_to?(:migration_context)
113
- ActiveRecord::Base.connection.migration_context.needs_migration?
114
- elsif defined?(ActiveRecord::MigrationContext)
115
- # Fallback: construct migration context manually
116
- paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
117
- schema_migration = ActiveRecord::Base.connection.schema_migration
118
- internal_metadata = ActiveRecord::Base.connection.internal_metadata
119
- ActiveRecord::MigrationContext.new(paths, schema_migration, internal_metadata).needs_migration?
120
- else
121
- # Very old Rails, assume migrations are pending to be safe
122
- true
123
- end
30
+ ActiveRecord.schema_format == :sql && File.directory?(schema_directory)
124
31
  end
125
32
 
126
- def purge_current_test_schema_with_directory_support
127
- # Purge the test database
128
- ActiveRecord::Tasks::DatabaseTasks.purge_current('test')
129
- rescue ActiveRecord::NoDatabaseError
130
- # Database doesn't exist, that's fine
33
+ def schema_directory
34
+ Rails.root.join(BetterStructureSql.configuration.output_path).to_s
131
35
  end
132
36
 
133
- def load_schema_with_directory_support
134
- if defined?(BetterStructureSql) && BetterStructureSql.configured?
135
- # Use our loader which handles both files and directories
136
- loader = BetterStructureSql::SchemaLoader.new(BetterStructureSql.configuration)
137
- loader.load
138
- else
139
- # Fallback to Rails default
140
- ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql)
141
- end
37
+ # load_schema records the environment and the schema checksum in ar_internal_metadata
38
+ def load_schema_directory(tasks, db_config)
39
+ tasks.purge(db_config)
40
+ ActiveRecord::Base.establish_connection(db_config)
41
+ tasks.load_schema(db_config, :sql, schema_directory)
142
42
  end
143
43
  end
144
44
 
@@ -152,7 +52,7 @@ module BetterStructureSql
152
52
  if File.directory?(filename)
153
53
  return if Dir.glob(File.join(filename, '**', '*.sql')).any?
154
54
 
155
- message = +"#{filename} exists but contains no SQL files. Run `bin/rails db:migrate` to create schema files."
55
+ message = "#{filename} exists but contains no SQL files. Run `bin/rails db:migrate` to create schema files."
156
56
  Kernel.abort message
157
57
  end
158
58
 
@@ -160,20 +60,23 @@ module BetterStructureSql
160
60
  super
161
61
  end
162
62
 
63
+ # Loads a schema directory with SchemaLoader: the database's command line client only loads a file
64
+ # @param db_config [ActiveRecord::DatabaseConfigurations::DatabaseConfig] Database configuration
65
+ # @param filename [String, Pathname] Schema file or directory
66
+ # @return [void]
67
+ def structure_load(db_config, filename, *)
68
+ return super unless File.directory?(filename)
69
+
70
+ BetterStructureSql::SchemaLoader.new.load(filename)
71
+ end
72
+
163
73
  # Override schema_sha1 to handle directories
164
74
  # @param file [String] Path to schema file or directory
165
75
  # @return [String] SHA1 checksum
166
76
  def schema_sha1(file)
167
- if File.directory?(file)
168
- # For directory mode, generate checksum from all SQL files combined
169
- # Sort files to ensure deterministic ordering
170
- sql_files = Dir.glob(File.join(file, '**', '*.sql')).sort
171
- combined_content = sql_files.map { |f| File.read(f) }.join("\n")
172
- OpenSSL::Digest::SHA1.hexdigest(combined_content)
173
- else
174
- # For file mode, use default Rails behavior
175
- super
176
- end
77
+ return super unless File.directory?(file)
78
+
79
+ BetterStructureSql::SchemaLoader.schema_sha1(file)
177
80
  end
178
81
  end
179
82
 
@@ -184,9 +87,6 @@ module BetterStructureSql
184
87
  # Patch maintain_test_schema! if it exists
185
88
  ActiveRecord::Migration.singleton_class.prepend(MaintainTestSchemaPatch) if ActiveRecord::Migration.respond_to?(:maintain_test_schema!)
186
89
 
187
- # Patch schema_cache handling
188
- ActiveRecord::MigrationContext.prepend(SchemaCachePatch) if defined?(ActiveRecord::MigrationContext)
189
-
190
90
  # Patch DatabaseTasks for development/production use
191
91
  return unless defined?(ActiveRecord::Tasks::DatabaseTasks)
192
92
 
@@ -32,38 +32,47 @@ module BetterStructureSql
32
32
  BetterStructureSql::MigrationPatch.apply!
33
33
 
34
34
  if config.replace_default_dump && !is_ruby_format
35
- # Automatically set Rails to use SQL schema format
35
+ # Rails copies app config into ActiveRecord before this hook can run, so set both
36
36
  Rails.application.config.active_record.schema_format = :sql
37
+ ActiveRecord.schema_format = :sql
37
38
 
38
- ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(DatabaseTasksExtension)
39
- ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(DatabaseTasksDumpInfoExtension)
40
- # Also prepend path override for dump
41
39
  ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(DatabaseTasksPathExtension)
40
+ ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(DatabaseTasksExtension)
42
41
  end
43
42
 
44
43
  if config.replace_default_load && !is_ruby_format
45
- ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(DatabaseTasksLoadExtension)
46
- # Also prepend path override for load
47
44
  ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(DatabaseTasksPathExtension)
45
+ ActiveRecord::Tasks::DatabaseTasks.singleton_class.prepend(DatabaseTasksLoadExtension)
48
46
  end
49
47
  end
50
48
  end
51
49
 
50
+ # Resolves the schema format Rails would use for a database
51
+ #
52
+ # @param db_config [ActiveRecord::DatabaseConfigurations::DatabaseConfig] Database configuration
53
+ # @param format [Symbol, String, nil] Explicit format, nil for the database's default
54
+ # @return [Symbol] :sql or :ruby
55
+ def self.schema_format_for(db_config, format)
56
+ format ||= db_config.respond_to?(:schema_format) ? db_config.schema_format : ActiveRecord.schema_format
57
+ format.to_sym
58
+ end
59
+
52
60
  # Extension to override schema_dump_path for BetterStructureSql
53
61
  module DatabaseTasksPathExtension
54
- # Returns schema dump path based on configuration
62
+ # Returns the configured output path for the primary database's SQL schema
63
+ #
64
+ # Other databases of a multi-database app keep the path Rails derives from
65
+ # their name, so every database gets its own schema file.
55
66
  #
56
67
  # @param db_config [ActiveRecord::DatabaseConfigurations::DatabaseConfig] Database configuration
57
- # @param format [Symbol] Schema format (:sql or :ruby)
58
- # @return [Pathname] Path to schema file
59
- def schema_dump_path(db_config, format = ActiveRecord.schema_format)
60
- if format.to_sym == :sql && !BetterStructureSql.configuration.output_path.to_s.end_with?('.rb')
61
- # Return our configured path for SQL format
62
- Rails.root.join(BetterStructureSql.configuration.output_path)
63
- else
64
- # Use default Rails path for Ruby format
65
- super
66
- end
68
+ # @param format [Symbol, nil] Schema format (:sql or :ruby), nil for the database's default
69
+ # @return [Pathname, String, nil] Path to schema file or directory
70
+ def schema_dump_path(db_config, format = nil)
71
+ format = Railtie.schema_format_for(db_config, format)
72
+ return super unless format == :sql && db_config.primary? && db_config.schema_dump(format)
73
+ return super if ENV['SCHEMA']
74
+
75
+ Rails.root.join(BetterStructureSql.configuration.output_path)
67
76
  end
68
77
  end
69
78
 
@@ -71,53 +80,41 @@ module BetterStructureSql
71
80
  module DatabaseTasksExtension
72
81
  # Dumps schema using BetterStructureSql for SQL format
73
82
  #
83
+ # Each database is dumped through its own connection into its own path.
84
+ #
74
85
  # @param db_config [ActiveRecord::DatabaseConfigurations::DatabaseConfig] Database configuration
75
- # @param format [Symbol] Schema format
86
+ # @param format [Symbol, nil] Schema format, nil for the database's default
76
87
  # @return [void]
77
- def dump_schema(db_config, format = db_config.schema_format)
78
- # Only override SQL format dumps
79
- if format.to_sym == :sql
80
- return unless db_config.schema_dump
81
-
82
- filename = schema_dump_path(db_config, format)
83
- return unless filename
84
-
85
- FileUtils.mkdir_p(File.dirname(filename))
86
-
87
- # Call our dumper which already includes schema_migrations
88
- # Don't auto-store version here - use explicit db:schema:store task
89
- BetterStructureSql::Dumper.new.dump(store_version: false)
90
- else
91
- # For Ruby format, call the original method
92
- super
88
+ def dump_schema(db_config, format = nil)
89
+ format = Railtie.schema_format_for(db_config, format)
90
+ return super unless format == :sql
91
+
92
+ filename = schema_dump_path(db_config, format)
93
+ return unless filename
94
+
95
+ # Don't auto-store version here - use explicit db:schema:store task
96
+ with_temporary_connection(db_config) do |connection|
97
+ BetterStructureSql::Dumper.new(dump_configuration(filename), connection).dump(store_version: false)
93
98
  end
94
99
  end
95
- end
96
100
 
97
- # No longer needed - we override dump_schema instead
98
- module DatabaseTasksDumpInfoExtension
99
- # This module is kept for backward compatibility but is no longer used
101
+ private
102
+
103
+ def dump_configuration(filename)
104
+ BetterStructureSql.configuration.dup.tap { |config| config.output_path = filename }
105
+ end
100
106
  end
101
107
 
102
- # Extension to override DatabaseTasks#load_schema for multi-file support
108
+ # Extension to load SQL schemas (single file or multi-file directory) with SchemaLoader
103
109
  module DatabaseTasksLoadExtension
104
- # Override load_schema to handle both file and directory schemas
105
- def load_schema(db_config, format = ActiveRecord.schema_format, *_args)
106
- if format.to_sym == :sql
107
- # Get the configured schema path (could be file or directory)
108
- config = BetterStructureSql.configuration
109
- schema_path = Rails.root.join(config.output_path)
110
-
111
- # Check if schema exists (file or directory)
112
- abort "#{schema_path} doesn't exist yet. Run `bin/rails db:migrate` to create it, then try again." unless File.exist?(schema_path)
113
-
114
- # Use our loader which handles both file and directory
115
- loader = BetterStructureSql::SchemaLoader.new(config)
116
- loader.load
117
- else
118
- # For Ruby format, call the original method
119
- super
120
- end
110
+ # Rails calls this from load_schema with the database's connection already
111
+ # established, then records the environment and schema checksum itself.
112
+ #
113
+ # @param _configuration [ActiveRecord::DatabaseConfigurations::DatabaseConfig] Database configuration
114
+ # @param filename [String, Pathname] Schema file or directory
115
+ # @return [void]
116
+ def structure_load(_configuration, filename, *)
117
+ BetterStructureSql::SchemaLoader.new(BetterStructureSql.configuration).load(filename)
121
118
  end
122
119
  end
123
120
  end
@@ -5,6 +5,21 @@ module BetterStructureSql
5
5
  class SchemaLoader
6
6
  class LoadError < StandardError; end
7
7
 
8
+ # Line opening a compound statement block ("BEGIN", "FOR EACH ROW BEGIN", "label: BEGIN")
9
+ MYSQL_BLOCK_START = /\bBEGIN\z/i
10
+
11
+ # Line closing a block: "END", "END;" or "END label;" (not END IF, END LOOP, ...)
12
+ MYSQL_BLOCK_END = /\AEND(?:\s+(?!(?:IF|LOOP|WHILE|CASE|REPEAT)\b)\w+)?\s*;?\z/i
13
+
14
+ # Checksum Rails keeps as schema_sha1 to tell whether a database matches its schema
15
+ #
16
+ # @param path [String] Schema file or directory
17
+ # @return [String] SHA1 of the file, or of every SQL file of the directory in path order
18
+ def self.schema_sha1(path)
19
+ files = File.directory?(path) ? Dir.glob(File.join(path, '**', '*.sql')) : [path]
20
+ OpenSSL::Digest::SHA1.hexdigest(files.map { |file| File.read(file) }.join("\n"))
21
+ end
22
+
8
23
  attr_reader :config
9
24
 
10
25
  def initialize(config = BetterStructureSql.configuration)
@@ -26,41 +41,49 @@ module BetterStructureSql
26
41
  end
27
42
  end
28
43
 
44
+ # Loads the schema, then records the environment and the schema checksum in
45
+ # ar_internal_metadata, as Rails' own schema load does. Without the environment
46
+ # Rails refuses to drop or purge the database later (NoEnvironmentInSchemaError).
47
+ #
48
+ # @param path [String, nil] Path to schema file or directory (defaults to config.output_path)
49
+ # @return [void]
50
+ def load_and_record(path = nil)
51
+ path ||= config.output_path
52
+ load(path)
53
+
54
+ schema_sha1 = self.class.schema_sha1(Rails.root.join(path).to_s)
55
+ internal_metadata.create_table_and_set_flags(ActiveRecord::Base.connection_db_config.env_name, schema_sha1)
56
+ end
57
+
29
58
  private
30
59
 
60
+ # Rails 7.2 moved internal_metadata from the connection to the pool
61
+ def internal_metadata
62
+ pool = ActiveRecord::Base.connection_pool
63
+ pool.respond_to?(:internal_metadata) ? pool.internal_metadata : ActiveRecord::Base.connection.internal_metadata
64
+ end
65
+
31
66
  def load_directory(dir_path)
32
67
  connection = ActiveRecord::Base.connection
33
68
 
34
- # Load header first
35
- header_path = File.join(dir_path, '_header.sql')
36
- connection.execute(File.read(header_path)) if File.exist?(header_path)
37
-
38
- # Load numbered directories in order (01_extensions through 20_migrations)
39
- # Load all files in each directory and execute statements
40
- # Use [012]* pattern to match directories starting with 0, 1, or 2 (covers 01-29)
41
- Dir.glob(File.join(dir_path, '[012]*_*')).sort.each do |dir|
42
- next unless File.directory?(dir)
69
+ sql_files_in_load_order(dir_path).each do |file_path|
70
+ sql_content = File.read(file_path)
71
+ next if sql_content.strip.empty?
43
72
 
44
- dir_name = File.basename(dir)
45
-
46
- # Process files in this directory
47
- Dir.glob(File.join(dir, '*.sql')).sort.each do |file_path|
48
- sql_content = File.read(file_path)
49
- next if sql_content.strip.empty?
73
+ execute_sql_statements(connection, sql_content)
74
+ end
50
75
 
51
- # Execute SQL (connection.execute can handle multiple statements for SQLite)
52
- execute_sql_statements(connection, sql_content)
53
- end
76
+ Rails.logger.debug { "Schema loaded from #{dir_path}" }
77
+ end
54
78
 
55
- Rails.logger.debug { "Loaded #{dir_name}" }
79
+ # Header first, then the numbered directories (01_extensions through 20_migrations) in order
80
+ def sql_files_in_load_order(dir_path)
81
+ header_path = File.join(dir_path, '_header.sql')
82
+ section_files = Dir.glob(File.join(dir_path, '[012]*_*')).flat_map do |dir|
83
+ File.directory?(dir) ? Dir.glob(File.join(dir, '*.sql')) : []
56
84
  end
57
85
 
58
- # Read manifest for file count (optional, for logging only)
59
- manifest_path = File.join(dir_path, '_manifest.json')
60
- return unless File.exist?(manifest_path)
61
-
62
- manifest = JSON.parse(File.read(manifest_path))
63
- Rails.logger.debug { "Schema loaded from #{manifest['total_files']} files" }
86
+ (File.exist?(header_path) ? [header_path] : []) + section_files
64
87
  end
65
88
 
66
89
  def load_file(file_path)
@@ -85,84 +108,82 @@ module BetterStructureSql
85
108
 
86
109
  case adapter_name
87
110
  when 'sqlite'
88
- # SQLite's ActiveRecord execute() uses prepare() which can't handle multiple statements
89
- # We need to use the raw database connection's execute_batch method
90
- connection.raw_connection.execute_batch(sql)
91
- when 'postgresql', 'postgis'
92
- # PostgreSQL can handle multiple statements in one execute call
93
- connection.execute(sql)
111
+ execute_sqlite_batch(connection, sql)
94
112
  when 'mysql', 'mysql2', 'trilogy'
95
113
  # MySQL needs statements executed individually
96
114
  execute_mysql_statements(connection, sql)
97
115
  else
98
- # Fallback: Try executing as-is first
99
- begin
100
- connection.execute(sql)
101
- rescue StandardError
102
- # If that fails, split by semicolon and execute individually
103
- sql.split(/;\\s*$/).each do |statement|
104
- next if statement.strip.empty?
105
-
106
- connection.execute("#{statement};")
107
- end
108
- end
116
+ # PostgreSQL can handle multiple statements in one execute call
117
+ connection.execute(sql)
109
118
  end
110
119
  end
111
120
 
121
+ # ActiveRecord's SQLite execute runs only the first of several statements
122
+ # (silently dropping the rest), so the batch goes to the raw connection;
123
+ # its errors are re-raised as ActiveRecord::StatementInvalid like every
124
+ # other adapter's.
125
+ def execute_sqlite_batch(connection, sql)
126
+ connection.raw_connection.execute_batch(sql)
127
+ rescue SQLite3::Exception => e
128
+ raise ActiveRecord::StatementInvalid.new(e.message, sql:)
129
+ end
130
+
131
+ # Execute a MySQL dump one statement at a time
132
+ #
133
+ # Statements are sent without their trailing ";" and with query transformers
134
+ # (Rails query log tags) switched off: MySQL stores whatever follows the
135
+ # body of a single-statement routine or trigger, so either would become
136
+ # part of the object and grow on every dump/load cycle.
112
137
  def execute_mysql_statements(connection, sql)
113
- # Split SQL into individual statements for MySQL
114
- # MySQL can't execute multiple statements in one call via ActiveRecord normally.
115
- # For procedures/triggers with BEGIN/END blocks, we need special handling.
138
+ statements = split_mysql_statements(sql)
116
139
 
117
- # Split into statements, respecting BEGIN/END blocks
140
+ without_query_transformers do
141
+ statements.each_with_index do |statement, index|
142
+ connection.execute(statement.delete_suffix(';'))
143
+ rescue StandardError => e
144
+ Rails.logger.error "Failed to execute MySQL statement #{index + 1}/#{statements.length}: #{e.message}"
145
+ Rails.logger.error "Statement: #{statement[0..200]}"
146
+ raise
147
+ end
148
+ end
149
+ end
150
+
151
+ # Split a MySQL dump into statements without needing DELIMITER
152
+ #
153
+ # A statement ends at a line ending in ";" outside any BEGIN ... END block.
154
+ # Blocks nest (procedures with inner BEGIN ... END), so the depth is
155
+ # counted; END IF/LOOP/WHILE/CASE/REPEAT close control flow, not blocks.
156
+ #
157
+ # @param sql [String] SQL text
158
+ # @return [Array<String>] Statements, each ending in ";"
159
+ def split_mysql_statements(sql)
118
160
  statements = []
119
- current_statement = +'' # Unfreeze string with unary plus
120
- in_block = false # Track if we're inside a BEGIN/END block
161
+ current = +''
162
+ depth = 0
121
163
 
122
164
  sql.each_line do |line|
123
- # Skip standalone comment lines
124
- next if line.strip.start_with?('--') && current_statement.strip.empty?
125
-
126
- current_statement << line
165
+ stripped = line.strip
166
+ next if current.empty? && (stripped.empty? || stripped.start_with?('--'))
127
167
 
128
- # Track BEGIN/END blocks (procedures and triggers)
129
- # MySQL procedures: CREATE PROCEDURE name(...) BEGIN ... END;
130
- # MySQL triggers: CREATE TRIGGER ... FOR EACH ROW BEGIN ... END;
131
- stripped_line = line.strip.upcase
168
+ current << line
169
+ depth += 1 if MYSQL_BLOCK_START.match?(stripped)
170
+ depth -= 1 if MYSQL_BLOCK_END.match?(stripped)
171
+ next unless depth.zero? && stripped.end_with?(';')
132
172
 
133
- # Detect start of block: "BEGIN" on its own line or "FOR EACH ROW BEGIN"
134
- in_block = true if stripped_line == 'BEGIN' || stripped_line.end_with?(' BEGIN')
135
-
136
- # Detect end of block: "END" or "END;"
137
- in_block = false if ['END;', 'END'].include?(stripped_line)
138
-
139
- # Statement is complete when:
140
- # 1. Line ends with semicolon, AND
141
- # 2. We just closed a block (ended with END or END;), OR we're not in a block
142
- if line.strip.end_with?(';') && !in_block
143
- statements << current_statement.strip
144
- current_statement = +'' # Unfreeze new string
145
- end
173
+ statements << current.strip
174
+ current = +''
146
175
  end
147
176
 
148
- # Add any remaining statement
149
- statements << current_statement.strip unless current_statement.strip.empty?
150
-
151
- # Execute each statement using raw connection
152
- statements.each_with_index do |statement, index|
153
- next if statement.empty?
154
- next if statement.start_with?('--') # Skip standalone comments
177
+ statements << current.strip unless current.strip.empty?
178
+ statements
179
+ end
155
180
 
156
- begin
157
- # Use ActiveRecord connection execute which works for procedures/triggers
158
- connection.execute(statement)
159
- rescue StandardError => e
160
- # Log helpful error with statement number
161
- Rails.logger.error "Failed to execute MySQL statement #{index + 1}/#{statements.length}: #{e.message}"
162
- Rails.logger.error "Statement: #{statement[0..200]}"
163
- raise
164
- end
165
- end
181
+ def without_query_transformers
182
+ transformers = ActiveRecord.query_transformers
183
+ ActiveRecord.query_transformers = []
184
+ yield
185
+ ensure
186
+ ActiveRecord.query_transformers = transformers
166
187
  end
167
188
  end
168
189
  end
@@ -26,11 +26,12 @@ module BetterStructureSql
26
26
  scope :by_format, ->(type) { where(format_type: type) }
27
27
  scope :by_output_mode, ->(mode) { where(output_mode: mode) }
28
28
  scope :recent, ->(limit) { order(created_at: :desc).limit(limit) }
29
- scope :oldest_first, -> { order(created_at: :asc) }
29
+ scope :oldest_first, -> { order(created_at: :asc, id: :asc) }
30
30
 
31
31
  # Class method to get latest version
32
+ # Ties on created_at (second-precision columns) resolve to the most recently inserted row
32
33
  def self.latest
33
- order(created_at: :desc).first
34
+ order(created_at: :desc, id: :desc).first
34
35
  end
35
36
 
36
37
  # Instance methods