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
@@ -4,10 +4,23 @@ module BetterStructureSql
4
4
  module Adapters
5
5
  # SQLite adapter implementing introspection via sqlite_master and PRAGMA statements
6
6
  #
7
- # Provides SQLite-specific SQL generation with proper dialect support.
8
- # This adapter handles SQLite's unique features including PRAGMA settings,
9
- # inline foreign keys, AUTOINCREMENT, and type affinities.
7
+ # Tables, indexes and views carry their original CREATE statements from
8
+ # sqlite_master, the only lossless record of SQLite DDL (AUTOINCREMENT,
9
+ # WITHOUT ROWID, STRICT, inline foreign keys, partial/expression indexes).
10
10
  class SqliteAdapter < BaseAdapter
11
+ # Persistent PRAGMAs that describe the database file (all default to 0)
12
+ PERSISTENT_PRAGMAS = %w[application_id auto_vacuum user_version].freeze
13
+
14
+ # PRAGMA table_xinfo "hidden" values marking generated columns
15
+ GENERATED_COLUMN_KINDS = { 2 => 'VIRTUAL', 3 => 'STORED' }.freeze
16
+
17
+ # Characters opening a quoted string or identifier in SQLite SQL
18
+ QUOTE_CHARS = %w[' " `].freeze
19
+
20
+ # CREATE VIEW statement; captures the SELECT after an optionally quoted view name
21
+ VIEW_STATEMENT = /\ACREATE\s+(?:TEMP(?:ORARY)?\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?
22
+ (?:"(?:[^"]|"")+"|`[^`]+`|\[[^\]]+\]|[^\s(]+)\s+AS\s+(.*)\z/imx
23
+
11
24
  # Introspection methods using sqlite_master and PRAGMA
12
25
 
13
26
  # Fetch extensions (PRAGMA settings for SQLite)
@@ -21,60 +34,21 @@ module BetterStructureSql
21
34
  fetch_pragma_settings(connection)
22
35
  end
23
36
 
24
- # Fetch important PRAGMA settings for SQLite
37
+ # Fetch PRAGMA settings stored in the database file
38
+ #
39
+ # Only persistent, schema-level PRAGMAs with non-default values are returned.
40
+ # Connection-scoped settings (journal_mode, synchronous, cache_size,
41
+ # foreign_keys, ...) are configured by Rails per connection, are not part
42
+ # of the schema, and would make the dump differ between environments.
25
43
  #
26
44
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
27
45
  # @return [Array<Hash>] Array of PRAGMA hashes with :name, :value, :sql
28
46
  def fetch_pragma_settings(connection)
29
- # List of important PRAGMAs to preserve in schema dump
30
- important_pragmas = %w[
31
- foreign_keys
32
- recursive_triggers
33
- defer_foreign_keys
34
- journal_mode
35
- synchronous
36
- temp_store
37
- locking_mode
38
- auto_vacuum
39
- cache_size
40
- ]
41
-
42
- pragmas = []
43
- important_pragmas.each do |pragma_name|
44
- result = connection.execute("PRAGMA #{pragma_name}").first
45
- next unless result
46
-
47
- value = result.is_a?(Hash) ? (result[pragma_name] || result.values.first) : result[0]
48
-
49
- # Only include non-default values that make sense to preserve
50
- next if value.nil? || value.to_s.empty?
51
- next if pragma_name == 'foreign_keys' && value.to_i.zero? # Skip if FK disabled
52
-
53
- pragmas << {
54
- name: pragma_name,
55
- value: value,
56
- sql: "PRAGMA #{pragma_name} = #{format_pragma_value(pragma_name, value)};"
57
- }
58
- rescue StandardError => e
59
- # Skip PRAGMAs that fail (might not be supported in this SQLite version)
60
- Rails.logger.debug { "Skipping PRAGMA #{pragma_name}: #{e.message}" } if defined?(Rails)
61
- end
62
-
63
- pragmas
64
- end
47
+ PERSISTENT_PRAGMAS.filter_map do |pragma_name|
48
+ value = connection.select_value("PRAGMA #{pragma_name}")
49
+ next if value.to_i.zero?
65
50
 
66
- # Format PRAGMA value for SQL statement
67
- #
68
- # @param pragma_name [String] Name of the PRAGMA
69
- # @param value [Object] Value of the PRAGMA
70
- # @return [String] Formatted value (quoted if string, unquoted if numeric)
71
- def format_pragma_value(pragma_name, value)
72
- # String values need quotes, numeric values don't
73
- case pragma_name
74
- when 'journal_mode', 'locking_mode', 'temp_store', 'synchronous'
75
- value.to_s.match?(/^\d+$/) ? value.to_s : "'#{value}'"
76
- else
77
- value.to_s
51
+ { name: pragma_name, value:, sql: "PRAGMA #{pragma_name} = #{value};" }
78
52
  end
79
53
  end
80
54
 
@@ -89,96 +63,80 @@ module BetterStructureSql
89
63
 
90
64
  # Fetch all tables from the database
91
65
  #
66
+ # :sql holds the original CREATE TABLE statement from sqlite_master, the
67
+ # only lossless source for AUTOINCREMENT, WITHOUT ROWID, STRICT, generated
68
+ # column expressions, collations and constraint names.
69
+ #
92
70
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
93
71
  # @return [Array<Hash>] Array of table hashes with :name, :schema, :sql, :columns, :primary_key, :constraints
94
72
  def fetch_tables(connection)
95
- # Performance optimized: Reduces PRAGMA calls by batching table_info queries
96
- # For 1000 tables: ~2000 fewer PRAGMA calls (~2x faster)
97
- query = <<~SQL.squish
98
- SELECT name, sql
99
- FROM sqlite_master
100
- WHERE type = 'table'
101
- AND name NOT LIKE 'sqlite_%'
102
- AND name != 'schema_migrations'
103
- AND name != 'ar_internal_metadata'
104
- ORDER BY name
105
- SQL
106
-
107
- table_rows = connection.execute(query).to_a
108
- return [] if table_rows.empty?
109
-
110
- table_names = table_rows.map { |row| row['name'] || row[0] }
111
-
112
- # Batch fetch all table_info (columns + primary keys) and constraints
113
- table_info_by_table = fetch_all_table_info(connection, table_names)
114
- constraints_by_table = fetch_all_constraints(connection, table_names)
115
-
116
- # Combine results
117
- table_rows.map do |row|
118
- table_name = row['name'] || row[0]
119
- table_info = table_info_by_table[table_name] || []
73
+ connection.execute(tables_query).map do |row|
74
+ table_info = connection.execute("PRAGMA table_xinfo(#{quote_identifier(row['name'])})").to_a
120
75
 
121
76
  {
122
- name: table_name,
77
+ name: row['name'],
123
78
  schema: 'main',
124
- sql: row['sql'] || row[1],
125
- columns: extract_columns_from_table_info(table_info),
79
+ sql: row['sql'],
80
+ columns: extract_columns_from_table_info(table_info, row['sql']),
126
81
  primary_key: extract_primary_key_from_table_info(table_info),
127
- constraints: constraints_by_table[table_name] || []
82
+ constraints: extract_check_constraints(row['sql'])
128
83
  }
129
84
  end
130
85
  end
131
86
 
132
- # Fetch all indexes from the database
87
+ # Fetch all explicitly created indexes from the database
88
+ #
89
+ # The definition is the original CREATE INDEX statement, so partial
90
+ # (WHERE) and expression indexes are preserved. Indexes SQLite creates
91
+ # implicitly for PRIMARY KEY/UNIQUE constraints have no SQL and are
92
+ # recreated by their CREATE TABLE.
133
93
  #
134
94
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
135
95
  # @return [Array<Hash>] Array of index hashes with :table, :name, :columns, :unique, :type, :definition
136
96
  def fetch_indexes(connection)
137
- tables = fetch_table_names(connection)
138
- indexes = []
97
+ query = <<~SQL.squish
98
+ SELECT name, tbl_name, sql
99
+ FROM sqlite_master
100
+ WHERE type = 'index'
101
+ AND sql IS NOT NULL
102
+ ORDER BY tbl_name, name
103
+ SQL
139
104
 
140
- tables.each do |table_name|
141
- indexes.concat(fetch_table_indexes(connection, table_name))
105
+ connection.execute(query).map do |row|
106
+ {
107
+ table: row['tbl_name'],
108
+ name: row['name'],
109
+ columns: fetch_index_columns(connection, row['name']),
110
+ unique: row['sql'].match?(/\ACREATE\s+UNIQUE\b/i),
111
+ type: 'BTREE',
112
+ definition: row['sql']
113
+ }
142
114
  end
143
-
144
- indexes
145
115
  end
146
116
 
147
117
  # Fetch all foreign keys from the database
148
118
  #
119
+ # PRAGMA foreign_key_list reports one row per column and numbers keys in
120
+ # reverse declaration order; keys are regrouped (composite keys become a
121
+ # single entry listing their columns) and returned in declaration
122
+ # order so a dump/load cycle keeps the original order.
123
+ #
149
124
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
150
- # @return [Array<Hash>] Array of foreign key hashes with :table, :name, :column, :foreign_table, :foreign_column, :on_update, :on_delete
125
+ # @return [Array<Hash>] Array of foreign key hashes with :table, :name, :columns, :foreign_table, :foreign_columns, :on_update, :on_delete
151
126
  def fetch_foreign_keys(connection)
152
- tables = fetch_table_names(connection)
153
- foreign_keys = []
154
-
155
- tables.each do |table_name|
156
- fk_list = connection.execute("PRAGMA foreign_key_list(#{quote_identifier(table_name)})")
157
-
158
- fk_list.each do |fk_row|
159
- from_col = fk_row['from'] || fk_row[3]
160
- to_table = fk_row['table'] || fk_row[2]
161
- to_col = fk_row['to'] || fk_row[4]
162
-
163
- foreign_keys << {
164
- table: table_name,
165
- name: "fk_#{table_name}_#{to_table}_#{from_col}", # Generate name
166
- column: from_col,
167
- foreign_table: to_table,
168
- foreign_column: to_col,
169
- on_update: fk_row['on_update'] || fk_row[5],
170
- on_delete: fk_row['on_delete'] || fk_row[6]
171
- }
172
- end
127
+ fetch_table_names(connection).flat_map do |table_name|
128
+ connection.execute("PRAGMA foreign_key_list(#{quote_identifier(table_name)})")
129
+ .group_by { |row| row['id'] }
130
+ .sort_by { |id, _rows| -id }
131
+ .map { |_id, rows| build_foreign_key(table_name, rows.sort_by { |row| row['seq'] }) }
173
132
  end
174
-
175
- foreign_keys
176
133
  end
177
134
 
178
135
  # Fetch all views from the database
179
136
  #
180
137
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
181
- # @return [Array<Hash>] Array of view hashes with :schema, :name, :definition, :updatable
138
+ # @return [Array<Hash>] Array of view hashes with :schema, :name, :definition, :sql, :updatable
139
+ # (:definition is the SELECT statement; :sql the original CREATE VIEW statement)
182
140
  def fetch_views(connection)
183
141
  query = <<~SQL.squish
184
142
  SELECT name, sql
@@ -188,20 +146,12 @@ module BetterStructureSql
188
146
  SQL
189
147
 
190
148
  connection.execute(query).map do |row|
191
- sql = row['sql'] || row[1]
192
- # Extract just the SELECT part from CREATE VIEW statement for compatibility
193
- # with existing ViewGenerator
194
- definition = if sql&.match(/CREATE\s+VIEW\s+\w+\s+AS\s+(.*)/im)
195
- ::Regexp.last_match(1)
196
- else
197
- sql
198
- end
199
-
200
149
  {
201
150
  schema: 'main',
202
- name: row['name'] || row[0],
203
- definition: definition || '',
204
- updatable: false # SQLite views are generally not updatable
151
+ name: row['name'],
152
+ definition: view_select(row['sql']),
153
+ sql: row['sql'],
154
+ updatable: false # SQLite views are read-only unless INSTEAD OF triggers exist
205
155
  }
206
156
  end
207
157
  end
@@ -253,7 +203,8 @@ module BetterStructureSql
253
203
  columns: {},
254
204
  indexes: {},
255
205
  views: {},
256
- functions: {}
206
+ functions: {},
207
+ procedures: {}
257
208
  }
