Skip to content

Commit 476bc79

Browse files
committed
perf: Optimized ChoiceType
1 parent 1ba0594 commit 476bc79

1 file changed

Lines changed: 16 additions & 13 deletions

File tree

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,17 @@
11
from typing import Type
22

33
from sqlalchemy import types
4-
from sqlalchemy.engine import Dialect
54

65
from ._enums import Choices
76

87

9-
class ChoiceType(types.TypeDecorator):
10-
impl = types.CHAR
11-
cache_ok = True
12-
8+
class BaseChoicesType(types.TypeDecorator):
139
def __init__(self, choices: Type[Choices], impl=None, *args, **kwargs):
1410
super().__init__(*args, **kwargs)
1511
self.choices = choices
1612

17-
@property
18-
def python_type(self):
19-
return self.impl.python_type
20-
21-
def load_dialect_impl(self, dialect: Dialect):
22-
return dialect.type_descriptor(types.CHAR(20))
23-
2413
def process_bind_param(self, value, dialect):
25-
if value and isinstance(value, Choices):
14+
if value is not None and isinstance(value, Choices):
2615
return value.value
2716
return value
2817

@@ -32,3 +21,17 @@ def process_result_value(self, value, dialect):
3221
value = int(value)
3322
return self.choices(value)
3423
return value
24+
25+
26+
class TextChoicesType(BaseChoicesType):
27+
impl = types.CHAR
28+
cache_ok = True
29+
30+
31+
class IntegerChoicesType(BaseChoicesType):
32+
impl = types.Integer
33+
cache_ok = True
34+
35+
36+
def ChoiceType(choices: Type[Choices], *args, **kwargs):
37+
return (IntegerChoicesType if issubclass(choices, int) else TextChoicesType)(choices, *args, **kwargs)

0 commit comments

Comments
 (0)