pgsqlasync2fast-fastapi 0.5.0__tar.gz → 0.5.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. {pgsqlasync2fast_fastapi-0.5.0/src/pgsqlasync2fast_fastapi.egg-info → pgsqlasync2fast_fastapi-0.5.1}/PKG-INFO +1 -1
  2. pgsqlasync2fast_fastapi-0.5.1/src/pgsqlasync2fast_fastapi/__version__.py +1 -0
  3. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/seeder.py +94 -19
  4. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1/src/pgsqlasync2fast_fastapi.egg-info}/PKG-INFO +1 -1
  5. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi.egg-info/SOURCES.txt +2 -1
  6. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/tests/test_sync_sequence.py +2 -1
  7. pgsqlasync2fast_fastapi-0.5.1/tests/test_upsert_by_id.py +186 -0
  8. pgsqlasync2fast_fastapi-0.5.0/src/pgsqlasync2fast_fastapi/__version__.py +0 -1
  9. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/LICENSE +0 -0
  10. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/MANIFEST.in +0 -0
  11. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/README.md +0 -0
  12. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/docs/.env.example +0 -0
  13. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/docs/seeder-format.md +0 -0
  14. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/basic_usage.py +0 -0
  15. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/database_creation.py +0 -0
  16. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/fastapi_integration.py +0 -0
  17. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/multi_database.py +0 -0
  18. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/seeders/dev/categories.json +0 -0
  19. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/seeders/dev/permissions.json +0 -0
  20. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/seeders/dev/roles.json +0 -0
  21. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/seeders/manifest.json +0 -0
  22. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/seeders/prod/categories.json +0 -0
  23. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/seeders/prod/permissions.json +0 -0
  24. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/examples/seeders/prod/roles.json +0 -0
  25. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/pyproject.toml +0 -0
  26. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/setup.cfg +0 -0
  27. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/__init__.py +0 -0
  28. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/connection.py +0 -0
  29. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/database.py +0 -0
  30. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/dependencies.py +0 -0
  31. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/migrations/__init__.py +0 -0
  32. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/migrations/env.py +0 -0
  33. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/migrations/registry.py +0 -0
  34. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/migrations/runner.py +0 -0
  35. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/settings.py +0 -0
  36. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi/skills/SKILL.md +0 -0
  37. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi.egg-info/dependency_links.txt +0 -0
  38. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi.egg-info/requires.txt +0 -0
  39. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/src/pgsqlasync2fast_fastapi.egg-info/top_level.txt +0 -0
  40. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/tests/test_completo.py +0 -0
  41. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/tests/test_insert_if_missing.py +0 -0
  42. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/tests/test_migration_chains.py +0 -0
  43. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/tests/test_seeder.py +0 -0
  44. {pgsqlasync2fast_fastapi-0.5.0 → pgsqlasync2fast_fastapi-0.5.1}/tests/test_seeder_override.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pgsqlasync2fast-fastapi
3
- Version: 0.5.0
3
+ Version: 0.5.1
4
4
  Summary: Simple and fast PostgreSQL async module for FastAPI with multi-database support
5
5
  Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
6
6
  License: MIT License
