pgsqlasync2fast-fastapi 0.5.0__py3-none-any.whl → 0.5.1__py3-none-any.whl

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.
@@ -1 +1 @@
1
- __version__ = "0.5.0"
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
@@ -1,17 +1,17 @@
1
1
  pgsqlasync2fast_fastapi/__init__.py,sha256=-U0xx28dHrtx7HnexGqZOmFGJs0Qx4SzB-1SIQxypos,2884
2
- pgsqlasync2fast_fastapi/__version__.py,sha256=LBK46heutvn3KmsCrKIYu8RQikbfnjZaj2xFrXaeCzQ,22
2
+ pgsqlasync2fast_fastapi/__version__.py,sha256=eZ1bOun1DDVV0YLOBW4wj2FP1ajReLjbIrGmzN7ASBw,22
3
3
  pgsqlasync2fast_fastapi/connection.py,sha256=vyR3SLpLTENYGKWkEoou0ud5IwUOJ9ksfkysUW5tz-I,6168
4
4
  pgsqlasync2fast_fastapi/database.py,sha256=t6i8V4Bbec0sPoWYsBPScSqQpde1tVkqGx0CBRnAupk,8856
5
5
  pgsqlasync2fast_fastapi/dependencies.py,sha256=jgX14S6h6i4Uk6edMDGh-wiDpxTlB16qvYMlIm1QofQ,4444
6
- pgsqlasync2fast_fastapi/seeder.py,sha256=b_7fKP19Qh08NaTyY4kA7HL48dqZIE-Re5I-ki3M5a4,33284
6
+ pgsqlasync2fast_fastapi/seeder.py,sha256=s6Qo2eAgMRKydcJg4PmB4107rgWL1yR0WYuhlhFzDcI,35955
7
7
  pgsqlasync2fast_fastapi/settings.py,sha256=9SAmEVtotKJYlbTjI4qkKBjEOghTTtaICAFBBrR-eHk,6678
8
8
  pgsqlasync2fast_fastapi/migrations/__init__.py,sha256=MNfOsJCNpkDyWpp5n7n_KHOm8BomXsVIccdfi-UjovM,1546
9
9
  pgsqlasync2fast_fastapi/migrations/env.py,sha256=sVmPKWHbeuXeSVKAgRZrsTxy92CWW3-fBbUOs-kRUms,4531
10
10
  pgsqlasync2fast_fastapi/migrations/registry.py,sha256=L2fOmXgtQUPUtrKajczq3031kavF0R3TC_qiQl8glv4,2111
11
11
  pgsqlasync2fast_fastapi/migrations/runner.py,sha256=vwahudRUHcfkJqHpa-YjX2QE8t3wczargORghspg9K0,5713
12
12
  pgsqlasync2fast_fastapi/skills/SKILL.md,sha256=z-7VP85jUuzmwYIlT7n9yoC7a-QNcLp1jy_zdkAUHl8,8156
13
- pgsqlasync2fast_fastapi-0.5.0.dist-info/licenses/LICENSE,sha256=CkISX1hNEwxxrPTOXet3IYMEH28Bn7SoUyKniRjg68I,1086
14
- pgsqlasync2fast_fastapi-0.5.0.dist-info/METADATA,sha256=BeMGdjPyYerBuuxiDXzxx98YEiGpjPbJszL8W29urIA,10136
15
- pgsqlasync2fast_fastapi-0.5.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
16
- pgsqlasync2fast_fastapi-0.5.0.dist-info/top_level.txt,sha256=7pllDm9nlFGWKJDtG5zukxqdADqjZddU-GzaQJPLMVc,24
17
- pgsqlasync2fast_fastapi-0.5.0.dist-info/RECORD,,
13
+ pgsqlasync2fast_fastapi-0.5.1.dist-info/licenses/LICENSE,sha256=CkISX1hNEwxxrPTOXet3IYMEH28Bn7SoUyKniRjg68I,1086
14
+ pgsqlasync2fast_fastapi-0.5.1.dist-info/METADATA,sha256=HzgTDbmMTeb7uKlfAifqChHrH_UGeorYSYBSm2euTPk,10136
15
+ pgsqlasync2fast_fastapi-0.5.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
16
+ pgsqlasync2fast_fastapi-0.5.1.dist-info/top_level.txt,sha256=7pllDm9nlFGWKJDtG5zukxqdADqjZddU-GzaQJPLMVc,24
17
+ pgsqlasync2fast_fastapi-0.5.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5