diff options
| author | Federico Caselli <cfederico87@gmail.com> | 2020-03-24 21:06:04 +0100 |
|---|---|---|
| committer | Federico Caselli <cfederico87@gmail.com> | 2020-04-06 20:02:28 +0200 |
| commit | a902660f711da0b428fd2b9abf9b281a1ef6a118 (patch) | |
| tree | 81bf42dd358d36b2f159c331529f15e5c6ea65e3 /lib/sqlalchemy/sql | |
| parent | 49b6c50016c8a038a6df7104560bb3945debe064 (diff) | |
| download | sqlalchemy-a902660f711da0b428fd2b9abf9b281a1ef6a118.tar.gz | |
Add length parameter in `Enum`
The `Enum` type now supports the parameter `Enum.length`
to specify the length of the VARCHAR column to create when using
non native enums by setting `Enum.native_enum` to `False`
Fixes: #5183
Change-Id: Iea05dc8cd9e33959bb968b394fb10a7dd068c873
Diffstat (limited to 'lib/sqlalchemy/sql')
| -rw-r--r-- | lib/sqlalchemy/sql/sqltypes.py | 19 |
1 files changed, 18 insertions, 1 deletions
diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py index e106684bc..05d6ec36b 100644 --- a/lib/sqlalchemy/sql/sqltypes.py +++ b/lib/sqlalchemy/sql/sqltypes.py @@ -1303,7 +1303,14 @@ class Enum(Emulated, String, SchemaType): :param native_enum: Use the database's native ENUM type when available. Defaults to True. When False, uses VARCHAR + check - constraint for all backends. + constraint for all backends. The VARCHAR length can be controlled + with :paramref:`.Enum.length` + + :param length: Allows specifying a custom length for the VARCHAR + when :paramref:`.Enum.native_enum` is False. By default it uses the + length of the longest value. + + .. versionadded:: 1.3.16 :param schema: Schema name of this type. For types that exist on the target database as an independent schema construct (PostgreSQL), @@ -1375,6 +1382,7 @@ class Enum(Emulated, String, SchemaType): self.create_constraint = kw.pop("create_constraint", True) self.values_callable = kw.pop("values_callable", None) self._sort_key_function = kw.pop("sort_key_function", NO_ARG) + length_arg = kw.pop("length", NO_ARG) values, objects = self._parse_into_values(enums, kw) self._setup_for_values(values, objects, kw) @@ -1398,6 +1406,15 @@ class Enum(Emulated, String, SchemaType): length = max(len(x) for x in self.enums) else: length = 0 + if not self.native_enum and length_arg is not NO_ARG: + if length_arg < length: + raise ValueError( + "When provided, length must be larger or equal" + " than the length of the longest enum value. %s < %s" + % (length_arg, length) + ) + length = length_arg + self._valid_lookup[None] = self._object_lookup[None] = None super(Enum, self).__init__( |
