sisyo 1.6.8 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +16 -16
- package/README.md +167 -162
- package/bin/known-hashes.json +100 -7
- package/package.json +1 -1
- package/templates/.claude/rules/agents-and-tests.md +32 -0
- package/templates/.claude/rules/docs.md +19 -19
- package/templates/.claude/skills/fastapi-best-practices/ASYNC-PATTERNS.md +121 -121
- package/templates/.claude/skills/fastapi-best-practices/DATABASE.md +153 -153
- package/templates/.claude/skills/fastapi-best-practices/DEPENDENCIES.md +140 -140
- package/templates/.claude/skills/fastapi-best-practices/PROJECT-STRUCTURE.md +90 -90
- package/templates/.claude/skills/fastapi-best-practices/PYDANTIC-GUIDE.md +155 -155
- package/templates/.claude/skills/fastapi-best-practices/SKILL.md +123 -123
- package/templates/.claude/skills/g6-style/SKILL.md +125 -0
- package/templates/.claude/skills/g6-style/references/checks.md +58 -0
- package/templates/.claude/skills/g6-style/references/imagery.md +103 -0
- package/templates/.claude/skills/g6-style/references/motion.md +121 -0
- package/templates/.claude/skills/g6-style/references/sections.md +263 -0
- package/templates/.claude/skills/g6-style/references/tokens.md +197 -0
- package/templates/.claude/skills/hindsight/SKILL.md +175 -172
- package/templates/.claude/skills/hoang-auth/SKILL.md +188 -0
- package/templates/.claude/skills/html-docs/SKILL.md +207 -207
- package/templates/.claude/skills/i18n-multilang/SKILL.md +153 -0
- package/templates/.claude/skills/i18n-multilang/assets/languages.json +47 -0
- package/templates/.claude/skills/i18n-multilang/assets/plural-vectors.json +46 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/README.md +17 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/gitattributes.txt +6 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/gitignore.txt +4 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/glossary.json +6 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/i18n.config.json +22 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/locales/__source__/common.json +10 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/notes/common.json +5 -0
- package/templates/.claude/skills/i18n-multilang/assets/project/style.md +20 -0
- package/templates/.claude/skills/i18n-multilang/references/format.md +100 -0
- package/templates/.claude/skills/i18n-multilang/references/languages.md +97 -0
- package/templates/.claude/skills/i18n-multilang/references/layout-and-versioning.md +256 -0
- package/templates/.claude/skills/i18n-multilang/references/numbers.md +161 -0
- package/templates/.claude/skills/i18n-multilang/references/platform-unity.md +142 -0
- package/templates/.claude/skills/i18n-multilang/references/platform-web.md +107 -0
- package/templates/.claude/skills/i18n-multilang/references/translation.md +143 -0
- package/templates/.claude/skills/i18n-multilang/references/voice.md +271 -0
- package/templates/.claude/skills/i18n-multilang/scripts/i18n.py +1041 -0
- package/templates/.claude/skills/i18n-multilang/scripts/numwords.py +1013 -0
- package/templates/.claude/skills/i18n-multilang/scripts/voice.py +478 -0
- package/templates/.claude/skills/react-page-oriented/SKILL.md +407 -407
- package/templates/.claude/skills/react-page-oriented/triggers.md +12 -12
- package/templates/.claude/skills/terraform-best-practices/SKILL.md +341 -341
- package/templates/.claude/skills/typesafe-jev/SKILL.md +148 -148
- package/templates/.claude/skills/vibe-docs/SKILL.md +242 -242
- package/templates/SISYO.md +37 -37
- package/templates/docs/99_progress/features.md +7 -7
- package/templates/docs/99_progress/handoff.md +19 -19
- package/templates/docs/99_progress/todo.md +15 -15
- package/templates/docs/MAP.md +26 -26
|
@@ -1,121 +1,121 @@
|
|
|
1
|
-
# Async Patterns
|
|
2
|
-
|
|
3
|
-
## Route Types Comparison
|
|
4
|
-
|
|
5
|
-
| Route Type | Blocking Code | Event Loop | Use Case |
|
|
6
|
-
|------------|--------------|------------|----------|
|
|
7
|
-
| `async def` + `await` | Non-blocking | Free | Async I/O (httpx, asyncpg) |
|
|
8
|
-
| `def` (sync) | Runs in threadpool | Free | Sync libraries, simple ops |
|
|
9
|
-
| `async def` + blocking | BLOCKS EVERYTHING | Blocked | NEVER DO THIS |
|
|
10
|
-
|
|
11
|
-
## I/O Operations
|
|
12
|
-
|
|
13
|
-
### Async Database Calls
|
|
14
|
-
|
|
15
|
-
```python
|
|
16
|
-
# GOOD - async database
|
|
17
|
-
@router.get("/users/{user_id}")
|
|
18
|
-
async def get_user(user_id: int):
|
|
19
|
-
user = await db.fetch_one("SELECT * FROM users WHERE id = $1", user_id)
|
|
20
|
-
return user
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
### Sync Libraries in Async Routes
|
|
24
|
-
|
|
25
|
-
```python
|
|
26
|
-
from fastapi.concurrency import run_in_threadpool
|
|
27
|
-
|
|
28
|
-
@router.get("/sync-lib")
|
|
29
|
-
async def use_sync_library():
|
|
30
|
-
# Run sync code in threadpool
|
|
31
|
-
result = await run_in_threadpool(sync_client.fetch_data)
|
|
32
|
-
return result
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
### HTTP Calls
|
|
36
|
-
|
|
37
|
-
```python
|
|
38
|
-
import httpx
|
|
39
|
-
|
|
40
|
-
# GOOD - async HTTP client
|
|
41
|
-
@router.get("/external")
|
|
42
|
-
async def call_external():
|
|
43
|
-
async with httpx.AsyncClient() as client:
|
|
44
|
-
response = await client.get("https://api.example.com/data")
|
|
45
|
-
return response.json()
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
## CPU-Intensive Tasks
|
|
49
|
-
|
|
50
|
-
CPU-bound work blocks regardless of async/sync. Offload to workers:
|
|
51
|
-
|
|
52
|
-
```python
|
|
53
|
-
from fastapi import BackgroundTasks
|
|
54
|
-
|
|
55
|
-
@router.post("/process")
|
|
56
|
-
async def process_data(background_tasks: BackgroundTasks):
|
|
57
|
-
# Queue for background processing
|
|
58
|
-
background_tasks.add_task(heavy_computation, data)
|
|
59
|
-
return {"status": "processing"}
|
|
60
|
-
|
|
61
|
-
# For heavy CPU work, use Celery or multiprocessing
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
## Common Mistakes
|
|
65
|
-
|
|
66
|
-
### Blocking in Async Route
|
|
67
|
-
|
|
68
|
-
```python
|
|
69
|
-
# BAD - blocks entire server
|
|
70
|
-
@router.get("/terrible")
|
|
71
|
-
async def terrible():
|
|
72
|
-
time.sleep(10) # NEVER do this in async route
|
|
73
|
-
return {"done": True}
|
|
74
|
-
|
|
75
|
-
# GOOD - use sync route for blocking code
|
|
76
|
-
@router.get("/acceptable")
|
|
77
|
-
def acceptable():
|
|
78
|
-
time.sleep(10) # runs in threadpool
|
|
79
|
-
return {"done": True}
|
|
80
|
-
|
|
81
|
-
# BEST - use async sleep
|
|
82
|
-
@router.get("/perfect")
|
|
83
|
-
async def perfect():
|
|
84
|
-
await asyncio.sleep(10)
|
|
85
|
-
return {"done": True}
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
### Sync ORM in Async Route
|
|
89
|
-
|
|
90
|
-
```python
|
|
91
|
-
# BAD
|
|
92
|
-
@router.get("/users")
|
|
93
|
-
async def get_users():
|
|
94
|
-
return db.query(User).all() # sync ORM blocks event loop
|
|
95
|
-
|
|
96
|
-
# GOOD - use async ORM or threadpool
|
|
97
|
-
@router.get("/users")
|
|
98
|
-
async def get_users():
|
|
99
|
-
return await run_in_threadpool(lambda: db.query(User).all())
|
|
100
|
-
|
|
101
|
-
# BEST - use async ORM (SQLAlchemy 2.0 async)
|
|
102
|
-
@router.get("/users")
|
|
103
|
-
async def get_users():
|
|
104
|
-
result = await session.execute(select(User))
|
|
105
|
-
return result.scalars().all()
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
## Dependencies
|
|
109
|
-
|
|
110
|
-
Prefer async dependencies when possible:
|
|
111
|
-
|
|
112
|
-
```python
|
|
113
|
-
# GOOD - async dependency
|
|
114
|
-
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
115
|
-
user = await users_service.get_by_token(token)
|
|
116
|
-
return user
|
|
117
|
-
|
|
118
|
-
# OK but less efficient - sync dependency runs in threadpool
|
|
119
|
-
def get_settings():
|
|
120
|
-
return Settings()
|
|
121
|
-
```
|
|
1
|
+
# Async Patterns
|
|
2
|
+
|
|
3
|
+
## Route Types Comparison
|
|
4
|
+
|
|
5
|
+
| Route Type | Blocking Code | Event Loop | Use Case |
|
|
6
|
+
|------------|--------------|------------|----------|
|
|
7
|
+
| `async def` + `await` | Non-blocking | Free | Async I/O (httpx, asyncpg) |
|
|
8
|
+
| `def` (sync) | Runs in threadpool | Free | Sync libraries, simple ops |
|
|
9
|
+
| `async def` + blocking | BLOCKS EVERYTHING | Blocked | NEVER DO THIS |
|
|
10
|
+
|
|
11
|
+
## I/O Operations
|
|
12
|
+
|
|
13
|
+
### Async Database Calls
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
# GOOD - async database
|
|
17
|
+
@router.get("/users/{user_id}")
|
|
18
|
+
async def get_user(user_id: int):
|
|
19
|
+
user = await db.fetch_one("SELECT * FROM users WHERE id = $1", user_id)
|
|
20
|
+
return user
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Sync Libraries in Async Routes
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from fastapi.concurrency import run_in_threadpool
|
|
27
|
+
|
|
28
|
+
@router.get("/sync-lib")
|
|
29
|
+
async def use_sync_library():
|
|
30
|
+
# Run sync code in threadpool
|
|
31
|
+
result = await run_in_threadpool(sync_client.fetch_data)
|
|
32
|
+
return result
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### HTTP Calls
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import httpx
|
|
39
|
+
|
|
40
|
+
# GOOD - async HTTP client
|
|
41
|
+
@router.get("/external")
|
|
42
|
+
async def call_external():
|
|
43
|
+
async with httpx.AsyncClient() as client:
|
|
44
|
+
response = await client.get("https://api.example.com/data")
|
|
45
|
+
return response.json()
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## CPU-Intensive Tasks
|
|
49
|
+
|
|
50
|
+
CPU-bound work blocks regardless of async/sync. Offload to workers:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from fastapi import BackgroundTasks
|
|
54
|
+
|
|
55
|
+
@router.post("/process")
|
|
56
|
+
async def process_data(background_tasks: BackgroundTasks):
|
|
57
|
+
# Queue for background processing
|
|
58
|
+
background_tasks.add_task(heavy_computation, data)
|
|
59
|
+
return {"status": "processing"}
|
|
60
|
+
|
|
61
|
+
# For heavy CPU work, use Celery or multiprocessing
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Common Mistakes
|
|
65
|
+
|
|
66
|
+
### Blocking in Async Route
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# BAD - blocks entire server
|
|
70
|
+
@router.get("/terrible")
|
|
71
|
+
async def terrible():
|
|
72
|
+
time.sleep(10) # NEVER do this in async route
|
|
73
|
+
return {"done": True}
|
|
74
|
+
|
|
75
|
+
# GOOD - use sync route for blocking code
|
|
76
|
+
@router.get("/acceptable")
|
|
77
|
+
def acceptable():
|
|
78
|
+
time.sleep(10) # runs in threadpool
|
|
79
|
+
return {"done": True}
|
|
80
|
+
|
|
81
|
+
# BEST - use async sleep
|
|
82
|
+
@router.get("/perfect")
|
|
83
|
+
async def perfect():
|
|
84
|
+
await asyncio.sleep(10)
|
|
85
|
+
return {"done": True}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Sync ORM in Async Route
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
# BAD
|
|
92
|
+
@router.get("/users")
|
|
93
|
+
async def get_users():
|
|
94
|
+
return db.query(User).all() # sync ORM blocks event loop
|
|
95
|
+
|
|
96
|
+
# GOOD - use async ORM or threadpool
|
|
97
|
+
@router.get("/users")
|
|
98
|
+
async def get_users():
|
|
99
|
+
return await run_in_threadpool(lambda: db.query(User).all())
|
|
100
|
+
|
|
101
|
+
# BEST - use async ORM (SQLAlchemy 2.0 async)
|
|
102
|
+
@router.get("/users")
|
|
103
|
+
async def get_users():
|
|
104
|
+
result = await session.execute(select(User))
|
|
105
|
+
return result.scalars().all()
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Dependencies
|
|
109
|
+
|
|
110
|
+
Prefer async dependencies when possible:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
# GOOD - async dependency
|
|
114
|
+
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
115
|
+
user = await users_service.get_by_token(token)
|
|
116
|
+
return user
|
|
117
|
+
|
|
118
|
+
# OK but less efficient - sync dependency runs in threadpool
|
|
119
|
+
def get_settings():
|
|
120
|
+
return Settings()
|
|
121
|
+
```
|
|
@@ -1,153 +1,153 @@
|
|
|
1
|
-
# Database Patterns
|
|
2
|
-
|
|
3
|
-
## Naming Conventions
|
|
4
|
-
|
|
5
|
-
| Convention | Rule | Example |
|
|
6
|
-
|------------|------|---------|
|
|
7
|
-
| Tables | `lower_case_snake`, singular | `post`, `user_playlist` |
|
|
8
|
-
| Group by module | prefix with module | `payment_account`, `payment_bill` |
|
|
9
|
-
| Datetime columns | `_at` suffix | `created_at`, `updated_at` |
|
|
10
|
-
| Date columns | `_date` suffix | `birth_date`, `due_date` |
|
|
11
|
-
|
|
12
|
-
## SQLAlchemy Index Naming
|
|
13
|
-
|
|
14
|
-
```python
|
|
15
|
-
from sqlalchemy import MetaData
|
|
16
|
-
|
|
17
|
-
POSTGRES_INDEXES_NAMING_CONVENTION = {
|
|
18
|
-
"ix": "%(column_0_label)s_idx",
|
|
19
|
-
"uq": "%(table_name)s_%(column_0_name)s_key",
|
|
20
|
-
"ck": "%(table_name)s_%(constraint_name)s_check",
|
|
21
|
-
"fk": "%(table_name)s_%(column_0_name)s_fkey",
|
|
22
|
-
"pk": "%(table_name)s_pkey",
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION)
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
## SQL-First Approach
|
|
29
|
-
|
|
30
|
-
Let database do the heavy lifting:
|
|
31
|
-
|
|
32
|
-
```python
|
|
33
|
-
from sqlalchemy import select, func, text, desc
|
|
34
|
-
|
|
35
|
-
async def get_posts_with_creator(
|
|
36
|
-
creator_id: UUID4,
|
|
37
|
-
limit: int = 10,
|
|
38
|
-
offset: int = 0
|
|
39
|
-
) -> list[dict]:
|
|
40
|
-
query = (
|
|
41
|
-
select(
|
|
42
|
-
posts.c.id,
|
|
43
|
-
posts.c.title,
|
|
44
|
-
posts.c.slug,
|
|
45
|
-
# Build JSON in database
|
|
46
|
-
func.json_build_object(
|
|
47
|
-
text("'id', profiles.id"),
|
|
48
|
-
text("'name', profiles.name"),
|
|
49
|
-
text("'username', profiles.username"),
|
|
50
|
-
).label("creator"),
|
|
51
|
-
)
|
|
52
|
-
.select_from(posts.join(profiles, posts.c.owner_id == profiles.c.id))
|
|
53
|
-
.where(posts.c.owner_id == creator_id)
|
|
54
|
-
.order_by(desc(posts.c.created_at))
|
|
55
|
-
.limit(limit)
|
|
56
|
-
.offset(offset)
|
|
57
|
-
)
|
|
58
|
-
return await database.fetch_all(query)
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
## Alembic Migrations
|
|
62
|
-
|
|
63
|
-
### Config
|
|
64
|
-
|
|
65
|
-
```ini
|
|
66
|
-
# alembic.ini
|
|
67
|
-
file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(slug)s
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
Generates: `2024-01-15_add_user_email_index.py`
|
|
71
|
-
|
|
72
|
-
### Migration Best Practices
|
|
73
|
-
|
|
74
|
-
1. **Always reversible** - include `downgrade()` function
|
|
75
|
-
2. **Descriptive names** - `add_posts_title_idx`, not `update_1`
|
|
76
|
-
3. **Static structure** - only data can be dynamic, not schema
|
|
77
|
-
|
|
78
|
-
```python
|
|
79
|
-
# Good migration
|
|
80
|
-
def upgrade():
|
|
81
|
-
op.add_column('users', sa.Column('avatar_url', sa.String(500)))
|
|
82
|
-
op.create_index('users_email_idx', 'users', ['email'])
|
|
83
|
-
|
|
84
|
-
def downgrade():
|
|
85
|
-
op.drop_index('users_email_idx', 'users')
|
|
86
|
-
op.drop_column('users', 'avatar_url')
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
## Async Database Setup
|
|
90
|
-
|
|
91
|
-
```python
|
|
92
|
-
# src/database.py
|
|
93
|
-
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
94
|
-
from sqlalchemy.orm import sessionmaker
|
|
95
|
-
|
|
96
|
-
engine = create_async_engine(
|
|
97
|
-
settings.DATABASE_URL,
|
|
98
|
-
echo=settings.ENVIRONMENT == "local",
|
|
99
|
-
)
|
|
100
|
-
|
|
101
|
-
async_session = sessionmaker(
|
|
102
|
-
engine,
|
|
103
|
-
class_=AsyncSession,
|
|
104
|
-
expire_on_commit=False,
|
|
105
|
-
)
|
|
106
|
-
|
|
107
|
-
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|
108
|
-
async with async_session() as session:
|
|
109
|
-
try:
|
|
110
|
-
yield session
|
|
111
|
-
await session.commit()
|
|
112
|
-
except Exception:
|
|
113
|
-
await session.rollback()
|
|
114
|
-
raise
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
## Query Patterns
|
|
118
|
-
|
|
119
|
-
### Pagination
|
|
120
|
-
|
|
121
|
-
```python
|
|
122
|
-
from pydantic import BaseModel
|
|
123
|
-
|
|
124
|
-
class PaginationParams(BaseModel):
|
|
125
|
-
limit: int = 10
|
|
126
|
-
offset: int = 0
|
|
127
|
-
|
|
128
|
-
async def get_paginated(
|
|
129
|
-
session: AsyncSession,
|
|
130
|
-
params: PaginationParams
|
|
131
|
-
) -> list[Post]:
|
|
132
|
-
result = await session.execute(
|
|
133
|
-
select(Post)
|
|
134
|
-
.order_by(Post.created_at.desc())
|
|
135
|
-
.limit(params.limit)
|
|
136
|
-
.offset(params.offset)
|
|
137
|
-
)
|
|
138
|
-
return result.scalars().all()
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
### Eager Loading
|
|
142
|
-
|
|
143
|
-
```python
|
|
144
|
-
from sqlalchemy.orm import selectinload
|
|
145
|
-
|
|
146
|
-
# Avoid N+1 queries
|
|
147
|
-
async def get_posts_with_comments(session: AsyncSession):
|
|
148
|
-
result = await session.execute(
|
|
149
|
-
select(Post)
|
|
150
|
-
.options(selectinload(Post.comments))
|
|
151
|
-
)
|
|
152
|
-
return result.scalars().all()
|
|
153
|
-
```
|
|
1
|
+
# Database Patterns
|
|
2
|
+
|
|
3
|
+
## Naming Conventions
|
|
4
|
+
|
|
5
|
+
| Convention | Rule | Example |
|
|
6
|
+
|------------|------|---------|
|
|
7
|
+
| Tables | `lower_case_snake`, singular | `post`, `user_playlist` |
|
|
8
|
+
| Group by module | prefix with module | `payment_account`, `payment_bill` |
|
|
9
|
+
| Datetime columns | `_at` suffix | `created_at`, `updated_at` |
|
|
10
|
+
| Date columns | `_date` suffix | `birth_date`, `due_date` |
|
|
11
|
+
|
|
12
|
+
## SQLAlchemy Index Naming
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from sqlalchemy import MetaData
|
|
16
|
+
|
|
17
|
+
POSTGRES_INDEXES_NAMING_CONVENTION = {
|
|
18
|
+
"ix": "%(column_0_label)s_idx",
|
|
19
|
+
"uq": "%(table_name)s_%(column_0_name)s_key",
|
|
20
|
+
"ck": "%(table_name)s_%(constraint_name)s_check",
|
|
21
|
+
"fk": "%(table_name)s_%(column_0_name)s_fkey",
|
|
22
|
+
"pk": "%(table_name)s_pkey",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
metadata = MetaData(naming_convention=POSTGRES_INDEXES_NAMING_CONVENTION)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## SQL-First Approach
|
|
29
|
+
|
|
30
|
+
Let database do the heavy lifting:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from sqlalchemy import select, func, text, desc
|
|
34
|
+
|
|
35
|
+
async def get_posts_with_creator(
|
|
36
|
+
creator_id: UUID4,
|
|
37
|
+
limit: int = 10,
|
|
38
|
+
offset: int = 0
|
|
39
|
+
) -> list[dict]:
|
|
40
|
+
query = (
|
|
41
|
+
select(
|
|
42
|
+
posts.c.id,
|
|
43
|
+
posts.c.title,
|
|
44
|
+
posts.c.slug,
|
|
45
|
+
# Build JSON in database
|
|
46
|
+
func.json_build_object(
|
|
47
|
+
text("'id', profiles.id"),
|
|
48
|
+
text("'name', profiles.name"),
|
|
49
|
+
text("'username', profiles.username"),
|
|
50
|
+
).label("creator"),
|
|
51
|
+
)
|
|
52
|
+
.select_from(posts.join(profiles, posts.c.owner_id == profiles.c.id))
|
|
53
|
+
.where(posts.c.owner_id == creator_id)
|
|
54
|
+
.order_by(desc(posts.c.created_at))
|
|
55
|
+
.limit(limit)
|
|
56
|
+
.offset(offset)
|
|
57
|
+
)
|
|
58
|
+
return await database.fetch_all(query)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Alembic Migrations
|
|
62
|
+
|
|
63
|
+
### Config
|
|
64
|
+
|
|
65
|
+
```ini
|
|
66
|
+
# alembic.ini
|
|
67
|
+
file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(slug)s
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Generates: `2024-01-15_add_user_email_index.py`
|
|
71
|
+
|
|
72
|
+
### Migration Best Practices
|
|
73
|
+
|
|
74
|
+
1. **Always reversible** - include `downgrade()` function
|
|
75
|
+
2. **Descriptive names** - `add_posts_title_idx`, not `update_1`
|
|
76
|
+
3. **Static structure** - only data can be dynamic, not schema
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# Good migration
|
|
80
|
+
def upgrade():
|
|
81
|
+
op.add_column('users', sa.Column('avatar_url', sa.String(500)))
|
|
82
|
+
op.create_index('users_email_idx', 'users', ['email'])
|
|
83
|
+
|
|
84
|
+
def downgrade():
|
|
85
|
+
op.drop_index('users_email_idx', 'users')
|
|
86
|
+
op.drop_column('users', 'avatar_url')
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Async Database Setup
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
# src/database.py
|
|
93
|
+
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
94
|
+
from sqlalchemy.orm import sessionmaker
|
|
95
|
+
|
|
96
|
+
engine = create_async_engine(
|
|
97
|
+
settings.DATABASE_URL,
|
|
98
|
+
echo=settings.ENVIRONMENT == "local",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
async_session = sessionmaker(
|
|
102
|
+
engine,
|
|
103
|
+
class_=AsyncSession,
|
|
104
|
+
expire_on_commit=False,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|
108
|
+
async with async_session() as session:
|
|
109
|
+
try:
|
|
110
|
+
yield session
|
|
111
|
+
await session.commit()
|
|
112
|
+
except Exception:
|
|
113
|
+
await session.rollback()
|
|
114
|
+
raise
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Query Patterns
|
|
118
|
+
|
|
119
|
+
### Pagination
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from pydantic import BaseModel
|
|
123
|
+
|
|
124
|
+
class PaginationParams(BaseModel):
|
|
125
|
+
limit: int = 10
|
|
126
|
+
offset: int = 0
|
|
127
|
+
|
|
128
|
+
async def get_paginated(
|
|
129
|
+
session: AsyncSession,
|
|
130
|
+
params: PaginationParams
|
|
131
|
+
) -> list[Post]:
|
|
132
|
+
result = await session.execute(
|
|
133
|
+
select(Post)
|
|
134
|
+
.order_by(Post.created_at.desc())
|
|
135
|
+
.limit(params.limit)
|
|
136
|
+
.offset(params.offset)
|
|
137
|
+
)
|
|
138
|
+
return result.scalars().all()
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Eager Loading
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from sqlalchemy.orm import selectinload
|
|
145
|
+
|
|
146
|
+
# Avoid N+1 queries
|
|
147
|
+
async def get_posts_with_comments(session: AsyncSession):
|
|
148
|
+
result = await session.execute(
|
|
149
|
+
select(Post)
|
|
150
|
+
.options(selectinload(Post.comments))
|
|
151
|
+
)
|
|
152
|
+
return result.scalars().all()
|
|
153
|
+
```
|