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
@@ -5,6 +5,11 @@ module BetterStructureSql
5
5
  #
6
6
  # Provides controllers and views for browsing stored schema versions
7
7
  # through a web interface. Uses Bootstrap 5 from CDN for styling.
8
+ #
9
+ # The UI exposes the full database schema, so outside development and test
10
+ # every request is denied until the host application states how access is
11
+ # controlled, with one of {authenticate_with} or
12
+ # {authentication_handled_by_routes!}.
8
13
  class Engine < ::Rails::Engine
9
14
  isolate_namespace BetterStructureSql
10
15
 
@@ -19,10 +24,51 @@ module BetterStructureSql
19
24
  g.factory_bot dir: 'spec/factories'
20
25
  end
21
26
 
22
- # No asset pipeline dependencies - we use Bootstrap from CDN
23
- initializer 'better_structure_sql.assets' do |app|
24
- # Views and controllers are automatically loaded from app/ directory
25
- # when using isolate_namespace
27
+ class << self
28
+ # @return [Proc, nil] the access check registered with {authenticate_with}
29
+ attr_reader :authenticator
30
+
31
+ # Registers the access check run before every engine action
32
+ #
33
+ # The block receives the controller instance. Access is granted when it
34
+ # returns a truthy value; otherwise the engine responds 403 Forbidden,
35
+ # unless the block already rendered or redirected.
36
+ #
37
+ # @example config/initializers/better_structure_sql.rb
38
+ # BetterStructureSql::Engine.authenticate_with do |controller|
39
+ # controller.request.env['warden']&.user&.admin?
40
+ # end
41
+ #
42
+ # @yieldparam controller [BetterStructureSql::ApplicationController]
43
+ # @return [void]
44
+ # @raise [ArgumentError] when no block is given
45
+ def authenticate_with(&block)
46
+ raise ArgumentError, 'authenticate_with requires a block' unless block
47
+
48
+ @authenticator = block
49
+ end
50
+
51
+ # Declares that the routes mounting the engine already restrict access
52
+ # (for example Devise's +authenticate+ or a +constraints+ block), so the
53
+ # engine must not perform a check of its own.
54
+ #
55
+ # @return [void]
56
+ def authentication_handled_by_routes!
57
+ @authentication_handled_by_routes = true
58
+ end
59
+
60
+ # @return [Boolean] whether the host declared route-level access control
61
+ def authentication_handled_by_routes?
62
+ @authentication_handled_by_routes == true
63
+ end
64
+
65
+ # Clears any registered access control, restoring the defaults
66
+ #
67
+ # @return [void]
68
+ def reset_authentication!
69
+ @authenticator = nil
70
+ @authentication_handled_by_routes = false
71
+ end
26
72
  end
27
73
  end
28
74
  end
@@ -1,9 +1,36 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'active_support/core_ext/file/atomic'
4
+
3
5
  module BetterStructureSql
4
6
  # Handles writing schema output to either a single file or multiple files
5
7
  # with intelligent chunking based on line count limits.
6
8
  class FileWriter
9
+ HEADER_FILENAME = '_header.sql'
10
+ MANIFEST_FILENAME = '_manifest.json'
11
+ OBJECT_SEPARATOR = "\n\n"
12
+ SEPARATOR_LINES = 1
13
+
14
+ # Section => directory. Order is CRITICAL for schema loading, it respects the dependency chain:
15
+ # extensions -> types -> functions -> sequences -> tables -> indexes/fks -> views -> triggers -> migrations
16
+ SECTION_DIRECTORIES = {
17
+ extensions: '01_extensions', # Must be first (enable features)
18
+ types: '02_types', # Enums, composites, ranges, domains that need no function
19
+ functions: '03_functions', # Plus the types that need a function (dependency-ordered)
20
+ sequences: '04_sequences', # Before tables that use them
21
+ tables: '05_tables', # Core schema
22
+ indexes: '06_indexes', # After tables exist
23
+ foreign_keys: '07_foreign_keys', # After all tables exist
24
+ views: '08_views', # After tables (may use functions)
25
+ materialized_views: '08_views', # Bundled with views
26
+ triggers: '09_triggers', # After tables and functions
27
+ comments: '10_comments', # After all objects are created
28
+ migrations: '20_migrations' # Last (schema_migrations INSERT)
29
+ }.freeze
30
+
31
+ # Matches every numbered section directory, including ones no longer written
32
+ SECTION_DIRECTORY_GLOB = '[0-9]*_*'
33
+
7
34
  attr_reader :config
