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
data/app/CLAUDE.md ADDED
@@ -0,0 +1,12 @@
1
+ # app/ — the schema versions engine
2
+
3
+ Mountable engine (`lib/better_structure_sql/engine.rb`, routes in `config/routes.rb`): `schema_versions` index, show, `raw`, `download`. It displays the host application's full database schema, so treat every change as security-relevant.
4
+
5
+ - **Fails closed.** `ApplicationController#authenticate_access!` is a `before_action` on every controller. Outside `development` and `test` it answers 403 until the host calls `Engine.authenticate_with { |controller| ... }` or `Engine.authentication_handled_by_routes!`. Never add an action, controller or environment that bypasses it; never widen `LOCAL_ENVIRONMENTS`.
6
+ - **Stored content is untrusted text.** Views escape it: no `raw`, no `html_safe`, no `<%==` on schema content. `raw` and `download` respond `text/plain` or as an attachment, never as HTML.
7
+ - **No caching of schemas.** Keep the `no_store` `before_action`.
8
+ - **Large columns stay out of lists.** `index` and metadata lookups select `METADATA_COLUMNS` only; `content` and `zip_archive` are read only by the action that sends them, and large content is streamed in chunks.
9
+ - No asset pipeline: Bootstrap and icons come from a CDN in `app/views/layouts/better_structure_sql/application.html.erb`.
10
+ - Specs: `spec/controllers/better_structure_sql/`, `spec/requests/better_structure_sql/engine_spec.rb`, `spec/routing/`, `spec/helpers/`. A new action needs the denied-access case as well as the allowed one. Specs that register access control call `Engine.reset_authentication!` afterwards.
11
+ - See it running: `bin/dev`, then http://127.0.0.1:3000/better_structure_sql/schema_versions.
12
+ - Docs to update with behaviour changes: `docs/features/web-ui.md`.
@@ -3,59 +3,99 @@
3
3
  module BetterStructureSql
4
4
  # Base controller for BetterStructureSql Rails Engine
5
5
  #
6
- # Provides authentication and authorization hooks for the web UI
7
- # that displays stored schema versions. By default, no authentication
8
- # is required (open access), but this should be overridden in production.
6
+ # The web UI exposes the full database schema, so access control fails
7
+ # closed: outside development and test every request is answered with
8
+ # 403 Forbidden until the host application configures one of the following.
9
9
  #
10
- # @example Using Devise route constraints (recommended)
10
+ # @example Access check in an initializer
11
+ # BetterStructureSql::Engine.authenticate_with do |controller|
12
+ # controller.request.env['warden']&.user&.admin?
13
+ # end
14
+ #
15
+ # @example Route constraints (Devise shown), declared to the engine
16
+ # # config/initializers/better_structure_sql.rb
17
+ # BetterStructureSql::Engine.authentication_handled_by_routes!
18
+ #
19
+ # # config/routes.rb
11
20
  # authenticate :user, ->(user) { user.admin? } do
12
21
  # mount BetterStructureSql::Engine, at: "/better_structure_sql"
13
22
  # end
14
23
  #
15
- # @example Using controller-level authentication
24
+ # @example Overriding the hook
16
25
  # BetterStructureSql::ApplicationController.class_eval do
17
- # before_action :authenticate_admin!
18
- #
19
26
  # private
20
27
  #
21
- # def authenticate_admin!
28
+ # def authenticate_access!
22
29
  # head :unauthorized unless current_user&.admin?
23
30
  # end
24
31
  # end
25
32
  class ApplicationController < ActionController::Base
33
+ # Response body sent when no access control has been configured
34
+ ACCESS_NOT_CONFIGURED_MESSAGE = <<~MESSAGE
35
+ BetterStructureSql: access to the schema versions UI is not configured.
36
+
37
+ This UI exposes your database schema, so outside development and test it
38
+ is disabled until the application declares how access is controlled.
39
+ Add one of these to config/initializers/better_structure_sql.rb:
40
+
41
+ # 1. Check access in the engine
42
+ BetterStructureSql::Engine.authenticate_with do |controller|
43
+ controller.request.env['warden']&.user&.admin?
44
+ end
45
+
46
+ # 2. The routes mounting the engine already restrict access
47
+ # (Devise `authenticate`, a `constraints` block, ...)
48
+ BetterStructureSql::Engine.authentication_handled_by_routes!
49
+ MESSAGE
50
+
51
+ # Environments where the UI is open when no access control is configured
52
+ LOCAL_ENVIRONMENTS = %w[development test].freeze
53
+
26
54
  layout 'better_structure_sql/application'
