Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize get_for_dialect, get_db_field_types #1863

Merged
merged 10 commits into from
Jan 28, 2025
27 changes: 21 additions & 6 deletions tortoise/fields/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,12 +326,17 @@ def get_db_field_types(self) -> Optional[dict[str, str]]:
"""
if not self.has_db_field: # pragma: nocoverage
return None
default = getattr(self, "SQL_TYPE")
return {
"": getattr(self, "SQL_TYPE"),
"": default,
**{
dialect: _db["SQL_TYPE"]
for dialect, _db in self._get_dialects().items()
if "SQL_TYPE" in _db
dialect: sql_type
for dialect, sql_type in (
(key[4:], self.get_for_dialect(key[4:], "SQL_TYPE"))
for key in dir(self)
if key.startswith("_db_")
)
if sql_type != default
},
}

Expand All @@ -342,8 +347,18 @@ def get_for_dialect(self, dialect: str, key: str) -> Any:
:param dialect: The requested SQL Dialect.
:param key: The attribute/method name.
"""
dialect_data = self._get_dialects().get(dialect, {})
return dialect_data.get(key, getattr(self, key, None))
try:
dialect_cls = getattr(self, f"_db_{dialect}") # throws AttributeError if not present
dialect_value = getattr(dialect_cls, key) # throws AttributeError if not present
except AttributeError:
pass
else: # we have dialect_cls and dialect_value, so lets use it
# it could be that dialect_value is a computed property, like in CharField._db_oracle.SQL_TYPE,
# and therefore one first needs to instantiate dialect_cls
if isinstance(dialect_value, property):
return getattr(dialect_cls(self), key)
return dialect_value
return getattr(self, key, None) # there is nothing special defined, return the value of self

def describe(self, serializable: bool) -> dict:
"""
Expand Down
Loading