258
209
  end
259
210
 
@@ -315,92 +266,6 @@ module BetterStructureSql
315
266
  true # SQLite has always supported CHECK constraints
316
267
  end
317
268
 
318
- # SQL Generation methods - SQLite-specific syntax
319
-
320
- # Generate CREATE TABLE statement for SQLite
321
- #
322
- # @param table [Hash] Table hash with :name, :columns, :primary_key, :foreign_keys
323
- # @return [String] CREATE TABLE SQL statement
324
- def generate_table(table)
325
- sql = table[:sql]
326
- return sql if sql # Use original SQL from sqlite_master if available
327
-
328
- # Generate from columns if needed
329
- lines = ["CREATE TABLE #{quote_identifier(table[:name])} ("]
330
-
331
- column_defs = table[:columns].map do |col|
332
- generate_column_definition(col, table[:primary_key])
333
- end
334
-
335
- # Add foreign keys inline if present
336
- table[:foreign_keys]&.each do |fk|
337
- column_defs << generate_foreign_key_inline(fk)
338
- end
339
-
340
- lines << column_defs.map { |col_def| " #{col_def}" }.join(",\n")
341
- lines << ');'
342
-
343
- lines.join("\n")
344
- end
345
-
346
- # Generate CREATE INDEX statement for SQLite
347
- #
348
- # @param index [Hash] Index hash with :name, :table, :columns, :unique
349
- # @return [String] CREATE INDEX SQL statement
350
- def generate_index(index)
351
- unique = index[:unique] ? 'UNIQUE ' : ''
352
- columns = index[:columns].map { |col| quote_identifier(col) }.join(', ')
353
-
354
- "CREATE #{unique}INDEX #{quote_identifier(index[:name])} " \
355
- "ON #{quote_identifier(index[:table])} (#{columns});"
356
- end
357
-
358
- # Generate foreign key constraint (inline with table definition)
359
- #
360
- # @param fk [Hash] Foreign key hash with :column, :foreign_table, :foreign_column, :on_delete, :on_update
361
- # @return [String] FOREIGN KEY constraint SQL
362
- # @note SQLite requires foreign keys inline with CREATE TABLE
363
- # rubocop:disable Naming/MethodParameterName
364
- def generate_foreign_key(fk)
365
- # SQLite requires foreign keys inline with CREATE TABLE
366
- # This method is for documentation - actual usage is generate_foreign_key_inline
367
- generate_foreign_key_inline(fk)
368
- end
369
-
370
- # Generate CREATE VIEW statement for SQLite
371
- #
372
- # @param view [Hash] View hash with :name, :definition
373
- # @return [String] CREATE VIEW SQL statement
374
- def generate_view(view)
375
- definition = view[:definition]
376
- return definition if /^CREATE\s+VIEW/i.match?(definition) # Already complete
377
-
378
- "CREATE VIEW #{quote_identifier(view[:name])} AS\n#{definition};"
379
- end
380
-
381
- # Generate CREATE TRIGGER statement for SQLite
382
- #
383
- # @param trigger [Hash] Trigger hash with :name, :timing, :event, :table_name, :definition, :body
384
- # @return [String] CREATE TRIGGER SQL statement
385
- def generate_trigger(trigger)
386
- definition = trigger[:definition]
387
- return definition if /^CREATE\s+TRIGGER/i.match?(definition) # Already complete
388
-
389
- # Generate from components
390
- timing = trigger[:timing] || 'AFTER'
391
- event = trigger[:event] || 'INSERT'
392
- table = trigger[:table_name]
393
- body = trigger[:body] || trigger[:definition]
394
-
395
- <<~SQL.strip
396
- CREATE TRIGGER #{quote_identifier(trigger[:name])}
397
- #{timing} #{event} ON #{quote_identifier(table)}
398
- BEGIN
399
- #{body}
400
- END;
401
- SQL
402
- end
403
-
404
269
  # Version detection
