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
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,231 +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
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 single-file versions
51
- if @schema_version.output_mode == 'single_file' && @schema_version.content_size <= MAX_DISPLAY_SIZE
52
- @schema_version = SchemaVersion.find(params[:id]) # Load with content
53
- elsif @schema_version.output_mode == 'multi_file'
54
- # Load content to extract manifest
55
- full_version = SchemaVersion.select(:id, :content).find(params[:id])
56
- @manifest = extract_manifest_from_content(full_version.content)
57
- end
58
- rescue ActiveRecord::RecordNotFound
59
- render plain: 'Schema version not found', status: :not_found
55
+ @schema_version = SchemaVersion.select(*METADATA_COLUMNS, displayable_content_sql).find(params[:id])
60
56
  end
61
57
 
62
58
  # Downloads raw content of a schema version as plain text
63
59
  #
64
- # Streams large files (>2MB) in chunks to avoid memory issues.
65
- # Smaller files are sent directly using send_data.
66
- #
67
60
  # @return [void]
68
- # @raise [ActiveRecord::RecordNotFound] if schema version not found
69
61
  # GET /better_structure_sql/schema_versions/:id/raw
70
62
  def raw
71
- version = SchemaVersion.select(:id, :format_type, :content_size).find(params[:id])
72
-
73
- filename = "schema_version_#{version.id}_#{version.format_type}.txt"
74
-
75
- # For large files, stream from database to avoid loading into memory
76
- if version.content_size > MAX_MEMORY_SIZE
77
- stream_large_file(version.id, filename)
78
- else
79
- # For smaller files, use regular send_data
80
- content = SchemaVersion.find(version.id).content
81
- send_data content,
82
- filename: filename,
83
- type: 'text/plain',
84
- disposition: 'attachment'
85
- end
86
- rescue ActiveRecord::RecordNotFound
87
- 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")
88
65
  end
89
66
 
90
67
  # Downloads schema version in appropriate format
91
68
  #
92
69
  # Multi-file versions with ZIP archives are sent as .zip files.
93
- # 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.
94
71
  #
95
72
  # @return [void]
96
- # @raise [ActiveRecord::RecordNotFound] if schema version not found
97
73
  # GET /better_structure_sql/schema_versions/:id/download
98
74
  def download
99
- version = SchemaVersion.find(params[:id])
75
+ version = find_metadata
76
+ zip_archive = SchemaVersion.where(id: version.id).pick(:zip_archive) if version.multi_file?
100
77
 
101
- if version.multi_file? && version.zip_archive?
102
- send_zip_download(version)
78
+ if zip_archive.present?
79
+ send_zip_download(version, zip_archive)
103
80
  else
104
- send_file_download(version)
81
+ send_content(version, "structure.#{file_extension(version)}")
105
82
  end
106
- rescue ActiveRecord::RecordNotFound
107
- render plain: 'Schema version not found', status: :not_found
108
83
  end
109
84
 
110
85
  private
111
86
 
112
- # Sends ZIP archive download for multi-file schema versions
113
- #
114
- # Validates ZIP archive before sending to prevent corrupted downloads.
115
- # Filename includes version ID and timestamp.
116
- #
117
- # @param version [SchemaVersion] the schema version to download
118
- # @return [void]
119
- def send_zip_download(version)
120
- # Validate ZIP
121
- BetterStructureSql::ZipGenerator.validate_zip!(version.zip_archive)
122
-
123
- filename = "schema_version_#{version.id}_#{version.created_at.to_i}.zip"
87
+ def requested_page
88
+ Integer(params[:page].to_s, 10)
89
+ rescue ArgumentError
90
+ 1
91
+ end
124
92
 
125
- send_data version.zip_archive,
126
- filename: filename,
127
- type: 'application/zip',
128
- disposition: 'attachment'
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")
129
96
  end
130
97
 
131
- # Sends single-file schema version download
132
- #
133
- # Streams large files (>2MB) to avoid memory issues. Filename is
134
- # structure.sql or structure.rb based on format_type.
135
- #
136
- # @param version [SchemaVersion] the schema version to download
137
- # @return [void]
138
- def send_file_download(version)
139
- extension = version.format_type == 'rb' ? 'rb' : 'sql'
140
- filename = "structure.#{extension}"
98
+ def find_metadata
99
+ SchemaVersion.select(*METADATA_COLUMNS).find(params[:id])
100
+ end
141
101
 
