Skip to content

Setting up a new project

Vsevolod Romashov edited this page Apr 8, 2020 · 3 revisions
  1. add gem 'db_schema' to your Gemfile and run bundle install
  2. create a file that will be loaded during the bootup of your app (like a Rails initializer)
  3. configure the database connection settings in that file:
DbSchema.configure(
  adapter:  'postgresql',
  host:     ENV['db_host'],    # database host
  port:     ENV['db_port'],    # database port
  database: ENV['db_name'],    # database name
  user:     ENV['db_user'],    # database username
  password: ENV['db_password'] # database password
)

or if you are setting up a Rails app:

DbSchema.configure_from_yaml(Rails.root.join('config', 'database.yml'), Rails.env)

(don't forget to create the database itself - DbSchema won't do that for you)

  1. load the schema definition file in development and test environments (db/schema.rb in this example, but you can choose any path you like):
if Rails.env.development? || Rails.env.test?
  load Rails.root.join('db', 'schema.rb')
end
  1. create the schema definition file and describe your desired database schema with DbSchema DSL:
DbSchema.describe do |db|
  db.table :users do |t|
    t.serial  :id,    primary_key: true
    t.varchar :email, null: false
    t.varchar :name,  null: false

    t.index :email, unique: true
  end
end
  1. launch your app - database schema will be automatically aligned with your schema definition
  2. commit all these files to version control

You're all set!

Now each time you need to change your database structure you just make corresponding changes in your schema definition - DbSchema will always keep your database in sync with it.

Clone this wiki locally