pg_enum.rb

lib/sequel/extensions/pg_enum.rb
Last Update: 2023-04-13 12:51:52 -0700

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 rename an enum type, you can use rename_enum:

DB.rename_enum(:enum_type_name, :enum_type_another_name)

If you want to rename an enum value, you can use rename_enum_value:

DB.rename_enum_value(
  :enum_type_name, :enum_value_name, :enum_value_another_name
)

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']}]]

This extension integrates with the pg_array extension. If you plan to use arrays of enum types, load the pg_array extension before the pg_enum extension:

DB.extension :pg_array, :pg_enum

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