Guides Intro arrow Setting Up & Migrating the Database

Lucky can help drop the database, create the database, and manage creating and altering tables using migrations.

Create or drop the database

If you’re using for the database, make sure you have set up CLI Tools.

First you’ll need to create a database using lucky db.create

The database name and settings can be changed in config/

You can drop the database by calling lucky db.drop

Generating a new migration

When you want to add or modify the database you can create a new migration using lucky gen.migration {migration_name}

For example:

lucky gen.migration CreateUsers or lucky gen.migration AddAgeToUsers

Creating and altering tables

# created_at, updated_at, and id are added automatically
create :users do
  add name : String # will set the column to NULL FALSE
  add age : Int32? # will allow NULL values because of the nilable type

Lucky currently supports String, Int32, Bool, Float, and Time.

Altering a table

alter :users do
  add phone : String
  remove :age

  # Sometimes you need things that LuckyMigrator doesn't support
  execute "custom SQL"

Adding indices

# Add them while creating the column
add email : String, index: true

# Add a unique index
add email : String, unique: true

# Add an index after the fact
# Note: Do this *inside* of a `create` or `alter` block
add_index :email
add_index :email, unique: true

Adding associations

  belongs_to User, on_delete: :cascade

This will create a user_id column with an index, a foreign key, and a cascade constraint.

You must always pass an on_delete option

Custom SQL

For things Lucky doesn’t support, you can use execute to run any sql you want.

Running and rolling back migrations

lucky db.migrate and lucky db.rollback