sisyo 1.7.0 → 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 -166
- package/bin/known-hashes.json +6 -1
- package/bin/sisyo.js +285 -285
- package/package.json +30 -30
- package/templates/.claude/rules/agents-and-tests.md +32 -24
- 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 -125
- package/templates/.claude/skills/g6-style/references/checks.md +58 -58
- package/templates/.claude/skills/g6-style/references/imagery.md +103 -103
- package/templates/.claude/skills/g6-style/references/motion.md +121 -121
- package/templates/.claude/skills/g6-style/references/sections.md +263 -263
- package/templates/.claude/skills/g6-style/references/tokens.md +197 -197
- package/templates/.claude/skills/hindsight/SKILL.md +175 -175
- 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 -153
- package/templates/.claude/skills/i18n-multilang/assets/languages.json +47 -47
- package/templates/.claude/skills/i18n-multilang/assets/plural-vectors.json +46 -46
- package/templates/.claude/skills/i18n-multilang/assets/project/README.md +17 -17
- package/templates/.claude/skills/i18n-multilang/assets/project/gitattributes.txt +6 -6
- package/templates/.claude/skills/i18n-multilang/assets/project/gitignore.txt +4 -4
- package/templates/.claude/skills/i18n-multilang/assets/project/glossary.json +6 -6
- package/templates/.claude/skills/i18n-multilang/assets/project/i18n.config.json +22 -22
- package/templates/.claude/skills/i18n-multilang/assets/project/locales/__source__/common.json +10 -10
- package/templates/.claude/skills/i18n-multilang/assets/project/notes/common.json +5 -5
- package/templates/.claude/skills/i18n-multilang/assets/project/style.md +20 -20
- package/templates/.claude/skills/i18n-multilang/references/format.md +100 -100
- package/templates/.claude/skills/i18n-multilang/references/languages.md +97 -97
- package/templates/.claude/skills/i18n-multilang/references/layout-and-versioning.md +256 -256
- package/templates/.claude/skills/i18n-multilang/references/numbers.md +161 -161
- package/templates/.claude/skills/i18n-multilang/references/platform-unity.md +142 -142
- package/templates/.claude/skills/i18n-multilang/references/platform-web.md +107 -107
- package/templates/.claude/skills/i18n-multilang/references/translation.md +143 -143
- package/templates/.claude/skills/i18n-multilang/references/voice.md +271 -271
- package/templates/.claude/skills/i18n-multilang/scripts/i18n.py +1041 -1041
- package/templates/.claude/skills/i18n-multilang/scripts/numwords.py +1013 -1013
- package/templates/.claude/skills/i18n-multilang/scripts/voice.py +478 -478
- package/templates/.claude/skills/neon-game-ui-ux-skill/COMPONENTS.md +490 -490
- package/templates/.claude/skills/neon-game-ui-ux-skill/GAMIFICATION.md +246 -246
- package/templates/.claude/skills/neon-game-ui-ux-skill/ICONS.md +249 -249
- package/templates/.claude/skills/neon-game-ui-ux-skill/LAYOUT-NAV.md +362 -362
- package/templates/.claude/skills/neon-game-ui-ux-skill/MOTION-A11Y.md +168 -168
- package/templates/.claude/skills/neon-game-ui-ux-skill/SKILL.md +137 -137
- package/templates/.claude/skills/neon-game-ui-ux-skill/TOKENS.md +323 -323
- 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,24 +1,32 @@
|
|
|
1
|
-
# Agents, Tests and Deploys Rule
|
|
2
|
-
|
|
3
|
-
The owner's rules (2026-11-16) for every project. A project's `SISYO.md` may be stricter, never looser.
|
|
4
|
-
|
|
5
|
-
## Models
|
|
6
|
-
- Default: Opus (Opus 5.5 as of 2026-11) at effort `xhigh`, for the main session and for every agent it starts (`model: "opus"`, `effort: "xhigh"`).
|
|
7
|
-
- A model above Opus (Fable) only when the owner names it for a task, typically one about money or something important. Never switch on your own judgement.
|
|
8
|
-
- Small or single-area work is done in the main session. Agents are for work that splits into independent parts running in parallel.
|
|
9
|
-
|
|
10
|
-
## Writing code
|
|
11
|
-
1. Before writing code, read the related parts: the code that calls it and that it calls, the existing tests, the project's skills and docs for the area.
|
|
12
|
-
2. Write the test cases first, then the code.
|
|
13
|
-
3. Working alone: run the tests related to the change once, at the end (the tests of the packages changed, the browser or e2e checks of the pages changed). Not the whole suite.
|
|
14
|
-
4. Agents in parallel: each writes its tests and runs none. When all are done, one pass runs the tests of the combined work once, on the zone the batch touched (lint, typecheck, the touched packages' tests, the changed pages' checks), and fixes what fails.
|
|
15
|
-
5. Nobody runs the project's whole test gate locally "to be sure".
|
|
16
|
-
|
|
17
|
-
##
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
|
|
23
|
-
##
|
|
24
|
-
|
|
1
|
+
# Agents, Tests and Deploys Rule
|
|
2
|
+
|
|
3
|
+
The owner's rules (2026-11-16) for every project. A project's `SISYO.md` may be stricter, never looser.
|
|
4
|
+
|
|
5
|
+
## Models
|
|
6
|
+
- Default: Opus (Opus 5.5 as of 2026-11) at effort `xhigh`, for the main session and for every agent it starts (`model: "opus"`, `effort: "xhigh"`).
|
|
7
|
+
- A model above Opus (Fable) only when the owner names it for a task, typically one about money or something important. Never switch on your own judgement.
|
|
8
|
+
- Small or single-area work is done in the main session. Agents are for work that splits into independent parts running in parallel.
|
|
9
|
+
|
|
10
|
+
## Writing code
|
|
11
|
+
1. Before writing code, read the related parts: the code that calls it and that it calls, the existing tests, the project's skills and docs for the area.
|
|
12
|
+
2. Write the test cases first, then the code.
|
|
13
|
+
3. Working alone: run the tests related to the change once, at the end (the tests of the packages changed, the browser or e2e checks of the pages changed). Not the whole suite.
|
|
14
|
+
4. Agents in parallel: each writes its tests and runs none. When all are done, one pass runs the tests of the combined work once, on the zone the batch touched (lint, typecheck, the touched packages' tests, the changed pages' checks), and fixes what fails.
|
|
15
|
+
5. Nobody runs the project's whole test gate locally "to be sure".
|
|
16
|
+
|
|
17
|
+
## Sessions and agents
|
|
18
|
+
- Do the work in the main session and manage it yourself. Start an agent only for a large part that is independent and truly runs in parallel, never for a short step (a lookup, a build or deploy with the project's existing scripts) that the main session would then sit waiting on.
|
|
19
|
+
- At most 4 agents run at the same time in one session. More parallel work waits for a free place or goes to another session.
|
|
20
|
+
- Keep each batch small: if its changes would make the test pass select most of the project's test groups, split the batch, so each pass runs only the groups that batch touched.
|
|
21
|
+
- A session is not the project's memory; the docs and git are. When a session has run long (about a day of work, a transcript over about 5 MB, tool calls that take minutes to answer, or a frozen tab), write the handoff, end the session, and continue in a new one that starts from the handoff.
|
|
22
|
+
|
|
23
|
+
## Deploys
|
|
24
|
+
- A deploy to dev or staging does not run the whole test gate: build, deploy, smoke check. A broken build still stops it.
|
|
25
|
+
- A deploy that reaches production runs the whole gate on the exact commit released, and deploys nothing if it fails. Where a push to `main` deploys production, that push is a production deploy.
|
|
26
|
+
- The PR's CI run, where a project has one, is the one whole run for a change before production.
|
|
27
|
+
- If a project's CI does not work this way yet, propose the change (a workflow change usually goes through the project's review rule); do not change it on your own.
|
|
28
|
+
|
|
29
|
+
## Why
|
|
30
|
+
Batches took hours: the whole gate ran in each agent, again in each integration pass, on the PR, on the push to `main` and in the dev deploy, the last ones at once on one shared runner host.
|
|
31
|
+
|
|
32
|
+
A long session slowed to a crawl (2026-11-16): one session carried its lead and up to ten agents for a day. Simple file reads and edits took one to three minutes each, while other sessions on the same PC took seconds. The lead waited 2 h 40 min on an agent writing a deploy runbook, and one batch of 811 changed files made the test pass select every group (3 h 30 min).
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
# Doc Management Rule
|
|
2
|
-
|
|
3
|
-
3-level routing: MAP.md → _summary.md → detail files.
|
|
4
|
-
|
|
5
|
-
When changing code that affects project structure or behavior:
|
|
6
|
-
1. Read docs/MAP.md to find relevant folder
|
|
7
|
-
2. Read _summary.md of that folder (if exists)
|
|
8
|
-
3. Update detail file (or create if new)
|
|
9
|
-
4. Update _summary.md table
|
|
10
|
-
5. Update MAP.md summary line
|
|
11
|
-
|
|
12
|
-
When a feature is completed or added:
|
|
13
|
-
- Log it in docs/99_progress/features.md (date, name, status, link to spec)
|
|
14
|
-
|
|
15
|
-
Before ending session or when context gets large:
|
|
16
|
-
- Write docs/99_progress/handoff.md
|
|
17
|
-
|
|
18
|
-
At session start:
|
|
19
|
-
- Read docs/MAP.md then docs/99_progress/handoff.md
|
|
1
|
+
# Doc Management Rule
|
|
2
|
+
|
|
3
|
+
3-level routing: MAP.md → _summary.md → detail files.
|
|
4
|
+
|
|
5
|
+
When changing code that affects project structure or behavior:
|
|
6
|
+
1. Read docs/MAP.md to find relevant folder
|
|
7
|
+
2. Read _summary.md of that folder (if exists)
|
|
8
|
+
3. Update detail file (or create if new)
|
|
9
|
+
4. Update _summary.md table
|
|
10
|
+
5. Update MAP.md summary line
|
|
11
|
+
|
|
12
|
+
When a feature is completed or added:
|
|
13
|
+
- Log it in docs/99_progress/features.md (date, name, status, link to spec)
|
|
14
|
+
|
|
15
|
+
Before ending session or when context gets large:
|
|
16
|
+
- Write docs/99_progress/handoff.md
|
|
17
|
+
|
|
18
|
+
At session start:
|
|
19
|
+
- Read docs/MAP.md then docs/99_progress/handoff.md
|
|
@@ -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
|
+
```
|