Firstly, we all might have or might not have heard about migration files. It's okay let me share you something. For that we should have some basic knowledge regarding migration.
what are the migration files and their purpose?
Migrations are used to modify your database schema over time and to tell the database about expected structure to have. Phoenix provides many helpers for migrating the database, allowing developers to use Elixir to alter their storage in a way that is database independent.
While working on project I had to create one table in existing database. So I did like as
PC:~/project/myproject$ mix ecto.gen.migration add_weather_table * creating priv/repo/migrations * creating priv/repo/migrations/20180331170622_add_weather_table.exs
Here migration file get generated as
defmodule MyProject.Repo.Migrations.AddWeatherTable do use Ecto.Migration def change do end end
Above we suppose to fill in the empty change/0 function. So I did as
defmodule MyRepo.Migrations.AddWeatherTable do use Ecto.Migration def change do create table("weather") do add :city, :string, size: 40 add :temp_lo, :integer add :temp_hi, :integer add :prcp, :float timestamps() end end end
After migrating file table get created in database as
PC:~/project/myproject$ mix ecto.migrate 22:55:43.405 [info] == Running Trackbees.Repo.Migrations.AddWeatherTable.change/0 forward 22:55:43.423 [info] == Migrated in 0.0s
Then requirement get changed and need to rolled back that migration to delete that table. So I did using file version number (actually timestamp) as
mix ecto.rollback -v 20180331170622
Everything worked fine but later I came to know that there is other better way to do all this. We can use up/0 and down/0 functions, where up/0 is used to update your database and down/0 rolls back the requested changes. We can write migration file as
defmodule MyRepo.Migrations.AddWeatherTable do use Ecto.Migration def up do create table("weather") do add :city, :string, size: 40 add :temp_lo, :integer add :temp_hi, :integer add :prcp, :float timestamps() end end def down do drop table("weather") end end
Later in project I implemented it for one other file where I wanted to change the column name for table as below
defmodule MyRepo.Migrations.RenameStatusIdToMeetingIdInMentions do use Ecto.Migration def up do rename table(:mentions), :status_id, to: :meeting_id end def down do rename table(:mentions), :meeting_id, to: :status_id end end