🗄️ Migrations

In Lila Framework, database migrations can be managed using SQLAlchemy and Lila's configuration to make migrations as easy as possible. The framework now supports command-line migrations through Typer, providing a more intuitive and flexible way to manage your database schema.


📋 Migration Methods

There are two main ways to define database tables:

1. Using Table

This method manually defines the table structure using SQLAlchemy's Table object.

app/models/tables.py

from sqlalchemy import Table, Column, Integer, String, TIMESTAMP
from lila.core.database import Base  # Import Base

table_users = Table(
    'users', Base.metadata, # IMPORTANT: Use Base.metadata
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('name', String(length=50), nullable=False),
    Column('email', String(length=50), unique=True),
    Column('password', String(length=150), nullable=False),
    Column('token', String(length=150), nullable=False),
    Column('active', Integer, default=1, nullable=False),
    Column('created_at', TIMESTAMP),
)
                                    

2. Using Models (Recommended)

This approach defines database tables as Python classes that inherit from "Base". This is the recommended method as it provides more structure and ORM capabilities.

app/models/user.py

from lila.core.database import Base
from sqlalchemy import Column, Integer, String, TIMESTAMP

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=False)
    active = Column(Integer, nullable=False, default=1)
    created_at = Column(TIMESTAMP)
                                    
Run Migrations

Once your model is defined in app/models/, Lila will automatically load it to register it in the database. Simply run:

Terminal
lila-migrations migrate

🚀 Running Migrations

To execute migrations, use the following command in your terminal:

Terminal Command

# Basic migration
lila-migrations 

# Refresh all tables (drop and recreate)
lila-migrations --refresh
                                    

Command Options

Note: When using Models, make sure to import all your model classes in the migrations file so SQLAlchemy can detect them for migrations.