27
55
 
28
- # Override this method in your host application to add authentication
29
- # Example using Devise route constraints (recommended):
30
- # authenticate :user, ->(user) { user.admin? } do
31
- # mount BetterStructureSql::Engine, at: "/better_structure_sql"
32
- # end
33
- #
34
- # Or override at controller level:
35
- # BetterStructureSql::ApplicationController.class_eval do
36
- # before_action :authenticate_admin!
37
- #
38
- # private
39
- #
40
- # def authenticate_admin!
41
- # head :unauthorized unless current_user&.admin?
42
- # end
43
- # end
56
+ protect_from_forgery with: :exception
57
+
44
58
  before_action :authenticate_access!
59
+ # Schema dumps are sensitive: keep them out of browser and proxy caches
60
+ before_action :no_store
61
+
62
+ rescue_from ActiveRecord::RecordNotFound, with: :render_not_found
45
63
 
46
64
  private
47
65
 
48
66
  # Authentication hook for engine access control
49
67
  #
50
- # Default implementation allows open access. Override this method
51
- # in your host application to add authentication and authorization.
52
- # This method is called before all controller actions via before_action.
68
+ # Runs the check registered with {Engine.authenticate_with}. Without one,
69
+ # access is open only in development and test, or when the host declared
70
+ # {Engine.authentication_handled_by_routes!}. May be overridden by the
71
+ # host application.
53
72
  #
54
- # @return [Boolean] true to allow access, false or head :unauthorized to deny
73
+ # @return [void]
55
74
  def authenticate_access!
56
- # Default: no authentication (open access)
57
- # Override this in your host application for production use
58
- true
75
+ authenticator = Engine.authenticator
76
+ return run_authenticator(authenticator) if authenticator
77
+ return if Engine.authentication_handled_by_routes? || local_environment?
78
+
79
+ deny_unconfigured_access
80
+ end
81
+
82
+ def run_authenticator(authenticator)
83
+ return if authenticator.call(self) || performed?
84
+
85
+ render plain: 'Forbidden', status: :forbidden
86
+ end
87
+
88
+ def local_environment?
89
+ LOCAL_ENVIRONMENTS.include?(Rails.env.to_s)
90
+ end
91
+
92
+ def deny_unconfigured_access
93
+ logger&.error('[BetterStructureSql] Request denied: engine access control is not configured')
94
+ render plain: ACCESS_NOT_CONFIGURED_MESSAGE, status: :forbidden
95
+ end
96
+
97
+ def render_not_found
98
+ render plain: 'Schema version not found', status: :not_found
59
99
  end
60
100
  end
61
101
  end
@@ -4,8 +4,8 @@ module BetterStructureSql
4
4
  # Controller for browsing and downloading stored schema versions
5
5
  #
6
6
  # Provides web UI actions for listing, viewing, and downloading schema
7
- # versions stored in the database. Implements memory-efficient streaming
8
- # for large files and multi-file ZIP archive support.
7
+ # versions stored in the database. Large columns (content, zip_archive)
8
+ # are only read by the actions that send them.
9
9
  #
10
10
  # @see SchemaVersion
11
11
  class SchemaVersionsController < ApplicationController
@@ -14,206 +14,147 @@ module BetterStructureSql
14
14
  # Maximum file size to display in browser (1MB)
15
15
  # Large enough for most schemas but keeps browser responsive
16
16
  MAX_DISPLAY_SIZE = 1.megabyte
17
-
18
- # Lists stored schema versions with pagination
17
+ # Schema versions listed per page
18
+ PER_PAGE = 100
19
+ # Characters read from the database per streamed chunk
20
+ STREAM_CHUNK_CHARS = 512.kilobytes
21
+ # Columns that are cheap to load (everything except content and zip_archive)
22
+ METADATA_COLUMNS = %i[
23
+ id pg_version format_type output_mode created_at
24
+ content_size line_count file_count content_hash
25
+ ].freeze
26
+ # Content type of every schema text response
27
+ TEXT_CONTENT_TYPE = 'text/plain; charset=utf-8'
28
+
29
+ # Lists stored schema versions, newest first, one page at a time
19
30
  #