8
35
 
9
36
  def initialize(config = BetterStructureSql.configuration)
@@ -28,147 +55,131 @@ module BetterStructureSql
28
55
  def write_single_file(path, content)
29
56
  full_path = Rails.root.join(path)
30
57
  FileUtils.mkdir_p(File.dirname(full_path))
31
- File.write(full_path, content)
58
+ atomic_write(full_path, content)
32
59
  end
33
60
 
34
61
  # Write schema sections to multiple files with chunking
62
+ #
63
+ # Files left over from a previous, larger dump are removed so the directory
64
+ # always mirrors the current schema (the loader executes every SQL file it finds).
65
+ #
35
66
  # @param base_path [String] The base directory path
36
67
  # @param sections [Hash] Hash of section_name => array of SQL strings
37
- # @param header [String] The header content (SET statements, etc.)
68
+ # @param header [String, nil] The header content (SET statements, etc.)
69
+ # @return [Hash<String, String>] Map of relative file path => content
38
70
  def write_multi_file(base_path, sections, header)
39
71
  full_base_path = Rails.root.join(base_path)
40
72
  FileUtils.mkdir_p(full_base_path)
41
73
 
42
- # Write header file
43
- write_chunk(full_base_path, '_header.sql', header)
44
-
45
- # Define section order with directory prefixes
46
- # Order CRITICAL for schema loading - respects dependency chain:
47
- # extensions -> types/domains -> functions -> sequences -> tables -> indexes/fks -> views -> triggers -> migrations
48
- section_order = {
49
- extensions: '01_extensions', # Must be first (enable features)
50
- types: '02_types', # Before domains and tables
51
- domains: '02_types', # Bundled with types (domains are custom types)
52
- functions: '03_functions', # Before triggers that call them
53
- sequences: '04_sequences', # Before tables that use them
54
- tables: '05_tables', # Core schema
55
- indexes: '06_indexes', # After tables exist
56
- foreign_keys: '07_foreign_keys', # After all tables exist
57
- views: '08_views', # After tables (may use functions)
58
- materialized_views: '08_views', # Bundled with views
59
- triggers: '09_triggers', # After tables and functions
60
- comments: '10_comments', # After all objects are created
61
- migrations: '20_migrations' # Last (schema_migrations INSERT)
62
- }
74
+ atomic_write(full_base_path.join(HEADER_FILENAME), header.to_s)
63
75
 
64
76
  file_map = {}
65
- directory_file_counters = Hash.new(0) # Track file numbers per directory
77
+ group_sections_by_directory(sections).each do |directory_name, objects|
78
+ file_map.merge!(write_directory(full_base_path, directory_name, objects))
79
+ end
80
+
81
+ remove_stale_files(full_base_path, file_map)
82
+ file_map
83
+ end
84
+
85
+ # Write the manifest file, or remove a leftover one when content is nil
86
+ # @param base_path [String] The base directory path
87
+ # @param content [String, nil] Manifest JSON
88
+ def write_manifest(base_path, content)
89
+ manifest_path = Rails.root.join(base_path, MANIFEST_FILENAME)
90
+ return FileUtils.rm_f(manifest_path) if content.nil?
66
91
 
67
- # Group sections by directory to handle shared directories correctly
68
- sections_by_directory = {}
69
- section_order.each do |section_key, directory_name|
70
- next unless sections.key?(section_key)
92
+ atomic_write(manifest_path, content)
93
+ end
94
+
95
+ private
71
96
 
97
+ # Merge section contents that share a directory, preserving load order
98
+ # @param sections [Hash] Hash of section_name => array of SQL strings
99
+ # @return [Hash<String, Array<String>>] Directory name => SQL strings
100
+ def group_sections_by_directory(sections)
101
+ SECTION_DIRECTORIES.each_with_object({}) do |(section_key, directory_name), grouped|
72
102
  section_content = sections[section_key]
73
103
  next if section_content.blank?
74
104
 
75
- sections_by_directory[directory_name] ||= []
76
- sections_by_directory[directory_name].concat(section_content)
105
+ (grouped[directory_name] ||= []).concat(section_content)
77
106
  end
107
+ end
78
108
 
