🗄️ Models (SQLAlchemy)

Models are used to define the structure of data in the application.

SQLAlchemy as the default ORM for database management. SQLAlchemy allows creating database models, executing queries, and handling migrations efficiently.

🔧 Using Models

The `Base` class, imported from `lila.core.database`, serves as the foundation for all models . Models inherit from `Base` to define database tables with SQLAlchemy.

👤 Example: User Model

This example demonstrates how to create a `User` model using SQLAlchemy. The model defines a `users` table with columns such as `id`, `name`, `email`, `password`, `token`, `active`, and `created_at`.
app/models/user.py

        
from sqlalchemy import Column, Integer, String, TIMESTAMP, func
from sqlalchemy.orm import Session
from lila.core.database import Base
from app.connections import connection 

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(length=50), nullable=False)
    email = Column(String(length=50), unique=True)
    password = Column(String(length=150), nullable=False)
    token = Column(String(length=150), nullable=True)
    active = Column(Integer, nullable=False, default=1)
    created_at = Column(TIMESTAMP, nullable=False, server_default=func.now())

    @classmethod
    def get_all(cls, limit: int = 1000):
        db = connection.get_session()
        try:
            result = db.query(cls).filter(cls.active == 1).limit(limit).all()
            return result
        finally:
            db.close()

    @classmethod
    def get_by_id(cls, id: int):
        db = connection.get_session()
        try:
            return db.query(cls).filter(cls.id == id, cls.active == 1).first()
        finally:
            db.close()

# Example usage
users = User.get_all()
user = User.get_by_id(1)
                    
                    

For details on SQLAlchemy, visit the official documentation: SQLAlchemy Documentation.