@@ -0,0 +1 @@
1
+ __version__ = "0.5.1"
@@ -284,6 +284,61 @@ async def insert_if_missing(
284
284
  return row
285
285
 
286
286
 
287
+ async def upsert_by_id(
288
+ session: Any,
289
+ model: type,
290
+ data: dict[str, Any],
291
+ ):
292
+ """
293
+ Upsert a row by ID: update if exists, insert if not.
294
+
295
+ This is the shared, reusable idempotent **upsert** primitive.
296
+ Unlike ``insert_if_missing`` (which uses natural keys), this uses the
297
+ primary key (ID) to determine if the row exists. If it exists, all fields
298
+ are updated with the new values. If not, a new row is inserted.
299
+
300
+ This is useful for seeders that need to evolve over time (e.g., rename
301
+ roles from "Admin" to "admin").
302
+
303
+ Args:
304
+ session: SQLModel AsyncSession (supports both ``exec`` and ``execute``).
305
+ model: SQLModel table class to query/insert.
306
+ data: Dict with all row fields including 'id'.
307
+
308
+ Returns:
309
+ The existing (updated) or newly created row instance.
310
+
311
+ Raises:
312
+ ValueError: If 'id' is not present in data.
313
+ """
314
+ from sqlmodel import select
315
+
316
+ row_id = data.get("id")
317
+ if row_id is None:
318
+ raise ValueError("upsert_by_id requires 'id' field in data")
319
+
320
+ # Check if row exists by ID
321
+ result = await session.exec(
322
+ select(model).where(model.id == row_id)
323
+ )
324
+ existing = result.first()
325
+
326
+ if existing is not None:
327
+ # Update existing row
328
+ for key, value in data.items():
329
+ if key != "id" and hasattr(existing, key):
330
+ setattr(existing, key, value)
331
+ session.add(existing)
332
+ await session.flush()
333
+ return existing
334
+ else:
335
+ # Insert new row
336
+ row = model(**data)
337
+ session.add(row)
338
+ await session.flush()
339
+ return row
340
+
341
+
287
342
  # ============================================================================
288
343
  # Manifest and Data Loading
289
344
  # ============================================================================
@@ -724,14 +779,18 @@ async def _seed_table_idempotent_generic(
724
779
  rows: list[dict[str, Any]],
725
780
  model_class: type,
726
781
  fk_field_mapping: dict[str, dict[str, str]] | None = None
727
- ) -> tuple[int, int]:
782
+ ) -> tuple[int, int, int]:
728
783
  """
729
- Generic idempotent seed function for packages that use the orchestrator.
784
+ Generic upsert seed function for packages that use the orchestrator.
730
785
 
731
786
  This is used when the package doesn't provide its own seed_fn.
732
787
  The orchestrator handles all the seeding logic using the model_classes
733
788
  provided in the SeederConfig.
734
789
 
790
+ **Upsert behavior**: If a row with the same ID exists, it's updated with
791
+ the new values. If it doesn't exist, it's inserted. This allows seeders
792
+ to evolve over time (e.g., rename roles from "Admin" to "admin").
793
+
735
794
  Args:
736
795
  session: SQLModel AsyncSession
737
796
  table_name: Name of the table (for logging)
@@ -740,11 +799,12 @@ async def _seed_table_idempotent_generic(
740
799
  fk_field_mapping: Optional mapping for FK field names (JSON -> model)
741
800
 
742
801
  Returns:
743
- Tuple of (rows_inserted, rows_skipped)
802
+ Tuple of (rows_inserted, rows_updated, rows_skipped)
744
803
  """
745
804
  from sqlmodel import select
746
805
 
747
806
  rows_inserted = 0
807
+ rows_updated = 0
748
808
  rows_skipped = 0
749
809
 
750
810
  # Get FK field mapping for this table if provided
@@ -767,26 +827,40 @@ async def _seed_table_idempotent_generic(
767
827
  )
768
828
  existing = result.one_or_none()
769
829
 
770
- if existing is not None:
771
- logger.debug(f"Skipping existing row id={row_id} in table '{table_name}'")
772
- rows_skipped += 1
773
- continue
774
-
775
- # Insert new row
776
830
  try:
777
- obj = model_class(**row)
778
- session.add(obj)
779
- await session.commit()
780
- rows_inserted += 1
781
- logger.debug(f"Inserted row id={row_id} in table '{table_name}'")
831
+ if existing is not None:
832
+ # UPSERT: Update existing row with new values
833
+ changed = False
834
+ for key, value in row.items():
835
+ if key != "id" and hasattr(existing, key):
836
+ current_value = getattr(existing, key)
837
+ if current_value != value:
838
+ setattr(existing, key, value)
839
+ changed = True
840
+
841
+ if changed:
842
+ session.add(existing)
843
+ await session.commit()
844
+ rows_updated += 1
845
+ logger.debug(f"Updated row id={row_id} in table '{table_name}'")
846
+ else:
847
+ logger.debug(f"Skipping unchanged row id={row_id} in table '{table_name}'")
848
+ rows_skipped += 1
849
+ else:
850
+ # INSERT: Create new row
851
+ obj = model_class(**row)
852
+ session.add(obj)
853
+ await session.commit()
854
+ rows_inserted += 1
855
+ logger.debug(f"Inserted row id={row_id} in table '{table_name}'")
782
856
  except Exception as e:
783
857
  await session.rollback()
784
- logger.error(f"Failed to insert row in table '{table_name}': {e}")
858
+ logger.error(f"Failed to upsert row in table '{table_name}': {e}")
785
859
  raise
786
860
 
787
861
  await sync_table_sequence(session, model_class)
788
862
 
789
- return rows_inserted, rows_skipped
863
+ return rows_inserted, rows_updated, rows_skipped
790
864
 
791
865
 
792
866
  # ============================================================================
