Hacker News new | ask | show | jobs
by clarkdave 4573 days ago
Native "enums" (types) in PostgreSQL are a mixed bag. They do have some advantages:

- you can treat them like strings (e.g. `SET status = 'approved'`, but they are a fixed size (four bytes)

- when queried they appear as strings too. Nice for debugging

- if you enter an invalid value (anywhere, not just in Rails) PG will throw a wibbly

But the biggest problem with enum types is if/when you want to add a new value to an enum type, it's annoyingly non-trivial. You can't run `ALTER TYPE ... ADD` because it doesn't work in a transaction. [0]

Instead you need to drop the type, recreate it (with the new value) and then alter all the tables that use this type. If you have a huge DB this can get a bit silly, although you can at least do it all in a transaction.

It is fairly trivial to add support for real Postgres enum types - https://gist.github.com/clarkdave/5936375 - but it's not as elegant as having it properly supported by ActiveRecord.

As other posters have mentioned here, it'd be useful if Rails' enum support used text instead of integers. You could then set up a Check constraint in PG to enforce the correct values and stop invalid data slipping into your database from other sources, whilst keeping the nice sugar in ActiveRecord.

[0] http://www.postgresql.org/message-id/3543.1317224437@sss.pgh...