wag-managment-api-service-v.../Services/PostgresDb/Models/how_to.py

191 lines
5.7 KiB
Python

"""
How to Use PostgreSQL Models
This module provides examples of how to use the base models and database sessions
effectively in your application.
"""
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Integer
from sqlalchemy.orm import Mapped, mapped_column
from Services.Postgres.Models.my_base_model import CrudCollection
from Services.Postgres.database import get_db
# Example Model Definition
class User(CrudCollection):
"""Example user model demonstrating CrudCollection usage."""
__tablename__ = "users"
# Additional fields (id and other common fields come from CrudCollection)
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
email: Mapped[str] = mapped_column(String(100), unique=True)
age: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# Example Usage
def example_create():
"""Example of creating a new record."""
with get_db() as db:
# Create a new user
user = User.find_or_create(
db, username="john_doe", email="john@example.com", age=30
)
db.commit()
return user
def example_batch_create():
"""Example of creating multiple records in a single transaction."""
with get_db() as db:
try:
# Create multiple users in one transaction
users = []
for i in range(3):
user = User.find_or_create(
db, username=f"user_{i}", email=f"user_{i}@example.com"
)
users.append(user)
db.commit()
return users
except Exception:
db.rollback()
raise
def example_update():
"""Example of updating a record."""
with get_db() as db:
# Find user and update
user = db.query(User).filter(User.username == "john_doe").first()
if user:
user.update(db, email="john.doe@newdomain.com", age=31)
db.commit()
return user
def example_soft_delete():
"""Example of soft deleting a record."""
with get_db() as db:
user = db.query(User).filter(User.username == "john_doe").first()
if user:
# This will set deleted=True instead of actually deleting the record
user.update(db, deleted=True)
db.commit()
def example_query():
"""Example of querying records."""
with get_db() as db:
# Get active (non-deleted) users
active_users = (
db.query(User)
.filter(User.active == True, User.deleted == False, User.age >= 18)
.order_by(User.created_at.desc())
.all()
)
return active_users
def example_complex_transaction():
"""Example of a complex transaction with multiple operations."""
with get_db() as db:
try:
# Multiple operations in single transaction
user = User.find_or_create(db, username="new_user", email="new@example.com")
# Update existing user
other_user = db.query(User).filter(User.username == "old_user").first()
if other_user:
other_user.update(db, email="updated@example.com")
# Soft delete another user
deleted_user = db.query(User).filter(User.username == "to_delete").first()
if deleted_user:
deleted_user.update(db, deleted=True)
# Commit all changes at once
db.commit()
except Exception:
# Rollback all changes if any operation fails
db.rollback()
raise
def example_serialization():
"""Example of serializing records to dictionaries."""
with get_db() as db:
user = db.query(User).first()
if user:
# Get all fields except specified ones
dict_with_excludes = user.get_dict(exclude=["created_at", "updated_at"])
# Get only specified fields
dict_with_includes = user.get_dict(include=["id", "username", "email"])
return {"excluded": dict_with_excludes, "included": dict_with_includes}
def example_confirmation():
"""Example of confirming a record."""
with get_db() as db:
user = db.query(User).filter(User.username == "pending_user").first()
if user:
# Only update confirmation status
user.update(db, is_confirmed=True)
db.commit()
return user
# Example of error handling
def example_error_handling():
"""Example of proper error handling."""
with get_db() as db:
try:
# Attempt to create user
user = User.find_or_create(
db,
username="existing_user", # This might cause unique constraint violation
email="exists@example.com",
)
db.commit()
return {"status": "success", "user": user.get_dict()}
except Exception as e:
db.rollback()
return {
"status": "error",
"message": str(e),
"error_type": e.__class__.__name__,
}
# Example of working with dates
def example_date_handling():
"""Example of working with dates and expiry."""
with get_db() as db:
# Find records valid at current time
current_users = (
db.query(User)
.filter(
User.expiry_starts <= datetime.utcnow(),
User.expiry_ends > datetime.utcnow(),
)
.all()
)
# Set expiry for a user
user = db.query(User).first()
if user:
user.update(db, expiry_ends=datetime(2024, 12, 31, 23, 59, 59))
db.commit()
return current_users