20
31
  # Loads only metadata (no content or zip_archive) for performance.
21
- # Displays up to 100 most recent versions ordered by creation date.
22
32
  #
23
33
  # @return [void]
24
- # GET /better_structure_sql/schema_versions
34
+ # GET /better_structure_sql/schema_versions?page=2
25
35
  def index
26
- # Load only metadata for listing (no content or zip_archive)
27
- @schema_versions = SchemaVersion
28
- .select(:id, :pg_version, :format_type, :output_mode, :created_at,
29
- :content_size, :file_count, :content_hash)
30
- .order(created_at: :desc)
31
- .limit(100)
36
+ @total_count = SchemaVersion.count
37
+ @total_pages = [(@total_count.to_f / PER_PAGE).ceil, 1].max
38
+ @page = requested_page.clamp(1, @total_pages)
39
+ @schema_versions = SchemaVersion.select(*METADATA_COLUMNS)
40
+ .order(created_at: :desc, id: :desc)
41
+ .limit(PER_PAGE)
42
+ .offset((@page - 1) * PER_PAGE)
43
+ .load
32
44
  end
33
45
 
34
46
  # Displays details of a specific schema version
35
47
  #
36
- # Loads metadata first for performance. For small single-file versions
37
- # (under 200KB), loads content for inline display. For multi-file versions,
38
- # extracts and parses the embedded manifest JSON.
48
+ # Content is loaded for inline display only when it is at most
49
+ # MAX_DISPLAY_SIZE; otherwise +content+ is nil. The ZIP archive is never
50
+ # loaded.
39
51
  #
40
52
  # @return [void]
41
- # @raise [ActiveRecord::RecordNotFound] if schema version not found
42
53
  # GET /better_structure_sql/schema_versions/:id
43
54
  def show
44
- # Load metadata first (no content or ZIP to minimize memory usage)
45
- @schema_version = SchemaVersion
46
- .select(:id, :pg_version, :format_type, :output_mode, :created_at,
47
- :content_size, :line_count, :file_count, :content_hash)
48
- .find(params[:id])
49
-
50
- # Only load content for small files to display inline
51
- # For large files, metadata is sufficient
52
- if @schema_version.content_size <= MAX_DISPLAY_SIZE
53
- # Reload full record with content column
54
- # Note: We don't select zip_archive to avoid loading large binary data
55
- @schema_version = SchemaVersion.select(
56
- :id, :pg_version, :format_type, :output_mode, :created_at,
57
- :content_size, :line_count, :file_count, :content_hash, :content
58
- ).find(params[:id])
59
- end
60
-
61
- # NOTE: Manifest extraction intentionally skipped to avoid loading
62
- # potentially large ZIP archives into memory. Manifest is primarily
63
- # useful for tooling and can be extracted from the download if needed.
64
- rescue ActiveRecord::RecordNotFound
65
- render plain: 'Schema version not found', status: :not_found
55
+ @schema_version = SchemaVersion.select(*METADATA_COLUMNS, displayable_content_sql).find(params[:id])
66
56
  end
67
57
 
68
58
  # Downloads raw content of a schema version as plain text
69
59
  #
70
- # Streams large files (>2MB) in chunks to avoid memory issues.
71
- # Smaller files are sent directly using send_data.
72
- #
73
60
  # @return [void]
74
- # @raise [ActiveRecord::RecordNotFound] if schema version not found
75
61
  # GET /better_structure_sql/schema_versions/:id/raw
76
62
  def raw
77
- version = SchemaVersion.select(:id, :format_type, :content_size).find(params[:id])
78
-
79
- filename = "schema_version_#{version.id}_#{version.format_type}.txt"
80
-
81
- # For large files, stream from database to avoid loading into memory
82
- if version.content_size > MAX_MEMORY_SIZE
83
- stream_large_file(version.id, filename)
84
- else
85
- # For smaller files, use regular send_data
86
- content = SchemaVersion.find(version.id).content
87
- send_data content,
88
- filename: filename,
89
- type: 'text/plain',
90
- disposition: 'attachment'
91
- end
92
- rescue ActiveRecord::RecordNotFound
93
- render plain: 'Schema version not found', status: :not_found
63
+ version = find_metadata
64
+ send_content(version, "schema_version_#{version.id}_#{file_extension(version)}.txt")
94
65
  end