79
- # Process each directory (with merged content from multiple sections)
80
- sections_by_directory.each do |directory_name, merged_content|
81
- # Create directory
82
- section_dir = full_base_path.join(directory_name)
83
- FileUtils.mkdir_p(section_dir)
84
-
85
- # Chunk the merged content and write files
86
- chunks = chunk_section(merged_content, config.max_lines_per_file)
87
- chunks.each do |chunk|
88
- # Increment counter for this directory
89
- directory_file_counters[directory_name] += 1
90
- filename = format_filename(directory_file_counters[directory_name])
91
- file_path = section_dir.join(filename)
92
- content = chunk.join("\n\n")
93
- File.write(file_path, "#{content}\n")
94
-
95
- # Track in file map for manifest
96
- relative_path = "#{directory_name}/#{filename}"
97
- file_map[relative_path] = content
98
- end
99
- end
109
+ # Chunk and write all objects of one directory
110
+ # @return [Hash<String, String>] Map of relative file path => content
111
+ def write_directory(full_base_path, directory_name, objects)
112
+ section_dir = full_base_path.join(directory_name)
113
+ FileUtils.mkdir_p(section_dir)
100
114
 
101
- file_map
115
+ chunks = chunk_section(objects, config.max_lines_per_file)
116
+ chunks.each_with_index.to_h do |chunk, index|
117
+ filename = format_filename(index + 1)
118
+ content = chunk.join(OBJECT_SEPARATOR)
119
+ atomic_write(section_dir.join(filename), "#{content}\n")
120
+
121
+ ["#{directory_name}/#{filename}", content]
122
+ end
102
123
  end
103
124
 
104
- private
125
+ # Remove SQL files (and emptied section directories) that the current dump did not write
126
+ def remove_stale_files(full_base_path, file_map)
127
+ Dir.glob(full_base_path.join(SECTION_DIRECTORY_GLOB).to_s).each do |section_dir|
128
+ next unless File.directory?(section_dir)
129
+
130
+ Dir.glob(File.join(section_dir, '*.sql')).each do |file_path|
131
+ relative_path = "#{File.basename(section_dir)}/#{File.basename(file_path)}"
132
+ File.delete(file_path) unless file_map.key?(relative_path)
133
+ end
134
+
135
+ Dir.rmdir(section_dir) if Dir.empty?(section_dir)
136
+ end
137
+ end
105
138
 
106
139
  # Chunk an array of SQL strings into file-sized groups
107
- # Each chunk respects max_lines_per_file with overflow_threshold
140
+ # Each chunk respects max_lines_per_file with overflow_threshold, counting
141
+ # the blank line that separates objects in the written file.
108
142
  # Single objects larger than max_lines get their own file
109
143
  #
110
144
  # @param objects [Array<String>] Array of SQL strings
111
145
  # @param max_lines [Integer] Maximum lines per file
112
146
  # @return [Array<Array<String>>] Array of chunks, each chunk is array of SQL strings
113
147
  def chunk_section(objects, max_lines)
114
- return [] if objects.empty?
115
-
148
+ max_with_overflow = (max_lines * config.overflow_threshold).to_i
116
149
  chunks = []
117
- current_chunk = []
118
150
  current_lines = 0
119
- max_with_overflow = (max_lines * config.overflow_threshold).to_i
120
151
 
121
152
  objects.each do |object|
122
- object_lines = object.lines.count
123
-
124
- # If this single object exceeds max_lines, give it a dedicated file
125
- if object_lines > max_lines
126
- # Flush current chunk if it has content
127
- chunks << current_chunk unless current_chunk.empty?
153
+ object_lines = line_count(object)
154
+ lines_if_added = current_lines + SEPARATOR_LINES + object_lines
128
155
 
129
- # Single object in its own chunk
156
+ if chunks.empty? || start_new_chunk?(current_lines, lines_if_added, max_lines, max_with_overflow)
130
157
  chunks << [object]
131
-
132
- # Reset for next chunk
133
- current_chunk = []
134
- current_lines = 0
135
- next
136
- end
137
-
138
- # Decide whether to start a new chunk
139
- # If current chunk is already at max_lines, definitely start new chunk
140
- # If current chunk is under max_lines but adding this would exceed overflow, start new chunk
141
- # Otherwise, add to current chunk (even if it puts us slightly over max_lines, up to overflow threshold)
142
- if current_lines >= max_lines
143
- # Current chunk is full, start new one
144
- chunks << current_chunk unless current_chunk.empty?
145
- current_chunk = [object]
146
- current_lines = object_lines
147
- elsif current_lines.positive? && (current_lines + object_lines) > max_with_overflow
148
- # Adding this would exceed overflow threshold, start new chunk
149
- chunks << current_chunk
150
- current_chunk = [object]
151
158
  current_lines = object_lines
