diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 23725b8..c00b338 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: diff --git a/src/airmodel/main.py b/src/airmodel/main.py index fb9790e..f170721 100644 --- a/src/airmodel/main.py +++ b/src/airmodel/main.py @@ -40,6 +40,8 @@ class UnicornSighting(AirModel): from pydantic import ( BaseModel, ConfigDict, +) +from pydantic import ( Field as PydanticField, ) from pydantic.fields import FieldInfo @@ -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": @@ -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, @@ -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: @@ -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 *' @@ -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) diff --git a/tests/test_airmodel.py b/tests/test_airmodel.py index 49fe303..8eeda46 100644 --- a/tests/test_airmodel.py +++ b/tests/test_airmodel.py @@ -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" @@ -483,6 +482,7 @@ class Article(AirModel): assert '"body" TEXT NOT NULL' in sql assert '"draft" BOOLEAN NOT NULL' in sql + # --------------------------------------------------------------------------- # UUID field support # --------------------------------------------------------------------------- @@ -515,7 +515,6 @@ class OptionalUUIDModel(AirModel): assert "NOT NULL" not in col_dict["trace_id"] - # --------------------------------------------------------------------------- # order_by parameter # --------------------------------------------------------------------------- @@ -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 @@ -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. @@ -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() @@ -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 @@ -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() @@ -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 @@ -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"') @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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"]) @@ -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"]) @@ -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"]) @@ -1603,8 +1605,11 @@ 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() @@ -1612,9 +1617,7 @@ async def test_save_without_update_fields_still_updates_all(self) -> None: 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() @@ -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=[])