405
270
 
406
271
  # Get the current SQLite database version
@@ -429,327 +294,209 @@ module BetterStructureSql
429
294
 
430
295
  # Helper methods for introspection
431
296
 
432
- # Fetch table names from the database
297
+ # Query for tables, excluding SQLite's own (sqlite_%)
433
298
  #
434
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
435
- # @return [Array<String>] Array of table names
436
- def fetch_table_names(connection)
437
- query = <<~SQL.squish
438
- SELECT name
299
+ # schema_migrations and ar_internal_metadata are dumped like on the other
300
+ # adapters: a loaded dump needs schema_migrations for its INSERT, or every
301
+ # migration is pending.
302
+ #
303
+ # @return [String] SQL query returning name and sql
304
+ def tables_query
305
+ <<~SQL.squish
306
+ SELECT name, sql
439
307
  FROM sqlite_master
440
308
  WHERE type = 'table'
441
309
  AND name NOT LIKE 'sqlite_%'
442
- AND name != 'schema_migrations'
443
- AND name != 'ar_internal_metadata'
444
310
  ORDER BY name
445
311
  SQL
446
-
447
- connection.execute(query).map { |row| row['name'] || row[0] }
448
312
  end
449
313
 
450
- # Fetch columns for a specific table using PRAGMA table_info
314
+ # Fetch table names from the database
451
315
  #
