Skip to content

Instantly share code, notes, and snippets.

@jaymcgavren
Last active August 31, 2022 02:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jaymcgavren/e075c615f5e9f7e1e24631f7550dc65f to your computer and use it in GitHub Desktop.
A script to generate a grep-able list of tables in your Rails project's database.
Copyright 2022 Jay McGavren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Outputs a list of tables in a Rails/ActiveRecord database.
# Format: table_name [column_1 column_2 etc] {{index 1 column(s)} {index 2 column(s)} {etc}}
# E.g.:
# doctors [name phone] {{phone}}
# patients [doctor_id email name] {{doctor_id email} {email}}
# Save this file as e.g. tables.rb within the root of your Rails project.
# Then cd into the directory and run:
# bin/rails runner tables.rb > tables.txt
def format_columns(db, table)
db.columns(table).map(&:name).reject{|c| omit_column?(c) }.sort.join(" ")
end
def format_index_columns(table)
table.columns.try(:join, " ")
end
def omit_column?(column)
%w{id created_at updated_at}.include?(column)
end
def format_indexes(db, table)
db.indexes(table).map{|t| "{#{format_index_columns(t)}}"}.sort.join(" ")
end
def format_table(db, table)
"#{table} [#{format_columns(db, table)}] {#{format_indexes(db, table)}}"
end
def format_tables(db)
db.tables.sort.map do |table|
format_table(db, table)
end
end
db = ActiveRecord::Base.connection
puts format_tables(db)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment