[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,220 @@
|
||||
id: wiki-2026-0508-schema
|
||||
title: Schema
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-SCHE-001]
|
||||
aliases: [Data Schema, Schema Definition]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.94
|
||||
tags: [auto-reinforced, schema, data-structure, organization, blueprint, database-design]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [schema, validation, zod, json-schema, database]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript
|
||||
framework: Zod 4
|
||||
---
|
||||
|
||||
# [[Schema]]
|
||||
# Schema
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터의 골격: 수만 개의 정보가 중구난방으로 쌓이지 않도록, 각각의 이름과 형식을 미리 정의해 둔 설계도이자, 시스템이 '이 데이터가 여기에 들어갈 자리가 맞는지'를 즉각 판별하게 돕는 질서의 틀."
|
||||
## 매 한 줄
|
||||
> **"매 schema 는 data 의 contract — 매 runtime + compile-time 양쪽에서 enforce"**. 매 origin 은 1970s relational DB DDL; 매 modern state 는 Zod 4 (TS-first, runtime + types), JSON Schema 2020-12, Schema.org (web), Avro/Protobuf (wire), Postgres 17 declarative migration.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
스키마(Schema)는 자료의 구조, 자료의 표현 방법, 자료 간의 관계를 형식 언어로 정의한 것입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **3대 유형**:
|
||||
* **Conceptual Schema**: 사용자 관점에서의 전체적인 데이터 구조 (개념적 설계).
|
||||
* **[[Logic]]al Schema**: DBMS가 이해할 수 있는 구체적인 테이블과 관계 정의. ([[Relational-Database]]와 연결)
|
||||
* **Physical Schema**: 실제 저장 장치에 데이터가 어떻게 박힐지 결정.
|
||||
2. **왜 중요한가?**:
|
||||
* 스키마가 없는 지식 시스템은 결국 쓰레기통(Data swamp)이 되기 때문이며, 데이터의 무결성(Inte[[Grit]]y)과 검색 효율성을 보장하는 유일한 방법임. ([[Scalability]]의 전제 조건)
|
||||
### 매 schema layer (매 stack 별)
|
||||
- **DB schema**: DDL (Postgres `CREATE TABLE`), constraints, indexes.
|
||||
- **Wire schema**: Protobuf, Avro, JSON Schema — 매 inter-service contract.
|
||||
- **App-runtime schema**: Zod, Pydantic, Valibot — 매 API boundary 의 validation.
|
||||
- **Web schema**: Schema.org JSON-LD — 매 SEO + semantic web.
|
||||
- **AI schema**: 매 LLM structured output (OpenAI structured outputs, Anthropic tool use schema).
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 한 번 정하면 바꾸기 힘든 '경직된 정책(Hard schema)'이었으나, 현대 정책은 지식의 변화에 따라 구조를 유연하게 확장하는 '스키마리스(NoSQL) 정책'이나 '동적 스키마 정책'과 상호 보완하며 발전함(RL Update).
|
||||
- **정책 변화(RL Update)**: 본 시스템의 메타데이터(YAML) 정책 또한 일종의 지식 스키마 정책이며, `P-Reinforce` 프로토콜 정책을 통해 모든 지식 파일이 통일된 구조 정책을 유지하도록 강제 중임.
|
||||
### 매 Zod 4 의 modern 위치 (2026)
|
||||
- 매 single source of truth → infer TS type + runtime validate + JSON Schema 변환.
|
||||
- v4 (2026) 의 major: pure-ESM, smaller bundle, sync error throw, `.brand()` first-class.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Relational-Database]], [[Scalability]], [[Inexact-Science]], [[Standard-[[Opera]]ting-Procedure]], [[Management]]
|
||||
- **Modern Tech/Tools**: JSON Schema, SQL DDL, GraphQL, XML Schema.
|
||||
---
|
||||
### 매 응용
|
||||
1. API request/response validation (Hono, tRPC, Next.js Route Handler).
|
||||
2. Form validation (React Hook Form + Zod resolver).
|
||||
3. LLM structured output (Anthropic tool schema, function calling).
|
||||
4. Config validation (env vars at boot).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 Zod 4 schema → TS type infer
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
export const UserSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
email: z.string().email(),
|
||||
age: z.number().int().min(0).max(150),
|
||||
role: z.enum(["admin", "user", "guest"]),
|
||||
createdAt: z.date(),
|
||||
});
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
export type User = z.infer<typeof UserSchema>;
|
||||
// → { id: string; email: string; age: number; role: "admin"|"user"|"guest"; createdAt: Date }
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
const parsed = UserSchema.parse(rawJson); // 매 throw on invalid
|
||||
const safe = UserSchema.safeParse(rawJson); // 매 { success, data | error }
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 매 Zod → JSON Schema (LLM structured output)
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
import { zodToJsonSchema } from "zod-to-json-schema";
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const ExtractedInvoice = z.object({
|
||||
vendor: z.string(),
|
||||
total: z.number(),
|
||||
lineItems: z.array(z.object({
|
||||
desc: z.string(),
|
||||
qty: z.number().int(),
|
||||
unitPrice: z.number(),
|
||||
})),
|
||||
});
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const jsonSchema = zodToJsonSchema(ExtractedInvoice);
|
||||
// 매 Anthropic tool input_schema 에 그대로 사용
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### 매 Anthropic tool use (Claude Opus 4.7 structured output)
|
||||
```python
|
||||
import anthropic
|
||||
client = anthropic.Anthropic()
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=2048,
|
||||
tools=[{
|
||||
"name": "extract_invoice",
|
||||
"description": "Extract structured invoice data",
|
||||
"input_schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"vendor": {"type": "string"},
|
||||
"total": {"type": "number"},
|
||||
"line_items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"desc": {"type": "string"},
|
||||
"qty": {"type": "integer"},
|
||||
"unit_price": {"type": "number"},
|
||||
},
|
||||
"required": ["desc", "qty", "unit_price"],
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": ["vendor", "total", "line_items"],
|
||||
},
|
||||
}],
|
||||
tool_choice={"type": "tool", "name": "extract_invoice"},
|
||||
messages=[{"role": "user", "content": invoice_text}],
|
||||
)
|
||||
# resp.content[0].input → 매 schema-validated dict
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### 매 Postgres 17 declarative schema (with constraints)
|
||||
```sql
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email TEXT NOT NULL UNIQUE CHECK (email ~ '^[^@]+@[^@]+$'),
|
||||
age INT NOT NULL CHECK (age >= 0 AND age <= 150),
|
||||
role TEXT NOT NULL CHECK (role IN ('admin','user','guest')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_users_email_lower ON users (LOWER(email));
|
||||
CREATE INDEX idx_users_role_created ON users (role, created_at DESC);
|
||||
```
|
||||
|
||||
### 매 Schema.org JSON-LD (SEO, 매 Article)
|
||||
```html
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Article",
|
||||
"headline": "Modern Schema Validation in 2026",
|
||||
"author": {"@type": "Person", "name": "Jane Doe"},
|
||||
"datePublished": "2026-05-10",
|
||||
"image": "https://example.com/cover.jpg"
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### 매 Pydantic v2 (Python, 매 FastAPI 와 함께)
|
||||
```python
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Literal
|
||||
|
||||
class User(BaseModel):
|
||||
id: str
|
||||
email: EmailStr
|
||||
age: int = Field(ge=0, le=150)
|
||||
role: Literal["admin", "user", "guest"]
|
||||
|
||||
# FastAPI route — 매 자동 OpenAPI + validation
|
||||
@app.post("/users")
|
||||
def create_user(user: User) -> User:
|
||||
return user
|
||||
```
|
||||
|
||||
### 매 schema migration (Drizzle, TS 2026)
|
||||
```ts
|
||||
// schema.ts — 매 source of truth
|
||||
import { pgTable, uuid, text, integer, timestamp } from "drizzle-orm/pg-core";
|
||||
|
||||
export const users = pgTable("users", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
email: text("email").notNull().unique(),
|
||||
age: integer("age").notNull(),
|
||||
role: text("role", { enum: ["admin","user","guest"] }).notNull(),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
});
|
||||
|
||||
// $ drizzle-kit generate → 매 SQL migration auto
|
||||
// $ drizzle-kit migrate
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 TS API boundary | Zod 4 |
|
||||
| 매 Python API | Pydantic v2 |
|
||||
| 매 cross-language wire | Protobuf / Avro |
|
||||
| 매 LLM structured output | JSON Schema (via Zod/Pydantic) |
|
||||
| 매 SEO web page | Schema.org JSON-LD |
|
||||
| 매 RDB | Postgres DDL + Drizzle/Prisma migration |
|
||||
|
||||
**기본값**: TS 면 Zod 4 (single source → type + runtime + JSON Schema).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Type System]] · [[Validation]]
|
||||
- 변형: [[Zod]] · [[Pydantic]] · [[JSON Schema]] · [[Protobuf]]
|
||||
- 응용: [[API Design]] · [[Form Validation]] · [[LLM Structured Output]]
|
||||
- Adjacent: [[Database Migration]] · [[OpenAPI]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 LLM structured output 강제 (tool use input_schema). 매 unstructured text → typed object extraction.
|
||||
**언제 X**: 매 schema 자체의 design — 매 domain modeling 은 human 의 일.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`z.any()` everywhere**: 매 schema 의 의미 X.
|
||||
- **Schema drift**: API schema 와 DB schema 가 따로 → 매 single source 필요.
|
||||
- **Over-validation in hot path**: 매 매 request 마다 deep validate → 매 boundary 만 validate.
|
||||
- **Stringly-typed enums**: 매 `z.string()` for role → 매 `z.enum()` 으로 narrow.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Zod docs v4, JSON Schema 2020-12 spec, Schema.org, Postgres 17 docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Zod 4 + Pydantic v2 + LLM tool schema + Drizzle |
|
||||
|
||||
Reference in New Issue
Block a user