1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activerecord/test/cases/adapters
Alex Ghiculescu 4eef348584 PostgreSQL: support custom enum types
Something I've seen on many Rails + PostgreSQL apps is that the only reason `structure.sql` is used instead of `schema.rb` is to support custom [enum types](https://www.postgresql.org/docs/current/datatype-enum.html). Enum types are great for type integrity and they work well with [`ActiveRecord::Enum`](https://api.rubyonrails.org/classes/ActiveRecord/Enum.html). And schema.rb is much easier to use than structure.sql. It would be great if more PostgreSQL projects could use schema.rb. To enable that, this PR adds native support for PostgreSQL enums in schema.rb.

In migrations, you can now use `create_enum` to add a new enum type, and `t.enum` to add a column:

```ruby
def up
  # note that enums cannot be dropped
  create_enum :mood, ["happy", "sad"]

  change_table :cats do |t|
    t.enum :current_mood, enum_type: "mood", default: "happy", null: false
  end
end
```

The enum definitions and enum columns will be presented in schema.rb, so you can load them into a test database and they'll work correctly.

-------------------------------

It's worth noting again that this is *not* compatible with other database engines. So this will not work with `rails db:system:change` (or the equivalent manual process). My assumption is that this is a fairly unlikely thing to happen midway through a project - as opposed to when the app is first spun up - so it's safe to assume that once you've dug into using enums you probably aren't going to switch databases on a whim.

For what it's worth, the MySQL adapter also supports enums (https://github.com/rails/rails/blob/main/activerecord/test/cases/adapters/mysql2/enum_test.rb) but the syntax doesn't look easy to translate (I also don't have much MySQL experience so don't really want to wade into this).
2021-09-22 16:34:10 -05:00
..
mysql2 Address FixturesWithForeignKeyViolationsTest#test_does_not_raise_if_no_fk_violations 2021-07-21 16:54:35 +09:00
postgresql PostgreSQL: support custom enum types 2021-09-22 16:34:10 -05:00
sqlite3 Address FixturesWithForeignKeyViolationsTest#test_does_not_raise_if_no_fk_violations 2021-07-21 16:54:35 +09:00