Created
July 2, 2016 12:43
-
-
Save samsondav/3050c462c77775e39651805bd2d35154 to your computer and use it in GitHub Desktop.
Rails read Postgres database column comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# A tiny class for reading column database comments | |
class DatabaseComment | |
DATABASE_NAME = Rails.configuration.database_configuration[Rails.env]['database'].freeze | |
# Reads back a postgres comment based on table_name and column_name | |
# Sanitizes inputs but it would be better not to allow user input strings here regardless | |
def self.read(table_name, column_name) | |
unless table_name.is_a?(Symbol) && column_name.is_a?(Symbol) | |
raise TypeError, <<~STERN_WARNING | |
Table and column names must be symbols. | |
If you are trying to pass strings input by a user, well, please don't do that." | |
STERN_WARNING | |
end | |
quoted_table_name = ActiveRecord::Base.connection.quote_table_name(table_name) | |
table_name = ActiveRecord::Base.connection.quote(table_name) | |
column_name = ActiveRecord::Base.connection.quote(column_name) | |
select_comment = <<~SQL | |
SELECT col_description( | |
(select distinct tableoid from #{quoted_table_name}), | |
(SELECT ordinal_position | |
FROM information_schema.columns | |
WHERE table_catalog = 'progolfme_development' | |
AND column_name = #{column_name} | |
AND table_name = #{table_name}) | |
) | |
SQL | |
ActiveRecord::Base.connection.execute(select_comment).to_a.dig(0, 'col_description') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires Ruby >= 2.3 unless you remove the squiggly heredocs.