Search code examples
elixirphoenix-frameworkecto

In Phoenix Framework, why is there a redundancy of "schemes" and migration?


You can not modify the schema without creating migration? Why is there migration and schemes? Why not just migration? It seems redundant.


Solution

  • Migrations are convenient ways to alter your database schema. Each migration can be considered as a new version of your database. You add or remove tables, columns, or entries as per your requirement. Where as Schema is the current state of the database.

    It is recommended to alter your schema through migrations, since you know the history of how you altered your database and it provides features like rolling back your migration.

    Consider a newly generated phoenix app,when we run mix ecto.create, there are no tables currently just an empty database. As per our requirements we want a table say user. We create a migration using mix ecto.gen.migration add_users_table.

    def change do
      create table(:users) do
        add :name,       :string
        add :age, :integer
        timestamps
      end
    end
    

    We can migrate(apply) this migration using mix ecto.migrate. Now we have some schema, which basically consists of the user table and its relevant columns we added. We could rollback this migration if we think its inappropriate using mix ecto.rollback, which will undo the schema changes