Note that there are some explanatory texts on larger screens.

plurals
  1. POCombining PostgreSQL Enum with a TypeDecorator
    primarykey
    data
    text
    <p>Is there a way to have an Enum class that will both get created automatically when creating a new DB, like the standard Enum, but also connect it to a <code>TypeDecorator</code> that runs <code>process_bind_param</code>?</p> <p>This first code block creates an <code>Enum</code> type that automatically lowercases input before saving it, but, unlike a normal <code>Enum</code>, the specific PostgreSQL enum type isn't created automatically in the database, so running a <code>create_all()</code> causes an error when creating the table, because the <code>language_code</code> type doesn't exist in the PostgreSQL schema. </p> <pre><code>class LowercaseEnum(sqlalchemy.types.TypeDecorator): '''Converts input to lowercase.''' impl = sqlalchemy.types.Enum def process_bind_param(self, value, dialect): return value.lower() class Foo(Model): id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) language_code = sqlalchemy.Column(LowercaseEnum(*['de', 'en'], name='language_code')) </code></pre> <p>If, on the other hand, I define my custom type like in this second code block, then it gets created automatically when calling <code>create_all()</code>, but the <code>process_bind_param</code> method is never called when sending values to the database, so the lowercasing doesn't work. </p> <pre><code>class LowercaseEnum(sqlalchemy.dialects.postgresql.ENUM, sqlalchemy.types.TypeDecorator): '''Converts input to lowercase.''' impl = sqlalchemy.types.Enum def process_bind_param(self, value, dialect): return value.lower() </code></pre> <p>I have also tried several different combinations of inheriting from <code>TypeDecorator</code> in a separate class that is mixed-in, and also switching up <code>sqlalchemy.types.Enum</code> and <code>sqlalchemy.dialects.postgresql.ENUM</code>, but it seems no matter what I do, I either get a class that gets created automatically, or a class that runs <code>process_bind_param</code>, but never both.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload