I would like to add comments on objects such as database itself, tables, etc while using rake. For example, when I issue rake db:create
I'd like to automagically add a comment via PostgreSQL extended SQL statement (if the adapter doesn't support this directly), like
COMMENT ON DATABASE myapp_development IS 'Rails DB for project at c:/some/path/myapp/';
I'd like a similar behavior for ActiveRecord::Migration, if possible (by extracting RDoc?) for tables and columns.
It occurs to me that this may be more like a feature request rather than something that could be done quickly. Is this already possible to do, and how can I do it?
You should be able to just execute the raw SQL where you need it. Try this:
sql = "COMMENT ON DATABASE myapp_development IS 'Rails DB for project at c:/some/path/myapp/';"
records_array = ActiveRecord::Base.connection.execute(sql)
Note that you can use string interpolation (e.g. "#{value}"
) to include variable values if you need. You have all the expressive power of Ruby and the ability to run any native SQL that you need.
The MigrationComments gem gives inline support for comments on migration objects. To install it, simply add this to your Gemfile
:
gem 'migration_comments'
Once installed, you can include both inline comments:
def self.up
create_table :users, comment: "User records are stored in this table." do |t|
t.string :canonical_email, comment: "This column contains the email address that has been URL decoded and lowercased, to ensure system-wide uniqueness"
end
end
and standalone comment changes:
def self.up
change_table :users do |t|
t.comment "User records are stored in this table."
t.change_comment :canonical_email, "This column contains the email address that has been URL decoded and lowercased, to ensure system-wide uniqueness"
end
end
You can find the PgComment gem that will give you commenting with an ActiveRecord-like syntax. Simply add this to your Gemfile
:
gem 'pg_comment'
And you'll be able to do cool things like this:
set_table_comment :users, "User records are stored in this table."
set_column_comment(:users, :canonical_email, "This column contains the email address that has been URL decoded and lowercased, to ensure system-wide uniqueness")
Unfortunately, there's no set_database_comment
with either gem, so database comments (and other unsupported Postgres objects) would require use of the raw SQL solution shown at the top of the answer.