95
66
 
96
67
  # Downloads schema version in appropriate format
97
68
  #
98
69
  # Multi-file versions with ZIP archives are sent as .zip files.
99
- # Single-file versions are sent as .sql or .rb files based on format_type.
70
+ # Single-file versions are sent as structure.sql or structure.rb.
100
71
  #
101
72
  # @return [void]
102
- # @raise [ActiveRecord::RecordNotFound] if schema version not found
103
73
  # GET /better_structure_sql/schema_versions/:id/download
104
74
  def download
105
- version = SchemaVersion.find(params[:id])
75
+ version = find_metadata
76
+ zip_archive = SchemaVersion.where(id: version.id).pick(:zip_archive) if version.multi_file?
106
77
 
107
- if version.multi_file? && version.zip_archive?
108
- send_zip_download(version)
78
+ if zip_archive.present?
79
+ send_zip_download(version, zip_archive)
109
80
  else
110
- send_file_download(version)
81
+ send_content(version, "structure.#{file_extension(version)}")
111
82
  end
112
- rescue ActiveRecord::RecordNotFound
113
- render plain: 'Schema version not found', status: :not_found
114
83
  end
115
84
 
116
85
  private
117
86
 
118
- # Sends ZIP archive download for multi-file schema versions
119
- #
120
- # Validates ZIP archive before sending to prevent corrupted downloads.
121
- # Filename includes version ID and timestamp.
122
- #
123
- # @param version [SchemaVersion] the schema version to download
124
- # @return [void]
125
- def send_zip_download(version)
126
- # Validate ZIP
127
- BetterStructureSql::ZipGenerator.validate_zip!(version.zip_archive)
87
+ def requested_page
88
+ Integer(params[:page].to_s, 10)
89
+ rescue ArgumentError
90
+ 1
91
+ end
128
92
 
129
- filename = "schema_version_#{version.id}_#{version.created_at.to_i}.zip"
93
+ # Selects content only when small enough to display, in a single query
94
+ def displayable_content_sql
95
+ Arel.sql("CASE WHEN content_size <= #{MAX_DISPLAY_SIZE.to_i} THEN content END AS content")
96
+ end
130
97
 
131
- send_data version.zip_archive,
132
- filename: filename,
133
- type: 'application/zip',
134
- disposition: 'attachment'
98
+ def find_metadata
99
+ SchemaVersion.select(*METADATA_COLUMNS).find(params[:id])
135
100
  end
136
101
 
137
- # Sends single-file schema version download
138
- #
139
- # Streams large files (>2MB) to avoid memory issues. Filename is
140
- # structure.sql or structure.rb based on format_type.
141
- #
142
- # @param version [SchemaVersion] the schema version to download
143
- # @return [void]
144
- def send_file_download(version)
145
- extension = version.format_type == 'rb' ? 'rb' : 'sql'
146
- filename = "structure.#{extension}"
102
+ # Maps the stored format to a known extension so the stored value never
103
+ # reaches a response header
104
+ def file_extension(version)
105
+ version.format_type == 'rb' ? 'rb' : 'sql'
106
+ end
147
107
 
148
- # Handle large files with streaming
149
- if version.content_size > MAX_MEMORY_SIZE
150
- stream_large_content(version, filename)
151
- else
152
- send_data version.content,
153
- filename: filename,
154
- type: 'text/plain',
155
- disposition: 'attachment'
156
- end
108
+ # Sends the validated ZIP archive of a multi-file schema version
109
+ def send_zip_download(version, zip_archive)
110
+ BetterStructureSql::ZipGenerator.validate_zip!(zip_archive)
111
+
112
+ send_data zip_archive,
113
+ filename: "schema_version_#{version.id}_#{version.created_at.to_i}.zip",
114
+ type: 'application/zip',
115
+ disposition: 'attachment'
116
+ rescue Zip::Error, BetterStructureSql::ZipGenerator::ZipError => e
117
+ logger&.error("[BetterStructureSql] Invalid ZIP archive for schema version #{version.id}: #{e.message}")
118
+ render plain: 'Stored ZIP archive is invalid', status: :internal_server_error
157
119
  end
