Skip to content

optimize get_for_dialect, get_db_field_types #1863

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

Merged
merged 10 commits into from
Jan 28, 2025
24 changes: 19 additions & 5 deletions tortoise/fields/base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sys
import traceback
import warnings
from collections.abc import Callable
from enum import Enum
Expand Down Expand Up @@ -326,12 +327,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"),
**{
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 +348,16 @@ 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))
cls = getattr(self, f"_db_{dialect}", None)
value = getattr(cls, key, None)
if value is None:
v = getattr(self, key, None)
if isinstance(v, property):
return getattr(self, key)
return v
elif isinstance(value, property) and isinstance(cls, type):
return getattr(cls(self), key)
return value

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