452
316
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
453
- # @param table_name [String] Name of the table
454
- # @return [Array<Hash>] Array of column hashes with :name, :type, :nullable, :default, :primary_key
455
- def fetch_columns(connection, table_name)
456
- table_info = connection.execute("PRAGMA table_info(#{quote_identifier(table_name)})")
317
+ # @return [Array<String>] Array of table names
318
+ def fetch_table_names(connection)
319
+ connection.execute(tables_query).pluck('name')
320
+ end
457
321
 
458
- table_info.map do |row|
322
+ # Extract columns from PRAGMA table_xinfo rows
323
+ #
324
+ # table_xinfo (unlike table_info) includes generated columns, flagged by
325
+ # hidden = 2 (VIRTUAL) or 3 (STORED). The declared type is kept verbatim
326
+ # (e.g. "varchar(255)") because Rails derives column limits from it.
327
+ #
328
+ # @param table_info [Array<Hash>] Rows from PRAGMA table_xinfo
329
+ # @param sql [String] CREATE TABLE statement (source of generation expressions)
330
+ # @return [Array<Hash>] Array of column hashes
331
+ def extract_columns_from_table_info(table_info, sql)
332
+ table_info.reject { |row| row['hidden'] == 1 }.map do |row|
459
333
  {
460
- name: row['name'] || row[1],
461
- type: resolve_column_type(row['type'] || row[2]),
462
- nullable: (row['notnull'] || row[3]).to_i.zero?,
463
- default: row['dflt_value'] || row[4],
464
- primary_key: (row['pk'] || row[5]).to_i == 1
334
+ name: row['name'],
335
+ type: row['type'],
336
+ nullable: row['notnull'].to_i.zero?,
337
+ default: row['dflt_value'],
338
+ primary_key: row['pk'].to_i.positive?,
339
+ generated: generated_column(sql, row['name'], GENERATED_COLUMN_KINDS[row['hidden']])
465
340
  }
