Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion aiohttp_admin/backends/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@

logger = logging.getLogger(__name__)

# Canonical hyphenated UUID form (8-4-4-4-12 hex), matching str(uuid.UUID(...)).
_UUID_REGEX = ("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")

_FieldTypesValues = tuple[str, str, MPT[str, object], MPT[str, object]]
FIELD_TYPES: MPT[type[sa.types.TypeEngine[Any]], _FieldTypesValues] = MPT({
sa.Boolean: ("BooleanField", "BooleanInput", MPT({}), MPT({})),
Expand All @@ -43,7 +47,7 @@
sa.Numeric: ("NumberField", "NumberInput", MPT({}), MPT({})),
sa.String: ("TextField", "TextInput", MPT({}), MPT({})),
sa.Time: ("TimeField", "TimeInput", MPT({}), MPT({})),
sa.Uuid: ("TextField", "TextInput", MPT({}), MPT({})), # TODO: validators
sa.Uuid: ("TextField", "TextInput", MPT({}), MPT({})),
# TODO: Set fields for below types.
# sa.sql.sqltypes._AbstractInterval: (),
# sa.types._Binary: (),
Expand Down Expand Up @@ -427,6 +431,8 @@ def _get_validators(self, table: sa.Table, c: sa.Column[object]) -> list[Functio
max_length = getattr(c.type, "length", None)
if max_length:
validators.append(func("maxLength", (max_length,)))
if isinstance(c.type, sa.Uuid):
validators.append(func("regex", (regex(_UUID_REGEX),)))

for constr in table.constraints:
if not isinstance(constr, sa.CheckConstraint):
Expand Down
15 changes: 15 additions & 0 deletions tests/test_backends_sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,21 @@ class TestModel(base): # type: ignore[misc,valid-type]
}


def test_uuid_validator(base: type[DeclarativeBase], mock_engine: AsyncEngine) -> None:
import uuid as uuid_mod

class TestModel(base): # type: ignore[misc,valid-type]
__tablename__ = "dummy"
id: Mapped[int] = mapped_column(primary_key=True)
token: Mapped[uuid_mod.UUID] = mapped_column(nullable=True)

r = SAResource(mock_engine, TestModel)
uuid_pattern = ("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
assert r.inputs["token"]["props"]["validate"] == [
func("regex", (regex(uuid_pattern),))]


def test_table(mock_engine: AsyncEngine) -> None:
dummy_table = sa.Table("dummy", sa.MetaData(),
sa.Column("id", sa.Integer, primary_key=True),
Expand Down
Loading