42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
from sqlalchemy import create_engine, select
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
from allmende_payment_system.models import User
|
|
|
|
SQLALCHEMY_DATABASE_URL = "sqlite:///./aps_db.db"
|
|
engine = create_engine(SQLALCHEMY_DATABASE_URL)
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
|
|
def create_tables():
|
|
from allmende_payment_system.models import Base
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
|
|
def ensure_user(user_info: dict, session: Session) -> User:
|
|
"""
|
|
Retrieve an existing user or create a new one if it doesn't exist.
|
|
This function queries the database for a user with the given username.
|
|
If found, it returns the existing user. If not found, it creates a new user
|
|
with the provided information, adds it to the session, and returns it.
|
|
|
|
:param user_info: Dictionary containing user information with keys:
|
|
- "username" (str): The unique username to search for or create
|
|
- "display_name" (str, optional): The display name for the new user
|
|
:param session: SQLAlchemy session for database operations
|
|
:return: The existing or newly created user object
|
|
"""
|
|
statement = select(User).where(User.username == user_info["username"])
|
|
|
|
if user := session.scalars(statement).one_or_none():
|
|
return user
|
|
|
|
user = User(
|
|
username=user_info["username"], display_name=user_info.get("display_name")
|
|
)
|
|
session.add(user)
|
|
session.flush()
|
|
|
|
return user
|