152
159
  else
153
- # Add to current chunk (may go slightly over max_lines, within overflow)
154
- current_chunk << object
155
- current_lines += object_lines
160
+ chunks.last << object
161
+ current_lines = lines_if_added
156
162
  end
157
163
  end
158
164
 
159
- # Don't forget the last chunk
160
- chunks << current_chunk unless current_chunk.empty?
161
-
162
165
  chunks
163
166
  end
164
167
 
165
- # Write a single chunk file
166
- # @param directory [Pathname] The directory path
167
- # @param filename [String] The filename
168
+ # A chunk is closed once it is full, or when the next object would push it past the overflow limit
169
+ def start_new_chunk?(current_lines, lines_if_added, max_lines, max_with_overflow)
170
+ current_lines >= max_lines || lines_if_added > max_with_overflow
171
+ end
172
+
173
+ # Number of lines an object occupies in the written file
174
+ def line_count(object)
175
+ object.chomp.count("\n") + 1
176
+ end
177
+
178
+ # Write a file so readers never observe a partially written dump
179
+ # @param path [Pathname, String] The destination path
168
180
  # @param content [String] The file content
169
- def write_chunk(directory, filename, content)
170
- file_path = directory.join(filename)
171
- File.write(file_path, content)
181
+ def atomic_write(path, content)
182
+ File.atomic_write(path.to_s, File.dirname(path)) { |file| file.write(content) }
172
183
  end
173
184
 
174
185
  # Generate zero-padded filename
@@ -7,6 +7,9 @@ module BetterStructureSql
7
7
  # Provides common functionality for generating SQL statements
8
8
  # from database object metadata.
9
9
  class Base
10
+ # Schemas whose objects are referenced without a schema prefix
11
+ DEFAULT_SCHEMAS = %w[public main].freeze
12
+
10
13
  attr_reader :config
11
14
 
12
15
  def initialize(config = BetterStructureSql.configuration)
@@ -37,25 +40,49 @@ module BetterStructureSql
37
40
  # Quote identifier based on database adapter
38
41
  #
39
42
  # @param identifier [String] Database identifier (table, column, index name)
40
- # @return [String] Quoted identifier
43
+ # @return [String] Quoted identifier, with embedded quote characters doubled
41
44
  def quote_identifier(identifier)
42
45
  return identifier if identifier.nil?
43
46
 
44
47
  adapter_name = detect_adapter_name
45
48
 
46
49
  if mysql_adapter?(adapter_name)
47
- "`#{identifier}`"
50
+ "`#{identifier.to_s.gsub('`', '``')}`"
48
51
  else
49
- "\"#{identifier}\""
52
+ "\"#{identifier.to_s.gsub('"', '""')}\""
50
53
  end
51
54
  end
52
55
 
56
+ # Quote a list of identifiers (e.g. the columns of a composite key)
57
+ #
58
+ # @param identifiers [Array<String>] Identifiers in order
59
+ # @return [String] Comma-separated quoted identifiers
60
+ def quote_identifier_list(identifiers)
61
+ identifiers.map { |identifier| quote_identifier(identifier) }.join(', ')
62
+ end
63
+
64
+ # Quote a possibly schema-qualified identifier
65
+ #
66
+ # The schema is omitted for default schemas (PostgreSQL 'public', SQLite 'main').
67
+ #
68
+ # @param schema [String, nil] Schema name
69
+ # @param name [String] Object name
70
+ # @return [String] Quoted, optionally schema-qualified identifier
71
+ def qualified_identifier(schema, name)
72
+ return quote_identifier(name) if schema.nil? || DEFAULT_SCHEMAS.include?(schema)
73
+
74
+ "#{quote_identifier(schema)}.#{quote_identifier(name)}"
75
+ end
76
+
53
77
  # Detect current adapter name
54
78
  #
79
+ # Without an established connection (generators used standalone) there is
80
+ # no adapter to match, so identifiers get standard SQL double quotes.
81
+ #
55
82
  # @return [String, nil] Adapter name or nil
