Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.12", "3.13", "3.14"]
python-version: ["3.13", "3.14"]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
Expand Down
27 changes: 20 additions & 7 deletions src/airmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ class UnicornSighting(AirModel):
from pydantic import (
BaseModel,
ConfigDict,
)
from pydantic import (
Field as PydanticField,
)
from pydantic.fields import FieldInfo
Expand Down Expand Up @@ -179,11 +181,11 @@ def _parse_kwargs(kwargs: dict[str, Any], *, start_idx: int = 1) -> tuple[list[s
values.append(value)
param_idx += 1
elif lookup == "contains":
conditions.append(f'"{field}" LIKE \'%\' || ${param_idx} || \'%\'')
conditions.append(f"\"{field}\" LIKE '%' || ${param_idx} || '%'")
values.append(value)
param_idx += 1
elif lookup == "icontains":
conditions.append(f'"{field}" ILIKE \'%\' || ${param_idx} || \'%\'')
conditions.append(f"\"{field}\" ILIKE '%' || ${param_idx} || '%'")
values.append(value)
param_idx += 1
elif lookup == "in":
Expand Down Expand Up @@ -378,7 +380,14 @@ async def get(cls, **kwargs: Any) -> Self | None:
return cls.model_validate(dict(rows[0]))

@classmethod
async def filter(cls, *, order_by: str | None = None, limit: int | None = None, offset: int | None = None, **kwargs: Any) -> list[Self]:
async def filter(
cls,
*,
order_by: str | None = None,
limit: int | None = None,
offset: int | None = None,
**kwargs: Any,
) -> list[Self]:
"""Fetch all rows matching the given keyword filters.

Supports Django-style ``__`` lookups (gt, gte, lt, lte, contains,
Expand Down Expand Up @@ -414,7 +423,13 @@ async def filter(cls, *, order_by: str | None = None, limit: int | None = None,
return [cls.model_validate(dict(r)) for r in rows]

@classmethod
async def all(cls, *, order_by: str | None = None, limit: int | None = None, offset: int | None = None) -> list[Self]:
async def all(
cls,
*,
order_by: str | None = None,
limit: int | None = None,
offset: int | None = None,
) -> list[Self]:
"""Fetch every row from the table.

Args:
Expand Down Expand Up @@ -490,8 +505,7 @@ async def bulk_create(cls, items: list[dict[str, Any]]) -> list[Self]:
offset = i * len(insert_fields)
placeholders = ", ".join(f"${offset + j + 1}" for j in range(len(insert_fields)))
value_groups.append(f"({placeholders})")
all_values.extend(
item[f] for f in insert_fields)
all_values.extend(item[f] for f in insert_fields)

values_sql = ", ".join(value_groups)
sql = f'INSERT INTO "{cls._table_name()}" ({columns}) VALUES {values_sql} RETURNING *'
Expand Down Expand Up @@ -561,7 +575,6 @@ async def save(self, *, update_fields: list[str] | None = None) -> None:
msg = "Cannot save a row without a primary key value. Use create() for new rows."
raise ValueError(msg)


if update_fields is not None and len(update_fields) == 0:
msg = "update_fields cannot be empty. Omit the argument to update all fields."
raise ValueError(msg)
Expand Down
98 changes: 52 additions & 46 deletions tests/test_airmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ def test_bool_maps_to_boolean(self) -> None:
def test_datetime_maps_to_timestamptz(self) -> None:
assert _PY_TO_PG[datetime] == "TIMESTAMP WITH TIME ZONE"


def test_uuid_maps_to_uuid(self) -> None:
assert _PY_TO_PG[UUID] == "UUID"

Expand Down Expand Up @@ -483,6 +482,7 @@ class Article(AirModel):
assert '"body" TEXT NOT NULL' in sql
assert '"draft" BOOLEAN NOT NULL' in sql


# ---------------------------------------------------------------------------
# UUID field support
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -515,7 +515,6 @@ class OptionalUUIDModel(AirModel):
assert "NOT NULL" not in col_dict["trace_id"]



# ---------------------------------------------------------------------------
# order_by parameter
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -588,9 +587,7 @@ async def test_save_sql_contains_returning(self) -> None:
db = AirDB()
db.connect(fake_pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta"
)
fruit = DragonFruit(id=1, name="Pink Pitaya", color="magenta")
await fruit.save()
assert fake_pool.last_sql is not None
assert "RETURNING *" in fake_pool.last_sql
Expand All @@ -612,10 +609,7 @@ async def test_save_refreshes_fields_from_returned_row(self) -> None:
db = AirDB()
db.connect(fake_pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta",
sweetness="", origin=""
)
fruit = DragonFruit(id=1, name="Pink Pitaya", color="magenta", sweetness="", origin="")
await fruit.save()

# The database returned different values for these fields.
Expand All @@ -642,9 +636,7 @@ async def test_delete_clears_pk(self) -> None:
db = AirDB()
db.connect(fake_pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta"
)
fruit = DragonFruit(id=1, name="Pink Pitaya", color="magenta")
assert fruit.id == 1

await fruit.delete()
Expand Down Expand Up @@ -734,6 +726,7 @@ async def test_create_calls_fetchrow_with_insert_returning(self) -> None:
try:
result = await DragonFruit.create(name="Pink Pitaya", color="magenta")

assert isinstance(result, DragonFruit)
assert pool.last_sql is not None
assert pool.last_sql.startswith('INSERT INTO "dragon_fruit"')
assert "RETURNING *" in pool.last_sql
Expand Down Expand Up @@ -1299,9 +1292,7 @@ async def test_crud_inside_transaction_uses_connection(self) -> None:
await DragonFruit.create(name="Pink Pitaya", color="magenta")

# The connection's fetchrow should have been called, not the pool's
assert conn.fetchrow_called, (
"create() inside transaction should use the connection, not the pool"
)
assert conn.fetchrow_called, "create() inside transaction should use the connection, not the pool"
finally:
db.disconnect()

Expand Down Expand Up @@ -1361,10 +1352,12 @@ async def test_bulk_create_returns_list(self) -> None:
)
_wire_pool(pool)
try:
results = await DragonFruit.bulk_create([
{"name": "Pink Pitaya", "color": "magenta"},
{"name": "Yellow Dragon", "color": "yellow"},
])
results = await DragonFruit.bulk_create(
[
{"name": "Pink Pitaya", "color": "magenta"},
{"name": "Yellow Dragon", "color": "yellow"},
]
)

assert isinstance(results, list)
assert len(results) == 2
Expand All @@ -1388,11 +1381,13 @@ async def test_bulk_create_sql_is_multi_row_insert(self) -> None:
)
_wire_pool(pool)
try:
await DragonFruit.bulk_create([
{"name": "Pink Pitaya", "color": "magenta"},
{"name": "Yellow Dragon", "color": "yellow"},
{"name": "White Pitaya", "color": "white"},
])
await DragonFruit.bulk_create(
[
{"name": "Pink Pitaya", "color": "magenta"},
{"name": "Yellow Dragon", "color": "yellow"},
{"name": "White Pitaya", "color": "white"},
]
)

assert pool.last_sql is not None
assert pool.last_sql.startswith('INSERT INTO "dragon_fruit"')
Expand Down Expand Up @@ -1423,10 +1418,9 @@ async def test_bulk_update_generates_update_where(self) -> None:
pool = BulkPool(execute_return="UPDATE 3")
_wire_pool(pool)
try:
count = await DragonFruit.bulk_update(
{"color": "red"}, name="Pink Pitaya"
)
count = await DragonFruit.bulk_update({"color": "red"}, name="Pink Pitaya")

assert count == 3
assert pool.last_sql is not None
assert pool.last_sql.startswith('UPDATE "dragon_fruit" SET')
assert '"color" =' in pool.last_sql
Expand All @@ -1441,10 +1435,9 @@ async def test_bulk_update_with_lookup_operators(self) -> None:
pool = BulkPool(execute_return="UPDATE 5")
_wire_pool(pool)
try:
count = await DragonFruit.bulk_update(
{"color": "red"}, sweetness__contains="high"
)
count = await DragonFruit.bulk_update({"color": "red"}, sweetness__contains="high")

assert count == 5
assert pool.last_sql is not None
assert "WHERE" in pool.last_sql
assert "LIKE" in pool.last_sql
Expand All @@ -1457,9 +1450,7 @@ async def test_bulk_update_returns_row_count(self) -> None:
pool = BulkPool(execute_return="UPDATE 7")
_wire_pool(pool)
try:
count = await DragonFruit.bulk_update(
{"color": "red"}, name__contains="Dragon"
)
count = await DragonFruit.bulk_update({"color": "red"}, name__contains="Dragon")

