Bỏ qua

Database & Models

SQLAlchemy ORM

Project sử dụng SQLAlchemy với declarative base pattern để định nghĩa database models.

Course Model

from sqlalchemy import Column, Integer, String, Text
from core.database import Base

class Course(Base):
    __tablename__ = "courses"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(255), nullable=False)
    slug = Column(String(255), unique=True, index=True, nullable=False)
    content_html = Column(Text, nullable=True)
    thumbnail_key = Column(String(512), nullable=True)
Column Type Constraints Mô tả
id Integer PK, auto-increment Primary key
title String(255) NOT NULL Tên khóa học
slug String(255) UNIQUE, INDEX URL-friendly slug
content_html Text Nullable Nội dung HTML
thumbnail_key String(512) Nullable Key file trên R2 storage

Slug Generation

Slug được tạo tự động từ title qua hàm utils/slugify.py. Nếu slug bị trùng, hệ thống tự thêm suffix (-1, -2, ...):

# services/course_service.py
slug = generate_slug(course_data.title)  # "Khóa học Python" → "khoa-hoc-python"
# Nếu trùng → "khoa-hoc-python-1"

Database Connection

Connection Pool

Engine config trong core/database.py:

Setting Giá trị Ý nghĩa
pool_pre_ping True Test connection trước khi dùng
pool_size 5 Số connection giữ sẵn
max_overflow 10 Connection thêm khi pool đầy

Connection String

postgresql://postgres:123456@localhost:5432/course_dev
postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres?sslmode=require

Supabase

Luôn dùng Transaction Mode (Port 6543) cho SQLAlchemy. Port 5432 (Session Mode) sẽ nhanh hết connection pool trên free tier.

Thêm Model mới

  1. Tạo file models/your_model.py:

    from sqlalchemy import Column, Integer, String
    from core.database import Base
    
    class YourModel(Base):
        __tablename__ = "your_table"
        id = Column(Integer, primary_key=True, index=True)
        name = Column(String(255), nullable=False)
    
  2. Import trong migration env (nếu cần):

    # alembic/env.py — đảm bảo import model
    from models.your_model import YourModel
    
  3. Tạo và chạy migration:

    alembic revision --autogenerate -m "Add your_table"
    alembic upgrade head