pg_enum.rb

lib/sequel/extensions/pg_enum.rb
Last Update: 2017-01-19 10:04:33 -0800

The pg_enum extension adds support for Sequel to handle PostgreSQL's enum types. To use this extension, first load it into your Database instance:

DB.extension :pg_enum

It allows creation of enum types using create_enum:

DB.create_enum(:enum_type_name, %w'value1 value2 value3')

You can also add values to existing enums via add_enum_value:

DB.add_enum_value(:enum_type_name, 'value4')

If you want to drop an enum type, you can use drop_enum:

DB.drop_enum(:enum_type_name)

Just like any user-created type, after creating the type, you can create tables that have a column of that type:

DB.create_table(:table_name) do
  enum_type_name :column_name
end

When parsing the schema, enum types are recognized, and available values returned in the schema hash:

DB.schema(:table_name)
[[:column_name, {:type=>:enum, :enum_values=>['value1', 'value2']}]]

If the pg_array extension is used, arrays of enums are returned as a PGArray:

DB.create_table(:table_name) do
  column :column_name, 'enum_type_name[]'
end
DB[:table_name].get(:column_name)
# ['value1', 'value2']

If the migration extension is loaded before this one (the order is important), you can use create_enum in a reversible migration:

Sequel.migration do
  change do
    create_enum(:enum_type_name, %w'value1 value2 value3')
  end
end

Finally, typecasting for enums is setup to cast to strings, which allows you to use symbols in your model code. Similar, you can provide the enum values as symbols when creating enums using create_enum or add_enum_value.

Related module: Sequel::Postgres::EnumDatabaseMethods