142
- # Handle large files with streaming
143
- if version.content_size > MAX_MEMORY_SIZE
144
- stream_large_content(version, filename)
145
- else
146
- send_data version.content,
147
- filename: filename,
148
- type: 'text/plain',
149
- disposition: 'attachment'
150
- end
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'
151
106
  end
152
107
 
153
- # Streams large content in 64KB chunks to avoid memory issues
154
- #
155
- # Sets response headers for streaming and disables proxy buffering.
156
- # Fetches content from database and yields chunks via Enumerator.
157
- #
158
- # @param version [SchemaVersion] the schema version to stream
159
- # @param filename [String] the filename for Content-Disposition header
160
- # @return [void]
161
- def stream_large_content(version, filename)
162
- response.headers['Content-Type'] = 'text/plain'
163
- response.headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
164
- response.headers['X-Accel-Buffering'] = 'no'
165
-
166
- self.response_body = Enumerator.new do |yielder|
167
- content = SchemaVersion.connection.select_value(
168
- "SELECT content FROM #{SchemaVersion.table_name} WHERE id = #{version.id}"
169
- )
170
-
171
- chunk_size = 64.kilobytes
172
- offset = 0
173
- while offset < content.bytesize
174
- yielder << content.byteslice(offset, chunk_size)
175
- offset += chunk_size
176
- end
177
- 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
178
119
  end
179
120
 
180
- # Extracts embedded manifest JSON from multi-file schema content
181
- #
182
- # Manifest is stored between MANIFEST_JSON_START and MANIFEST_JSON_END markers
183
- # as SQL comments. Parses and returns the manifest hash.
184
- #
185
- # @param content [String] the schema content containing embedded manifest
186
- # @return [Hash, nil] parsed manifest hash or nil if not found/invalid
187
- def extract_manifest_from_content(content)
188
- # Manifest is embedded in content between MANIFEST_JSON_START and MANIFEST_JSON_END markers
189
- return nil unless content.include?('MANIFEST_JSON_START')
190
-
191
- # Extract JSON from between markers, removing comment prefixes
192
- start_marker = '-- MANIFEST_JSON_START'
193
- end_marker = '-- MANIFEST_JSON_END'
194
-
195
- start_pos = content.index(start_marker)
196
- end_pos = content.index(end_marker)
197
-
198
- return nil unless start_pos && end_pos
199
-
200
- manifest_section = content[(start_pos + start_marker.length)..(end_pos - 1)]
201
- manifest_json = manifest_section.lines
202
- .map { |line| line.sub(/^--\s?/, '') }
203
- .join
204
-
205
- JSON.parse(manifest_json)
206
- rescue JSON::ParserError => e
207
- Rails.logger.debug { "Failed to parse manifest: #{e.message}" }
208
- nil
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'
209
129
  end
210
130
 
211
- # Streams large file content from database in chunks
212
- #
213
- # Sets appropriate headers for streaming downloads and disables proxy buffering.
214
- # Fetches content from database and streams in 64KB chunks via Enumerator.
215
- #
216
- # @param version_id [Integer] the schema version ID
217
- # @param filename [String] the filename for Content-Disposition header
218
- # @return [void]
219
- def stream_large_file(version_id, filename)
220
- # Set headers for streaming
221
- response.headers['Content-Type'] = 'text/plain'
222
- response.headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
223
- 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:)
224
135
  response.headers['X-Accel-Buffering'] = 'no' # Disable proxy buffering
225
136
 
226
- # Stream the content in chunks
227
- self.response_body = Enumerator.new do |yielder|
228
- # Fetch content in a streaming fashion from database
229
- SchemaVersion.connection.select_value(
230
- "SELECT content FROM #{SchemaVersion.table_name} WHERE id = #{version_id}"
231
- ).tap do |content|
232
- # Stream in 64KB chunks
233
- chunk_size = 64.kilobytes
234
- offset = 0
235
-
236
- while offset < content.bytesize
237
- yielder << content.byteslice(offset, chunk_size)
238
- offset += chunk_size
239
- 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
240
151
  end
241
152
  end
242
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
243
159
  end
244
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