gjaldon / ecto_enum

Ecto extension to support enums in models
MIT License
563 stars 131 forks source link

Fix `CREATE TYPE` query for Postgres #18

Closed aquarhead closed 8 years ago

aquarhead commented 8 years ago

String values should be single-quoted ref: https://www.postgresql.org/docs/current/static/datatype-enum.html

Before the change the SQL query generated for Postgres is incorrect and breaks ecto.migrate

16:24:39.302 [info]  == Running Shocolle.Repo.Migrations.AddCollesTable.up/0 forward

16:24:39.304 [info]  execute "CREATE TYPE joutai AS ENUM (wish, doing, done, pending, ditched)"
** (Postgrex.Error) ERROR (syntax_error): syntax error at or near "wish"
    (ecto) lib/ecto/adapters/sql.ex:180: Ecto.Adapters.SQL.query!/5
    (ecto) lib/ecto/adapters/postgres.ex:69: Ecto.Adapters.Postgres.execute_ddl/3
    (ecto) lib/ecto/migration/runner.ex:101: anonymous fn/2 in Ecto.Migration.Runner.flush/0
    (elixir) lib/enum.ex:1623: Enum."-reduce/3-lists^foldl/2-0-"/3
    (ecto) lib/ecto/migration/runner.ex:99: Ecto.Migration.Runner.flush/0
    (stdlib) timer.erl:181: :timer.tc/2
    (ecto) lib/ecto/migration/runner.ex:27: Ecto.Migration.Runner.run/6
    (ecto) lib/ecto/migrator.ex:121: Ecto.Migrator.attempt/6
    (ecto) lib/ecto/migrator.ex:70: anonymous fn/4 in Ecto.Migrator.do_up/4
    (ecto) lib/ecto/adapters/sql.ex:480: anonymous fn/3 in Ecto.Adapters.SQL.do_transaction/3
    (db_connection) lib/db_connection.ex:1063: DBConnection.transaction_run/4
    (db_connection) lib/db_connection.ex:987: DBConnection.run_begin/3
    (db_connection) lib/db_connection.ex:667: DBConnection.transaction/3
    (ecto) lib/ecto/migrator.ex:244: anonymous fn/4 in Ecto.Migrator.migrate/4
    (elixir) lib/enum.ex:1184: Enum."-map/2-lists^map/1-0-"/2
    (elixir) lib/enum.ex:1184: Enum."-map/2-lists^map/1-0-"/2
    (ecto) lib/mix/tasks/ecto.migrate.ex:84: anonymous fn/4 in Mix.Tasks.Ecto.Migrate.run/2
    (elixir) lib/enum.ex:651: Enum."-each/2-lists^foreach/1-0-"/2
    (elixir) lib/enum.ex:651: Enum.each/2
    (mix) lib/mix/task.ex:296: Mix.Task.run_task/3

The change might look a bit tricky (in the way it does the single-quoting), I could change that if you want. With this fix we can run ecto.migrate correctly:

17:06:56.187 [info]  == Running Shocolle.Repo.Migrations.AddCollesTable.up/0 forward

17:06:56.189 [info]  execute "CREATE TYPE joutai AS ENUM ('wish', 'doing', 'done', 'pending', 'ditched')"

17:06:56.192 [info]  create table colles

17:06:56.204 [info]  == Migrated in 0.0s

There's no test for create_type and drop_type, which I could also try to add if you want.

gjaldon commented 8 years ago

Thanks for this @aquarhead! Please go ahead and add tests for those too. :)

gjaldon commented 8 years ago

Let's just merge this and add the tests later. :)