466
341
  end
467
342
  end
468
343
 
469
- # Fetch primary key columns for a specific table using PRAGMA table_info
344
+ # Generation expression of a generated column, parsed from CREATE TABLE
470
345
  #
471
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
472
- # @param table_name [String] Name of the table
473
- # @return [Array<String>] Array of primary key column names in pk order
474
- def fetch_primary_key(connection, table_name)
475
- table_info = connection.execute("PRAGMA table_info(#{quote_identifier(table_name)})")
346
+ # @param sql [String] CREATE TABLE statement
347
+ # @param name [String] Column name
348
+ # @param kind [String, nil] "VIRTUAL", "STORED" or nil for ordinary columns
349
+ # @return [Hash, nil] { expression:, kind: } for generated columns
350
+ def generated_column(sql, name, kind)
351
+ return nil unless kind
476
352
 
477
- table_info
478
- .select { |row| (row['pk'] || row[5]).to_i == 1 }
479
- .sort_by { |row| row['pk'] || row[5] } # Sort by pk order
480
- .map { |row| row['name'] || row[1] }
353
+ definition = table_elements(sql).find { |element| element_name(element).casecmp?(name) }
354
+ open_index = definition.index(/\bAS\s*\(/i)
355
+ raise Error, "Unable to find expression of generated column #{name} in: #{sql}" unless open_index
356
+
357
+ expression = balanced_parenthesized(definition, definition.index('(', open_index))
358
+ { expression: expression[1...-1].strip, kind: }
481
359
  end
482
360
 
483
- # Fetch CHECK constraints for a specific table by parsing table SQL
361
+ # Top-level comma-separated elements (columns and table constraints) of a CREATE TABLE
484
362
  #
485
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
486
- # @param table_name [String] Name of the table
487
- # @return [Array<Hash>] Array of constraint hashes with :name, :definition, :type
488
- def fetch_constraints(connection, table_name)
489
- # SQLite stores CHECK constraints in the table SQL
490
- # Parse from sqlite_master
491
- query = <<~SQL.squish
492
- SELECT sql
493
- FROM sqlite_master
494
- WHERE type = 'table'
495
- AND name = '#{table_name}'
496
- SQL
363
+ # @param sql [String] CREATE TABLE statement
364
+ # @return [Array<String>] Element definitions
365
+ def table_elements(sql)
366
+ body = balanced_parenthesized(sql, sql.index('('))[1...-1]
367
+ elements = [+'']
368
+ scan_sql(body) do |char, depth|
369
+ next elements << +'' if char == ',' && depth&.zero?
497
370
 
498
- result = connection.execute(query).first
499
- return [] unless result
500
-
501
- sql = result['sql'] || result[0]
502
- return [] unless sql
503
-
504
- # Extract CHECK constraints from SQL
505
- # This is a simplified parser - real implementation would be more robust
506
- checks = []
507
- sql.scan(/CONSTRAINT\s+(\w+)\s+CHECK\s*\(([^)]+)\)/i) do |match|
508
- checks << {
509
- name: match[0],
510
- definition: match[1],
511
- type: :check
512
- }
371
+ elements.last << char
513
372
  end
514
-
515
- checks
373
+ elements.map(&:strip)
516
374
  end
517
375
 
518
- # Batch fetch all table_info for multiple tables (performance optimization)
376
+ # Unquoted leading identifier of a table element
519
377
  #