158
120
 
159
- # Streams large content in 64KB chunks to avoid memory issues
160
- #
161
- # Sets response headers for streaming and disables proxy buffering.
162
- # Fetches content from database and yields chunks via Enumerator.
163
- #
164
- # @param version [SchemaVersion] the schema version to stream
165
- # @param filename [String] the filename for Content-Disposition header
166
- # @return [void]
167
- def stream_large_content(version, filename)
168
- response.headers['Content-Type'] = 'text/plain'
169
- response.headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
170
- response.headers['X-Accel-Buffering'] = 'no'
171
-
172
- self.response_body = Enumerator.new do |yielder|
173
- content = SchemaVersion.connection.select_value(
174
- "SELECT content FROM #{SchemaVersion.table_name} WHERE id = #{version.id}"
175
- )
176
-
177
- chunk_size = 64.kilobytes
178
- offset = 0
179
- while offset < content.bytesize
180
- yielder << content.byteslice(offset, chunk_size)
181
- offset += chunk_size
182
- end
183
- end
121
+ # Sends content as a text attachment, streaming it when larger than MAX_MEMORY_SIZE
122
+ def send_content(version, filename)
123
+ return stream_content(version.id, filename) if version.content_size > MAX_MEMORY_SIZE
124
+
125
+ send_data SchemaVersion.where(id: version.id).pick(:content),
126
+ filename:,
127
+ type: TEXT_CONTENT_TYPE,
128
+ disposition: 'attachment'
184
129
  end
185
130
 
186
- # Streams large file content from database in chunks
187
- #
188
- # Sets appropriate headers for streaming downloads and disables proxy buffering.
189
- # Fetches content from database and streams in 64KB chunks via Enumerator.
190
- #
191
- # @param version_id [Integer] the schema version ID
192
- # @param filename [String] the filename for Content-Disposition header
193
- # @return [void]
194
- def stream_large_file(version_id, filename)
195
- # Set headers for streaming
196
- response.headers['Content-Type'] = 'text/plain'
197
- response.headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
198
- response.headers['Cache-Control'] = 'no-cache'
131
+ def stream_content(version_id, filename)
132
+ response.headers['Content-Type'] = TEXT_CONTENT_TYPE
133
+ response.headers['Content-Disposition'] =
134
+ ActionDispatch::Http::ContentDisposition.format(disposition: 'attachment', filename:)
199
135
  response.headers['X-Accel-Buffering'] = 'no' # Disable proxy buffering
200
136
 
201
- # Stream the content in chunks
202
- self.response_body = Enumerator.new do |yielder|
203
- # Fetch content in a streaming fashion from database
204
- SchemaVersion.connection.select_value(
205
- "SELECT content FROM #{SchemaVersion.table_name} WHERE id = #{version_id}"
206
- ).tap do |content|
207
- # Stream in 64KB chunks
208
- chunk_size = 64.kilobytes
209
- offset = 0
210
-
211
- while offset < content.bytesize
212
- yielder << content.byteslice(offset, chunk_size)
213
- offset += chunk_size
214
- end
137
+ self.response_body = content_chunks(version_id)
138
+ end
139
+
140
+ # Reads content from the database one slice at a time, so a large schema
141
+ # is never held in memory as a whole
142
+ def content_chunks(version_id)
143
+ Enumerator.new do |yielder|
144
+ position = 1
145
+ loop do
146
+ chunk = content_slice(version_id, position)
147
+ break if chunk.to_s.empty?
148
+
149
+ yielder << chunk
150
+ position += STREAM_CHUNK_CHARS
215
151
  end
216
152
  end
217
153
  end
154
+
155
+ def content_slice(version_id, position)
156
+ SchemaVersion.where(id: version_id)
157
+ .pick(Arel.sql("SUBSTR(content, #{position.to_i}, #{STREAM_CHUNK_CHARS.to_i})"))
158
+ end
218
159
  end
219
160
  end