56
83
  def detect_adapter_name
57
84
  ActiveRecord::Base.connection.adapter_name.downcase
58
- rescue StandardError
85
+ rescue ActiveRecord::ConnectionNotEstablished
59
86
  nil
60
87
  end
61
88
 
@@ -10,6 +10,7 @@ module BetterStructureSql
10
10
  # Generates COMMENT ON statement
11
11
  #
12
12
  # @param comment_data [Hash] Comment metadata with :object_type, :object_name, :comment
13
+ # (and :table_name for a column, whose :object_name is the column name)
13
14
  # @return [String] SQL statement
14
15
  def generate(comment_data)
15
16
  object_type = comment_data[:object_type]
@@ -23,13 +24,15 @@ module BetterStructureSql
23
24
  when :table
24
25
  generate_table_comment(object_name, escaped_comment)
25
26
  when :column
26
- generate_column_comment(object_name, escaped_comment)
27
+ generate_column_comment(comment_data.fetch(:table_name), object_name, escaped_comment)
27
28
  when :index
28
29
  generate_index_comment(object_name, escaped_comment)
29
30
  when :view
30
31
  generate_view_comment(object_name, escaped_comment)
31
32
  when :function
32
- generate_function_comment(object_name, escaped_comment)
33
+ generate_routine_comment('FUNCTION', object_name, escaped_comment)
34
+ when :procedure
35
+ generate_routine_comment('PROCEDURE', object_name, escaped_comment)
33
36
  else
34
37
  raise ArgumentError, "Unknown object type: #{object_type}"
35
38
  end
@@ -54,12 +57,11 @@ module BetterStructureSql
54
57
 
55
58
  # Generate comment for column
56
59
  #
57
- # @param column_identifier [String] Format: "table_name.column_name"
60
+ # @param table_name [String] Table name
61
+ # @param column_name [String] Column name
58
62
  # @param comment [String] Comment text (already escaped)
59
63
  # @return [String] SQL statement
60
- def generate_column_comment(column_identifier, comment)
61
- table_name, column_name = column_identifier.split('.')
62
-
64
+ def generate_column_comment(table_name, column_name, comment)
63
65
  if mysql_adapter?(detect_adapter_name)
64
66
  # MySQL requires full column definition in ALTER TABLE
65
67
  # This is a limitation - we'd need to fetch column type, which is complex
@@ -100,17 +102,19 @@ module BetterStructureSql
100
102
  end
101
103
  end
102
104
 
103
- # Generate comment for function
105
+ # Generate comment for a function or procedure
104
106
  #
105
- # @param function_name [String] Function name
107
+ # @param kind [String] 'FUNCTION' or 'PROCEDURE'
108
+ # @param signature [String] Quoted routine name with argument types,
109
+ # e.g. "add(a integer, b integer)", so overloaded routines are unambiguous
106
110
  # @param comment [String] Comment text (already escaped)
107
111
  # @return [String] SQL statement
108
- def generate_function_comment(function_name, comment)
109
- # Only PostgreSQL supports function comments
112
+ def generate_routine_comment(kind, signature, comment)
113
+ # Only PostgreSQL supports routine comments
110
114
  if mysql_adapter?(detect_adapter_name)
111
- '-- MySQL does not support function comments'
115
+ "-- MySQL does not support #{kind.downcase} comments"
112
116
  else
113
- "COMMENT ON FUNCTION #{quote_identifier(function_name)} IS '#{comment}';"
117
+ "COMMENT ON #{kind} #{signature} IS '#{comment}';"
114
118
  end
115
119
  end
116
120
  end
@@ -6,15 +6,17 @@ module BetterStructureSql
6
6
  class DomainGenerator < Base
7
7
  # Generates CREATE DOMAIN statement
8
8
  #
9
- # @param domain [Hash] Domain metadata
9
+ # @param domain [Hash] Domain metadata with :name, :schema, :base_type and
10
+ # optional :default, :not_null and :constraints (array of :name, :definition)
10
11
  # @return [String] SQL statement
11
12
  def generate(domain)
12
- schema_prefix = domain[:schema] == 'public' ? '' : "#{domain[:schema]}."
13
-
14
13
  # NOTE: PostgreSQL does not support IF NOT EXISTS for domains
