Print Rails db schema or structure

These simple bash functions let you conveniently see schemas of your Rails models by printing them from schema.rb or structure.sql files.

schema

#!/usr/bin/env bash
#
# USAGE
#   schema - list table names
#   schema users - show structure of table users
if test "$1" = ""; then
  grep 'create_table' db/schema.rb | cut -d \" -f2
else
  sed -n "/create_table \"$1/,/^ *end *$/p" db/schema.rb
fi

structure

#!/usr/bin/env bash
#
# USAGE
#   structure - list table names
#   structure users - show structure of table users
if test "$1" = ""; then
  grep 'CREATE TABLE' db/structure.sql | cut -d " " -f3
else
  sed -n "/CREATE TABLE $1 (/,/^);$/p" db/structure.sql
fi

Don’t forget to chmod +x these files.


Code snippets in this post are covered by MIT License.



Date
August 26, 2023