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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +69 -0
- data/README.md +218 -686
- data/app/CLAUDE.md +12 -0
- data/app/controllers/better_structure_sql/application_controller.rb +71 -31
- data/app/controllers/better_structure_sql/schema_versions_controller.rb +94 -153
- data/app/helpers/better_structure_sql/schema_versions_helper.rb +48 -24
- data/app/views/better_structure_sql/schema_versions/index.html.erb +46 -49
- data/app/views/better_structure_sql/schema_versions/show.html.erb +73 -120
- data/app/views/layouts/better_structure_sql/application.html.erb +27 -18
- data/config/routes.rb +1 -1
- data/lib/CLAUDE.md +73 -0
- data/lib/better_structure_sql/adapters/base_adapter.rb +16 -1
- data/lib/better_structure_sql/adapters/mysql_adapter.rb +396 -364
- data/lib/better_structure_sql/adapters/postgresql_adapter.rb +574 -478
- data/lib/better_structure_sql/adapters/registry.rb +18 -15
- data/lib/better_structure_sql/adapters/sqlite_adapter.rb +221 -474
- data/lib/better_structure_sql/configuration.rb +9 -2
- data/lib/better_structure_sql/creation_order.rb +157 -0
- data/lib/better_structure_sql/dependency_resolver.rb +4 -2
- data/lib/better_structure_sql/dumper.rb +173 -315
- data/lib/better_structure_sql/engine.rb +50 -4
- data/lib/better_structure_sql/file_writer.rb +108 -97
- data/lib/better_structure_sql/generators/base.rb +31 -4
- data/lib/better_structure_sql/generators/comment_generator.rb +16 -12
- data/lib/better_structure_sql/generators/domain_generator.rb +8 -6
- data/lib/better_structure_sql/generators/extension_generator.rb +7 -2
- data/lib/better_structure_sql/generators/foreign_key_generator.rb +14 -4
- data/lib/better_structure_sql/generators/index_generator.rb +0 -20
- data/lib/better_structure_sql/generators/materialized_view_generator.rb +17 -2
- data/lib/better_structure_sql/generators/sequence_generator.rb +13 -5
- data/lib/better_structure_sql/generators/table_generator.rb +164 -47
- data/lib/better_structure_sql/generators/type_generator.rb +25 -14
- data/lib/better_structure_sql/generators/view_generator.rb +12 -8
- data/lib/better_structure_sql/introspection/extensions.rb +1 -14
- data/lib/better_structure_sql/introspection/foreign_keys.rb +1 -14
- data/lib/better_structure_sql/introspection/functions.rb +1 -14
- data/lib/better_structure_sql/introspection/indexes.rb +1 -14
- data/lib/better_structure_sql/introspection/sequences.rb +1 -14
- data/lib/better_structure_sql/introspection/tables.rb +1 -14
- data/lib/better_structure_sql/introspection/triggers.rb +1 -14
- data/lib/better_structure_sql/introspection/types.rb +1 -14
- data/lib/better_structure_sql/introspection/views.rb +2 -19
- data/lib/better_structure_sql/introspection.rb +12 -1
- data/lib/better_structure_sql/migration_patch.rb +39 -139
- data/lib/better_structure_sql/railtie.rb +53 -56
- data/lib/better_structure_sql/schema_loader.rb +107 -86
- data/lib/better_structure_sql/schema_version.rb +3 -2
- data/lib/better_structure_sql/schema_versions.rb +70 -71
- data/lib/better_structure_sql/version.rb +1 -1
- data/lib/better_structure_sql/zip_generator.rb +43 -6
- data/lib/better_structure_sql.rb +2 -1
- data/lib/generators/better_structure_sql/migration_generator.rb +1 -1
- data/lib/generators/better_structure_sql/templates/README +17 -34
- data/lib/tasks/better_structure_sql.rake +19 -40
- metadata +9 -147
- 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
|
-
#
|
|
8
|
-
#
|
|
9
|
-
# inline foreign keys,
|
|
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
|
|
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
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
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
|
-
|
|
96
|
-
|
|
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:
|
|
77
|
+
name: row['name'],
|
|
123
78
|
schema: 'main',
|
|
124
|
-
sql: row['sql']
|
|
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:
|
|
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
|
-
|
|
138
|
-
|
|
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
|
-
|
|
141
|
-
|
|
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, :
|
|
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
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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']
|
|
203
|
-
definition:
|
|
204
|
-
|
|
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
|
-
#
|
|
297
|
+
# Query for tables, excluding SQLite's own (sqlite_%)
|
|
433
298
|
#
|
|
434
|
-
#
|
|
435
|
-
#
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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
|
|
314
|
+
# Fetch table names from the database
|
|
451
315
|
#
|
|
452
316
|
# @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
|
|
453
|
-
# @
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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
|
-
|
|
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']
|
|
461
|
-
type:
|
|
462
|
-
nullable:
|
|
463
|
-
default: row['dflt_value']
|
|
464
|
-
primary_key:
|
|
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
|
-
#
|
|
344
|
+
# Generation expression of a generated column, parsed from CREATE TABLE
|
|
470
345
|
#
|
|
471
|
-
# @param
|
|
472
|
-
# @param
|
|
473
|
-
# @
|
|
474
|
-
|
|
475
|
-
|
|
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
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
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
|
-
#
|
|
361
|
+
# Top-level comma-separated elements (columns and table constraints) of a CREATE TABLE
|
|
484
362
|
#
|
|
485
|
-
# @param
|
|
486
|
-
# @
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
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
|
-
|
|
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
|
-
#
|
|
376
|
+
# Unquoted leading identifier of a table element
|
|
519
377
|
#
|
|
520
|
-
# @param
|
|
521
|
-
# @
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
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
|
-
#
|
|
385
|
+
# Extract primary key columns from PRAGMA table_xinfo rows
|
|
535
386
|
#
|
|
536
|
-
# @param
|
|
537
|
-
# @
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
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
|
|
396
|
+
# Extract named CHECK constraints from a CREATE TABLE statement
|
|
572
397
|
#
|
|
573
|
-
# @param
|
|
574
|
-
# @return [Array<Hash>]
|
|
575
|
-
def
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
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
|
-
#
|
|
411
|
+
# Return the parenthesized expression starting at +open_index+, honoring
|
|
412
|
+
# nesting and quoted strings/identifiers
|
|
588
413
|
#
|
|
589
|
-
# @param
|
|
590
|
-
# @
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
#
|
|
601
|
-
#
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
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
|
-
#
|
|
453
|
+
# Extract the SELECT statement from a CREATE VIEW statement
|
|
632
454
|
#
|
|
633
|
-
# @param
|
|
634
|
-
# @
|
|
635
|
-
# @
|
|
636
|
-
def
|
|
637
|
-
|
|
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
|
-
|
|
462
|
+
select
|
|
649
463
|
end
|
|
650
464
|
|
|
651
|
-
#
|
|
465
|
+
# Build a foreign key hash from PRAGMA foreign_key_list rows of one key
|
|
652
466
|
#
|
|
653
|
-
# @param
|
|
654
|
-
# @
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|