15
- parts = ["CREATE DOMAIN #{schema_prefix}#{domain[:name]} AS #{domain[:base_type]}"]
16
-
17
- parts << domain[:constraint] if domain[:constraint].present?
14
+ parts = ["CREATE DOMAIN #{qualified_identifier(domain[:schema], domain[:name])} AS #{domain[:base_type]}"]
15
+ parts << "DEFAULT #{domain[:default]}" if domain[:default]
16
+ parts << 'NOT NULL' if domain[:not_null]
17
+ Array(domain[:constraints]).each do |constraint|
18
+ parts << "CONSTRAINT #{quote_identifier(constraint[:name])} #{constraint[:definition]}"
19
+ end
18
20
 
19
21
  "#{parts.join(' ')};"
20
22
  end
@@ -6,6 +6,9 @@ module BetterStructureSql
6
6
  class ExtensionGenerator < Base
7
7
  # Generates CREATE EXTENSION or PRAGMA statement
8
8
  #
9
+ # Extensions installed outside 'public' also get a CREATE SCHEMA IF NOT EXISTS,
10
+ # since WITH SCHEMA requires the schema to exist.
11
+ #
9
12
  # @param extension [Hash] Extension metadata
10
13
  # @return [String] SQL statement
11
14
  def generate(extension)
@@ -15,8 +18,10 @@ module BetterStructureSql
15
18
  # PostgreSQL extensions
16
19
  # Quote extension name if it contains special characters
17
20
  ext_name = extension[:name].include?('-') ? "\"#{extension[:name]}\"" : extension[:name]
18
- schema_clause = extension[:schema] == 'public' ? '' : " WITH SCHEMA #{extension[:schema]}"
19
- "CREATE EXTENSION IF NOT EXISTS #{ext_name}#{schema_clause};"
21
+ return "CREATE EXTENSION IF NOT EXISTS #{ext_name};" if extension[:schema] == 'public'
22
+
23
+ schema = quote_identifier(extension[:schema])
24
+ "CREATE SCHEMA IF NOT EXISTS #{schema};\nCREATE EXTENSION IF NOT EXISTS #{ext_name} WITH SCHEMA #{schema};"
20
25
  end
21
26
  end
22
27
  end
@@ -8,14 +8,19 @@ module BetterStructureSql
8
8
  class ForeignKeyGenerator < Base
9
9
  # Generates ALTER TABLE ADD CONSTRAINT for foreign key
10
10
  #
11
+ # PostgreSQL supplies the full constraint :definition (columns, MATCH,
12
+ # actions, DEFERRABLE, NOT VALID); other adapters supply its components.
13
+ #
11
14
  # @param foreign_key [Hash] Foreign key metadata
12
15
  # @return [String] SQL statement
13
16
  def generate(foreign_key)
17
+ return generate_from_definition(foreign_key) if foreign_key[:definition]
18
+
14
19
  parts = [
15
- "ALTER TABLE #{foreign_key[:table]}",
16
- "ADD CONSTRAINT #{foreign_key[:name]}",
17
- "FOREIGN KEY (#{foreign_key[:column]})",
18
- "REFERENCES #{foreign_key[:foreign_table]} (#{foreign_key[:foreign_column]})"
20
+ "ALTER TABLE #{quote_identifier(foreign_key[:table])}",
21
+ "ADD CONSTRAINT #{quote_identifier(foreign_key[:name])}",
22
+ "FOREIGN KEY (#{quote_identifier_list(foreign_key[:columns])})",
23
+ "REFERENCES #{quote_identifier(foreign_key[:foreign_table])} (#{quote_identifier_list(foreign_key[:foreign_columns])})"
19
24
  ]
20
25
 
21
26
  on_delete = format_action(foreign_key[:on_delete])
@@ -29,6 +34,11 @@ module BetterStructureSql
29
34
 
30
35
  private
31
36
 
37
+ def generate_from_definition(foreign_key)
38
+ "ALTER TABLE #{quote_identifier(foreign_key[:table])} " \
39
+ "ADD CONSTRAINT #{quote_identifier(foreign_key[:name])} #{foreign_key[:definition]};"
40
+ end
41
+
32
42
  def format_action(action)
33
43
  case action&.upcase
34
44
  when 'CASCADE' then 'CASCADE'
@@ -27,26 +27,6 @@ module BetterStructureSql
27
27
  # For simplicity, omit IF NOT EXISTS for cross-database compatibility
