Diego Francisco
Diego Francisco

Reputation: 1910

Phoenix - Alter columns order

So, I'm creating an ecto migration for adding a new column to my model in the database, and I want to change the order of the columns because this new column gets put at the end of the columns, so I tried it like this:

def change do
  alter table(:users) do
    add :password_hash, :string, after: :email
  end
end

But it seems that it doesn't has effect nor doesn't throws an error.

PD: I'm using Maria DB.

Upvotes: 0

Views: 1085

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

I definitely would not advise doing this at home or school :), I am also not sure if it ever works, but it should. Let me know if it does not and I will remove the answer; posting not as a comment for the sake of formatting.

def change do
  query = "ALTER TABLE users
           ADD COLUMN password_hash VARCHAR(255)
           AFTER email;"
  Ecto.Adapters.SQL.query!(Repo, query, [])
end

It uses Ecto.Adapters.SQL.query/4 to execute raw SQL.


NB please also check the very valuable comment by @PatrickOscity below.

Upvotes: 1

Jonas Dellinger
Jonas Dellinger

Reputation: 1364

Since you didn't write which database you are using, I assume PostgreSQL, which doesn't support column reordering. There are some hacky workarounds tho, which are of course not implemented in ecto.

And normally there are no reasons or needs to alter column order. Why would you need it?

Upvotes: 0

Related Questions