Skip to content

Commit

Permalink
dump inherited table options to schema.rb
Browse files Browse the repository at this point in the history
  • Loading branch information
waymondo committed Jan 11, 2024
1 parent 7575d55 commit 51f5850
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/hoardable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require "fx"
require_relative "hoardable/version"
require_relative "hoardable/arel_visitors"
require_relative "hoardable/schema_statements"
require_relative "hoardable/engine"
require_relative "hoardable/finder_methods"
require_relative "hoardable/scopes"
Expand Down
6 changes: 6 additions & 0 deletions lib/hoardable/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,11 @@ class Engine < ::Rails::Engine
require_relative "encrypted_rich_text" if SUPPORTS_ENCRYPTED_ACTION_TEXT
end
end

initializer "hoardable.schema_statements" do
ActiveSupport.on_load(:active_record_postgresqladapter) do
ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaStatements.prepend(SchemaStatements)
end
end
end
end
26 changes: 26 additions & 0 deletions lib/hoardable/schema_statements.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module Hoardable
module SchemaStatements
def table_options(table_name)
options = super || {}
if inherited_table_names = parent_table_names(table_name)
options[:options] = "INHERITS (#{inherited_table_names.join(", ")})"
end
options
end

private def parent_table_names(table_name)
scope = quoted_scope(table_name, type: "BASE TABLE")

query_values(<<~SQL.presence, "SCHEMA")
SELECT parent.relname
FROM pg_catalog.pg_inherits i
JOIN pg_catalog.pg_class child ON i.inhrelid = child.oid
JOIN pg_catalog.pg_class parent ON i.inhparent = parent.oid
LEFT JOIN pg_namespace n ON n.oid = child.relnamespace
WHERE child.relname = #{scope[:name]}
AND child.relkind IN (#{scope[:type]})
AND n.nspname = #{scope[:schema]}
SQL
end
end
end
18 changes: 18 additions & 0 deletions test/test_schema_statements.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# frozen_string_literal: true

require "helper"

class TestSchemaStatements < ActiveSupport::TestCase
test "it dumps table inheritance options to schema.rb" do
connection = ActiveRecord::Base.connection
ActiveRecord::SchemaDumper.ignore_tables = connection.data_sources - ["post_versions"]
stream = StringIO.new
output = ActiveRecord::SchemaDumper.dump(connection, stream).string
assert_match(<<~SCHEMA.squish, output)
create_table \"post_versions\",
id: :bigint,
default: -> { \"nextval('posts_id_seq'::regclass)\" },
options: \"INHERITS (posts)\"
SCHEMA
end
end

0 comments on commit 51f5850

Please sign in to comment.