@@ -897,11 +971,11 @@ async def seed_all(
897
971
  continue
898
972
 
899
973
  # Use generic seed logic with model classes and FK mapping
900
- inserted, skipped = await _seed_table_idempotent_generic(
974
+ inserted, updated, skipped = await _seed_table_idempotent_generic(
901
975
  session, table_name, rows, model_class,
902
976
  fk_field_mapping=seeder.fk_field_mapping
903
977
  )
904
- result.rows_seeded += inserted
978
+ result.rows_seeded += inserted + updated
905
979
  result.tables_seeded += 1
906
980
 
907
981
  logger.info(f"Completed seeding: {pkg_name}")
@@ -940,6 +1014,7 @@ __all__ = [
940
1014
  "clear_registry",
941
1015
  # Main orchestrator
942
1016
  "seed_all",
943
- # Shared idempotent insert-if-missing primitive
1017
+ # Shared idempotent primitives
944
1018
  "insert_if_missing",
1019
+ "upsert_by_id",
945
1020
  ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pgsqlasync2fast-fastapi
3
- Version: 0.5.0
3
+ Version: 0.5.1
4
4
  Summary: Simple and fast PostgreSQL async module for FastAPI with multi-database support
5
5
  Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
6
6
  License: MIT License
@@ -37,4 +37,5 @@ tests/test_insert_if_missing.py
37
37
  tests/test_migration_chains.py
38
38
  tests/test_seeder.py
39
39
  tests/test_seeder_override.py
40
- tests/test_sync_sequence.py
40
+ tests/test_sync_sequence.py
41
+ tests/test_upsert_by_id.py
@@ -193,9 +193,10 @@ async def test_generic_seeder_calls_sync_sequence():
193
193
  "pgsqlasync2fast_fastapi.seeder.sync_table_sequence",
194
194
  new=AsyncMock(),
195
195
  ) as mock_sync:
196
- inserted, skipped = await _seed_table_idempotent_generic(
196
+ inserted, updated, skipped = await _seed_table_idempotent_generic(
197
197
  session, "seq_fruits", [{"id": 1, "name": "apple"}], SeqFruit
198
198
  )
199
199
 
200
200
  assert inserted == 1
201
+ assert updated == 0
201
202
  mock_sync.assert_awaited_once_with(session, SeqFruit)
@@ -0,0 +1,186 @@
1
+ """
2
+ Tests for the upsert_by_id primitive (pgsqlasync2fast-fastapi).
3
+
4
+ Upsert by ID: update if exists, insert if not.
5
+ This allows seeders to evolve over time (e.g., rename roles).
6
+
7
+ Run with:
8
+ pytest tests/test_upsert_by_id.py -v
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import pytest
14
+ from sqlalchemy.ext.asyncio import create_async_engine
15
+ from sqlmodel import Field, SQLModel
16
+ from sqlmodel.ext.asyncio.session import AsyncSession
17
+
18
+
19
+ DB_URL = "sqlite+aiosqlite:///:memory:"
20
+
21
+
22
+ class ARole(SQLModel, table=True):
23
+ """Minimal SQLModel table with integer ID for upsert testing."""
24
+
25
+ __tablename__ = "aroles"
26
+
27
+ id: int | None = Field(default=None, primary_key=True)
28
+ name: str = Field(index=True)
29
+ description: str = Field(default="")
30
+
31
+
32
+ async def _engine():
33
+ engine = create_async_engine(DB_URL, echo=False)
34
+ async with engine.begin() as conn:
35
+ await conn.run_sync(SQLModel.metadata.create_all)
36
+ return engine
37
+
38
+
39
+ @pytest.mark.asyncio
40
+ async def test_upsert_inserts_when_not_exists():
41
+ """A row with a new ID is inserted."""
42
+ from pgsqlasync2fast_fastapi.seeder import upsert_by_id
43
+
44
+ engine = await _engine()
45
+ async with AsyncSession(engine) as session:
46
+ row = await upsert_by_id(
47
+ session,
48
+ ARole,
49
+ data={"id": 1, "name": "admin", "description": "Administrator"},
50
+ )
51
+ await session.commit()
52
+
53
+ # Re-read to confirm persistence
54
+ from sqlmodel import select
55
+
56
+ stored = (await session.exec(select(ARole).where(ARole.id == 1))).one()
57
+ assert stored.name == "admin"
58
+ assert stored.description == "Administrator"
59
+ assert row.id == 1
60
+ await engine.dispose()
61
+
62
+
63
+ @pytest.mark.asyncio
64
+ async def test_upsert_updates_when_exists():
65
+ """A row with an existing ID is updated with new values."""
66
+ from pgsqlasync2fast_fastapi.seeder import upsert_by_id
67
+ from sqlmodel import select
68
+
69
+ engine = await _engine()
70
+ async with AsyncSession(engine) as session:
71
+ # Insert initial row
72
+ await upsert_by_id(
73
+ session,
74
+ ARole,
75
+ data={"id": 1, "name": "Admin", "description": "Old description"},
76
+ )
77
+ await session.commit()
78
+
79
+ # Verify initial state
80
+ initial = (await session.exec(select(ARole).where(ARole.id == 1))).one()
81
+ assert initial.name == "Admin"
82
+ assert initial.description == "Old description"
83
+
84
+ # Upsert with new values (same ID)
85
+ updated = await upsert_by_id(
86
+ session,
87
+ ARole,
88
+ data={"id": 1, "name": "admin", "description": "New description"},
89
+ )
90
+ await session.commit()
91
+
92
+ # Verify updated state
93
+ final = (await session.exec(select(ARole).where(ARole.id == 1))).one()
94
+ assert final.name == "admin" # Updated
95
+ assert final.description == "New description" # Updated
96
+ assert final.id == 1 # Same ID
97
+ await engine.dispose()
98
+
99
+
100
+ @pytest.mark.asyncio
101
+ async def test_upsert_is_idempotent_for_unchanged_data():
102
+ """Upserting the same data doesn't change the row (no-op)."""
103
+ from pgsqlasync2fast_fastapi.seeder import upsert_by_id
104
+ from sqlmodel import select
105
+
106
+ engine = await _engine()
107
+ async with AsyncSession(engine) as session:
108
+ # Insert initial row
109
+ first = await upsert_by_id(
110
+ session,
111
+ ARole,
112
+ data={"id": 1, "name": "admin", "description": "Admin role"},
113
+ )
114
+ await session.commit()
115
+
116
+ # Upsert with same data
117
+ second = await upsert_by_id(
118
+ session,
119
+ ARole,
120
+ data={"id": 1, "name": "admin", "description": "Admin role"},
121
+ )
122
+ await session.commit()
123
+
124
+ # Only one row should exist
125
+ rows = (await session.exec(select(ARole))).all()
126
+ assert len(rows) == 1
127
+ assert rows[0].name == "admin"
128
+ await engine.dispose()
129
+
130
+
131
+ @pytest.mark.asyncio
132
+ async def test_upsert_raises_without_id():
133
+ """Upsert requires 'id' field in data."""
134
+ from pgsqlasync2fast_fastapi.seeder import upsert_by_id
135
+
136
+ engine = await _engine()
137
+ async with AsyncSession(engine) as session:
138
+ with pytest.raises(ValueError, match="requires 'id' field"):
139
+ await upsert_by_id(
140
+ session,
141
+ ARole,
142
+ data={"name": "admin", "description": "No ID"},
143
+ )
144
+ await engine.dispose()
145
+
146
+
147
+ @pytest.mark.asyncio
148
+ async def test_upsert_multiple_rows():
149
+ """Upsert works correctly with multiple rows in sequence."""
150
+ from pgsqlasync2fast_fastapi.seeder import upsert_by_id
151
+ from sqlmodel import select
152
+
153
+ engine = await _engine()
154
+ async with AsyncSession(engine) as session:
155
+ # Insert 3 roles
156
+ await upsert_by_id(
157
+ session, ARole, data={"id": 1, "name": "admin", "description": "Admin"}
158
+ )
159
+ await upsert_by_id(
160
+ session, ARole, data={"id": 2, "name": "user", "description": "User"}
161
+ )
162
+ await upsert_by_id(
163
+ session, ARole, data={"id": 3, "name": "manager", "description": "Manager"}
164
+ )
165
+ await session.commit()
166
+
167
+ # Verify all 3 exist
168
+ rows = (await session.exec(select(ARole))).all()
169
+ assert len(rows) == 3
170
+
171
+ # Update role 2
172
+ await upsert_by_id(
173
+ session, ARole, data={"id": 2, "name": "member", "description": "Member"}
174
+ )
175
+ await session.commit()
176
+
177
+ # Verify role 2 was updated
178
+ role2 = (await session.exec(select(ARole).where(ARole.id == 2))).one()
179
+ assert role2.name == "member"
180
+
181
+ # Verify other roles unchanged
182
+ role1 = (await session.exec(select(ARole).where(ARole.id == 1))).one()
183
+ assert role1.name == "admin"
184
+ role3 = (await session.exec(select(ARole).where(ARole.id == 3))).one()
185
+ assert role3.name == "manager"
186
+ await engine.dispose()
@@ -1 +0,0 @@
1
- __version__ = "0.5.0"