@@ -6,40 +6,64 @@ module BetterStructureSql
6
6
  # Provides formatting methods for rendering schema version attributes
7
7
  # in the web UI, including badges and icons for output modes and format types.
8
8
  module SchemaVersionsHelper
9
+ # Badge label, colour class and icon class per output mode
10
+ OUTPUT_MODE_BADGES = {
11
+ 'multi_file' => %w[Multi-File text-bg-info bi-folder],
12
+ 'single_file' => ['Single File', 'text-bg-secondary', 'bi-file-earmark']
13
+ }.freeze
14
+
15
+ # Badge label, colour class and icon class per format type
16
+ FORMAT_TYPE_BADGES = {
17
+ 'sql' => %w[SQL text-bg-primary bi-filetype-sql],
18
+ 'rb' => %w[RB text-bg-success bi-filetype-rb]
19
+ }.freeze
20
+
9
21
  # Formats output mode as a Bootstrap badge with icon
10
22
  #
11
23
  # @param mode [String] the output mode ('multi_file' or 'single_file')
12
- # @return [String] HTML-safe badge element with icon
24
+ # @return [String] HTML-safe badge element
13
25
  def format_output_mode(mode)
14
- case mode
15
- when 'multi_file'
16
- content_tag(:span, class: 'badge bg-info') do
17
- concat content_tag(:i, '', class: 'bi bi-folder')
18
- concat ' Multi-File'
19
- end
20
- when 'single_file'
21
- content_tag(:span, class: 'badge bg-secondary') do
22
- concat content_tag(:i, '', class: 'bi bi-file-earmark')
23
- concat ' Single File'
24
- end
25
- else
26
- content_tag(:span, 'Unknown', class: 'badge bg-warning')
27
- end
26
+ schema_badge(OUTPUT_MODE_BADGES[mode])
28
27
  end
29
28
 
30
29
  # Formats format type as a Bootstrap badge with icon
31
30
  #
32
- # SQL format uses blue badge with SQL icon, Ruby format uses green
33
- # badge with Ruby icon.
34
- #
35
31
  # @param format_type [String] the format type ('sql' or 'rb')
36
- # @return [String] HTML-safe badge element with icon
32
+ # @return [String] HTML-safe badge element
37
33
  def format_type_badge(format_type)
38
- bg_class = format_type == 'sql' ? 'bg-primary' : 'bg-success'
39
- icon_class = format_type == 'sql' ? 'bi-filetype-sql' : 'bi-filetype-rb'
40
- content_tag(:span, class: "badge #{bg_class}") do
41
- concat content_tag(:i, '', class: "bi #{icon_class}")
42
- concat " #{format_type.upcase}"
34
+ schema_badge(FORMAT_TYPE_BADGES[format_type])
35
+ end
36
+
37
+ # Renders the creation time as a machine-readable <time> element
38
+ #
39
+ # @param version [SchemaVersion] the schema version
40
+ # @return [String] HTML-safe time element
41
+ def schema_version_timestamp(version)
42
+ time_tag(version.created_at, version.created_at.strftime('%Y-%m-%d %H:%M:%S %Z'))
43
+ end
44
+
45
+ # Renders one previous/next entry of the index pagination
46
+ #
47
+ # @param label [String] the link text
48
+ # @param page [Integer] the page the entry points to
49
+ # @param enabled [Boolean] false renders a disabled, non-link entry
50
+ # @return [String] HTML-safe list item
51
+ def pagination_item(label, page, enabled:)
52
+ return content_tag(:li, content_tag(:span, label, class: 'page-link'), class: 'page-item disabled') unless enabled
53
+
54
+ link = link_to(label, schema_versions_path(page:), class: 'page-link')
55
+ content_tag(:li, link, class: 'page-item')
56
+ end
57
+
58
+ private
59
+
60
+ # Stored values never reach the markup: unknown ones render as "Unknown"
61
+ def schema_badge(badge)
62
+ label, colour_class, icon_class = badge || %w[Unknown text-bg-warning bi-question-circle]
63
+
64
+ content_tag(:span, class: "badge #{colour_class}") do
65
+ concat content_tag(:i, '', class: "bi #{icon_class}", 'aria-hidden': true)
66
+ concat " #{label}"
43
67
  end
44
68
  end
45
69
  end