28
28
  "CREATE #{unique_clause}INDEX #{name} ON #{table} (#{columns_list});"
29
29
  end
30
-
31
- private
32
-
33
- def quote_identifier(identifier)
34
- return identifier if identifier.nil?
35
-
36
- # Detect adapter from ActiveRecord connection
37
- adapter_name = begin
38
- ActiveRecord::Base.connection.adapter_name.downcase
39
- rescue StandardError
40
- nil
41
- end
42
-
43
- # MySQL/MariaDB use backticks, PostgreSQL/SQLite use double quotes
44
- if %w[mysql mysql2 trilogy].include?(adapter_name)
45
- "`#{identifier}`"
46
- else
47
- "\"#{identifier}\""
48
- end
49
- end
50
30
  end
51
31
  end
52
32
  end
@@ -9,13 +9,12 @@ module BetterStructureSql
9
9
  # @param matview [Hash] Materialized view metadata
10
10
  # @return [String] SQL statement
11
11
  def generate(matview)
12
- schema_prefix = matview[:schema] == 'public' ? '' : "#{matview[:schema]}."
13
12
  definition = matview[:definition].strip
14
13
 
15
14
  # Ensure definition ends with semicolon
16
15
  definition += ';' unless definition.end_with?(';')
17
16
 
18
- output = ["CREATE MATERIALIZED VIEW IF NOT EXISTS #{schema_prefix}#{matview[:name]} AS"]
17
+ output = ["CREATE MATERIALIZED VIEW IF NOT EXISTS #{qualified_identifier(matview[:schema], matview[:name])} AS"]
19
18
  output << definition
20
19
 
21
20
  # Add indexes if present
@@ -24,8 +23,24 @@ module BetterStructureSql
24
23
  output += matview[:indexes].map { |idx| "#{idx};" }
25
24
  end
26
25
 
26
+ output << comment_statement(matview) if matview[:comment] && config.include_comments
27
+
27
28
  output.join("\n")
28
29
  end
30
+
31
+ private
32
+
33
+ # COMMENT ON MATERIALIZED VIEW statement
34
+ #
35
+ # The comments section only covers tables, columns, indexes, views and
36
+ # functions, so materialized view comments are emitted with the view.
37
+ #
38
+ # @param matview [Hash] Materialized view metadata with :comment
39
+ # @return [String] SQL statement
40
+ def comment_statement(matview)
41
+ name = qualified_identifier(matview[:schema], matview[:name])
42
+ "COMMENT ON MATERIALIZED VIEW #{name} IS '#{matview[:comment].gsub("'", "''")}';"
43
+ end
29
44
  end
30
45
  end
31
46
  end
@@ -9,18 +9,26 @@ module BetterStructureSql
9
9
  # @param sequence [Hash] Sequence metadata
10
10
  # @return [String] SQL statement
11
11
  def generate(sequence)
12
- parts = ["CREATE SEQUENCE IF NOT EXISTS #{sequence[:name]}"]
12
+ parts = ["CREATE SEQUENCE IF NOT EXISTS #{quote_identifier(sequence[:name])}"]
13
+ parts << "AS #{sequence[:data_type]}" if sequence[:data_type] && sequence[:data_type] != 'bigint'
14
+ parts.concat(options(sequence))
13
15
 
16
+ "#{parts.join("\n ")};"
17
+ end
18
+
19
+ # Sequence option clauses shared by CREATE SEQUENCE and identity columns
20
+ #
21
+ # @param sequence [Hash] Sequence metadata
22
+ # @return [Array<String>] Option clauses (e.g. "START WITH 1", "CYCLE")
23
+ def options(sequence)
24
+ parts = []
14
25
  parts << "START WITH #{sequence[:start_value]}" if sequence[:start_value]
15
26
  parts << "INCREMENT BY #{sequence[:increment]}" if sequence[:increment] && sequence[:increment] != 1
16
27
  parts << "MINVALUE #{sequence[:min_value]}" if sequence[:min_value]
17
28
  parts << "MAXVALUE #{sequence[:max_value]}" if sequence[:max_value]
18
-
19
29
  parts << "CACHE #{sequence[:cache_size]}" if sequence[:cache_size] && sequence[:cache_size] > 1
20
-
21
30
  parts << 'CYCLE' if sequence[:cycle]
22
-
23
- "#{parts.join("\n ")};"
31
+ parts
24
32
  end
25
33
  end
26
34
  end