520
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
521
- # @param table_names [Array<String>] Array of table names
522
- # @return [Hash<String, Array<Hash>>] Hash of table_name => array of table_info rows
523
- def fetch_all_table_info(connection, table_names)
524
- result = {}
525
-
526
- table_names.each do |table_name|
527
- table_info = connection.execute("PRAGMA table_info(#{quote_identifier(table_name)})")
528
- result[table_name] = table_info.to_a
529
- end
530
-
531
- result
378
+ # @param element [String] Column or constraint definition
379
+ # @return [String] Identifier
380
+ def element_name(element)
381
+ token = element[/\A(?:"(?:[^"]|"")+"|`[^`]+`|\[[^\]]+\]|[^\s]+)/]
382
+ token.match?(/\A["`\[]/) ? token[1...-1].gsub('""', '"') : token
532
383
  end
533
384
 
534
- # Batch fetch all constraints for multiple tables (performance optimization)
385
+ # Extract primary key columns from PRAGMA table_xinfo rows
535
386
  #
536
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
537
- # @param table_names [Array<String>] Array of table names
538
- # @return [Hash<String, Array<Hash>>] Hash of table_name => array of constraint hashes
539
- def fetch_all_constraints(connection, table_names)
540
- return {} if table_names.empty?
541
-
542
- # Fetch all table SQL in one query
543
- quoted_names = table_names.map { |t| "'#{t}'" }.join(', ')
544
- query = <<~SQL.squish
545
- SELECT name, sql
546
- FROM sqlite_master
547
- WHERE type = 'table'
548
- AND name IN (#{quoted_names})
549
- SQL
550
-
551
- result = Hash.new { |h, k| h[k] = [] }
552
-
553
- connection.execute(query).each do |row|
554
- table_name = row['name'] || row[0]
555
- sql = row['sql'] || row[1]
556
- next unless sql
557
-
558
- # Extract CHECK constraints from SQL
559
- sql.scan(/CONSTRAINT\s+(\w+)\s+CHECK\s*\(([^)]+)\)/i) do |match|
560
- result[table_name] << {
561
- name: match[0],
562
- definition: match[1],
563
- type: :check
564
- }
565
- end
566
- end
567
-
568
- result
387
+ # @param table_info [Array<Hash>] Rows from PRAGMA table_xinfo
388
+ # @return [Array<String>] Primary key column names in key order (pk is the 1-based position)
389
+ def extract_primary_key_from_table_info(table_info)
390
+ table_info
391
+ .select { |row| row['pk'].to_i.positive? }
392
+ .sort_by { |row| row['pk'] }
393
+ .pluck('name')
569
394
  end
570
395
 
571
- # Extract columns from table_info rows
396
+ # Extract named CHECK constraints from a CREATE TABLE statement
572
397
  #
573
- # @param table_info [Array<Hash>] Array of table_info rows from PRAGMA table_info
574
- # @return [Array<Hash>] Array of column hashes
575
- def extract_columns_from_table_info(table_info)
576
- table_info.map do |row|
577
- {
578
- name: row['name'] || row[1],
579
- type: resolve_column_type(row['type'] || row[2]),
580
- nullable: (row['notnull'] || row[3]).to_i.zero?,
581
- default: row['dflt_value'] || row[4],
582
- primary_key: (row['pk'] || row[5]).to_i == 1
583
- }
398
+ # @param sql [String, nil] CREATE TABLE statement
399
+ # @return [Array<Hash>] Constraint hashes whose :definition is "CHECK (...)"
400
+ def extract_check_constraints(sql)
401
+ return [] unless sql
402
+
403
+ constraints = []
404
+ sql.scan(/CONSTRAINT\s+("(?:[^"]|"")+"|`[^`]+`|\[[^\]]+\]|\w+)\s+CHECK\s*\(/i) do |(name)|
405
+ expression = balanced_parenthesized(sql, Regexp.last_match.end(0) - 1)
406
+ constraints << { name:, definition: "CHECK #{expression}", type: :check }
584
407
  end
408
+ constraints
585
409
  end
586
410
 
587
- # Extract primary key columns from table_info rows
411
+ # Return the parenthesized expression starting at +open_index+, honoring
412
+ # nesting and quoted strings/identifiers
588
413
  #
589
- # @param table_info [Array<Hash>] Array of table_info rows from PRAGMA table_info
590
- # @return [Array<String>] Array of primary key column names in pk order
591
- def extract_primary_key_from_table_info(table_info)
592
- table_info
593
- .select { |row| (row['pk'] || row[5]).to_i == 1 }
594
- .sort_by { |row| row['pk'] || row[5] }
595
- .map { |row| row['name'] || row[1] }
596
- end
597
-
598
- # Resolve SQLite column type into normalized format using type affinity
599
- #
600
- # @param type_string [String] Raw column type from PRAGMA table_info
601
- # @return [String] Normalized column type based on SQLite type affinity rules
602
- def resolve_column_type(type_string)
603
- # SQLite type affinity mapping
604
- # Normalize common types
605
- type_lower = type_string.to_s.downcase
606
-
607
- case type_lower
608
- when /^int/
609
- 'integer'
610
- when /^varchar/, /^char/, /^text/
611
- 'text'
612
- when /^real/, /^float/, /^double/
613
- 'real'
614
- when /^decimal/, /^numeric/
615
- # Keep precision if specified
616
- type_string
617
- when /^blob/
618
- 'blob'
619
- when /^bool/
620
- 'boolean'
621
- when /^date/, /^time/
622
- # SQLite stores dates/times as TEXT or INTEGER
623
- type_string
624
- when /^json/
625
- 'json' # Stored as TEXT but semantically JSON
626
- else
627
- type_string
414
+ # @param sql [String] SQL text
415
+ # @param open_index [Integer] Index of the opening parenthesis
416
+ # @return [String] Text from the opening to the matching closing parenthesis
417
+ # @raise [Error] If the parenthesis is never closed
418
+ def balanced_parenthesized(sql, open_index)
419
+ scan_sql(sql[open_index..]).with_index do |(char, depth), offset|
420
+ return sql[open_index, offset + 1] if char == ')' && depth&.zero?
421
+ end
422
+ raise Error, "Unbalanced parentheses in: #{sql}"
423
+ end
424
+
425
+ # Yield each character with the parenthesis depth outside quoted text
426
+ # (depth after an opening and before a closing parenthesis are the same
427
+ # level, so a ")" yielded with depth 0 closes the outermost group)
428
+ #
429
+ # @param sql [String] SQL text
430
+ # @yieldparam char [String] Character
431
+ # @yieldparam depth [Integer, nil] Parenthesis depth, nil inside quotes
432
+ # @return [Enumerator] When no block is given
433
+ def scan_sql(sql)
434
+ return enum_for(:scan_sql, sql) unless block_given?
435
+
436
+ depth = 0
437
+ quote = nil
438
+ sql.each_char do |char|
439
+ if quote
440
+ quote = nil if char == quote
441
+ yield char, nil
442
+ elsif QUOTE_CHARS.include?(char)
443
+ quote = char
444
+ yield char, nil
445
+ else
446
+ depth -= 1 if char == ')'
447
+ yield char, depth
448
+ depth += 1 if char == '('
449
+ end
628
450
  end
629
451
  end
630
452
 
631
- # Generate column definition for CREATE TABLE
453
+ # Extract the SELECT statement from a CREATE VIEW statement
632
454
  #
633
- # @param col [Hash] Column hash with :name, :type, :nullable, :default, :primary_key, :extra
634
- # @param primary_keys [Array<String>] List of primary key column names
635
- # @return [String] Column definition SQL
636
- def generate_column_definition(col, primary_keys = [])
637
- parts = [quote_identifier(col[:name]), col[:type].upcase]
638
-
639
- # PRIMARY KEY for single-column pk with AUTOINCREMENT
640
- if col[:primary_key] && primary_keys.length == 1
641
- parts << 'PRIMARY KEY'
642
- parts << 'AUTOINCREMENT' if col[:extra]&.include?('auto_increment') || col[:type]&.downcase == 'integer'
643
- end
644
-
645
- parts << 'NOT NULL' unless col[:nullable]
646
- parts << "DEFAULT #{format_default_value(col[:default])}" if col[:default]
455
+ # @param sql [String] CREATE VIEW statement from sqlite_master
456
+ # @return [String] View query
457
+ # @raise [Error] If the statement cannot be parsed
458
+ def view_select(sql)
459
+ select = sql[VIEW_STATEMENT, 1]
460
+ raise Error, "Unable to parse view definition: #{sql}" unless select
647
461
 
648
- parts.join(' ')
462
+ select
649
463
  end
650
464
 
651
- # Generate inline foreign key constraint
465
+ # Build a foreign key hash from PRAGMA foreign_key_list rows of one key
652
466
  #
653
- # @param fk [Hash] Foreign key hash with :column, :foreign_table, :foreign_column, :on_delete, :on_update
654
- # @return [String] FOREIGN KEY constraint SQL
655
- def generate_foreign_key_inline(fk)
656
- parts = ["FOREIGN KEY (#{quote_identifier(fk[:column])})"]
657
- parts << "REFERENCES #{quote_identifier(fk[:foreign_table])}(#{quote_identifier(fk[:foreign_column])})"
658
- parts << "ON DELETE #{fk[:on_delete]}" if fk[:on_delete]
659
- parts << "ON UPDATE #{fk[:on_update]}" if fk[:on_update]
467
+ # @param table_name [String] Referencing table
468
+ # @param rows [Array<Hash>] Rows of one foreign key, in column order
469
+ # @return [Hash] Foreign key hash
470
+ def build_foreign_key(table_name, rows)
471
+ columns = rows.pluck('from')
472
+ first = rows.first
660
473
 
661
- parts.join(' ')
474
+ {
475
+ table: table_name,
476
+ name: "fk_#{table_name}_#{first['table']}_#{columns.join('_')}", # SQLite does not expose FK names
477
+ columns:,
478
+ foreign_table: first['table'],
479
+ foreign_columns: rows.pluck('to'),
480
+ on_update: first['on_update'],
481
+ on_delete: first['on_delete']
482
+ }
662
483
  end
663
- # rubocop:enable Naming/MethodParameterName
664
484
 
665
485
  # Quote identifier (table/column name) with double quotes
666
486
  #
667
487
  # @param name [String] Identifier to quote
668
488
  # @return [String] Quoted identifier (e.g., "table_name")
669
489
  def quote_identifier(name)
670
- "\"#{name}\""
671
- end
672
-
673
- # Format default value for SQL statement
674
- #
675
- # @param value [Object] Default value (can be nil, String, Boolean, or other)
676
- # @return [String] Formatted default value for SQL
677
- def format_default_value(value)
678
- case value
679
- when nil
680
- 'NULL'
681
- when String
682
- # Check if it looks like a function call (uppercase letters/underscores followed by parentheses)
683
- # or datetime/current_timestamp keywords
684
- if value =~ /^[A-Z_]+\(/i || value =~ /^(CURRENT_|datetime|date|time)/i
685
- value
686
- else
687
- "'#{value.gsub("'", "''")}'"
688
- end
689
- when TrueClass
690
- '1'
691
- when FalseClass
692
- '0'
693
- else
694
- value.to_s
695
- end
490
+ "\"#{name.gsub('"', '""')}\""
696
491
  end
697
492
 
698
- # Fetch indexes for a specific table
699
- #
700
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
701
- # @param table_name [String] Table name
702
- # @return [Array<Hash>] Array of index hashes
703
- def fetch_table_indexes(connection, table_name)
704
- index_list = connection.execute("PRAGMA index_list(#{quote_identifier(table_name)})")
705
- skip_origins = %w[pk u].freeze
706
- indexes = []
707
-
708
- index_list.each do |index_row|
709
- index_name = index_row['name'] || index_row[1]
710
- is_unique = (index_row['unique'] || index_row[2]).to_i == 1
711
- origin = index_row['origin'] || index_row[3]
712
-
713
- next if skip_origins.include?(origin)
714
-
715
- columns = fetch_index_columns(connection, index_name)
716
- definition = build_index_definition(table_name, index_name, is_unique, columns)
717
-
718
- indexes << {
719
- table: table_name,
720
- name: index_name,
721
- columns: columns,
722
- unique: is_unique,
723
- type: 'BTREE',
724
- definition: definition
725
- }
726
- end
727
-
728
- indexes
729
- end
730
-
731
- # Fetch columns for a specific index
493
+ # Fetch columns for a specific index (expression key parts are omitted)
732
494
  #
733
495
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
734
496
  # @param index_name [String] Index name
735
497
  # @return [Array<String>] Array of column names
736
498
  def fetch_index_columns(connection, index_name)
737
- index_info = connection.execute("PRAGMA index_info(#{quote_identifier(index_name)})")
738
- index_info.map { |col_row| col_row['name'] || col_row[2] }
739
- end
740
-
741
- # Build CREATE INDEX definition string
742
- #
743
- # @param table_name [String] Table name
744
- # @param index_name [String] Index name
745
- # @param is_unique [Boolean] Whether index is unique
746
- # @param columns [Array<String>] Column names
747
- # @return [String] CREATE INDEX SQL statement
748
- def build_index_definition(table_name, index_name, is_unique, columns)
749
- unique_clause = is_unique ? 'UNIQUE ' : ''
750
- columns_clause = columns.map { |col| quote_identifier(col) }.join(', ')
751
- "CREATE #{unique_clause}INDEX #{quote_identifier(index_name)} " \
752
- "ON #{quote_identifier(table_name)} (#{columns_clause})"
499
+ connection.execute("PRAGMA index_info(#{quote_identifier(index_name)})").filter_map { |row| row['name'] }
753
500
  end
754
501
 
755
502
  # SQL query for fetching triggers