assert isinstance(count, int)
assert count == 7
Expand All @@ -1475,6 +1466,7 @@ async def test_bulk_delete_generates_delete_where(self) -> None:
try:
count = await DragonFruit.bulk_delete(confirmed=False)

assert count == 2
assert pool.last_sql is not None
assert pool.last_sql.startswith('DELETE FROM "dragon_fruit" WHERE')
assert '"confirmed" = $1' in pool.last_sql
Expand All @@ -1488,6 +1480,7 @@ async def test_bulk_delete_with_lookup_operators(self) -> None:
try:
count = await DragonFruit.bulk_delete(sweetness__lt=3)

assert count == 4
assert pool.last_sql is not None
assert pool.last_sql.startswith('DELETE FROM "dragon_fruit" WHERE')
assert '"sweetness" < $1' in pool.last_sql
Expand Down Expand Up @@ -1542,8 +1535,11 @@ async def test_save_with_update_fields_only_sets_specified_columns(self) -> None
self._wire_pool(pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta",
sweetness="high", origin="Vietnam",
id=1,
name="Pink Pitaya",
color="magenta",
sweetness="high",
origin="Vietnam",
)
fruit.name = "White Pitaya"
await fruit.save(update_fields=["name"])
Expand All @@ -1567,8 +1563,11 @@ async def test_save_with_update_fields_still_uses_returning(self) -> None:
self._wire_pool(pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta",
sweetness="high", origin="Vietnam",
id=1,
name="Pink Pitaya",
color="magenta",
sweetness="high",
origin="Vietnam",
)
fruit.name = "White Pitaya"
await fruit.save(update_fields=["name"])
Expand All @@ -1585,8 +1584,11 @@ async def test_save_with_update_fields_passes_correct_values(self) -> None:
self._wire_pool(pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta",
sweetness="high", origin="Vietnam",
id=1,
name="Pink Pitaya",
color="magenta",
sweetness="high",
origin="Vietnam",
)
fruit.name = "White Pitaya"
await fruit.save(update_fields=["name"])
Expand All @@ -1603,18 +1605,19 @@ async def test_save_without_update_fields_still_updates_all(self) -> None:
self._wire_pool(pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta",
sweetness="high", origin="Vietnam",
id=1,
name="Pink Pitaya",
color="magenta",
sweetness="high",
origin="Vietnam",
)
await fruit.save()

sql = pool.last_sql
assert sql is not None
set_clause = sql.split("SET")[1].split("WHERE")[0]
for col in ("created_at", "name", "color", "sweetness", "origin"):
assert f'"{col}"' in set_clause, (
f'"{col}" should appear in SET when no update_fields given'
)
assert f'"{col}"' in set_clause, f'"{col}" should appear in SET when no update_fields given'
finally:
self._unwire_pool()

Expand All @@ -1625,8 +1628,11 @@ async def test_save_with_empty_update_fields_raises(self) -> None:
self._wire_pool(pool)
try:
fruit = DragonFruit(
id=1, name="Pink Pitaya", color="magenta",
sweetness="high", origin="Vietnam",
id=1,
name="Pink Pitaya",
color="magenta",
sweetness="high",
origin="Vietnam",
)
with pytest.raises(ValueError, match="update_fields"):
await fruit.save(update_fields=[])
Expand Down