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¶
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¶
-
Tạo file
models/your_model.py: -
Import trong migration env (nếu cần):
-
Tạo và chạy migration: