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
@@ -4,10 +4,26 @@ module BetterStructureSql
4
4
  module Adapters
5
5
  # MySQL adapter implementing introspection via information_schema and MySQL system tables.
6
6
  #
7
- # Provides MySQL-specific SQL generation with proper dialect support.
8
- # This adapter handles MySQL's unique features including stored procedures, triggers,
9
- # ENUM/SET types, and AUTO_INCREMENT sequences.
7
+ # Works with both the mysql2 and trilogy drivers (queries go through
8
+ # ActiveRecord's select_rows, never driver-specific result objects) and
9
+ # with MariaDB servers.
10
+ #
11
+ # Column defaults, CHECK constraint definitions and index definitions are
12
+ # returned as ready-to-use SQL fragments, matching the PostgreSQL adapter contract.
10
13
  class MysqlAdapter < BaseAdapter
14
+ # Numeric data types whose literal defaults are emitted unquoted
15
+ NUMERIC_TYPES = %w[tinyint smallint mediumint int integer bigint decimal numeric float double real year].freeze
16
+
17
+ # A relation in a canonical (SHOW CREATE VIEW) view definition: the identifier
18
+ # after FROM or [STRAIGHT_]JOIN, past any opening parentheses
19
+ VIEW_RELATION_REFERENCE = /(?<![\w`])(?:from|(?:straight_)?join)\s*(?:\(\s*)*`((?:[^`]|``)+)`/i
20
+
21
+ # Generation expression of a column line in SHOW CREATE TABLE output
22
+ GENERATED_EXPRESSION = /GENERATED ALWAYS AS \((.*)\) (?:VIRTUAL|STORED|PERSISTENT)\b/
23
+
24
+ # Defaults that MySQL accepts without the parentheses required around other expressions
25
+ TEMPORAL_DEFAULT = /\A(?:CURRENT_TIMESTAMP|NOW|LOCALTIME|LOCALTIMESTAMP)(?:\(\d*\))?\z/i
26
+
11
27
  # Introspection methods using information_schema
12
28
 
13
29
  # Fetch database extensions (not supported in MySQL)
@@ -15,7 +31,6 @@ module BetterStructureSql
15
31
  # @param _connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection (unused)
16
32
  # @return [Array] Empty array as MySQL doesn't support extensions like PostgreSQL
17
33
  def fetch_extensions(_connection)
18
- # MySQL doesn't support extensions like PostgreSQL
19
34
  []
20
35
  end
21
36
 
@@ -25,101 +40,77 @@ module BetterStructureSql
25
40
  # @return [Array] Empty array as MySQL doesn't support standalone custom types
26
41
  # @note MySQL has ENUM and SET types, but they are defined inline with columns, not as custom types
27
42
  def fetch_custom_types(_connection)
28
- # MySQL has limited support for custom types (ENUM and SET are inline)
29
- # Return empty array since ENUMs/SETs are defined per-column
30
43
  []
31
44
  end
32
45
 
33
46
  # Fetch all tables from the current database
34
47
  #
48
+ # Columns, primary keys and check constraints are fetched with one query each
49
+ # for the whole schema, avoiding N+1 queries on large schemas.
50
+ #
35
51
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
36
- # @return [Array<Hash>] Array of table hashes with :name, :schema, :columns, :primary_key, :constraints
52
+ # @return [Array<Hash>] Array of table hashes with :name, :schema, :engine, :collation,
53
+ # :columns, :primary_key, :constraints
37
54
  def fetch_tables(connection)
38
- # Performance optimized: Batches all table metadata queries to avoid N+1 queries
39
- # For 1000 tables: 4 queries instead of 3001 queries (~750x faster)
40
- query = <<~SQL.squish
41
- SELECT
42
- TABLE_NAME,
43
- TABLE_SCHEMA
55
+ table_rows = connection.select_rows(<<~SQL.squish)
56
+ SELECT TABLE_NAME, TABLE_SCHEMA, ENGINE, TABLE_COLLATION
44
57
  FROM information_schema.TABLES
45
58
  WHERE TABLE_SCHEMA = DATABASE()
46
59
  AND TABLE_TYPE = 'BASE TABLE'
47
60
  ORDER BY TABLE_NAME
48
61
  SQL
49
-
50
- table_rows = connection.execute(query).to_a
51
62
  return [] if table_rows.empty?
52
63
 
53
- table_names = table_rows.pluck(0)
64
+ columns_by_table = fetch_all_columns(connection)
65
+ primary_keys_by_table = fetch_all_primary_keys(connection)
66
+ constraints_by_table = fetch_all_constraints(connection)
54
67
 
55
- # Batch fetch all columns, primary keys, and constraints
56
- columns_by_table = fetch_all_columns(connection, table_names)
57
- primary_keys_by_table = fetch_all_primary_keys(connection, table_names)
58
- constraints_by_table = fetch_all_constraints(connection, table_names)
68
+ table_rows.map do |name, schema, engine, collation|
69
+ columns = with_generation_expressions(connection, name, columns_by_table[name])
70
+ json_columns = mariadb_json_columns(constraints_by_table[name])
59
71
 
60
- # Combine results
61
- table_rows.map do |row|
62
- table_name = row[0] # MySQL returns arrays not hashes by default
63
72
  {
64
- name: table_name,
65
- schema: row[1],
66
- columns: columns_by_table[table_name] || [],
67
- primary_key: primary_keys_by_table[table_name] || [],
68
- constraints: constraints_by_table[table_name] || []
73
+ name:,
74
+ schema:,
75
+ engine:,
76
+ collation:,
77
+ columns: columns.map { |column| json_columns.include?(column[:name]) ? as_json_column(column) : column },
78
+ primary_key: primary_keys_by_table[name],
79
+ constraints: constraints_by_table[name].reject { |constraint| json_columns.include?(constraint[:name]) }
69
80
  }
70
81
  end
71
82
  end
72
83
 
73
- # Fetch all indexes from the current database
84
+ # Fetch all secondary indexes from the current database
85
+ #
86
+ # Each index carries a complete CREATE INDEX :definition covering prefix
87
+ # lengths, descending key parts, functional key parts (MySQL 8.0.13+),
88
+ # FULLTEXT/SPATIAL indexes and invisible indexes.
74
89
  #
75
90
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
76
- # @return [Array<Hash>] Array of index hashes with :table, :name, :columns, :unique, :type
91
+ # @return [Array<Hash>] Array of index hashes with :table, :name, :columns, :unique, :type, :definition
77
92
  def fetch_indexes(connection)
78
- query = <<~SQL.squish
79
- SELECT
80
- TABLE_NAME,
81
- INDEX_NAME,
82
- COLUMN_NAME,
83
- SEQ_IN_INDEX,
84
- NON_UNIQUE,
85
- INDEX_TYPE
93
+ rows = connection.select_rows(<<~SQL.squish)
94
+ SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE, INDEX_TYPE, SUB_PART, COLLATION,
95
+ #{index_expression_columns}
86
96
  FROM information_schema.STATISTICS
87
97
  WHERE TABLE_SCHEMA = DATABASE()
88
98
  AND INDEX_NAME != 'PRIMARY'
89
99
  ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
90
100
  SQL
91
101
 
92
- # Group by table and index name to build multi-column indexes
93
- indexes_by_key = {}
94
-
95
- connection.execute(query).each do |row|
96
- table_name = row[0]
97
- index_name = row[1]
98
- column_name = row[2]
99
- # seq_in_index = row[3] # Used for ordering, handled by ORDER BY in query
100
- non_unique = row[4]
101
- index_type = row[5]
102
-
103
- key = "#{table_name}.#{index_name}"
104
- indexes_by_key[key] ||= {
105
- table: table_name,
106
- name: index_name,
107
- columns: [],
108
- unique: non_unique.to_i.zero?,
109
- type: index_type
110
- }
111
- indexes_by_key[key][:columns] << column_name
112
- end
113
-
114
- indexes_by_key.values
102
+ rows.group_by { |row| row[0..1] }.map { |(table, name), parts| build_index(table, name, parts) }
115
103
  end
116
104
 
117
105
  # Fetch all foreign keys from the current database
118
106
  #
107
+ # Composite foreign keys are returned as one entry whose :columns and
108
+ # :foreign_columns list the columns in key order.
109
+ #
119
110
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
120
- # @return [Array<Hash>] Array of foreign key hashes with :table, :name, :column, :foreign_table, :foreign_column, :on_update, :on_delete
111
+ # @return [Array<Hash>] Array of foreign key hashes with :table, :name, :columns, :foreign_table, :foreign_columns, :on_update, :on_delete
121
112
  def fetch_foreign_keys(connection)
122
- query = <<~SQL.squish
113
+ rows = connection.select_rows(<<~SQL.squish)
123
114
  SELECT
124
115
  kcu.TABLE_NAME,
125
116
  kcu.CONSTRAINT_NAME,
@@ -130,51 +121,43 @@ module BetterStructureSql
130
121
  rc.DELETE_RULE
131
122
  FROM information_schema.KEY_COLUMN_USAGE kcu
132
123
  JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
133
- ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
134
- AND kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
124
+ ON rc.CONSTRAINT_SCHEMA = kcu.TABLE_SCHEMA
125
+ AND rc.TABLE_NAME = kcu.TABLE_NAME
126
+ AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
135
127
  WHERE kcu.TABLE_SCHEMA = DATABASE()
136
128
  AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
137
- ORDER BY kcu.TABLE_NAME, kcu.CONSTRAINT_NAME
129
+ ORDER BY kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION
138
130
  SQL
139
131
 
140
- connection.execute(query).map do |row|
141
- {
142
- table: row[0],
143
- name: row[1],
144
- column: row[2],
145
- foreign_table: row[3],
146
- foreign_column: row[4],
147
- on_update: row[5],
148
- on_delete: row[6]
149
- }
150
- end
132
+ rows.group_by { |row| row[0..1] }.map { |(table, name), key_rows| build_foreign_key(table, name, key_rows) }
151
133
  end
152
134
 
153
- # Fetch all views from the current database
135
+ # Fetch all views from the current database, ordered so a view follows the views it reads
136
+ #
137
+ # The definition comes from SHOW CREATE VIEW, which (unlike
138
+ # information_schema.VIEWS) does not qualify objects of the current
139
+ # database with its name, so the dump loads into any database.
154
140
  #
155
141
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
156
142
  # @return [Array<Hash>] Array of view hashes with :schema, :name, :definition, :check_option, :updatable
157
143
  def fetch_views(connection)
158
- query = <<~SQL.squish
159
- SELECT
160
- TABLE_NAME,
161
- VIEW_DEFINITION,
162
- CHECK_OPTION,
163
- IS_UPDATABLE
144
+ rows = connection.select_rows(<<~SQL.squish)
145
+ SELECT TABLE_NAME, CHECK_OPTION, IS_UPDATABLE
164
146
  FROM information_schema.VIEWS
165
147
  WHERE TABLE_SCHEMA = DATABASE()
166
148
  ORDER BY TABLE_NAME
167
149
  SQL
168
150
 
169
- connection.execute(query).map do |row|
151
+ views = rows.map do |name, check_option, updatable|
170
152
  {
171
153
  schema: 'public', # MySQL doesn't use schemas like PostgreSQL
172
- name: row[0],
173
- definition: row[1],
174
- check_option: row[2],
175
- updatable: row[3] == 'YES'
154
+ name:,
155
+ definition: view_select(connection, name),
156
+ check_option:,
157
+ updatable: updatable == 'YES'
176
158
  }
177
159
  end
160
+ order_by_dependencies(views, view_dependencies(connection, views))
178
161
  end
179
162
 
180
163
  # Fetch materialized views (not supported in MySQL)
@@ -182,7 +165,6 @@ module BetterStructureSql
182
165
  # @param _connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection (unused)
183
166
  # @return [Array] Empty array as MySQL doesn't support materialized views
184
167
  def fetch_materialized_views(_connection)
185
- # MySQL doesn't support materialized views
186
168
  []
187
169
  end
188
170
 
@@ -191,35 +173,19 @@ module BetterStructureSql
191
173
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
192
174
  # @return [Array<Hash>] Array of routine hashes with :schema, :name, :definition
193
175
  def fetch_functions(connection)
194
- query = <<~SQL.squish
195
- SELECT
196
- ROUTINE_NAME,
197
- ROUTINE_TYPE
176
+ rows = connection.select_rows(<<~SQL.squish)
177
+ SELECT ROUTINE_NAME, ROUTINE_TYPE
198
178
  FROM information_schema.ROUTINES
199
179
  WHERE ROUTINE_SCHEMA = DATABASE()
200
180
  AND ROUTINE_TYPE IN ('PROCEDURE', 'FUNCTION')
201
181
  ORDER BY ROUTINE_NAME
202
182
  SQL
203
183
 
204
- connection.execute(query).map do |row|
205
- routine_name = row[0]
206
- routine_type = row[1]
207
-
208
- # Get complete CREATE statement using SHOW CREATE
209
- create_query = if routine_type == 'PROCEDURE'
210
- "SHOW CREATE PROCEDURE `#{routine_name}`"
211
- else
212
- "SHOW CREATE FUNCTION `#{routine_name}`"
213
- end
214
-
215
- create_result = connection.execute(create_query).first
216
- # SHOW CREATE returns: [procedure_name, sql_mode, create_statement, ...]
217
- create_statement = create_result[2] if create_result
218
-
184
+ rows.map do |name, type|
219
185
  {
220
186
  schema: 'public',
221
- name: routine_name,
222
- definition: create_statement
187
+ name:,
188
+ definition: show_create(connection, "SHOW CREATE #{type} #{quote_identifier(name)}", 2)
223
189
  }
224
190
  end
225
191
  end
@@ -229,40 +195,31 @@ module BetterStructureSql
229
195
  # @param _connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection (unused)
230
196
  # @return [Array] Empty array as MySQL doesn't support sequences (uses AUTO_INCREMENT instead)
231
197
  def fetch_sequences(_connection)
232
- # MySQL doesn't have sequences (uses AUTO_INCREMENT)
233
198
  []
234
199
  end
235
200
 
236
201
  # Fetch all triggers from the current database
237
202
  #
203
+ # Triggers sharing a table, timing and event are returned in firing order
204
+ # (ACTION_ORDER) so that re-creating them in dump order keeps that order.
205
+ #
238
206
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
239
207
  # @return [Array<Hash>] Array of trigger hashes with :table, :name, :event, :timing, :definition
240
208
  def fetch_triggers(connection)
241
- query = <<~SQL.squish
242
- SELECT
243
- TRIGGER_NAME,
244
- EVENT_MANIPULATION,
245
- EVENT_OBJECT_TABLE,
246
- ACTION_TIMING
209
+ rows = connection.select_rows(<<~SQL.squish)
210
+ SELECT TRIGGER_NAME, EVENT_MANIPULATION, EVENT_OBJECT_TABLE, ACTION_TIMING
247
211
  FROM information_schema.TRIGGERS
248
212
  WHERE TRIGGER_SCHEMA = DATABASE()
249
- ORDER BY EVENT_OBJECT_TABLE, TRIGGER_NAME
213
+ ORDER BY EVENT_OBJECT_TABLE, ACTION_TIMING, EVENT_MANIPULATION, ACTION_ORDER
250
214
  SQL
251
215
 
252
- connection.execute(query).map do |row|
253
- trigger_name = row[0]
254
-
255
- # Get complete CREATE statement using SHOW CREATE
256
- create_result = connection.execute("SHOW CREATE TRIGGER `#{trigger_name}`").first
257
- # SHOW CREATE TRIGGER returns: [trigger_name, sql_mode, create_statement, ...]
258
- create_statement = create_result[2] if create_result
259
-
216
+ rows.map do |name, event, table, timing|
260
217
  {
261
- table: row[2],
262
- name: trigger_name,
263
- event: row[1], # INSERT, UPDATE, DELETE
264
- timing: row[3], # BEFORE, AFTER
265
- definition: create_statement
218
+ table:,
219
+ name:,
220
+ event:,
221
+ timing:,
222
+ definition: show_create(connection, "SHOW CREATE TRIGGER #{quote_identifier(name)}", 2)
266
223
  }
267
224
  end
268
225
  end
@@ -277,7 +234,8 @@ module BetterStructureSql
277
234
  columns: fetch_column_comments(connection),
278
235
  indexes: {}, # MySQL doesn't support index comments via information_schema
279
236
  views: {}, # MySQL doesn't expose view comments via information_schema
280
- functions: {} # MySQL doesn't expose function comments via information_schema
237
+ functions: {}, # MySQL doesn't expose function comments via information_schema
238
+ procedures: {}
281
239
  }
282
240
  end
283
241
 
@@ -301,7 +259,7 @@ module BetterStructureSql
301
259
  #
302
260
  # @return [Boolean] Always false (ENUM/SET are inline with columns, not custom types)
303
261
  def supports_custom_types?
304
- false # ENUM/SET are inline with columns, not custom types
262
+ false
305
263
  end
306
264
 
307
265
  # Indicates whether MySQL supports domains
@@ -315,7 +273,7 @@ module BetterStructureSql
315
273
  #
316
274
  # @return [Boolean] Always true for MySQL
317
275
  def supports_functions?
318
- true # Stored procedures and functions
276
+ true
319
277
  end
320
278
 
321
279
  # Indicates whether MySQL supports triggers
@@ -329,21 +287,28 @@ module BetterStructureSql
329
287
  #
330
288
  # @return [Boolean] Always false (uses AUTO_INCREMENT instead)
331
289
  def supports_sequences?
332
- false # Uses AUTO_INCREMENT instead
290
+ false
333
291
  end
334
292
 
335
293
  # Indicates whether MySQL supports check constraints
336
294
  #
337
- # @return [Boolean] True for MySQL 8.0.16+, false for earlier versions
295
+ # @return [Boolean] True for MySQL 8.0.16+ and MariaDB 10.2+
338
296
  def supports_check_constraints?
339
- version_at_least?(database_version, '8.0.16')
297
+ version_at_least?(database_version, mariadb? ? '10.2' : '8.0.16')
340
298
  end
341
299
 
342
300
  # Indicates whether MySQL supports comments on database objects
343
301
  #
344
302
  # @return [Boolean] Always true for MySQL (tables and columns only)
345
303
  def supports_comments?
346
- true # MySQL supports table and column comments
304
+ true
305
+ end
306
+
307
+ # Indicates whether the server is MariaDB rather than Oracle MySQL
308
+ #
309
+ # @return [Boolean] True when VERSION() reports a MariaDB server
310
+ def mariadb?
311
+ server_version.include?('MariaDB')
347
312
  end
348
313
 
349
314
  # Version detection
@@ -352,10 +317,7 @@ module BetterStructureSql
352
317
  #
353
318
  # @return [String] Normalized version string (e.g., "8.0.35")
354
319
  def database_version
355
- @database_version ||= begin
356
- version_string = connection.select_value('SELECT VERSION()')
357
- parse_version(version_string)
358
- end
320
+ @database_version ||= parse_version(server_version)
359
321
  end
360
322
 
361
323
  # Parse MySQL version string into normalized format
@@ -363,8 +325,6 @@ module BetterStructureSql
363
325
  # @param version_string [String] Raw version string from MySQL (e.g., "8.0.35" or "5.7.44-log")
364
326
  # @return [String] Normalized version (e.g., "8.0.35") or "unknown" if parsing fails
365
327
  def parse_version(version_string)
366
- # Example: "8.0.35" or "5.7.44-log"
367
- # Extract major.minor.patch version
368
328
  match = version_string.match(/(\d+\.\d+\.\d+)/)
369
329
  return 'unknown' unless match
370
330
 
@@ -373,256 +333,339 @@ module BetterStructureSql
373
333
 
374
334
  private
375
335
 
376
- # Helper methods for introspection
336
+ # Raw VERSION() string, e.g. "8.0.35" or "11.4.2-MariaDB-ubu2404"
337
+ #
338
+ # @return [String]
339
+ def server_version
340
+ @server_version ||= connection.select_value('SELECT VERSION()')
341
+ end
377
342
 
378
- # Fetch columns for a specific table
343
+ # Batch fetch all columns of the current database
379
344
  #
380
345
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
381
- # @param table_name [String] Name of the table
382
- # @return [Array<Hash>] Array of column hashes with :name, :type, :nullable, :default, etc.
383
- def fetch_columns(connection, table_name)
384
- query = <<~SQL.squish
346
+ # @return [Hash<String, Array<Hash>>] Hash of table_name => array of column hashes
347
+ def fetch_all_columns(connection)
348
+ rows = connection.select_all(<<~SQL.squish)
385
349
  SELECT
386
- COLUMN_NAME,
387
- DATA_TYPE,
388
- IS_NULLABLE,
389
- COLUMN_DEFAULT,
390
- CHARACTER_MAXIMUM_LENGTH,
391
- NUMERIC_PRECISION,
392
- NUMERIC_SCALE,
393
- COLUMN_TYPE,
394
- EXTRA
350
+ TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, EXTRA,
351
+ CHARACTER_SET_NAME, COLLATION_NAME,
352
+ CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE
395
353
  FROM information_schema.COLUMNS
396
- WHERE TABLE_NAME = #{connection.quote(table_name)}
397
- AND TABLE_SCHEMA = DATABASE()
398
- ORDER BY ORDINAL_POSITION
354
+ WHERE TABLE_SCHEMA = DATABASE()
355
+ ORDER BY TABLE_NAME, ORDINAL_POSITION
399
356
  SQL
400
357
 
401
- connection.execute(query).map do |row|
402
- {
403
- name: row[0],
404
- type: resolve_column_type(row),
405
- nullable: row[2] == 'YES',
406
- default: row[3],
407
- length: row[4],
408
- precision: row[5],
409
- scale: row[6],
410
- column_type: row[7], # Full type with ENUM values, etc.
411
- extra: row[8] # AUTO_INCREMENT, etc.
412
- }
358
+ rows.each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |row, result|
359
+ result[row['TABLE_NAME']] << build_column(row)
413
360
  end
414
361
  end
415
362
 
416
- # Fetch primary key columns for a specific table
363
+ # Build a column hash from an information_schema.COLUMNS row
417
364
  #
418
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
419
- # @param table_name [String] Name of the table
420
- # @return [Array<String>] Array of primary key column names
421
- def fetch_primary_key(connection, table_name)
422
- query = <<~SQL.squish
423
- SELECT COLUMN_NAME
424
- FROM information_schema.KEY_COLUMN_USAGE
425
- WHERE TABLE_NAME = #{connection.quote(table_name)}
426
- AND TABLE_SCHEMA = DATABASE()
427
- AND CONSTRAINT_NAME = 'PRIMARY'
428
- ORDER BY ORDINAL_POSITION
429
- SQL
365
+ # @param row [Hash] information_schema.COLUMNS row keyed by column name
366
+ # @return [Hash] Column hash; :type is the full COLUMN_TYPE (e.g. "int unsigned",
367
+ # "datetime(6)", "enum('a','b')") and :default is a SQL fragment
368
+ def build_column(row)
369
+ extra = row['EXTRA']
370
+ {
371
+ name: row['COLUMN_NAME'],
372
+ type: row['COLUMN_TYPE'],
373
+ data_type: row['DATA_TYPE'],
374
+ nullable: row['IS_NULLABLE'] == 'YES',
375
+ default: column_default_sql(row['DATA_TYPE'], row['COLUMN_DEFAULT'], extra),
376
+ length: row['CHARACTER_MAXIMUM_LENGTH'],
377
+ precision: row['NUMERIC_PRECISION'],
378
+ scale: row['NUMERIC_SCALE'],
379
+ column_type: row['COLUMN_TYPE'],
380
+ extra:,
381
+ auto_increment: extra.include?('auto_increment'),
382
+ on_update: extra[/on update (.+)\z/i, 1],
383
+ generated: generated_column(extra),
384
+ charset: row['CHARACTER_SET_NAME'],
385
+ collation: row['COLLATION_NAME']
386
+ }
387
+ end
388
+
389
+ # Convert COLUMN_DEFAULT into the SQL that recreates it
390
+ #
391
+ # MySQL stores literal defaults unquoted and flags expression defaults
392
+ # with DEFAULT_GENERATED; MariaDB already stores SQL (quoted literals,
393
+ # bare expressions, and the string 'NULL' for no default).
394
+ #
395
+ # @return [String, nil] SQL default fragment or nil when the column has no default
396
+ def column_default_sql(data_type, default, extra)
397
+ return mariadb_default(default) if mariadb?
398
+ return nil if default.nil?
399
+ return expression_default(unescape_expression(default)) if extra.include?('DEFAULT_GENERATED')
400
+ return default if data_type == 'bit' || NUMERIC_TYPES.include?(data_type)
401
+
402
+ quote_string(default)
403
+ end
430
404
 
431
- connection.execute(query).pluck(0)
405
+ # @return [String, nil] MariaDB default (already SQL) or nil for NULL
406
+ def mariadb_default(default)
407
+ default unless default.nil? || default == 'NULL'
432
408
  end
433
409
 
434
- # Fetch check constraints for a specific table (MySQL 8.0.16+)
410
+ # Wrap expression defaults in parentheses, as MySQL 8.0.13+ requires
435
411
  #
436
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
437
- # @param table_name [String] Name of the table
438
- # @return [Array<Hash>] Array of constraint hashes with :name, :definition, :type
439
- def fetch_constraints(connection, table_name)
440
- # MySQL 8.0.16+ supports check constraints
441
- return [] unless supports_check_constraints?
412
+ # @return [String] SQL default fragment
413
+ def expression_default(expression)
414
+ TEMPORAL_DEFAULT.match?(expression) ? expression : "(#{expression})"
415
+ end
442
416
 
443
- query = <<~SQL.squish
444
- SELECT
445
- CONSTRAINT_NAME,
446
- CHECK_CLAUSE
447
- FROM information_schema.CHECK_CONSTRAINTS
448
- WHERE CONSTRAINT_SCHEMA = DATABASE()
449
- AND TABLE_NAME = #{connection.quote(table_name)}
450
- ORDER BY CONSTRAINT_NAME
451
- SQL
417
+ # @return [Hash, nil] { kind: } for generated columns, kind being "STORED" or
418
+ # "VIRTUAL" (MariaDB's PERSISTENT is its alias for STORED); the expression
419
+ # is added by #with_generation_expressions
420
+ def generated_column(extra)
421
+ storage = extra[/\b(VIRTUAL|STORED|PERSISTENT) GENERATED\b/i, 1]
422
+ return nil unless storage
452
423
 
453
- connection.execute(query).map do |row|
454
- {
455
- name: row[0],
456
- definition: row[1],
457
- type: :check
458
- }
459
- end
460
- rescue StandardError
461
- # If CHECK_CONSTRAINTS table doesn't exist (MySQL < 8.0.16), return empty
462
- []
424
+ { kind: storage.casecmp?('VIRTUAL') ? 'VIRTUAL' : 'STORED' }
463
425
  end
464
426
 
465
- # Batch fetch all columns for multiple tables (performance optimization)
427
+ # Add generation expressions to a table's generated columns
466
428
  #
467
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
468
- # @param table_names [Array<String>] Array of table names
469
- # @return [Hash<String, Array<Hash>>] Hash of table_name => array of column hashes
470
- def fetch_all_columns(connection, table_names)
471
- return {} if table_names.empty?
429
+ # information_schema.COLUMNS.GENERATION_EXPRESSION keeps the expression as
430
+ # the creating session printed it (its charset introducers, no implicit
431
+ # CONVERT), which MySQL canonicalizes differently once the dump is loaded.
432
+ # SHOW CREATE TABLE prints the canonical form, keeping dump/load/dump stable.
433
+ #
434
+ # @return [Array<Hash>] The columns, generated ones carrying :expression
435
+ def with_generation_expressions(connection, table, columns)
436
+ return columns if columns.none? { |column| column[:generated] }
472
437
 
473
- # Build IN clause with quoted table names
474
- quoted_names = table_names.map { |t| connection.quote(t) }.join(', ')
438
+ create_table = show_create(connection, "SHOW CREATE TABLE #{quote_identifier(table)}", 1)
439
+ columns.each do |column|
440
+ next unless column[:generated]
475
441
 
476
- query = <<~SQL.squish
477
- SELECT
478
- TABLE_NAME,
479
- COLUMN_NAME,
480
- DATA_TYPE,
481
- IS_NULLABLE,
482
- COLUMN_DEFAULT,
483
- CHARACTER_MAXIMUM_LENGTH,
484
- NUMERIC_PRECISION,
485
- NUMERIC_SCALE,
486
- COLUMN_TYPE,
487
- EXTRA,
488
- ORDINAL_POSITION
489
- FROM information_schema.COLUMNS
490
- WHERE TABLE_NAME IN (#{quoted_names})
491
- AND TABLE_SCHEMA = DATABASE()
442
+ line = create_table.lines.find { |text| text.start_with?(" #{quote_identifier(column[:name])} ") }
443
+ column[:generated][:expression] = line&.[](GENERATED_EXPRESSION, 1)
444
+ raise Error, "Unable to find expression of generated column #{table}.#{column[:name]}" unless column[:generated][:expression]
445
+ end
446
+ end
447
+
448
+ # Batch fetch all primary keys of the current database
449
+ #
450
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
451
+ # @return [Hash<String, Array<String>>] Hash of table_name => primary key column names in key order
452
+ def fetch_all_primary_keys(connection)
453
+ rows = connection.select_rows(<<~SQL.squish)
454
+ SELECT TABLE_NAME, COLUMN_NAME
455
+ FROM information_schema.KEY_COLUMN_USAGE
456
+ WHERE TABLE_SCHEMA = DATABASE()
457
+ AND CONSTRAINT_NAME = 'PRIMARY'
492
458
  ORDER BY TABLE_NAME, ORDINAL_POSITION
493
459
  SQL
494
460
 
495
- result = Hash.new { |h, k| h[k] = [] }
496
-
497
- connection.execute(query).each do |row|
498
- # Build row array compatible with resolve_column_type expectations
499
- # resolve_column_type expects: [nil, DATA_TYPE, nil, nil, LENGTH, PRECISION, SCALE, COLUMN_TYPE]
500
- column_row = [nil, row[2], nil, nil, row[5], row[6], row[7], row[8]]
501
-
502
- result[row[0]] << {
503
- name: row[1],
504
- type: resolve_column_type(column_row),
505
- nullable: row[3] == 'YES',
506
- default: row[4],
507
- length: row[5],
508
- precision: row[6],
509
- scale: row[7],
510
- column_type: row[8],
511
- extra: row[9]
512
- }
461
+ rows.each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |(table, column), result|
462
+ result[table] << column
513
463
  end
464
+ end
514
465
 
466
+ # Batch fetch all CHECK constraints of the current database
467
+ #
468
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
469
+ # @return [Hash<String, Array<Hash>>] Hash of table_name => constraint hashes whose
470
+ # :definition is a complete "CHECK (...)" clause
471
+ def fetch_all_constraints(connection)
472
+ result = Hash.new { |hash, key| hash[key] = [] }
473
+ return result unless supports_check_constraints?
474
+
475
+ connection.select_rows(check_constraints_query).each do |table, name, clause, enforced|
476
+ definition = "CHECK (#{unescape_expression(clause)})"
477
+ definition += ' NOT ENFORCED' if enforced == 'NO'
478
+ result[table] << { name:, definition:, type: :check }
479
+ end
515
480
  result
516
481
  end
517
482
 
518
- # Batch fetch all primary keys for multiple tables (performance optimization)
483
+ # MariaDB implements JSON as LONGTEXT plus a column-level CHECK
484
+ # (json_valid(`col`)) named after the column; such columns are dumped as
485
+ # JSON so loading recreates exactly that, not a table-level constraint.
519
486
  #
520
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
521
- # @param table_names [Array<String>] Array of table names
522
- # @return [Hash<String, Array<String>>] Hash of table_name => array of primary key column names
523
- def fetch_all_primary_keys(connection, table_names)
524
- return {} if table_names.empty?
487
+ # @param constraints [Array<Hash>] A table's CHECK constraints
488
+ # @return [Array<String>] Names of the table's JSON columns
489
+ def mariadb_json_columns(constraints)
490
+ return [] unless mariadb?
525
491
 
526
- quoted_names = table_names.map { |t| connection.quote(t) }.join(', ')
492
+ constraints.select { |constraint| constraint[:definition] == "CHECK (json_valid(`#{constraint[:name]}`))" }
493
+ .pluck(:name)
494
+ end
527
495
 
528
- query = <<~SQL.squish
529
- SELECT TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION
530
- FROM information_schema.KEY_COLUMN_USAGE
531
- WHERE TABLE_NAME IN (#{quoted_names})
532
- AND TABLE_SCHEMA = DATABASE()
533
- AND CONSTRAINT_NAME = 'PRIMARY'
534
- ORDER BY TABLE_NAME, ORDINAL_POSITION
535
- SQL
496
+ # @return [Hash] Column hash declared as JSON (charset and collation are implied)
497
+ def as_json_column(column)
498
+ column.merge(type: 'json', charset: nil, collation: nil)
499
+ end
536
500
 
537
- result = Hash.new { |h, k| h[k] = [] }
501
+ # MySQL keys CHECK constraints by schema (TABLE_NAME lives in TABLE_CONSTRAINTS);
502
+ # MariaDB keys them by table and has no ENFORCED column.
503
+ #
504
+ # @return [String] SQL query returning table, name, clause, enforced
505
+ def check_constraints_query
506
+ if mariadb?
507
+ <<~SQL.squish
508
+ SELECT TABLE_NAME, CONSTRAINT_NAME, CHECK_CLAUSE, 'YES'
509
+ FROM information_schema.CHECK_CONSTRAINTS
510
+ WHERE CONSTRAINT_SCHEMA = DATABASE()
511
+ ORDER BY TABLE_NAME, CONSTRAINT_NAME
512
+ SQL
513
+ else
514
+ <<~SQL.squish
515
+ SELECT tc.TABLE_NAME, cc.CONSTRAINT_NAME, cc.CHECK_CLAUSE, tc.ENFORCED
516
+ FROM information_schema.TABLE_CONSTRAINTS tc
517
+ JOIN information_schema.CHECK_CONSTRAINTS cc
518
+ ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
519
+ AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
520
+ WHERE tc.TABLE_SCHEMA = DATABASE()
521
+ AND tc.CONSTRAINT_TYPE = 'CHECK'
522
+ ORDER BY tc.TABLE_NAME, cc.CONSTRAINT_NAME
523
+ SQL
524
+ end
525
+ end
538
526
 
539
- connection.execute(query).each do |row|
540
- result[row[0]] << row[1]
527
+ # STATISTICS.EXPRESSION and IS_VISIBLE exist only on MySQL 8.0.13+
528
+ #
529
+ # @return [String] SELECT list fragment yielding expression and visibility
530
+ def index_expression_columns
531
+ if !mariadb? && version_at_least?(database_version, '8.0.13')
532
+ 'EXPRESSION, IS_VISIBLE'
533
+ else
534
+ "NULL AS EXPRESSION, 'YES' AS IS_VISIBLE"
541
535
  end
536
+ end
542
537
 
543
- result
538
+ # Build an index hash from its STATISTICS rows (one per key part)
539
+ #
540
+ # @return [Hash] Index hash with complete :definition
541
+ def build_index(table, name, parts)
542
+ _table, _name, _column, non_unique, index_type, = parts.first
543
+ unique = non_unique.to_i.zero?
544
+ key_parts = parts.map { |part| index_key_part(*part.values_at(2, 5, 6, 7)) }
545
+ visibility = parts.first[8] == 'NO' ? ' INVISIBLE' : ''
546
+
547
+ {
548
+ table:,
549
+ name:,
550
+ columns: parts.filter_map { |part| part[2] },
551
+ unique:,
552
+ type: index_type,
553
+ definition: "CREATE #{index_kind(index_type, unique)}INDEX #{quote_identifier(name)} " \
554
+ "ON #{quote_identifier(table)} (#{key_parts.join(', ')})#{visibility}"
555
+ }
544
556
  end
545
557
 
546
- # Batch fetch all constraints for multiple tables (performance optimization)
558
+ # @return [String] One key part: `col`, `col`(10), (expression), optionally DESC
559
+ def index_key_part(column, sub_part, collation, expression)
560
+ part = expression ? "(#{unescape_expression(expression)})" : quote_identifier(column)
561
+ part += "(#{sub_part})" if sub_part
562
+ part += ' DESC' if collation == 'D'
563
+ part
564
+ end
565
+
566
+ # @return [String] Index modifier keyword ("UNIQUE ", "FULLTEXT ", "SPATIAL " or "")
567
+ def index_kind(index_type, unique)
568
+ return "#{index_type} " if %w[FULLTEXT SPATIAL].include?(index_type)
569
+
570
+ unique ? 'UNIQUE ' : ''
571
+ end
572
+
573
+ # Build a foreign key hash from its KEY_COLUMN_USAGE rows (one per column)
547
574
  #
548
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
549
- # @param table_names [Array<String>] Array of table names
550
- # @return [Hash<String, Array<Hash>>] Hash of table_name => array of constraint hashes
551
- def fetch_all_constraints(connection, table_names)
552
- return {} if table_names.empty?
553
- return {} unless supports_check_constraints? # MySQL < 8.0.16
575
+ # @return [Hash] Foreign key hash
576
+ def build_foreign_key(table, name, key_rows)
577
+ _table, _name, _column, foreign_table, _foreign_column, on_update, on_delete = key_rows.first
554
578
 
555
- quoted_names = table_names.map { |t| connection.quote(t) }.join(', ')
579
+ {
580
+ table:,
581
+ name:,
582
+ columns: key_rows.pluck(2),
583
+ foreign_table:,
584
+ foreign_columns: key_rows.pluck(4),
585
+ on_update:,
586
+ on_delete:
587
+ }
588
+ end
556
589
 
557
- query = <<~SQL.squish
558
- SELECT
559
- TABLE_NAME,
560
- CONSTRAINT_NAME,
561
- CHECK_CLAUSE
562
- FROM information_schema.CHECK_CONSTRAINTS
563
- WHERE CONSTRAINT_SCHEMA = DATABASE()
564
- AND TABLE_NAME IN (#{quoted_names})
565
- ORDER BY TABLE_NAME, CONSTRAINT_NAME
590
+ # Extract the SELECT statement (plus any WITH CHECK OPTION) from SHOW CREATE VIEW
591
+ #
592
+ # @return [String] View query
593
+ # @raise [Error] If the statement cannot be parsed
594
+ def view_select(connection, name)
595
+ create_statement = show_create(connection, "SHOW CREATE VIEW #{quote_identifier(name)}", 1)
596
+ select = create_statement[/\sVIEW\s+`(?:[^`]|``)+`\s+AS\s+(.*)\z/m, 1]
597
+ raise Error, "Unable to parse definition of view #{name}: #{create_statement}" unless select
598
+
599
+ select
600
+ end
601
+
602
+ # Which views of the current database each view reads
603
+ #
604
+ # information_schema.VIEW_TABLE_USAGE exists on MySQL 8.0.13+ only. On
605
+ # MariaDB and older MySQL the view's own definition is scanned instead:
606
+ # SHOW CREATE VIEW backtick-quotes every identifier and writes every
607
+ # relation right after FROM or JOIN (comma joins become JOIN), so only
608
+ # those count. A column alias, table alias or qualifier named like
609
+ # another view is not a reference: as an edge it could close a cycle
610
+ # and put a view before the view it reads.
611
+ #
612
+ # @param views [Array<Hash>] Views with :name and :definition
613
+ # @return [Hash<String, Array<String>>] View name => names of views it reads
614
+ def view_dependencies(connection, views)
615
+ return view_table_usage(connection) if !mariadb? && version_at_least?(database_version, '8.0.13')
616
+
617
+ names = views.to_set { |view| view[:name] }
618
+ views.to_h do |view|
619
+ referenced = view[:definition].scan(VIEW_RELATION_REFERENCE).flatten.map { |name| name.gsub('``', '`') }
620
+ [view[:name], referenced.select { |name| names.include?(name) }.uniq - [view[:name]]]
621
+ end
622
+ end
623
+
624
+ # @return [Hash<String, Array<String>>] View name => names of the relations it reads
625
+ def view_table_usage(connection)
626
+ rows = connection.select_rows(<<~SQL.squish)
627
+ SELECT VIEW_NAME, TABLE_NAME
628
+ FROM information_schema.VIEW_TABLE_USAGE
629
+ WHERE VIEW_SCHEMA = DATABASE() AND TABLE_SCHEMA = DATABASE()
630
+ ORDER BY VIEW_NAME, TABLE_NAME
566
631
  SQL
567
632
 
568
- result = Hash.new { |h, k| h[k] = [] }
633
+ rows.group_by(&:first).transform_values { |pairs| pairs.map(&:last) }
634
+ end
569
635
 
570
- connection.execute(query).each do |row|
571
- result[row[0]] << {
572
- name: row[1],
573
- definition: row[2],
574
- type: :check
575
- }
576
- end
636
+ # Run a SHOW CREATE statement and return its CREATE statement column
637
+ #
638
+ # @param column [Integer] Result column holding the statement (views: 1;
639
+ # routines and triggers, which report sql_mode first: 2)
640
+ # @return [String] CREATE statement
641
+ # @raise [Error] If the statement is hidden (missing privileges)
642
+ def show_create(connection, statement, column)
643
+ create_statement = connection.select_rows(statement).first&.at(column)
644
+ raise Error, "#{statement} returned no definition; check the user's privileges" if create_statement.nil?
645
+
646
+ create_statement
647
+ end
577
648
 
578
- result
579
- rescue StandardError
580
- # If CHECK_CONSTRAINTS table doesn't exist, return empty hash
581
- {}
582
- end
583
-
584
- # Resolve MySQL column type into normalized format
585
- #
586
- # @param row [Array] Column information row from information_schema.COLUMNS
587
- # @return [String] Normalized column type with length/precision if applicable
588
- def resolve_column_type(row)
589
- data_type = row[1]
590
- column_type = row[7] # Full type definition
591
-
592
- case data_type
593
- when 'varchar', 'char'
594
- # Use CHARACTER_MAXIMUM_LENGTH
595
- length = row[4]
596
- length ? "#{data_type}(#{length})" : data_type
597
- when 'decimal', 'numeric'
598
- precision = row[5]
599
- scale = row[6]
600
- if precision && scale
601
- "#{data_type}(#{precision},#{scale})"
602
- else
603
- data_type
604
- end
605
- when 'enum', 'set'
606
- # Return full column_type which includes values: enum('admin','user','guest')
607
- column_type
608
- when 'int', 'integer'
609
- 'int'
610
- when 'bigint'
611
- 'bigint'
612
- when 'tinyint'
613
- # Check if it's boolean (tinyint(1))
614
- column_type.include?('tinyint(1)') ? 'boolean' : 'tinyint'
615
- when 'datetime', 'timestamp'
616
- data_type
617
- when 'text', 'mediumtext', 'longtext'
618
- data_type
619
- when 'blob', 'mediumblob', 'longblob'
620
- data_type
621
- when 'json'
622
- 'json'
623
- else
624
- data_type
625
- end
649
+ # MySQL's information_schema escapes quotes and backslashes inside
650
+ # expressions (CHECK_CLAUSE, expression defaults)
651
+ # as if they were string literals; undo it to get the SQL SHOW CREATE
652
+ # TABLE shows. MariaDB stores the SQL unescaped.
653
+ #
654
+ # @return [String] SQL expression
655
+ def unescape_expression(expression)
656
+ return expression if mariadb?
657
+
658
+ expression.gsub(/\\([\\'])/, '\1')
659
+ end
660
+
661
+ # @return [String] Single-quoted MySQL string literal
662
+ def quote_string(value)
663
+ "'#{value.gsub(/[\\']/) { |char| char * 2 }}'"
664
+ end
665
+
666
+ # @return [String] Backtick-quoted identifier
667
+ def quote_identifier(name)
668
+ "`#{name.gsub('`', '``')}`"
626
669
  end
627
670
 
628
671
  # Fetch comments on tables
@@ -630,7 +673,7 @@ module BetterStructureSql
630
673
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
631
674
  # @return [Hash<String, String>] Hash of table_name => comment
632
675
  def fetch_table_comments(connection)
633
- query = <<~SQL.squish
676
+ connection.select_rows(<<~SQL.squish).to_h
634
677
  SELECT TABLE_NAME, TABLE_COMMENT
635
678
  FROM information_schema.TABLES
636
679
  WHERE TABLE_SCHEMA = DATABASE()
@@ -638,20 +681,14 @@ module BetterStructureSql
638
681
  AND TABLE_COMMENT != ''
639
682
  ORDER BY TABLE_NAME
640
683
  SQL
641
-
642
- result = {}
643
- connection.execute(query).each do |row|
644
- result[row[0]] = row[1]
645
- end
646
- result
647
684
  end
648
685
 
649
686
  # Fetch comments on columns
650
687
  #
651
688
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
652
- # @return [Hash<String, String>] Hash of "table_name.column_name" => comment
689
+ # @return [Hash<Array(String, String), String>] Hash of [table_name, column_name] => comment
653
690
  def fetch_column_comments(connection)
654
- query = <<~SQL.squish
691
+ rows = connection.select_rows(<<~SQL.squish)
655
692
  SELECT TABLE_NAME, COLUMN_NAME, COLUMN_COMMENT
656
693
  FROM information_schema.COLUMNS
657
694
  WHERE TABLE_SCHEMA = DATABASE()
@@ -659,12 +696,7 @@ module BetterStructureSql
659
696
  ORDER BY TABLE_NAME, ORDINAL_POSITION
660
697
  SQL
661
698
 
662
- result = {}
663
- connection.execute(query).each do |row|
664
- key = "#{row[0]}.#{row[1]}"
665
- result[key] = row[2]
666
- end
667
- result
699
+ rows.to_h { |table, column, comment| [[table, column], comment] }
668
700
  end
669
701
  end
670
702
  end