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
@@ -5,10 +5,24 @@ module BetterStructureSql
5
5
  # PostgreSQL adapter implementing all introspection and generation methods
6
6
  #
7
7
  # Provides full PostgreSQL support including extensions, custom types, materialized views,
8
- # functions, triggers, sequences, and all standard database objects.
9
- # Preserves existing query logic for backward compatibility.
8
+ # functions, triggers, sequences, partitioned tables and all standard database objects.
9
+ #
10
+ # Introspection reads pg_catalog directly and relies on PostgreSQL's own deparse
11
+ # functions (format_type, pg_get_expr, pg_get_constraintdef, pg_get_indexdef, ...)
12
+ # so the generated SQL matches what the server understands. Objects owned by
13
+ # extensions are skipped because CREATE EXTENSION recreates them.
10
14
  class PostgresqlAdapter < BaseAdapter
11
- # Introspection methods - migrated from Introspection modules
15
+ # Schema whose objects are dumped. Extensions may live in any schema.
16
+ DUMPED_SCHEMA = 'public'
17
+
18
+ # Rewrites format_type output into the short type names used in dumps
19
+ TYPE_ALIASES = [
20
+ [/\Acharacter varying/, 'varchar'],
21
+ [/\Acharacter(?=\(|\[|\z)/, 'char'],
22
+ [/\Atimestamp(\(\d+\))? without time zone/, 'timestamp\1'],
23
+ [/\Atimestamp(\(\d+\))? with time zone/, 'timestamptz\1'],
24
+ [/\Atime(\(\d+\))? without time zone/, 'time\1']
25
+ ].freeze
12
26
 
13
27
  # Fetch all extensions from the database
14
28
  #
@@ -32,175 +46,146 @@ module BetterStructureSql
32
46
  end
33
47
  end
34
48
 
35
- # Fetch all custom types (enums, composite types, domains) from the database
49
+ # Fetch all custom types (enums, composite types, domains, ranges) from the database
36
50
  #
37
51
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
38
52
  # @return [Array<Hash>] Array of type hashes with :name, :schema, :type, and type-specific attributes
39
53
  def fetch_custom_types(connection)
40
- query = custom_types_query
41
- connection.execute(query).map { |row| build_custom_type(connection, row) }
54
+ connection.select_all(custom_types_query).map { |row| build_custom_type(connection, row) }
42
55
  end
43
56
 
44
57
  # Fetch all tables from the database
45
58
  #
46
- # Performance optimized: Batches all table metadata queries to avoid N+1 queries.
47
- # For 1000 tables: 4 queries instead of 3001 queries (~750x faster)
59
+ # Partitions are not returned at the top level: each partition is nested under
60
+ # its parent's :partitions so it is always created after the parent.
61
+ # Batches all table metadata queries to avoid N+1 queries.
48
62
  #
49
63
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
50
64
  # @return [Array<Hash>] Array of table hashes with :name, :schema, :columns, :primary_key, :constraints
51
65
  def fetch_tables(connection)
52
- # Fetch all table names first
53
- tables_query = <<~SQL.squish
54
- SELECT table_name, table_schema
55
- FROM information_schema.tables
56
- WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
57
- AND table_type = 'BASE TABLE'
58
- ORDER BY table_name
59
- SQL
60
-
61
- table_rows = connection.execute(tables_query).to_a
66
+ table_rows = connection.select_all(tables_query).to_a
62
67
  return [] if table_rows.empty?
63
68
 
64
- table_names = table_rows.pluck('table_name')
65
-
66
- # Batch fetch all columns, primary keys, and constraints
67
- columns_by_table = fetch_all_columns(connection, table_names)
68
- primary_keys_by_table = fetch_all_primary_keys(connection, table_names)
69
- constraints_by_table = fetch_all_constraints(connection, table_names)
69
+ oids = table_rows.pluck('oid')
70
+ columns = fetch_all_columns(connection, oids)
71
+ constraints = fetch_all_constraints(connection, oids)
72
+ sequences = fetch_owned_sequences(connection, oids)
70
73
 
71
- # Combine results
72
- table_rows.map do |row|
73
- table_name = row['table_name']
74
- {
75
- name: table_name,
76
- schema: row['table_schema'],
77
- columns: columns_by_table[table_name] || [],
78
- primary_key: primary_keys_by_table[table_name] || [],
79
- constraints: constraints_by_table[table_name] || []
80
- }
74
+ tables = table_rows.to_h do |row|
75
+ [row['oid'], build_table(row, columns, constraints, sequences)]
81
76
  end
77
+ nest_partitions(table_rows, tables)
82
78
  end
83
79
 
84
- # Fetch all indexes from the database
80
+ # Fetch all indexes that are not created by a constraint or a parent partitioned index
85
81
  #
86
82
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
87
83
  # @return [Array<Hash>] Array of index hashes with :schema, :table, :name, :definition
88
84
  def fetch_indexes(connection)
89
85
  query = <<~SQL.squish
90
86
  SELECT
91
- pi.schemaname,
92
- pi.tablename,
93
- pi.indexname,
94
- pi.indexdef
95
- FROM pg_indexes pi
96
- LEFT JOIN pg_matviews mv ON mv.matviewname = pi.tablename AND mv.schemaname = pi.schemaname
97
- WHERE pi.schemaname NOT IN ('pg_catalog', 'information_schema')
98
- AND mv.matviewname IS NULL
99
- ORDER BY pi.tablename, pi.indexname
87
+ n.nspname AS schemaname,
88
+ t.relname AS tablename,
89
+ ic.relname AS indexname,
90
+ ic.relkind = 'I' AS partitioned,
91
+ pg_get_indexdef(i.indexrelid) AS indexdef
92
+ FROM pg_index i
93
+ JOIN pg_class ic ON ic.oid = i.indexrelid
94
+ JOIN pg_class t ON t.oid = i.indrelid
95
+ JOIN pg_namespace n ON n.oid = t.relnamespace
96
+ WHERE n.nspname = '#{DUMPED_SCHEMA}'
97
+ AND t.relkind IN ('r', 'p')
98
+ AND NOT ic.relispartition
99
+ AND NOT EXISTS (
100
+ SELECT 1 FROM pg_constraint con
101
+ WHERE con.conindid = i.indexrelid AND con.contype IN ('p', 'u', 'x')
102
+ )
103
+ AND #{not_extension_member('t.oid')}
104
+ ORDER BY t.relname, ic.relname
100
105
  SQL
101
106
 
102
- connection.execute(query).map do |row|
107
+ connection.select_all(query).map do |row|
103
108
  {
104
109
  schema: row['schemaname'],
105
110
  table: row['tablename'],
106
111
  name: row['indexname'],
107
- definition: row['indexdef']
112
+ definition: index_definition(row)
108
113
  }
109
- end.reject { |idx| idx[:name].end_with?('_pkey') }
114
+ end
110
115
  end
111
116
 
112
117
  # Fetch all foreign keys from the database
113
118
  #
119
+ # Foreign keys cloned onto partitions are skipped; the parent's constraint recreates them.
120
+ #
114
121
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
115
- # @return [Array<Hash>] Array of foreign key hashes with :table, :name, :column, :foreign_table, :foreign_column, :on_update, :on_delete
122
+ # @return [Array<Hash>] Array of foreign key hashes with :table, :schema, :name, :definition
116
123
  def fetch_foreign_keys(connection)
117
124
  query = <<~SQL.squish
118
125
  SELECT
119
- tc.table_name,
120
- tc.constraint_name,
121
- kcu.column_name,
122
- ccu.table_name AS foreign_table_name,
123
- ccu.column_name AS foreign_column_name,
124
- rc.update_rule,
125
- rc.delete_rule
126
- FROM information_schema.table_constraints AS tc
127
- JOIN information_schema.key_column_usage AS kcu
128
- ON tc.constraint_name = kcu.constraint_name
129
- AND tc.table_schema = kcu.table_schema
130
- JOIN information_schema.constraint_column_usage AS ccu
131
- ON ccu.constraint_name = tc.constraint_name
132
- AND ccu.table_schema = tc.table_schema
133
- JOIN information_schema.referential_constraints AS rc
134
- ON rc.constraint_name = tc.constraint_name
135
- AND rc.constraint_schema = tc.table_schema
136
- WHERE tc.constraint_type = 'FOREIGN KEY'
137
- AND tc.table_schema = 'public'
138
- ORDER BY tc.table_name, tc.constraint_name
126
+ c.relname AS table_name,
127
+ n.nspname AS schema_name,
128
+ con.conname AS constraint_name,
129
+ pg_get_constraintdef(con.oid) AS definition
130
+ FROM pg_constraint con
131
+ JOIN pg_class c ON c.oid = con.conrelid
132
+ JOIN pg_namespace n ON n.oid = c.relnamespace
133
+ WHERE con.contype = 'f'
134
+ AND con.conparentid = 0
135
+ AND n.nspname = '#{DUMPED_SCHEMA}'
136
+ AND #{not_extension_member('c.oid')}
137
+ ORDER BY c.relname, con.conname
139
138
  SQL
140
139
 
141
- connection.execute(query).map do |row|
140
+ connection.select_all(query).map do |row|
142
141
  {
143
142
  table: row['table_name'],
143
+ schema: row['schema_name'],
144
144
  name: row['constraint_name'],
145
- column: row['column_name'],
146
- foreign_table: row['foreign_table_name'],
147
- foreign_column: row['foreign_column_name'],
148
- on_update: row['update_rule'],
149
- on_delete: row['delete_rule']
145
+ definition: row['definition']
150
146
  }
151
147
  end
152
148
  end
153
149
 
154
- # Fetch all views from the database
150
+ # Fetch all views from the database, ordered so dependencies come first
155
151
  #
156
152
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
157
- # @return [Array<Hash>] Array of view hashes with :schema, :name, :definition
153
+ # @return [Array<Hash>] Array of view hashes with :schema, :name, :definition, :options
158
154
  def fetch_views(connection)
159
- query = <<~SQL.squish
160
- SELECT
161
- schemaname,
162
- viewname,
163
- definition
164
- FROM pg_views
165
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
166
- ORDER BY viewname
167
- SQL
168
-
169
- connection.execute(query).map do |row|
155
+ rows = connection.select_all(relations_query('v')).map do |row|
170
156
  {
171
- schema: row['schemaname'],
172
- name: row['viewname'],
173
- definition: row['definition']
157
+ schema: row['schema_name'],
158
+ name: row['name'],
159
+ definition: row['definition'],
160
+ options: row['options']
174
161
  }
175
162
  end
163
+ order_by_dependencies(rows, fetch_relation_dependencies(connection, 'v'))
176
164
  end
177
165
 
178
- # Fetch all materialized views from the database
166
+ # Fetch all materialized views from the database, ordered so dependencies come first
179
167
  #
180
168
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
181
- # @return [Array<Hash>] Array of materialized view hashes with :schema, :name, :definition, :indexes
169
+ # @return [Array<Hash>] Array of materialized view hashes with :schema, :name, :definition, :indexes, :comment
182
170
  def fetch_materialized_views(connection)
183
- query = <<~SQL.squish
184
- SELECT
185
- schemaname,
186
- matviewname,
187
- definition
188
- FROM pg_matviews
189
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
190
- ORDER BY matviewname
191
- SQL
192
-
193
- connection.execute(query).map do |row|
171
+ indexes = fetch_materialized_view_indexes(connection)
172
+ comments = fetch_relation_comments(connection, %w[m])
173
+ rows = connection.select_all(relations_query('m')).map do |row|
194
174
  {
195
- schema: row['schemaname'],
196
- name: row['matviewname'],
175
+ schema: row['schema_name'],
176
+ name: row['name'],
197
177
  definition: row['definition'],
198
- indexes: fetch_materialized_view_indexes(connection, row['matviewname'])
178
+ indexes: indexes[row['name']],
179
+ comment: comments[row['name']]
199
180
  }
200
181
  end
182
+ order_by_dependencies(rows, fetch_relation_dependencies(connection, 'm'))
201
183
  end
202
184
 
203
- # Fetch all functions from the database
185
+ # Fetch all functions and procedures from the database
186
+ #
187
+ # Skips extension members and functions created implicitly by a type
188
+ # (e.g. range type constructors).
204
189
  #
205
190
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
206
191
  # @return [Array<Hash>] Array of function hashes with :schema, :name, :definition, :arguments, :return_type, :language, :volatility, :strict, :security_definer
@@ -219,14 +204,16 @@ module BetterStructureSql
219
204
  FROM pg_proc p
220
205
  JOIN pg_namespace n ON n.oid = p.pronamespace
221
206
  JOIN pg_language l ON l.oid = p.prolang
222
- LEFT JOIN pg_depend d ON d.objid = p.oid AND d.deptype = 'e'
223
- WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
224
- AND p.prokind = 'f'
225
- AND d.objid IS NULL
226
- ORDER BY n.nspname, p.proname
207
+ WHERE n.nspname = '#{DUMPED_SCHEMA}'
208
+ AND p.prokind IN ('f', 'p', 'w')
209
+ AND NOT EXISTS (
210
+ SELECT 1 FROM pg_depend d
211
+ WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype IN ('e', 'i')
212
+ )
213
+ ORDER BY n.nspname, p.proname, pg_get_function_identity_arguments(p.oid)
227
214
  SQL
228
215
 
229
- connection.execute(query).map do |row|
216
+ connection.select_all(query).map do |row|
230
217
  {
231
218
  schema: row['schema'],
232
219
  name: row['name'],
@@ -241,41 +228,41 @@ module BetterStructureSql
241
228
  end
242
229
  end
243
230
 
244
- # Fetch all sequences from the database
231
+ # Fetch standalone and serial sequences from the database
232
+ #
233
+ # Identity sequences are skipped: they are recreated by the identity column.
245
234
  #
246
235
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
247
- # @return [Array<Hash>] Array of sequence hashes with :name, :schema, :start_value, :increment, :min_value, :max_value, :cache_size, :cycle
236
+ # @return [Array<Hash>] Array of sequence hashes with :name, :schema, :data_type, :start_value, :increment, :min_value, :max_value, :cache_size, :cycle
248
237
  def fetch_sequences(connection)
249
238
  query = <<~SQL.squish
250
239
  SELECT
251
- sequencename,
252
- schemaname,
253
- start_value,
254
- increment_by,
255
- min_value,
256
- max_value,
257
- cache_size,
258
- cycle
259
- FROM pg_sequences
260
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
261
- ORDER BY sequencename
240
+ s.sequencename,
241
+ s.schemaname,
242
+ s.data_type::text AS data_type,
243
+ s.start_value,
244
+ s.increment_by,
245
+ s.min_value,
246
+ s.max_value,
247
+ s.cache_size,
248
+ s.cycle
249
+ FROM pg_sequences s
250
+ JOIN pg_namespace n ON n.nspname = s.schemaname
251
+ JOIN pg_class c ON c.relname = s.sequencename AND c.relnamespace = n.oid
252
+ WHERE s.schemaname = '#{DUMPED_SCHEMA}'
253
+ AND NOT EXISTS (
254
+ SELECT 1 FROM pg_depend d
255
+ WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype IN ('e', 'i')
256
+ )
257
+ ORDER BY s.sequencename
262
258
  SQL
263
259
 
264
- connection.execute(query).map do |row|
265
- {
266
- name: row['sequencename'],
267
- schema: row['schemaname'],
268
- start_value: row['start_value'],
269
- increment: row['increment_by'],
270
- min_value: row['min_value'],
271
- max_value: row['max_value'],
272
- cache_size: row['cache_size'],
273
- cycle: row['cycle']
274
- }
275
- end
260
+ connection.select_all(query).map { |row| build_sequence(row) }
276
261
  end
277
262
 
278
- # Fetch all triggers from the database
263
+ # Fetch all user triggers from the database
264
+ #
265
+ # Triggers cloned onto partitions are skipped; the parent's trigger recreates them.
279
266
  #
280
267
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
281
268
  # @return [Array<Hash>] Array of trigger hashes with :schema, :name, :table_name, :definition
@@ -290,11 +277,15 @@ module BetterStructureSql
290
277
  JOIN pg_class c ON c.oid = t.tgrelid
291
278
  JOIN pg_namespace n ON n.oid = c.relnamespace
292
279
  WHERE NOT t.tgisinternal
293
- AND n.nspname NOT IN ('pg_catalog', 'information_schema')
280
+ AND n.nspname = '#{DUMPED_SCHEMA}'
281
+ AND NOT EXISTS (
282
+ SELECT 1 FROM pg_depend d
283
+ WHERE d.classid = 'pg_trigger'::regclass AND d.objid = t.oid AND d.deptype IN ('e', 'P')
284
+ )
294
285
  ORDER BY c.relname, t.tgname
295
286
  SQL
296
287
 
297
- connection.execute(query).map do |row|
288
+ connection.select_all(query).map do |row|
298
289
  {
299
290
  schema: row['schema'],
300
291
  name: row['name'],
@@ -307,14 +298,16 @@ module BetterStructureSql
307
298
  # Fetch comments on database objects
308
299
  #
309
300
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
310
- # @return [Hash] Hash with object types as keys (:tables, :columns, :indexes, :views, :functions)
301
+ # @return [Hash] Hash with object types as keys (:tables, :columns, :indexes, :views, :functions, :procedures);
302
+ # :columns is keyed by [table_name, column_name]
311
303
  def fetch_comments(connection)
312
304
  {
313
- tables: fetch_table_comments(connection),
305
+ tables: fetch_relation_comments(connection, %w[r p]),
314
306
  columns: fetch_column_comments(connection),
315
- indexes: fetch_index_comments(connection),
316
- views: fetch_view_comments(connection),
317
- functions: fetch_function_comments(connection)
307
+ indexes: fetch_relation_comments(connection, %w[i I]),
308
+ views: fetch_relation_comments(connection, %w[v]),
309
+ functions: fetch_routine_comments(connection, %w[f w]),
310
+ procedures: fetch_routine_comments(connection, %w[p])
318
311
  }
319
312
  end
320
313
 
@@ -403,345 +396,388 @@ module BetterStructureSql
403
396
 
404
397
  private
405
398
 
406
- # Helper methods for introspection
407
-
408
- # Fetch columns for a specific table
399
+ # SQL condition excluding pg_class objects owned by an extension
409
400
  #
410
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
411
- # @param table_name [String] Name of the table
412
- # @return [Array<Hash>] Array of column hashes with :name, :type, :default, :nullable, etc.
413
- def fetch_columns(connection, table_name)
414
- query = <<~SQL.squish
415
- SELECT
416
- column_name,
417
- data_type,
418
- column_default,
419
- is_nullable,
420
- character_maximum_length,
421
- numeric_precision,
422
- numeric_scale,
423
- udt_name
424
- FROM information_schema.columns
425
- WHERE table_name = $1
426
- AND table_schema = 'public'
427
- ORDER BY ordinal_position
401
+ # @param oid_column [String] Column holding the pg_class oid
402
+ # @return [String] SQL condition
403
+ def not_extension_member(oid_column)
404
+ <<~SQL.squish
405
+ NOT EXISTS (
406
+ SELECT 1 FROM pg_depend ext
407
+ WHERE ext.classid = 'pg_class'::regclass AND ext.objid = #{oid_column} AND ext.deptype = 'e'
408
+ )
428
409
  SQL
410
+ end
429
411
 
430
- connection.select_all(
431
- query.gsub('$1', connection.quote(table_name))
432
- ).map do |row|
433
- {
434
- name: row['column_name'],
435
- type: resolve_column_type(row),
436
- default: row['column_default'],
437
- nullable: row['is_nullable'] == 'YES',
438
- length: row['character_maximum_length'],
439
- precision: row['numeric_precision'],
440
- scale: row['numeric_scale']
441
- }
442
- end
412
+ # SQL listing oids as an IN list
413
+ #
414
+ # @param oids [Array<Integer>] Object ids
415
+ # @return [String] Comma separated oids
416
+ def oid_list(oids)
417
+ oids.map { |oid| Integer(oid) }.join(', ')
443
418
  end
444
419
 
445
- # Fetch primary key columns for a specific table
420
+ # SQL query for regular and partitioned tables, with persistence, storage
421
+ # parameters (WITH (...)) and the parents of inheritance children (INHERITS)
446
422
  #
447
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
448
- # @param table_name [String] Name of the table
449
- # @return [Array<String>] Array of primary key column names
450
- def fetch_primary_key(connection, table_name)
451
- query = <<~SQL.squish
452
- SELECT a.attname as column_name
453
- FROM pg_index i
454
- JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
455
- WHERE i.indrelid = $1::regclass
456
- AND i.indisprimary
457
- ORDER BY a.attnum
423
+ # @return [String] SQL query string
424
+ def tables_query
425
+ <<~SQL.squish
426
+ SELECT
427
+ c.oid,
428
+ c.relname AS table_name,
429
+ n.nspname AS table_schema,
430
+ c.relispartition AS partition,
431
+ CASE WHEN c.relkind = 'p' THEN pg_get_partkeydef(c.oid) END AS partition_key,
432
+ pg_get_expr(c.relpartbound, c.oid) AS partition_bound,
433
+ parent.relname AS parent_name,
434
+ c.relpersistence = 'u' AS unlogged,
435
+ (
436
+ SELECT string_agg(o.option_name || '=' || CASE WHEN o.option_value ~ '^[A-Za-z0-9_.]+$'
437
+ THEN o.option_value ELSE quote_literal(o.option_value) END, ', ')
438
+ FROM pg_options_to_table(c.reloptions) o
439
+ ) AS storage_parameters,
440
+ (
441
+ SELECT json_agg(inherited.relname ORDER BY i.inhseqno)
442
+ FROM pg_inherits i
443
+ JOIN pg_class inherited ON inherited.oid = i.inhparent
444
+ WHERE i.inhrelid = c.oid AND NOT c.relispartition
445
+ ) AS inherits
446
+ FROM pg_class c
447
+ JOIN pg_namespace n ON n.oid = c.relnamespace
448
+ LEFT JOIN pg_inherits inh ON inh.inhrelid = c.oid AND c.relispartition
449
+ LEFT JOIN pg_class parent ON parent.oid = inh.inhparent
450
+ WHERE c.relkind IN ('r', 'p')
451
+ AND n.nspname = '#{DUMPED_SCHEMA}'
452
+ AND #{not_extension_member('c.oid')}
453
+ ORDER BY c.relname
458
454
  SQL
455
+ end
456
+
457
+ # Build a table hash from its row and batched metadata
458
+ #
459
+ # @param row [Hash] Row from tables_query
460
+ # @param columns [Hash<Integer, Array<Hash>>] Columns by table oid
461
+ # @param constraints [Hash<Integer, Array<Hash>>] Constraints by table oid
462
+ # @param sequences [Hash<Integer, Array<Hash>>] Owned sequences by table oid
463
+ # @return [Hash] Table metadata
464
+ def build_table(row, columns, constraints, sequences)
465
+ table_constraints = constraints[row['oid']]
466
+ primary_key = table_constraints.find { |con| con[:type] == :primary_key }
467
+ inherits = row['inherits'] ? JSON.parse(row['inherits']) : []
459
468
 
460
- result = connection.select_all(
461
- query.gsub('$1', connection.quote(table_name))
462
- )
463
- result.pluck('column_name')
469
+ {
470
+ name: row['table_name'],
471
+ schema: row['table_schema'],
472
+ columns: local_columns(columns[row['oid']], inherits),
473
+ primary_key: primary_key ? primary_key[:columns] : [],
474
+ primary_key_name: primary_key&.dig(:name),
475
+ constraints: table_constraints - [primary_key],
476
+ partition_key: row['partition_key'],
477
+ partition_of: row['parent_name'],
478
+ partition_bound: row['partition_bound'],
479
+ partitions: [],
480
+ owned_sequences: sequences[row['oid']],
481
+ unlogged: row['unlogged'],
482
+ storage_parameters: row['storage_parameters'],
483
+ inherits:
484
+ }
464
485
  end
465
486
 
466
- # Fetch constraints (CHECK, UNIQUE) for a specific table
487
+ # Columns an inheritance child defines itself; INHERITS recreates the rest
467
488
  #
468
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
469
- # @param table_name [String] Name of the table
470
- # @return [Array<Hash>] Array of constraint hashes with :name, :definition, :type
471
- def fetch_constraints(connection, table_name)
472
- query = <<~SQL.squish
473
- SELECT
474
- conname as name,
475
- pg_get_constraintdef(oid) as definition,
476
- contype as type
477
- FROM pg_constraint
478
- WHERE conrelid = $1::regclass
479
- AND contype IN ('c', 'u')
480
- ORDER BY conname
481
- SQL
489
+ # @param columns [Array<Hash>] Column hashes with :local
490
+ # @param inherits [Array<String>] Parent table names
491
+ # @return [Array<Hash>] Column hashes without :local
492
+ def local_columns(columns, inherits)
493
+ columns = columns.select { |column| column[:local] } if inherits.any?
494
+ columns.map { |column| column.except(:local) }
495
+ end
482
496
 
483
- connection.select_all(
484
- query.gsub('$1', connection.quote(table_name))
485
- ).map do |row|
486
- {
487
- name: row['name'],
488
- definition: row['definition'],
489
- type: constraint_type(row['type'])
490
- }
497
+ # Move partitions under their parent table
498
+ #
499
+ # @param table_rows [Array<Hash>] Rows from tables_query
500
+ # @param tables [Hash<Integer, Hash>] Table hashes by oid
501
+ # @return [Array<Hash>] Top-level tables
502
+ def nest_partitions(table_rows, tables)
503
+ by_name = tables.values.index_by { |table| table[:name] }
504
+ table_rows.each do |row|
505
+ by_name.fetch(row['parent_name'])[:partitions] << tables[row['oid']] if row['partition']
491
506
  end
507
+ table_rows.reject { |row| row['partition'] }.map { |row| tables[row['oid']] }
492
508
  end
493
509
 
494
- # Batch fetch all columns for multiple tables (performance optimization)
510
+ # Batch fetch all columns for multiple tables
495
511
  #
496
512
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
497
- # @param table_names [Array<String>] Array of table names
498
- # @return [Hash<String, Array<Hash>>] Hash of table_name => array of column hashes
499
- def fetch_all_columns(connection, table_names)
500
- return {} if table_names.empty?
501
-
513
+ # @param oids [Array<Integer>] Table oids
514
+ # @return [Hash<Integer, Array<Hash>>] Hash of table oid => array of column hashes
515
+ def fetch_all_columns(connection, oids)
502
516
  query = <<~SQL.squish
503
517
  SELECT
504
- table_name,
505
- column_name,
506
- data_type,
507
- column_default,
508
- is_nullable,
509
- character_maximum_length,
510
- numeric_precision,
511
- numeric_scale,
512
- udt_name,
513
- ordinal_position
514
- FROM information_schema.columns
515
- WHERE table_name IN (#{table_names.map { |t| connection.quote(t) }.join(', ')})
516
- AND table_schema = 'public'
517
- ORDER BY table_name, ordinal_position
518
+ a.attrelid AS table_oid,
519
+ a.attname AS column_name,
520
+ format_type(a.atttypid, a.atttypmod) AS data_type,
521
+ pg_get_expr(ad.adbin, ad.adrelid) AS expression,
522
+ NOT a.attnotnull AS nullable,
523
+ a.attidentity AS identity,
524
+ a.attgenerated AS generated,
525
+ a.attislocal AS local,
526
+ CASE WHEN a.attcollation <> t.typcollation THEN quote_ident(co.collname) END AS collation,
527
+ seq.seqstart, seq.seqincrement, seq.seqmin, seq.seqmax, seq.seqcache, seq.seqcycle
528
+ FROM pg_attribute a
529
+ JOIN pg_type t ON t.oid = a.atttypid
530
+ LEFT JOIN pg_collation co ON co.oid = a.attcollation
531
+ LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
532
+ LEFT JOIN pg_depend dep ON dep.refobjid = a.attrelid AND dep.refobjsubid = a.attnum
533
+ AND dep.classid = 'pg_class'::regclass AND dep.deptype = 'i' AND a.attidentity <> ''
534
+ LEFT JOIN pg_sequence seq ON seq.seqrelid = dep.objid
535
+ WHERE a.attrelid IN (#{oid_list(oids)})
536
+ AND a.attnum > 0
537
+ AND NOT a.attisdropped
538
+ ORDER BY a.attrelid, a.attnum
518
539
  SQL
519
540
 
520
- result = Hash.new { |h, k| h[k] = [] }
521
-
541
+ result = Hash.new { |hash, key| hash[key] = [] }
522
542
  connection.select_all(query).each do |row|
523
- result[row['table_name']] << {
524
- name: row['column_name'],
525
- type: resolve_column_type(row),
526
- default: row['column_default'],
527
- nullable: row['is_nullable'] == 'YES',
528
- length: row['character_maximum_length'],
529
- precision: row['numeric_precision'],
530
- scale: row['numeric_scale']
531
- }
543
+ result[row['table_oid']] << build_column(row)
532
544
  end
533
-
534
545
  result
535
546
  end
536
547
 
537
- # Batch fetch all primary keys for multiple tables (performance optimization)
548
+ # Build a column hash from a column row
538
549
  #
539
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
540
- # @param table_names [Array<String>] Array of table names
541
- # @return [Hash<String, Array<String>>] Hash of table_name => array of primary key column names
542
- def fetch_all_primary_keys(connection, table_names)
543
- return {} if table_names.empty?
544
-
545
- query = <<~SQL.squish
546
- SELECT
547
- c.relname as table_name,
548
- a.attname as column_name,
549
- a.attnum as column_position
550
- FROM pg_index i
551
- JOIN pg_class c ON c.oid = i.indrelid
552
- JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
553
- JOIN pg_namespace n ON n.oid = c.relnamespace
554
- WHERE i.indisprimary
555
- AND n.nspname = 'public'
556
- AND c.relname IN (#{table_names.map { |t| connection.quote(t) }.join(', ')})
557
- ORDER BY c.relname, a.attnum
558
- SQL
559
-
560
- result = Hash.new { |h, k| h[k] = [] }
550
+ # @param row [Hash] Row from fetch_all_columns
551
+ # @return [Hash] Column metadata
552
+ def build_column(row)
553
+ generated = row['generated'].presence
554
+ {
555
+ name: row['column_name'],
556
+ type: normalize_type(row['data_type']),
557
+ default: generated ? nil : row['expression'],
558
+ nullable: row['nullable'],
559
+ collation: row['collation'],
560
+ generated: generated && { expression: row['expression'], kind: generated == 's' ? 'STORED' : 'VIRTUAL' },
561
+ identity: row['identity'].presence && build_identity(row),
562
+ local: row['local']
563
+ }
564
+ end
561
565
 
562
- connection.select_all(query).each do |row|
563
- result[row['table_name']] << row['column_name']
564
- end
566
+ # Build identity column metadata
567
+ #
568
+ # @param row [Hash] Row from fetch_all_columns
569
+ # @return [Hash] Identity metadata with :generation and sequence options
570
+ def build_identity(row)
571
+ {
572
+ generation: row['identity'] == 'a' ? 'ALWAYS' : 'BY DEFAULT',
573
+ start_value: row['seqstart'],
574
+ increment: row['seqincrement'],
575
+ min_value: row['seqmin'],
576
+ max_value: row['seqmax'],
577
+ cache_size: row['seqcache'],
578
+ cycle: row['seqcycle']
579
+ }
580
+ end
565
581
 
566
- result
582
+ # Shorten format_type output to the type names used in dumps
583
+ #
584
+ # @param type [String] format_type output (e.g. "character varying(255)[]")
585
+ # @return [String] Normalized type (e.g. "varchar(255)[]")
586
+ def normalize_type(type)
587
+ TYPE_ALIASES.reduce(type) { |result, (pattern, replacement)| result.sub(pattern, replacement) }
567
588
  end
568
589
 
569
- # Batch fetch all constraints for multiple tables (performance optimization)
590
+ # Batch fetch primary key, unique, check and exclusion constraints
591
+ #
592
+ # Constraints a partition or an inheritance child inherits from its parent are skipped.
570
593
  #
571
594
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
572
- # @param table_names [Array<String>] Array of table names
573
- # @return [Hash<String, Array<Hash>>] Hash of table_name => array of constraint hashes
574
- def fetch_all_constraints(connection, table_names)
575
- return {} if table_names.empty?
576
-
595
+ # @param oids [Array<Integer>] Table oids
596
+ # @return [Hash<Integer, Array<Hash>>] Hash of table oid => array of constraint hashes
597
+ def fetch_all_constraints(connection, oids)
577
598
  query = <<~SQL.squish
578
599
  SELECT
579
- c.relname as table_name,
580
- con.conname as name,
581
- pg_get_constraintdef(con.oid) as definition,
582
- con.contype as type
600
+ con.conrelid AS table_oid,
601
+ con.conname AS name,
602
+ pg_get_constraintdef(con.oid) AS definition,
603
+ con.contype AS type,
604
+ con.convalidated AS validated,
605
+ (
606
+ SELECT json_agg(a.attname ORDER BY k.position)
607
+ FROM unnest(con.conkey) WITH ORDINALITY AS k(attnum, position)
608
+ JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum
609
+ ) AS columns
583
610
  FROM pg_constraint con
584
- JOIN pg_class c ON c.oid = con.conrelid
585
- JOIN pg_namespace n ON n.oid = c.relnamespace
586
- WHERE con.contype IN ('c', 'u')
587
- AND n.nspname = 'public'
588
- AND c.relname IN (#{table_names.map { |t| connection.quote(t) }.join(', ')})
589
- ORDER BY c.relname, con.conname
611
+ JOIN pg_class rel ON rel.oid = con.conrelid
612
+ WHERE con.conrelid IN (#{oid_list(oids)})
613
+ AND con.contype IN ('p', 'u', 'c', 'x')
614
+ AND con.conparentid = 0
615
+ AND con.conislocal
616
+ AND (NOT rel.relispartition OR con.coninhcount = 0)
617
+ ORDER BY con.conrelid, con.conname
590
618
  SQL
591
619
 
592
- result = Hash.new { |h, k| h[k] = [] }
593
-
620
+ result = Hash.new { |hash, key| hash[key] = [] }
594
621
  connection.select_all(query).each do |row|
595
- result[row['table_name']] << {
622
+ result[row['table_oid']] << {
596
623
  name: row['name'],
597
624
  definition: row['definition'],
598
- type: constraint_type(row['type'])
625
+ type: constraint_type(row['type']),
626
+ validated: row['validated'],
627
+ columns: row['columns'] ? JSON.parse(row['columns']) : []
599
628
  }
600
629
  end
601
-
602
630
  result
603
631
  end
604
632
 
605
- # Fetch enum values for a specific enum type
633
+ # Batch fetch serial sequences owned by table columns (OWNED BY)
606
634
  #
607
635
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
608
- # @param type_name [String] Name of the enum type
609
- # @return [Array<String>] Array of enum values in sort order
610
- def fetch_enum_values(connection, type_name)
636
+ # @param oids [Array<Integer>] Table oids
637
+ # @return [Hash<Integer, Array<Hash>>] Hash of table oid => array of :sequence, :column hashes
638
+ def fetch_owned_sequences(connection, oids)
611
639
  query = <<~SQL.squish
612
- SELECT e.enumlabel
613
- FROM pg_enum e
614
- JOIN pg_type t ON t.oid = e.enumtypid
615
- WHERE t.typname = $1
616
- ORDER BY e.enumsortorder
640
+ SELECT dep.refobjid AS table_oid, s.relname AS sequence_name, a.attname AS column_name
641
+ FROM pg_depend dep
642
+ JOIN pg_class s ON s.oid = dep.objid AND s.relkind = 'S'
643
+ JOIN pg_attribute a ON a.attrelid = dep.refobjid AND a.attnum = dep.refobjsubid
644
+ WHERE dep.classid = 'pg_class'::regclass
645
+ AND dep.refclassid = 'pg_class'::regclass
646
+ AND dep.deptype = 'a'
647
+ AND dep.refobjid IN (#{oid_list(oids)})
648
+ ORDER BY s.relname
617
649
  SQL
618
650
 
619
- connection.select_all(
620
- query.gsub('$1', connection.quote(type_name))
621
- ).pluck('enumlabel')
651
+ result = Hash.new { |hash, key| hash[key] = [] }
652
+ connection.select_all(query).each do |row|
653
+ result[row['table_oid']] << { sequence: row['sequence_name'], column: row['column_name'] }
654
+ end
655
+ result
622
656
  end
623
657
 
624
- # Fetch attributes for a composite type
658
+ # Build a sequence hash from a pg_sequences row
625
659
  #
626
- # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
627
- # @param type_name [String] Name of the composite type
628
- # @return [Array<Hash>] Array of attribute hashes with :name, :type
629
- def fetch_composite_attributes(connection, type_name)
630
- query = <<~SQL.squish
660
+ # @param row [Hash] Row from fetch_sequences
661
+ # @return [Hash] Sequence metadata
662
+ def build_sequence(row)
663
+ {
664
+ name: row['sequencename'],
665
+ schema: row['schemaname'],
666
+ data_type: row['data_type'],
667
+ start_value: row['start_value'],
668
+ increment: row['increment_by'],
669
+ min_value: row['min_value'],
670
+ max_value: row['max_value'],
671
+ cache_size: row['cache_size'],
672
+ cycle: row['cycle']
673
+ }
674
+ end
675
+
676
+ # Render an index definition that recreates the index on every partition
677
+ #
678
+ # pg_get_indexdef renders indexes on partitioned tables as "ON ONLY", which
679
+ # creates an invalid index until each partition index is attached.
680
+ #
681
+ # @param row [Hash] Row from fetch_indexes
682
+ # @return [String] CREATE INDEX statement
683
+ def index_definition(row)
684
+ return row['indexdef'] unless row['partitioned']
685
+
686
+ row['indexdef'].sub(' ON ONLY ', ' ON ')
687
+ end
688
+
689
+ # SQL query for views or materialized views
690
+ #
691
+ # @param relkind [String] 'v' for views, 'm' for materialized views
692
+ # @return [String] SQL query string
693
+ def relations_query(relkind)
694
+ <<~SQL.squish
631
695
  SELECT
632
- a.attname as name,
633
- format_type(a.atttypid, a.atttypmod) as type
634
- FROM pg_attribute a
635
- JOIN pg_type t ON t.typrelid = a.attrelid
636
- WHERE t.typname = $1
637
- AND a.attnum > 0
638
- AND NOT a.attisdropped
639
- ORDER BY a.attnum
696
+ n.nspname AS schema_name,
697
+ c.relname AS name,
698
+ pg_get_viewdef(c.oid) AS definition,
699
+ array_to_string(c.reloptions, ', ') AS options
700
+ FROM pg_class c
701
+ JOIN pg_namespace n ON n.oid = c.relnamespace
702
+ WHERE c.relkind = '#{relkind}'
703
+ AND n.nspname = '#{DUMPED_SCHEMA}'
704
+ AND #{not_extension_member('c.oid')}
705
+ ORDER BY c.relname
640
706
  SQL
641
-
642
- connection.select_all(
643
- query.gsub('$1', connection.quote(type_name))
644
- ).map do |row|
645
- { name: row['name'], type: row['type'] }
646
- end
647
707
  end
648
708
 
649
- # Fetch details for a domain type
709
+ # Fetch which views (or materialized views) reference each other
650
710
  #
651
711
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
652
- # @param type_name [String] Name of the domain type
653
- # @return [Hash] Domain details with :base_type, :constraint
654
- def fetch_domain_details(connection, type_name)
712
+ # @param relkind [String] 'v' for views, 'm' for materialized views
713
+ # @return [Hash<String, Array<String>>] Hash of relation name => names it depends on
714
+ def fetch_relation_dependencies(connection, relkind)
655
715
  query = <<~SQL.squish
656
- SELECT
657
- format_type(t.typbasetype, t.typtypmod) as base_type,
658
- pg_get_constraintdef(c.oid) as constraint
659
- FROM pg_type t
660
- LEFT JOIN pg_constraint c ON c.contypid = t.oid
661
- WHERE t.typname = $1
716
+ SELECT DISTINCT dependent.relname AS name, referenced.relname AS depends_on
717
+ FROM pg_depend d
718
+ JOIN pg_rewrite r ON r.oid = d.objid
719
+ JOIN pg_class dependent ON dependent.oid = r.ev_class
720
+ JOIN pg_class referenced ON referenced.oid = d.refobjid
721
+ JOIN pg_namespace n ON n.oid = dependent.relnamespace
722
+ WHERE d.classid = 'pg_rewrite'::regclass
723
+ AND d.refclassid = 'pg_class'::regclass
724
+ AND dependent.oid <> referenced.oid
725
+ AND dependent.relkind = '#{relkind}'
726
+ AND referenced.relkind = '#{relkind}'
727
+ AND n.nspname = '#{DUMPED_SCHEMA}'
728
+ ORDER BY 1, 2
662
729
  SQL
663
730
 
664
- result = connection.select_all(
665
- query.gsub('$1', connection.quote(type_name))
666
- ).first
667
- {
668
- base_type: result['base_type'],
669
- constraint: result['constraint']
670
- }
731
+ connection.select_all(query).each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |row, deps|
732
+ deps[row['name']] << row['depends_on']
733
+ end
671
734
  end
672
735
 
673
- # Fetch indexes for a materialized view
736
+ # Fetch indexes for all materialized views
674
737
  #
675
738
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
676
- # @param matview_name [String] Name of the materialized view
677
- # @return [Array<String>] Array of index definition SQL strings
678
- def fetch_materialized_view_indexes(connection, matview_name)
739
+ # @return [Hash<String, Array<String>>] Hash of materialized view name => index definitions
740
+ def fetch_materialized_view_indexes(connection)
679
741
  query = <<~SQL.squish
680
- SELECT indexdef
681
- FROM pg_indexes
682
- WHERE tablename = $1
683
- ORDER BY indexname
742
+ SELECT t.relname AS matview_name, pg_get_indexdef(i.indexrelid) AS indexdef
743
+ FROM pg_index i
744
+ JOIN pg_class ic ON ic.oid = i.indexrelid
745
+ JOIN pg_class t ON t.oid = i.indrelid
746
+ JOIN pg_namespace n ON n.oid = t.relnamespace
747
+ WHERE t.relkind = 'm'
748
+ AND n.nspname = '#{DUMPED_SCHEMA}'
749
+ ORDER BY t.relname, ic.relname
684
750
  SQL
685
751
 
686
- connection.select_all(
687
- query.gsub('$1', connection.quote(matview_name))
688
- ).pluck('indexdef')
689
- end
690
-
691
- # Resolve PostgreSQL column type into normalized format
692
- #
693
- # @param row [Hash] Column information row from information_schema.columns
694
- # @return [String] Normalized column type with length/precision if applicable
695
- def resolve_column_type(row)
696
- case row['data_type']
697
- when 'ARRAY'
698
- # For arrays, udt_name contains the base type with leading underscore (e.g., _varchar)
699
- base_type = row['udt_name'].sub(/^_/, '')
700
- "#{base_type}[]"
701
- when 'character varying'
702
- row['character_maximum_length'] ? "varchar(#{row['character_maximum_length']})" : 'varchar'
703
- when 'character'
704
- row['character_maximum_length'] ? "char(#{row['character_maximum_length']})" : 'char'
705
- when 'numeric'
706
- if row['numeric_precision'] && row['numeric_scale']
707
- "numeric(#{row['numeric_precision']},#{row['numeric_scale']})"
708
- else
709
- 'numeric'
710
- end
711
- when 'timestamp without time zone'
712
- 'timestamp'
713
- when 'timestamp with time zone'
714
- 'timestamptz'
715
- when 'time without time zone'
716
- 'time'
717
- when 'USER-DEFINED'
718
- row['udt_name']
719
- else
720
- row['data_type']
752
+ connection.select_all(query).each_with_object(Hash.new { |hash, key| hash[key] = [] }) do |row, indexes|
753
+ indexes[row['matview_name']] << row['indexdef']
721
754
  end
722
755
  end
723
756
 
724
757
  # Convert PostgreSQL constraint type code to symbol
725
758
  #
726
- # @param type_code [String] PostgreSQL constraint type code ('c' = check, 'u' = unique)
727
- # @return [Symbol] Constraint type (:check, :unique, :unknown)
759
+ # @param type_code [String] PostgreSQL constraint type code
760
+ # @return [Symbol] Constraint type (:primary_key, :unique, :check, :exclusion, :unknown)
728
761
  def constraint_type(type_code)
729
762
  case type_code
730
- when 'c' then :check
763
+ when 'p' then :primary_key
731
764
  when 'u' then :unique
765
+ when 'c' then :check
766
+ when 'x' then :exclusion
732
767
  else :unknown
733
768
  end
734
769
  end
735
770
 
736
771
  # Convert PostgreSQL type code to category string
737
772
  #
738
- # @param type_code [String] PostgreSQL type code ('e' = enum, 'c' = composite, 'd' = domain)
739
- # @return [String] Type category ('enum', 'composite', 'domain', 'unknown')
773
+ # @param type_code [String] PostgreSQL type code ('e' = enum, 'c' = composite, 'd' = domain, 'r' = range)
774
+ # @return [String] Type category ('enum', 'composite', 'domain', 'range', 'unknown')
740
775
  def type_category(type_code)
741
776
  case type_code
742
777
  when 'e' then 'enum'
743
778
  when 'c' then 'composite'
744
779
  when 'd' then 'domain'
780
+ when 'r' then 'range'
745
781
  else 'unknown'
746
782
  end
747
783
  end
@@ -761,19 +797,27 @@ module BetterStructureSql
761
797
 
762
798
  # SQL query for fetching custom types
763
799
  #
800
+ # Composite types backing tables, views and other relations are skipped,
801
+ # as are types owned by extensions.
802
+ #
764
803
  # @return [String] SQL query string
765
804
  def custom_types_query
766
805
  <<~SQL.squish
767
806
  SELECT
807
+ t.oid,
768
808
  t.typname as name,
769
809
  t.typtype as type,
770
810
  n.nspname as schema
771
811
  FROM pg_type t
772
812
  JOIN pg_namespace n ON n.oid = t.typnamespace
773
- LEFT JOIN pg_class c ON c.reltype = t.oid AND c.relkind IN ('r', 'v', 'm')
774
- WHERE t.typtype IN ('e', 'c', 'd')
775
- AND n.nspname NOT IN ('pg_catalog', 'information_schema')
776
- AND c.oid IS NULL
813
+ LEFT JOIN pg_class c ON c.oid = t.typrelid
814
+ WHERE t.typtype IN ('e', 'c', 'd', 'r')
815
+ AND n.nspname = '#{DUMPED_SCHEMA}'
816
+ AND (t.typrelid = 0 OR c.relkind = 'c')
817
+ AND NOT EXISTS (
818
+ SELECT 1 FROM pg_depend d
819
+ WHERE d.classid = 'pg_type'::regclass AND d.objid = t.oid AND d.deptype = 'e'
820
+ )
777
821
  ORDER BY t.typname
778
822
  SQL
779
823
  end
@@ -785,145 +829,197 @@ module BetterStructureSql
785
829
  # @return [Hash] Type hash with name, schema, type, and type-specific attributes
786
830
  def build_custom_type(connection, row)
787
831
  type_data = {
788
- name: row['schema'] == 'public' ? row['name'] : "#{row['schema']}.#{row['name']}",
832
+ name: row['name'],
789
833
  schema: row['schema'],
790
834
  type: type_category(row['type'])
791
835
  }
792
836
 
793
837
  case row['type']
794
838
  when 'e'
795
- type_data[:values] = fetch_enum_values(connection, row['name'])
839
+ type_data[:values] = fetch_enum_values(connection, row['oid'])
796
840
  when 'c'
797
- type_data[:attributes] = fetch_composite_attributes(connection, row['name'])
841
+ type_data[:attributes] = fetch_composite_attributes(connection, row['oid'])
798
842
  when 'd'
799
- type_data.merge!(fetch_domain_details(connection, row['name']))
843
+ type_data.merge!(fetch_domain_details(connection, row['oid']))
844
+ when 'r'
845
+ type_data.merge!(fetch_range_details(connection, row['oid']))
800
846
  end
801
847
 
802
848
  type_data
803
849
  end
804
850
 
805
- # Fetch comments on tables
851
+ # Fetch enum values for an enum type
806
852
  #
807
853
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
808
- # @return [Hash<String, String>] Hash of table_name => comment
809
- def fetch_table_comments(connection)
854
+ # @param type_oid [Integer] Enum type oid
855
+ # @return [Array<String>] Array of enum values in sort order
856
+ def fetch_enum_values(connection, type_oid)
810
857
  query = <<~SQL.squish
811
- SELECT
812
- c.relname as table_name,
813
- d.description as comment
814
- FROM pg_class c
815
- JOIN pg_namespace n ON n.oid = c.relnamespace
816
- JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = 0
817
- WHERE c.relkind = 'r'
818
- AND n.nspname NOT IN ('pg_catalog', 'information_schema')
819
- ORDER BY c.relname
858
+ SELECT enumlabel FROM pg_enum WHERE enumtypid = #{Integer(type_oid)} ORDER BY enumsortorder
820
859
  SQL
821
860
 
822
- result = {}
823
- connection.execute(query).each do |row|
824
- result[row['table_name']] = row['comment']
825
- end
826
- result
861
+ connection.select_all(query).pluck('enumlabel')
827
862
  end
828
863
 
829
- # Fetch comments on columns
864
+ # Fetch attributes for a composite type
830
865
  #
831
866
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
832
- # @return [Hash<String, String>] Hash of "table_name.column_name" => comment
833
- def fetch_column_comments(connection)
867
+ # @param type_oid [Integer] Composite type oid
868
+ # @return [Array<Hash>] Array of attribute hashes with :name, :type
869
+ def fetch_composite_attributes(connection, type_oid)
834
870
  query = <<~SQL.squish
835
- SELECT
836
- c.relname as table_name,
837
- a.attname as column_name,
838
- d.description as comment
839
- FROM pg_class c
840
- JOIN pg_namespace n ON n.oid = c.relnamespace
841
- JOIN pg_attribute a ON a.attrelid = c.oid
842
- JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = a.attnum
843
- WHERE c.relkind = 'r'
844
- AND n.nspname NOT IN ('pg_catalog', 'information_schema')
871
+ SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type
872
+ FROM pg_attribute a
873
+ JOIN pg_type t ON t.typrelid = a.attrelid
874
+ WHERE t.oid = #{Integer(type_oid)}
845
875
  AND a.attnum > 0
846
876
  AND NOT a.attisdropped
847
- ORDER BY c.relname, a.attnum
877
+ ORDER BY a.attnum
848
878
  SQL
849
879
 
850
- result = {}
851
- connection.execute(query).each do |row|
852
- key = "#{row['table_name']}.#{row['column_name']}"
853
- result[key] = row['comment']
880
+ connection.select_all(query).map do |row|
881
+ { name: row['name'], type: row['type'] }
854
882
  end
855
- result
856
883
  end
857
884
 
858
- # Fetch comments on indexes
885
+ # Fetch details for a domain type
859
886
  #
860
887
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
861
- # @return [Hash<String, String>] Hash of index_name => comment
862
- def fetch_index_comments(connection)
888
+ # @param type_oid [Integer] Domain type oid
889
+ # @return [Hash] Domain details with :base_type, :default, :not_null, :constraints
890
+ def fetch_domain_details(connection, type_oid)
863
891
  query = <<~SQL.squish
864
892
  SELECT
865
- c.relname as index_name,
866
- d.description as comment
893
+ format_type(t.typbasetype, t.typtypmod) AS base_type,
894
+ t.typdefault AS default_value,
895
+ t.typnotnull AS not_null
896
+ FROM pg_type t
897
+ WHERE t.oid = #{Integer(type_oid)}
898
+ SQL
899
+
900
+ row = connection.select_all(query).first
901
+ {
902
+ base_type: row['base_type'],
903
+ default: row['default_value'],
904
+ not_null: row['not_null'],
905
+ constraints: fetch_domain_constraints(connection, type_oid)
906
+ }
907
+ end
908
+
909
+ # Fetch CHECK constraints of a domain
910
+ #
911
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
912
+ # @param type_oid [Integer] Domain type oid
913
+ # @return [Array<Hash>] Array of constraint hashes with :name, :definition
914
+ def fetch_domain_constraints(connection, type_oid)
915
+ query = <<~SQL.squish
916
+ SELECT conname AS name, pg_get_constraintdef(oid) AS definition
917
+ FROM pg_constraint
918
+ WHERE contypid = #{Integer(type_oid)} AND contype = 'c'
919
+ ORDER BY conname
920
+ SQL
921
+
922
+ connection.select_all(query).map do |row|
923
+ { name: row['name'], definition: row['definition'] }
924
+ end
925
+ end
926
+
927
+ # Fetch details for a range type
928
+ #
929
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
930
+ # @param type_oid [Integer] Range type oid
931
+ # @return [Hash] Range details with :subtype, :subtype_opclass, :collation, :canonical, :subtype_diff
932
+ def fetch_range_details(connection, type_oid)
933
+ query = <<~SQL.squish
934
+ SELECT
935
+ format_type(r.rngsubtype, NULL) AS subtype,
936
+ CASE WHEN NOT opc.opcdefault THEN quote_ident(opc.opcname) END AS subtype_opclass,
937
+ CASE WHEN r.rngcollation <> st.typcollation THEN quote_ident(co.collname) END AS collation,
938
+ NULLIF(r.rngcanonical, 0)::regproc::text AS canonical,
939
+ NULLIF(r.rngsubdiff, 0)::regproc::text AS subtype_diff
940
+ FROM pg_range r
941
+ JOIN pg_type st ON st.oid = r.rngsubtype
942
+ JOIN pg_opclass opc ON opc.oid = r.rngsubopc
943
+ LEFT JOIN pg_collation co ON co.oid = r.rngcollation
944
+ WHERE r.rngtypid = #{Integer(type_oid)}
945
+ SQL
946
+
947
+ connection.select_all(query).first.symbolize_keys
948
+ end
949
+
950
+ # Fetch comments on relations of the given kinds
951
+ #
952
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
953
+ # @param relkinds [Array<String>] pg_class relkind codes
954
+ # @return [Hash<String, String>] Hash of relation name => comment
955
+ def fetch_relation_comments(connection, relkinds)
956
+ query = <<~SQL.squish
957
+ SELECT c.relname AS name, d.description AS comment
867
958
  FROM pg_class c
868
959
  JOIN pg_namespace n ON n.oid = c.relnamespace
869
- JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = 0
870
- WHERE c.relkind = 'i'
871
- AND n.nspname NOT IN ('pg_catalog', 'information_schema')
960
+ JOIN pg_description d ON d.objoid = c.oid AND d.classoid = 'pg_class'::regclass AND d.objsubid = 0
961
+ WHERE c.relkind IN (#{relkinds.map { |kind| "'#{kind}'" }.join(', ')})
962
+ AND n.nspname = '#{DUMPED_SCHEMA}'
963
+ AND #{not_extension_member('c.oid')}
872
964
  ORDER BY c.relname
873
965
  SQL
874
966
 
875
- result = {}
876
- connection.execute(query).each do |row|
877
- result[row['index_name']] = row['comment']
878
- end
879
- result
967
+ connection.select_all(query).to_h { |row| [row['name'], row['comment']] }
880
968
  end
881
969
 
882
- # Fetch comments on views
970
+ # Fetch comments on table and view columns
883
971
  #
884
972
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
885
- # @return [Hash<String, String>] Hash of view_name => comment
886
- def fetch_view_comments(connection)
973
+ # @return [Hash<Array(String, String), String>] Hash of [table_name, column_name] => comment
974
+ def fetch_column_comments(connection)
887
975
  query = <<~SQL.squish
888
976
  SELECT
889
- c.relname as view_name,
977
+ c.relname as table_name,
978
+ a.attname as column_name,
890
979
  d.description as comment
891
980
  FROM pg_class c
892
981
  JOIN pg_namespace n ON n.oid = c.relnamespace
893
- JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = 0
894
- WHERE c.relkind = 'v'
895
- AND n.nspname NOT IN ('pg_catalog', 'information_schema')
896
- ORDER BY c.relname
982
+ JOIN pg_attribute a ON a.attrelid = c.oid
983
+ JOIN pg_description d ON d.objoid = c.oid AND d.classoid = 'pg_class'::regclass AND d.objsubid = a.attnum
984
+ WHERE c.relkind IN ('r', 'p', 'v', 'm')
985
+ AND n.nspname = '#{DUMPED_SCHEMA}'
986
+ AND a.attnum > 0
987
+ AND NOT a.attisdropped
988
+ AND #{not_extension_member('c.oid')}
989
+ ORDER BY c.relname, a.attnum
897
990
  SQL
898
991
 
899
- result = {}
900
- connection.execute(query).each do |row|
901
- result[row['view_name']] = row['comment']
992
+ connection.select_all(query).to_h do |row|
993
+ [[row['table_name'], row['column_name']], row['comment']]
902
994
  end
903
- result
904
995
  end
905
996
 
906
- # Fetch comments on functions
997
+ # Fetch comments on functions or procedures
998
+ #
999
+ # Keys are full signatures (e.g. "add(integer, integer)") so overloads keep
1000
+ # their own comment and the COMMENT ON statement is unambiguous.
907
1001
  #
908
1002
  # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Database connection
909
- # @return [Hash<String, String>] Hash of function_name => comment
910
- def fetch_function_comments(connection)
1003
+ # @param prokinds [Array<String>] pg_proc prokind codes ('f' function, 'w' window, 'p' procedure)
1004
+ # @return [Hash<String, String>] Hash of routine signature => comment
1005
+ def fetch_routine_comments(connection, prokinds)
911
1006
  query = <<~SQL.squish
912
1007
  SELECT
913
- p.proname as function_name,
914
- d.description as comment
1008
+ format('%I(%s)', p.proname, pg_get_function_identity_arguments(p.oid)) AS signature,
1009
+ d.description AS comment
915
1010
  FROM pg_proc p
916
1011
  JOIN pg_namespace n ON n.oid = p.pronamespace
917
- JOIN pg_description d ON d.objoid = p.oid
918
- WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
919
- ORDER BY p.proname
1012
+ JOIN pg_description d ON d.objoid = p.oid AND d.classoid = 'pg_proc'::regclass
1013
+ WHERE n.nspname = '#{DUMPED_SCHEMA}'
1014
+ AND p.prokind IN (#{prokinds.map { |kind| connection.quote(kind) }.join(', ')})
1015
+ AND NOT EXISTS (
1016
+ SELECT 1 FROM pg_depend dep
1017
+ WHERE dep.classid = 'pg_proc'::regclass AND dep.objid = p.oid AND dep.deptype = 'e'
1018
+ )
1019
+ ORDER BY 1
920
1020
  SQL
921
1021
 
922
- result = {}
923
- connection.execute(query).each do |row|
924
- result[row['function_name']] = row['comment']
925
- end
926
- result
1022
+ connection.select_all(query).to_h { |row| [row['signature'], row['comment']] }
927
1023
  end
928
1024
  end
929
1025
  end