In etco doc, it use its independent create table statement by mix phx.gen.schema.
The command is as follows:
mix phx.gen.schema User users name:string email:string
The migration file is as follows:
defmodule Pen.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string
add :email, :string
add :password, :string
timestamps()
end
end
end
But in hexpm project, the migrations file is as follows:
My question is what's the difference between them? Is etco hasn't drop table method?
defmodule Hexpm.Repo.Migrations.AddUsersTable do
use Ecto.Migration
def up() do
execute("""
CREATE TABLE users (
id serial PRIMARY KEY,
username text,
email text UNIQUE,
password text,
created_at timestamp,
updated_at timestamp)
""")
execute("CREATE UNIQUE INDEX ON users (lower(username))")
end
def down() do
execute("DROP TABLE IF EXISTS users")
end
end
CodePudding user response:
Ecto.Migration has extensive documentation, explicitly stating:
Change
Having to write both
up/0anddown/0functions for every migration is tedious and error-prone. For this reason, Ecto allows you to define achange/0callback with all of the code you want to execute when migrating and Ecto will automatically figure out thedown/0for you.— https://hexdocs.pm/ecto_sql/Ecto.Migration.html#module-change
For this to work, the up migration should be clean enough for ecto to figure out down counterpart.
Why is it done that way in hexpm? Well, legacy (the project was started before ecto reached any mature state,) or because authors liked explicitness, or whatever else.
