diff --git a/docs/design/echo/grammar-practice-20261005/implementation-plan.md b/docs/design/echo/grammar-practice-20261005/implementation-plan.md index c1a3eb80..a4d80c05 100644 --- a/docs/design/echo/grammar-practice-20261005/implementation-plan.md +++ b/docs/design/echo/grammar-practice-20261005/implementation-plan.md @@ -39,3 +39,24 @@ - 최신 origin/main 9149f9f는 PR #144 병합 커밋. 별도 worktree에서 구현. - 첫 이슈 #149: 새 도메인 테스트 24개 통과. 화면·DB·외부 API 변경 없음. - FS MCP가 노출되지 않아 로컬 문서와 GitHub issue/PR로 작업 기록을 유지한다. + +## #152 저장·조회 구현 기록 — 2026-10-06 + +브랜치: `feature/152-grammar-note-persistence`, 기준: `main` (`f5bef12`). + +- `GrammarNoteRepositoryPort`를 정의하고 Supabase 구현을 추가했다. 소유자는 클라이언트 입력으로 받지 않고 DB의 `auth.uid()`에서 정한다. +- 하나의 노트 content에 기준 문장·메타데이터·분석·예문을 함께 저장한다. 생성은 `(owner_id, creation_request_id)`로 멱등성을 보장한다. 같은 생성 요청을 재시도하면 기존 노트를 반환하고, 같은 키에 다른 내용을 보내면 충돌을 반환한다. +- 최초 생성 content를 별도로 보관하므로 노트 수정 이후의 생성 재시도도 구분한다. 이 중복 저장은 최초 요청과의 정확한 비교를 위한 비용이다. RPC 응답과 목록에는 이 내부 스냅샷을 포함하지 않는다. +- 수정은 행 잠금과 `expectedVersion` 비교 후 한 번에 반영한다. 타 소유자와 없는 노트는 동일한 NOT_FOUND로 처리한다. RLS는 소유자 조회만 허용하고 인증 사용자의 직접 INSERT/UPDATE/DELETE는 막는다. +- 목록은 최신 수정일과 ID 내림차순으로 정렬한다. 제목·기준 문장 검색은 대소문자를 무시하는 문자열 부분 검색이며 `%`, `_`도 문자로 취급한다. 기본 20개, 최대 100개이고 화면에서 pageSize를 지정할 수 있다. 목록과 total은 같은 SQL 스냅샷에서 구하며 빈 페이지에도 total을 반환한다. 분석 전체 대신 요약 필드만 반환한다. +- 입력/DB 응답은 기존 도메인 schema로 검증한다. JSON 변환, DB 오류 매핑, repository의 요청 조합을 분리했다. 오류 코드는 UI가 해석하고 원래 DB 오류는 내부 로깅용 cause에 보존한다. 기능 요청 경계에서 로깅하는 기존 정책을 유지한다. +- SQL은 저장 경계의 필수 구조·텍스트/배열 제한·원문과 revision 일치를 검사한다. UTF-16 구간 경계, 계층·교차 참조·중복 ID 등의 상세 의미 규칙은 TypeScript 도메인 검증 책임이다. 인증 사용자가 직접 RPC를 호출해 이 상세 검증을 우회한 데이터는 Repository의 읽기 검증에서 거절된다. SQL이 TypeScript의 모든 의미 규칙을 보장한다고 간주하지 않는다. +- `database.types.ts`는 새 migration 계약에 맞춰 수동으로 추가했다. 배포 DB에서 생성한 타입이라고 간주하지 않는다. + +검증: 전체 Jest 122 suites / 454 tests 통과(새 Repository/직렬화 HTTP 경계 테스트 24개 포함), TypeScript·변경 범위 ESLint·production build 통과. Supabase SDK는 실제 query builder를 사용하며 HTTP 응답만 대체했다. DB의 실제 권한·동시성 보장은 이 단위 테스트의 대상이 아니다. + +별도로 PGlite의 임시 PostgreSQL에서 migration을 적용하고 SQL 런타임 검증 59개를 통과했다. `auth.uid`와 pgTAP assertion API를 임시 함수로 대체했으므로 실제 Supabase/pgTAP 통합 결과는 아니다. 다중 세션의 동시 요청도 실행하지 않았다. 원래 pgTAP 테스트는 `supabase/tests/grammar_notes.test.sql`에 보존했다. Docker daemon 및 native PostgreSQL이 없어 실제 Supabase 로컬 DB 검증은 미실행이다. 원격 DB 마이그레이션은 적용하지 않았다. + +DB 검증 재현: 로컬 Supabase가 실행되는 환경에서 이 migration을 적용한 다음 `npx supabase test db supabase/tests/grammar_notes.test.sql`. 마이그레이션 적용은 검증용 로컬 DB에서만 수행하며 원격 배포와 구분한다. PGlite 확인용 임시 harness와 로그는 `/tmp/echo-grammar-sql-check/check.mjs`, `/tmp/echo-grammar-sql-check/result.txt`에 있다. + +이 PR에는 화면 변경이 없다. 다음 #153에서 입력·사전 체크·분석 수정·저장 UI를 연결한다. #163·#164는 기존 feature 브랜치에만 있고 main에는 아직 없으므로 #153을 시작할 때 선행 변경 포함 여부를 확인한다. FS MCP 기록 도구가 제공되지 않아 실행 근거는 이 문서와 로컬 결과 및 PR에 남긴다. diff --git a/src/entities/grammar-note/index.ts b/src/entities/grammar-note/index.ts index b1f600aa..73e61d32 100644 --- a/src/entities/grammar-note/index.ts +++ b/src/entities/grammar-note/index.ts @@ -18,3 +18,15 @@ export { precheckResultSchema, } from "./models/schema"; export { isValidTextRange, getAnalysisIssues } from "./models/validation"; + +export type { + CreateGrammarNoteInput, + UpdateGrammarNoteInput, + FindGrammarNotesParams, + GrammarNoteSummary, + GrammarNotePage, + GrammarNoteRepositoryPort, +} from "./models/repository"; +export { GrammarNotePersistenceError } from "./models/errors"; +export type { GrammarNotePersistenceErrorCode } from "./models/errors"; +export { GrammarNoteRepository } from "./infrastructure/GrammarNoteRepository"; diff --git a/src/entities/grammar-note/infrastructure/GrammarNoteRepository.ts b/src/entities/grammar-note/infrastructure/GrammarNoteRepository.ts new file mode 100644 index 00000000..53696379 --- /dev/null +++ b/src/entities/grammar-note/infrastructure/GrammarNoteRepository.ts @@ -0,0 +1,83 @@ +import type { SupabaseClient } from "@supabase/supabase-js"; +import type { Database } from "@/shared/lib/supabase/database.types"; +import type { + GrammarNoteRepositoryPort, + CreateGrammarNoteInput, + UpdateGrammarNoteInput, + FindGrammarNotesParams, +} from "../models/repository"; +import { GrammarNotePersistenceError } from "../models/errors"; +import { + createGrammarNoteSchema, + updateGrammarNoteSchema, + findGrammarNotesSchema, + grammarNoteIdSchema, +} from "../models/schema"; +import { + mapGrammarNoteContentToJson, + mapGrammarNoteRowToEntity, + mapGrammarNotePageToEntity, +} from "../models/mapper"; +import { executeGrammarNoteRequest } from "./executeGrammarNoteRequest"; + +/** 로그인 사용자의 Supabase client를 받는다. 소유권은 DB의 auth.uid()/RLS가 결정한다. */ +export class GrammarNoteRepository implements GrammarNoteRepositoryPort { + constructor(private readonly supabase: SupabaseClient) {} + + async create(input: CreateGrammarNoteInput) { + const parsed = createGrammarNoteSchema.safeParse(input); + if (!parsed.success) throw new GrammarNotePersistenceError("INVALID_INPUT"); + return executeGrammarNoteRequest( + () => + this.supabase.rpc("create_grammar_note", { + p_request_id: parsed.data.requestId, + p_content: mapGrammarNoteContentToJson(parsed.data.content), + }), + mapGrammarNoteRowToEntity, + ); + } + + async update(input: UpdateGrammarNoteInput) { + const parsed = updateGrammarNoteSchema.safeParse(input); + if (!parsed.success) throw new GrammarNotePersistenceError("INVALID_INPUT"); + return executeGrammarNoteRequest( + () => + this.supabase.rpc("update_grammar_note", { + p_note_id: parsed.data.id, + p_expected_version: parsed.data.expectedVersion, + p_content: mapGrammarNoteContentToJson(parsed.data.content), + }), + mapGrammarNoteRowToEntity, + ); + } + + async findById(id: string) { + const parsed = grammarNoteIdSchema.safeParse(id); + if (!parsed.success) throw new GrammarNotePersistenceError("INVALID_INPUT"); + return executeGrammarNoteRequest( + () => + this.supabase + .from("grammar_notes") + .select("id,owner_id,content,version,created_at,updated_at") + .eq("id", parsed.data) + .maybeSingle(), + // RLS로 숨겨진 타 사용자 노트도 존재하지 않는 노트와 동일하게 처리한다. + (data) => (data === null ? null : mapGrammarNoteRowToEntity(data)), + ); + } + + async findMany(params: FindGrammarNotesParams = {}) { + const parsed = findGrammarNotesSchema.safeParse(params); + if (!parsed.success) throw new GrammarNotePersistenceError("INVALID_INPUT"); + const { page, pageSize, query } = parsed.data; + return executeGrammarNoteRequest( + () => + this.supabase.rpc("list_grammar_notes", { + p_page: page, + p_page_size: pageSize, + p_query: query, + }), + (data) => mapGrammarNotePageToEntity(data, { page, pageSize }), + ); + } +} diff --git a/src/entities/grammar-note/infrastructure/__tests__/GrammarNoteRepository.test.ts b/src/entities/grammar-note/infrastructure/__tests__/GrammarNoteRepository.test.ts new file mode 100644 index 00000000..38b16802 --- /dev/null +++ b/src/entities/grammar-note/infrastructure/__tests__/GrammarNoteRepository.test.ts @@ -0,0 +1,302 @@ +/** @jest-environment node */ +import { describe, expect, it, jest } from "@jest/globals"; +import { createClient } from "@supabase/supabase-js"; +import type { Database } from "@/shared/lib/supabase/database.types"; +import type { GrammarNoteContent } from "../../models/entity"; +import { GrammarNoteRepository } from "../GrammarNoteRepository"; +import { mapGrammarNoteContentToJson } from "../../models/mapper"; + +const id = "11111111-1111-4111-8111-111111111111"; +const ownerId = "22222222-2222-4222-8222-222222222222"; +const requestId = "33333333-3333-4333-8333-333333333333"; + +function content(): GrammarNoteContent { + return { + source: { sentence: "She is a doctor.", learningNote: "주격 보어", revision: 2 }, + metadata: { + source: "ai", + sourceRevision: 2, + title: "주격 보어", + tags: ["보어"], + grammarKey: null, + }, + analysis: { + sourceText: "She is a doctor.", + sourceRevision: 2, + reviewStatus: "reviewed", + chunks: [ + { + id: "chunk", + range: { start: 0, end: 16 }, + literalMeaning: "그녀는 의사이다.", + explanation: "", + }, + ], + syntax: [], + constructions: [], + naturalTranslation: "그녀는 의사입니다.", + }, + examples: [], + }; +} +function row() { + return { + id, + owner_id: ownerId, + content: content(), + version: 1, + created_at: "2026-10-06T00:00:00+00:00", + updated_at: "2026-10-06T00:00:00+00:00", + }; +} +function summary() { + const note = row(); + return { + id: note.id, + owner_id: note.owner_id, + version: note.version, + created_at: note.created_at, + updated_at: note.updated_at, + title: note.content.metadata.title, + sentence: note.content.source.sentence, + tags: note.content.metadata.tags, + }; +} +// Supabase query builder는 실제 구현을 쓰고 HTTP 경계만 대체한다. +function setup(data: unknown, status = 200) { + const fetcher = jest.fn().mockImplementation( + async () => + new Response(JSON.stringify(data), { + status, + headers: { "Content-Type": "application/json" }, + }), + ); + const client = createClient("https://echo-test.example", "test-anon-key", { + auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false }, + global: { fetch: fetcher }, + }); + return { repository: new GrammarNoteRepository(client), fetcher }; +} + +describe("GrammarNoteRepository", () => { + it("sends the same creation key on retries and returns the DB-owned identity/version", async () => { + // Given + const { repository, fetcher } = setup(row()); + // When + const first = await repository.create({ requestId, content: content() }); + const retry = await repository.create({ requestId, content: content() }); + // Then: idempotency 자체는 DB 테스트에서 검증하며 여기서는 동일 키/입력 전달을 검증한다. + expect(first).toEqual(retry); + expect(first).toMatchObject({ id, ownerId, version: 1, source: content().source }); + for (const [url, init] of fetcher.mock.calls) { + expect(String(url)).toContain("/rpc/create_grammar_note"); + expect(JSON.parse(String(init?.body))).toEqual({ + p_request_id: requestId, + p_content: content(), + }); + } + }); + + it("sends the expected version and maps the committed version from the update response", async () => { + // Given + const { repository, fetcher } = setup({ ...row(), version: 2 }); + // When + const result = await repository.update({ id, expectedVersion: 1, content: content() }); + // Then + expect(result.version).toBe(2); + expect(JSON.parse(String(fetcher.mock.calls[0][1]?.body))).toEqual({ + p_note_id: id, + p_expected_version: 1, + p_content: content(), + }); + }); + + it("reads only the public note fields and converts a visible row", async () => { + const { repository, fetcher } = setup([row()]); + const result = await repository.findById(id); + expect(result).toMatchObject({ id, ownerId, analysis: content().analysis }); + const url = new URL(String(fetcher.mock.calls[0][0])); + expect(url.searchParams.get("id")).toBe(`eq.${id}`); + expect(url.searchParams.get("select")).toBe( + "id,owner_id,content,version,created_at,updated_at", + ); + }); + + it("returns null for a row hidden by RLS or an unknown id", async () => { + const { repository } = setup([]); + await expect(repository.findById(id)).resolves.toBeNull(); + }); + + it("retains DB ordering/count and passes a literal search string with bounded pagination", async () => { + // Given + const { repository, fetcher } = setup({ items: [summary()], total: 21 }); + // When + const result = await repository.findMany({ page: 2, pageSize: 10, query: " 50%_(be) " }); + // Then + expect(result).toEqual({ + page: 2, + pageSize: 10, + total: 21, + items: [ + { + id, + ownerId, + version: 1, + createdAt: row().created_at, + updatedAt: row().updated_at, + title: "주격 보어", + sentence: "She is a doctor.", + tags: ["보어"], + }, + ], + }); + expect(JSON.parse(String(fetcher.mock.calls[0][1]?.body))).toEqual({ + p_page: 2, + p_page_size: 10, + p_query: "50%_(be)", + }); + expect(result.items[0]).not.toHaveProperty("analysis"); + }); + + it("preserves total on an out-of-range empty page and supplies defaults", async () => { + const { repository, fetcher } = setup({ items: [], total: 3 }); + await expect(repository.findMany({ page: 10 })).resolves.toEqual({ + items: [], + total: 3, + page: 10, + pageSize: 20, + }); + await repository.findMany(); + expect(JSON.parse(String(fetcher.mock.calls[1][1]?.body))).toEqual({ + p_page: 1, + p_page_size: 20, + p_query: "", + }); + }); + + it.each([ + { page: 0 }, + { page: 1.5 }, + { pageSize: 101 }, + { pageSize: 0 }, + { query: "a".repeat(201) }, + ])("rejects invalid pagination before a request: %j", async (params) => { + const { repository, fetcher } = setup(null); + await expect(repository.findMany(params)).rejects.toMatchObject({ code: "INVALID_INPUT" }); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it("rejects invalid ids, versions, and stale content before any DB request", async () => { + const { repository, fetcher } = setup(null); + const stale = { ...content(), source: { ...content().source, revision: 3 } }; + await expect(repository.findById("invalid")).rejects.toMatchObject({ code: "INVALID_INPUT" }); + await expect( + repository.create({ requestId: "invalid", content: content() }), + ).rejects.toMatchObject({ code: "INVALID_INPUT" }); + await expect(repository.create({ requestId, content: stale })).rejects.toMatchObject({ + code: "INVALID_INPUT", + }); + await expect( + repository.update({ id, expectedVersion: 0, content: content() }), + ).rejects.toMatchObject({ code: "INVALID_INPUT" }); + expect(fetcher).not.toHaveBeenCalled(); + }); + + it.each([ + "UNAUTHORIZED", + "NOT_FOUND", + "VERSION_CONFLICT", + "IDEMPOTENCY_CONFLICT", + "INVALID_INPUT", + ])("maps the DB %s contract without exposing SQL details", async (code) => { + const raw = { + code: "P0001", + message: `GRAMMAR_NOTE_${code}`, + details: "private SQL details", + hint: "", + }; + const { repository } = setup(raw, 400); + await expect( + repository.update({ id, expectedVersion: 1, content: content() }), + ).rejects.toMatchObject({ code, message: code, cause: raw }); + }); + + it("keeps an unexpected DB error in cause for internal logging", async () => { + const raw = { code: "XX000", message: "private DB text", details: "", hint: "" }; + const { repository } = setup(raw, 500); + await expect(repository.create({ requestId, content: content() })).rejects.toMatchObject({ + code: "PERSISTENCE_FAILED", + message: "PERSISTENCE_FAILED", + cause: raw, + }); + }); + + it("handles a rejected HTTP request without leaking the network error as a UI message", async () => { + const { repository, fetcher } = setup(null); + fetcher.mockRejectedValue(new Error("private network text")); + await expect(repository.findMany()).rejects.toMatchObject({ + code: "PERSISTENCE_FAILED", + message: "PERSISTENCE_FAILED", + }); + }); + + it.each([ + null, + { ...row(), version: 0 }, + { + ...row(), + content: { ...content(), analysis: { ...content().analysis, sourceRevision: 100 } }, + }, + ])("rejects malformed stored notes: %j", async (data) => { + const { repository } = setup(data); + await expect(repository.create({ requestId, content: content() })).rejects.toMatchObject({ + code: "INVALID_RESPONSE", + }); + }); + + it("does not turn a missing count or malformed list into a successful empty page", async () => { + const { repository } = setup({ items: [] }); + await expect(repository.findMany()).rejects.toMatchObject({ code: "INVALID_RESPONSE" }); + }); + + it("serializes nested ranges without mutating or normalizing the domain content", () => { + const note: GrammarNoteContent = { + ...content(), + analysis: { + ...content().analysis, + syntax: [ + { + id: "verb", + parentId: null, + role: "verb", + label: "동사", + explanation: "연결 동사", + ranges: [{ start: 4, end: 6 }], + }, + ], + constructions: [ + { + id: "be", + name: "be + 보어", + meaning: "~이다", + explanation: "주어 설명", + ranges: [{ start: 4, end: 15 }], + }, + ], + }, + examples: [ + { + id: "example", + sentence: "He is a nurse.", + translation: "그는 간호사이다.", + targetExplanation: "주격 보어", + reviewStatus: "reviewed", + }, + ], + }; + const serialized = mapGrammarNoteContentToJson(note); + expect(serialized).toEqual(note); + expect(serialized).not.toBe(note); + expect(note.source.sentence).toBe("She is a doctor."); + }); +}); diff --git a/src/entities/grammar-note/infrastructure/executeGrammarNoteRequest.ts b/src/entities/grammar-note/infrastructure/executeGrammarNoteRequest.ts new file mode 100644 index 00000000..0f9d843e --- /dev/null +++ b/src/entities/grammar-note/infrastructure/executeGrammarNoteRequest.ts @@ -0,0 +1,29 @@ +import type { PostgrestError } from "@supabase/supabase-js"; +import { GrammarNotePersistenceError } from "../models/errors"; +import type { GrammarNotePersistenceErrorCode } from "../models/errors"; + +const rpcErrors = new Map([ + ["GRAMMAR_NOTE_INVALID_INPUT", "INVALID_INPUT"], + ["GRAMMAR_NOTE_UNAUTHORIZED", "UNAUTHORIZED"], + ["GRAMMAR_NOTE_NOT_FOUND", "NOT_FOUND"], + ["GRAMMAR_NOTE_VERSION_CONFLICT", "VERSION_CONFLICT"], + ["GRAMMAR_NOTE_IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_CONFLICT"], +]); + +/** DB 오류와 네트워크 예외를 같은 계약으로 전파한다. 로깅/표시는 요청 경계와 UI가 담당한다. */ +export async function executeGrammarNoteRequest( + request: () => PromiseLike<{ data: unknown; error: PostgrestError | null }>, + convert: (data: unknown) => T, +): Promise { + try { + const { data, error } = await request(); + if (error) { + const code = error.code === "P0001" ? rpcErrors.get(error.message) : undefined; + throw new GrammarNotePersistenceError(code ?? "PERSISTENCE_FAILED", { cause: error }); + } + return convert(data); + } catch (error) { + if (error instanceof GrammarNotePersistenceError) throw error; + throw new GrammarNotePersistenceError("PERSISTENCE_FAILED", { cause: error }); + } +} diff --git a/src/entities/grammar-note/models/errors.ts b/src/entities/grammar-note/models/errors.ts new file mode 100644 index 00000000..18d61322 --- /dev/null +++ b/src/entities/grammar-note/models/errors.ts @@ -0,0 +1,19 @@ +export type GrammarNotePersistenceErrorCode = + | "INVALID_INPUT" + | "UNAUTHORIZED" + | "NOT_FOUND" + | "VERSION_CONFLICT" + | "IDEMPOTENCY_CONFLICT" + | "INVALID_RESPONSE" + | "PERSISTENCE_FAILED"; + +/** 소비자는 code를 UI 문구로 변환한다. 원래 오류는 내부 로깅용 cause에만 보존한다. */ +export class GrammarNotePersistenceError extends Error { + constructor( + readonly code: GrammarNotePersistenceErrorCode, + options?: ErrorOptions, + ) { + super(code, options); + this.name = "GrammarNotePersistenceError"; + } +} diff --git a/src/entities/grammar-note/models/mapper.ts b/src/entities/grammar-note/models/mapper.ts new file mode 100644 index 00000000..ae8e9ab1 --- /dev/null +++ b/src/entities/grammar-note/models/mapper.ts @@ -0,0 +1,63 @@ +import type { Json } from "@/shared/lib/supabase/database.types"; +import type { GrammarNote, GrammarNoteContent } from "./entity"; +import type { GrammarNotePage } from "./repository"; +import { GrammarNotePersistenceError } from "./errors"; +import { grammarNotePageSchema, grammarNoteRowSchema } from "./schema"; + +export function mapGrammarNoteRowToEntity(value: unknown): GrammarNote { + const parsed = grammarNoteRowSchema.safeParse(value); + if (!parsed.success) throw new GrammarNotePersistenceError("INVALID_RESPONSE"); + const row = parsed.data; + return { + ...row.content, + id: row.id, + ownerId: row.owner_id, + version: row.version, + createdAt: row.created_at, + updatedAt: row.updated_at, + }; +} + +export function mapGrammarNotePageToEntity( + value: unknown, + pagination: Pick, +): GrammarNotePage { + const parsed = grammarNotePageSchema.safeParse(value); + if (!parsed.success) throw new GrammarNotePersistenceError("INVALID_RESPONSE"); + return { + ...pagination, + total: parsed.data.total, + items: parsed.data.items.map((row) => ({ + id: row.id, + ownerId: row.owner_id, + version: row.version, + createdAt: row.created_at, + updatedAt: row.updated_at, + title: row.title, + sentence: row.sentence, + tags: row.tags, + })), + }; +} + +// Supabase Json은 변경 가능한 배열을 요구하므로 readonly 배열을 복사해 일반 JSON 객체로 구성한다. +// 원문과 구간 값은 함께 해석되므로 직렬화 과정에서 공백이나 오프셋을 보정하지 않는다. +export function mapGrammarNoteContentToJson(content: GrammarNoteContent): Json { + return { + source: { ...content.source }, + metadata: { ...content.metadata, tags: [...content.metadata.tags] }, + analysis: { + ...content.analysis, + chunks: content.analysis.chunks.map((chunk) => ({ ...chunk, range: { ...chunk.range } })), + syntax: content.analysis.syntax.map((item) => ({ + ...item, + ranges: item.ranges.map((range) => ({ ...range })), + })), + constructions: content.analysis.constructions.map((item) => ({ + ...item, + ranges: item.ranges.map((range) => ({ ...range })), + })), + }, + examples: content.examples.map((example) => ({ ...example })), + }; +} diff --git a/src/entities/grammar-note/models/repository.ts b/src/entities/grammar-note/models/repository.ts new file mode 100644 index 00000000..aebdd71f --- /dev/null +++ b/src/entities/grammar-note/models/repository.ts @@ -0,0 +1,39 @@ +import type { GrammarNote, GrammarNoteContent } from "./entity"; +import type { GrammarMetadata } from "./value-objects"; + +export interface CreateGrammarNoteInput { + /** 한 번의 생성 의도에 발급한 UUID. 네트워크 재시도에는 같은 값을 사용한다. */ + readonly requestId: string; + readonly content: GrammarNoteContent; +} +export interface UpdateGrammarNoteInput { + readonly id: string; + readonly expectedVersion: number; + readonly content: GrammarNoteContent; +} +export interface FindGrammarNotesParams { + readonly page?: number; + readonly pageSize?: number; + /** 제목과 기준 문장에 대한 대소문자 무시 부분 검색. SQL 와일드카드로 해석하지 않는다. */ + readonly query?: string; +} +export interface GrammarNoteSummary extends Pick< + GrammarNote, + "id" | "ownerId" | "version" | "createdAt" | "updatedAt" +> { + readonly title: string; + readonly sentence: string; + readonly tags: GrammarMetadata["tags"]; +} +export interface GrammarNotePage { + readonly items: readonly GrammarNoteSummary[]; + readonly total: number; + readonly page: number; + readonly pageSize: number; +} +export interface GrammarNoteRepositoryPort { + create(input: CreateGrammarNoteInput): Promise; + update(input: UpdateGrammarNoteInput): Promise; + findById(id: string): Promise; + findMany(params?: FindGrammarNotesParams): Promise; +} diff --git a/src/entities/grammar-note/models/schema.ts b/src/entities/grammar-note/models/schema.ts index 19b3f413..5873275b 100644 --- a/src/entities/grammar-note/models/schema.ts +++ b/src/entities/grammar-note/models/schema.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import type { GrammarNoteContent, PrecheckResult, SentenceAnalysis } from "./entity"; import { getAnalysisIssues } from "./validation"; -// Bounds protect provider/storage boundaries; source text is never trimmed or normalized. +// 원문을 trim/정규화하면 AI가 지정한 UTF-16 구간이 어긋나므로, 공백 여부만 검사하고 값은 보존한다. const requiredText = z .string() .max(4000) @@ -152,3 +152,54 @@ export const precheckResultSchema: z.ZodType = z.union([ }) .strict(), ]); + +export const grammarNoteIdSchema = z.string().uuid(); +export const createGrammarNoteSchema = z + .object({ + requestId: grammarNoteIdSchema, + content: grammarNoteContentSchema, + }) + .strict(); +export const updateGrammarNoteSchema = z + .object({ + id: grammarNoteIdSchema, + expectedVersion: z.number().int().min(1).max(2147483647), + content: grammarNoteContentSchema, + }) + .strict(); +export const findGrammarNotesSchema = z + .object({ + page: z.number().int().min(1).max(2147483647).default(1), + pageSize: z.number().int().min(1).max(100).default(20), + query: z.string().trim().max(200).default(""), + }) + .strict(); + +const rowIdentity = { + id: grammarNoteIdSchema, + owner_id: grammarNoteIdSchema, + version: z.number().int().min(1).max(2147483647), + created_at: z.string().datetime({ offset: true }), + updated_at: z.string().datetime({ offset: true }), +}; +export const grammarNoteRowSchema = z + .object({ + ...rowIdentity, + content: grammarNoteContentSchema, + }) + .strict(); +export const grammarNotePageSchema = z + .object({ + items: z.array( + z + .object({ + ...rowIdentity, + title: grammarMetadataSchema.shape.title, + sentence: grammarSourceSchema.shape.sentence, + tags: grammarMetadataSchema.shape.tags, + }) + .strict(), + ), + total: z.number().int().nonnegative().safe(), + }) + .strict(); diff --git a/src/shared/lib/supabase/database.types.ts b/src/shared/lib/supabase/database.types.ts index f308ada9..34480764 100644 --- a/src/shared/lib/supabase/database.types.ts +++ b/src/shared/lib/supabase/database.types.ts @@ -28,6 +28,39 @@ export type Database = { }; public: { Tables: { + grammar_notes: { + Row: { + id: string; + owner_id: string; + content: Json; + creation_request_id: string; + creation_content: Json; + version: number; + created_at: string; + updated_at: string; + }; + Insert: { + id?: string; + owner_id: string; + content: Json; + creation_request_id: string; + creation_content: Json; + version?: number; + created_at?: string; + updated_at?: string; + }; + Update: { + id?: string; + owner_id?: string; + content?: Json; + creation_request_id?: string; + creation_content?: Json; + version?: number; + created_at?: string; + updated_at?: string; + }; + Relationships: []; + }; accepted_recordings: { Row: { accepted_at: string; @@ -1022,6 +1055,22 @@ export type Database = { }; }; Functions: { + is_valid_grammar_note_content: { + Args: { p_content: Json }; + Returns: boolean; + }; + create_grammar_note: { + Args: { p_request_id: string; p_content: Json }; + Returns: Json; + }; + update_grammar_note: { + Args: { p_note_id: string; p_expected_version: number; p_content: Json }; + Returns: Json; + }; + list_grammar_notes: { + Args: { p_page?: number; p_page_size?: number; p_query?: string }; + Returns: Json; + }; update_roleplay_material: { Args: { p_material_id: string; p_content: Json }; Returns: undefined; diff --git a/supabase/migrations/20261006090000_grammar_notes.sql b/supabase/migrations/20261006090000_grammar_notes.sql new file mode 100644 index 00000000..a80e509c --- /dev/null +++ b/supabase/migrations/20261006090000_grammar_notes.sql @@ -0,0 +1,217 @@ +-- 저장 경계에서는 필수 구조·문자열·수량·원문/리비전 일치를 검증합니다. +-- 구간의 UTF-16 경계, 구문 계층 및 교차 참조는 TypeScript 도메인 스키마가 책임집니다. +create function public.is_valid_grammar_note_content(p_content jsonb) +returns boolean language plpgsql immutable set search_path = '' as $$ +declare + v_path text[]; + v_value jsonb; + v_item jsonb; + v_range jsonb; + v_key text; +begin + if jsonb_typeof(p_content) is distinct from 'object' then return false; end if; + foreach v_key in array array['source', 'metadata', 'analysis'] loop + if jsonb_typeof(p_content->v_key) is distinct from 'object' then return false; end if; + end loop; + + -- 필수 텍스트는 누락·null·공백만 있는 값과 길이 초과를 거부합니다. + foreach v_path slice 1 in array array[ + ['source','sentence'], ['source','learningNote'], ['metadata','title'], + ['analysis','sourceText'], ['analysis','naturalTranslation'] + ] loop + v_value := p_content #> v_path; + if jsonb_typeof(v_value) is distinct from 'string' then return false; end if; + if length(v_value #>> '{}') > 4000 or (v_value #>> '{}') !~ '[^[:space:]]' then return false; end if; + end loop; + + -- AI 메타데이터의 출처, 원문 일치 및 정수 리비전을 확인합니다. + if p_content #> '{metadata,source}' is distinct from '"ai"'::jsonb + or not coalesce(p_content #>> '{analysis,reviewStatus}' in ('needs-review','reviewed'), false) + or p_content #> '{source,sentence}' is distinct from p_content #> '{analysis,sourceText}' + then return false; end if; + v_value := p_content #> '{source,revision}'; + if jsonb_typeof(v_value) is distinct from 'number' then return false; end if; + if (v_value #>> '{}')::numeric < 0 or trunc((v_value #>> '{}')::numeric) <> (v_value #>> '{}')::numeric + or v_value is distinct from p_content #> '{metadata,sourceRevision}' + or v_value is distinct from p_content #> '{analysis,sourceRevision}' then return false; end if; + v_value := p_content #> '{metadata,grammarKey}'; + if v_value is null then return false; end if; + if v_value <> 'null'::jsonb then + if jsonb_typeof(v_value) is distinct from 'string' then return false; end if; + if length(v_value #>> '{}') not between 1 and 100 then return false; end if; + end if; + + -- 배열 타입을 먼저 확인하여 잘못된 JSON에 배열 함수를 호출하지 않습니다. + foreach v_path slice 1 in array array[ + ['metadata','tags'], ['analysis','chunks'], ['analysis','syntax'], ['analysis','constructions'] + ] loop + if jsonb_typeof(p_content #> v_path) is distinct from 'array' then return false; end if; + end loop; + if jsonb_typeof(p_content->'examples') is distinct from 'array' then return false; end if; + if jsonb_array_length(p_content #> '{metadata,tags}') > 20 + or jsonb_array_length(p_content #> '{analysis,chunks}') not between 1 and 200 + or jsonb_array_length(p_content #> '{analysis,syntax}') > 200 + or jsonb_array_length(p_content #> '{analysis,constructions}') > 100 + or jsonb_array_length(p_content->'examples') > 100 then return false; end if; + for v_item in select value from jsonb_array_elements(p_content #> '{metadata,tags}') loop + if jsonb_typeof(v_item) is distinct from 'string' then return false; end if; + if length(v_item #>> '{}') > 4000 or (v_item #>> '{}') !~ '[^[:space:]]' then return false; end if; + end loop; + -- 세부 항목의 필수 키와 텍스트 타입을 확인하고 의미론적 구간 검증은 도메인에 위임합니다. + for v_item in select value from jsonb_array_elements(p_content #> '{analysis,chunks}') loop + if jsonb_typeof(v_item) is distinct from 'object' + or jsonb_typeof(v_item->'range') is distinct from 'object' + or jsonb_typeof(v_item #> '{range,start}') is distinct from 'number' + or jsonb_typeof(v_item #> '{range,end}') is distinct from 'number' + or jsonb_typeof(v_item->'id') is distinct from 'string' + or length(v_item->>'id') not between 1 and 100 then return false; end if; + foreach v_key in array array['literalMeaning','explanation'] loop + if jsonb_typeof(v_item->v_key) is distinct from 'string' then return false; end if; + if length(v_item->>v_key) > 4000 then return false; end if; + end loop; + end loop; + for v_item in select value from jsonb_array_elements(p_content #> '{analysis,syntax}') + union all select value from jsonb_array_elements(p_content #> '{analysis,constructions}') loop + if jsonb_typeof(v_item) is distinct from 'object' + or jsonb_typeof(v_item->'id') is distinct from 'string' + or length(v_item->>'id') not between 1 and 100 + or jsonb_typeof(v_item->'explanation') is distinct from 'string' + or length(v_item->>'explanation') > 4000 + or jsonb_typeof(v_item->'ranges') is distinct from 'array' then return false; end if; + if jsonb_array_length(v_item->'ranges') not between 1 and 100 then return false; end if; + for v_range in select value from jsonb_array_elements(v_item->'ranges') loop + if jsonb_typeof(v_range) is distinct from 'object' + or jsonb_typeof(v_range->'start') is distinct from 'number' + or jsonb_typeof(v_range->'end') is distinct from 'number' then return false; end if; + end loop; + end loop; + for v_item in select value from jsonb_array_elements(p_content #> '{analysis,syntax}') loop + if not coalesce(v_item->>'role' in ('subject','verb','object','complement','modifier','other'), false) + or jsonb_typeof(v_item->'label') is distinct from 'string' + or length(v_item->>'label') > 4000 or (v_item->>'label') !~ '[^[:space:]]' + or not (v_item ? 'parentId') then return false; end if; + if v_item->'parentId' <> 'null'::jsonb then + if jsonb_typeof(v_item->'parentId') is distinct from 'string' + or length(v_item->>'parentId') not between 1 and 100 then return false; end if; + end if; + end loop; + for v_item in select value from jsonb_array_elements(p_content #> '{analysis,constructions}') loop + foreach v_key in array array['name','meaning'] loop + if jsonb_typeof(v_item->v_key) is distinct from 'string' then return false; end if; + if length(v_item->>v_key) > 4000 or (v_item->>v_key) !~ '[^[:space:]]' then return false; end if; + end loop; + end loop; + for v_item in select value from jsonb_array_elements(p_content->'examples') loop + if jsonb_typeof(v_item) is distinct from 'object' + or jsonb_typeof(v_item->'id') is distinct from 'string' + or length(v_item->>'id') not between 1 and 100 + or not coalesce(v_item->>'reviewStatus' in ('needs-review','reviewed'), false) then return false; end if; + foreach v_key in array array['sentence','translation','targetExplanation'] loop + if jsonb_typeof(v_item->v_key) is distinct from 'string' then return false; end if; + if length(v_item->>v_key) > 4000 or (v_item->>v_key) !~ '[^[:space:]]' then return false; end if; + end loop; + end loop; + return true; +end; +$$; + +create table public.grammar_notes ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references auth.users(id) on delete cascade, + content jsonb not null check (public.is_valid_grammar_note_content(content)), + creation_request_id uuid not null, + -- 수정 후 생성 재시도도 최초 요청과 비교하기 위해 원본을 별도로 보존합니다. + creation_content jsonb not null check (public.is_valid_grammar_note_content(creation_content)), + version integer not null default 1 check (version > 0), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (owner_id, creation_request_id) +); +create index grammar_notes_owner_updated_idx on public.grammar_notes(owner_id, updated_at desc, id desc); +alter table public.grammar_notes enable row level security; +create policy grammar_notes_owner_select on public.grammar_notes for select to authenticated + using (owner_id = (select auth.uid())); +revoke all on public.grammar_notes from public, anon, authenticated; +grant select on public.grammar_notes to authenticated; + +create function public.create_grammar_note(p_request_id uuid, p_content jsonb) +returns jsonb language plpgsql security definer set search_path = '' as $$ +declare + v_owner uuid := auth.uid(); + v_note public.grammar_notes; +begin + if v_owner is null then raise exception 'GRAMMAR_NOTE_UNAUTHORIZED'; end if; + if p_request_id is null or not public.is_valid_grammar_note_content(p_content) then + raise exception 'GRAMMAR_NOTE_INVALID_INPUT'; + end if; + -- 고유 제약이 동시 요청을 직렬화합니다. 이후 조회는 먼저 완료된 삽입을 확인합니다. + insert into public.grammar_notes(owner_id, content, creation_request_id, creation_content) + values (v_owner, p_content, p_request_id, p_content) + on conflict (owner_id, creation_request_id) do nothing; + select * into v_note from public.grammar_notes + where owner_id = v_owner and creation_request_id = p_request_id for update; + if v_note.creation_content is distinct from p_content then + raise exception 'GRAMMAR_NOTE_IDEMPOTENCY_CONFLICT'; + end if; + return to_jsonb(v_note) - 'creation_request_id' - 'creation_content'; +end; +$$; + +create function public.update_grammar_note(p_note_id uuid, p_expected_version integer, p_content jsonb) +returns jsonb language plpgsql security definer set search_path = '' as $$ +declare + v_owner uuid := auth.uid(); + v_note public.grammar_notes; +begin + if v_owner is null then raise exception 'GRAMMAR_NOTE_UNAUTHORIZED'; end if; + if p_note_id is null or p_expected_version is null or p_expected_version < 1 + or not public.is_valid_grammar_note_content(p_content) then raise exception 'GRAMMAR_NOTE_INVALID_INPUT'; end if; + -- 조회부터 갱신까지 잠가 오래된 탭의 수정이 최신 내용을 덮어쓰지 못하게 합니다. + select * into v_note from public.grammar_notes where id = p_note_id and owner_id = v_owner for update; + if not found then raise exception 'GRAMMAR_NOTE_NOT_FOUND'; end if; + if v_note.version <> p_expected_version then raise exception 'GRAMMAR_NOTE_VERSION_CONFLICT'; end if; + if v_note.version = 2147483647 then raise exception 'GRAMMAR_NOTE_VERSION_CONFLICT'; end if; + update public.grammar_notes set content = p_content, version = version + 1, updated_at = clock_timestamp() + where id = v_note.id and owner_id = v_owner returning * into v_note; + return to_jsonb(v_note) - 'creation_request_id' - 'creation_content'; +end; +$$; + +create function public.list_grammar_notes(p_page integer default 1, p_page_size integer default 20, p_query text default '') +returns jsonb language plpgsql stable security definer set search_path = '' as $$ +declare + v_owner uuid := auth.uid(); + v_query text := btrim(p_query); + v_result jsonb; +begin + if v_owner is null then raise exception 'GRAMMAR_NOTE_UNAUTHORIZED'; end if; + if p_page is null or p_page < 1 or p_page_size is null or p_page_size not between 1 and 100 + or v_query is null or length(v_query) > 200 then raise exception 'GRAMMAR_NOTE_INVALID_INPUT'; end if; + -- 총 개수와 페이지는 같은 SQL 스냅샷에서 읽습니다. 빈 페이지에도 전체 개수를 보존합니다. + with matching as materialized ( + select n.id, n.owner_id, n.version, n.created_at, n.updated_at, + n.content #>> '{metadata,title}' as title, n.content #>> '{source,sentence}' as sentence, + n.content #> '{metadata,tags}' as tags + from public.grammar_notes n where n.owner_id = v_owner + and (v_query = '' or strpos(lower(n.content #>> '{metadata,title}'), lower(v_query)) > 0 + or strpos(lower(n.content #>> '{source,sentence}'), lower(v_query)) > 0) + ), page as ( + select * from matching order by updated_at desc, id desc + limit p_page_size offset (p_page::bigint - 1) * p_page_size + ) + select jsonb_build_object('total', (select count(*) from matching), 'items', coalesce(( + select jsonb_agg(jsonb_build_object( + 'id', id, 'owner_id', owner_id, 'version', version, 'created_at', created_at, 'updated_at', updated_at, + 'title', title, 'sentence', sentence, 'tags', tags) order by updated_at desc, id desc) from page + ), '[]'::jsonb)) into v_result; + return v_result; +end; +$$; + +revoke all on function public.is_valid_grammar_note_content(jsonb) from public, anon, authenticated; +revoke all on function public.create_grammar_note(uuid, jsonb) from public, anon, authenticated; +revoke all on function public.update_grammar_note(uuid, integer, jsonb) from public, anon, authenticated; +revoke all on function public.list_grammar_notes(integer, integer, text) from public, anon, authenticated; +grant execute on function public.create_grammar_note(uuid, jsonb) to authenticated; +grant execute on function public.update_grammar_note(uuid, integer, jsonb) to authenticated; +grant execute on function public.list_grammar_notes(integer, integer, text) to authenticated; diff --git a/supabase/tests/grammar_notes.test.sql b/supabase/tests/grammar_notes.test.sql new file mode 100644 index 00000000..ad332443 --- /dev/null +++ b/supabase/tests/grammar_notes.test.sql @@ -0,0 +1,116 @@ +begin; +create extension if not exists pgtap with schema extensions; +select no_plan(); + +insert into auth.users(id) values + ('15151515-1111-4111-8111-111111111111'), + ('15151515-2222-4222-8222-222222222222'); +create function pg_temp.grammar_content(p_title text default 'Not A but B') returns jsonb +language sql immutable as $$ + select jsonb_build_object( + 'source', jsonb_build_object('sentence','She is not a teacher but a doctor.','learningNote','not A but B 대조','revision',0), + 'metadata', jsonb_build_object('source','ai','sourceRevision',0,'title',p_title,'tags',jsonb_build_array('대조'),'grammarKey',null), + 'analysis', jsonb_build_object('sourceText','She is not a teacher but a doctor.','sourceRevision',0, + 'chunks',jsonb_build_array(jsonb_build_object('id','c1','range',jsonb_build_object('start',0,'end',34),'literalMeaning','그녀는 교사가 아니라 의사입니다.','explanation','대조')), + 'syntax','[]'::jsonb,'constructions','[]'::jsonb,'naturalTranslation','그녀는 교사가 아니라 의사입니다.','reviewStatus','reviewed'), + 'examples','[]'::jsonb); +$$; +create temporary table grammar_test_results(label text primary key, value jsonb); +grant all on grammar_test_results to authenticated; + +set local role authenticated; +select set_config('request.jwt.claim.sub','',true); +select throws_ok($q$select public.create_grammar_note('25252525-1111-4111-8111-111111111111',pg_temp.grammar_content())$q$, + 'P0001','GRAMMAR_NOTE_UNAUTHORIZED','create rejects missing identity'); +select throws_ok($q$select public.update_grammar_note('35353535-1111-4111-8111-111111111111',1,pg_temp.grammar_content())$q$, + 'P0001','GRAMMAR_NOTE_UNAUTHORIZED','update rejects missing identity'); +select throws_ok($q$select public.list_grammar_notes()$q$, + 'P0001','GRAMMAR_NOTE_UNAUTHORIZED','list rejects missing identity'); +select set_config('request.jwt.claim.sub','15151515-1111-4111-8111-111111111111',true); + +insert into grammar_test_results values ('created',public.create_grammar_note('25252525-1111-4111-8111-111111111111',pg_temp.grammar_content())); +select is((select value->>'owner_id' from grammar_test_results where label='created'),'15151515-1111-4111-8111-111111111111','owner comes from authenticated identity'); +select is((select (value->>'version')::integer from grammar_test_results where label='created'),1,'version starts at one'); +select ok((select not (value ? 'creation_content') and not (value ? 'creation_request_id') from grammar_test_results where label='created'),'RPC response omits internal idempotency fields'); +select is(public.create_grammar_note('25252525-1111-4111-8111-111111111111',pg_temp.grammar_content()), + (select value from grammar_test_results where label='created'),'same create request returns the same row'); +select is((select count(*) from public.grammar_notes),1::bigint,'retry creates no duplicate'); + +select throws_ok($q$insert into public.grammar_notes(owner_id,content,creation_request_id,creation_content) + values('15151515-1111-4111-8111-111111111111',pg_temp.grammar_content(),'25252525-9999-4999-8999-999999999999',pg_temp.grammar_content())$q$, + '42501',null,'authenticated cannot bypass RPC with direct insert'); +select throws_ok($q$update public.grammar_notes set content=pg_temp.grammar_content('Bypass')$q$, + '42501',null,'authenticated cannot bypass version check with direct update'); +select throws_ok($q$delete from public.grammar_notes$q$,'42501',null,'authenticated cannot delete directly'); + +insert into grammar_test_results select 'updated',public.update_grammar_note((value->>'id')::uuid,1,pg_temp.grammar_content('Edited title')) + from grammar_test_results where label='created'; +select is((select (value->>'version')::integer from grammar_test_results where label='updated'),2,'successful update increments version once'); +select is((select value->'created_at' from grammar_test_results where label='updated'), + (select value->'created_at' from grammar_test_results where label='created'),'update retains creation timestamp'); +select ok((select (value->>'updated_at')::timestamptz >= (value->>'created_at')::timestamptz from grammar_test_results where label='updated'),'update timestamp advances'); +select is(public.create_grammar_note('25252525-1111-4111-8111-111111111111',pg_temp.grammar_content()), + (select value from grammar_test_results where label='updated'),'original create retry after edit returns current row without overwriting it'); +select throws_ok($q$select public.create_grammar_note('25252525-1111-4111-8111-111111111111',pg_temp.grammar_content('Edited title'))$q$, + 'P0001','GRAMMAR_NOTE_IDEMPOTENCY_CONFLICT','same request key with changed initial payload is rejected even when matching current content'); +select throws_ok($q$select public.update_grammar_note((select (value->>'id')::uuid from grammar_test_results where label='created'),1,pg_temp.grammar_content('Stale update'))$q$, + 'P0001','GRAMMAR_NOTE_VERSION_CONFLICT','stale expected version is rejected'); +select is((select content #>> '{metadata,title}' from public.grammar_notes),'Edited title','conflicting update leaves content unchanged'); +select is((select version from public.grammar_notes),2,'conflicting update leaves version unchanged'); + +-- SQL NULL과 JSON null을 포함해 잘못된 구조가 성공으로 처리되지 않는지 확인합니다. +select throws_ok($q$select public.create_grammar_note(null,pg_temp.grammar_content())$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','missing request ID is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',null)$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','SQL null content is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333','null'::jsonb)$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','JSON null content is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',pg_temp.grammar_content()-'source')$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','missing source is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',pg_temp.grammar_content() #- '{metadata,grammarKey}')$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','missing nullable field is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',jsonb_set(pg_temp.grammar_content(),'{metadata,title}','" "'))$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','blank required text is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',jsonb_set(pg_temp.grammar_content(),'{analysis,chunks}','{}'))$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','non-array chunks return domain error instead of database type error'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',jsonb_set(pg_temp.grammar_content(),'{analysis,chunks}','[]'))$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','empty chunks are rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',jsonb_set(pg_temp.grammar_content(),'{analysis,syntax}','[{"id":"s1","ranges":[null],"parentId":null,"role":"subject","label":"주어","explanation":""}]'))$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','malformed nested range is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',jsonb_set(pg_temp.grammar_content(),'{metadata,sourceRevision}','1'))$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','stale metadata revision is rejected'); +select throws_ok($q$select public.create_grammar_note('25252525-3333-4333-8333-333333333333',jsonb_set(pg_temp.grammar_content(),'{analysis,sourceText}','"Different."'))$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','analysis of a different sentence is rejected'); +select throws_ok($q$select public.update_grammar_note((select (value->>'id')::uuid from grammar_test_results where label='created'),2,pg_temp.grammar_content()-'analysis')$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','invalid aggregate update is rejected'); +select is((select version from public.grammar_notes),2,'invalid update leaves version unchanged'); +select is((select content #>> '{metadata,title}' from public.grammar_notes),'Edited title','invalid update leaves content unchanged'); +select is((select count(*) from public.grammar_notes),1::bigint,'failed creates leave no partial rows'); + +select set_config('request.jwt.claim.sub','15151515-2222-4222-8222-222222222222',true); +select is((select count(*) from public.grammar_notes),0::bigint,'RLS hides another owner rows'); +select is(public.list_grammar_notes(),' {"items":[],"total":0}'::jsonb,'list also hides another owner rows'); +select throws_ok($q$select public.update_grammar_note((select (value->>'id')::uuid from grammar_test_results where label='created'),2,pg_temp.grammar_content())$q$,'P0001','GRAMMAR_NOTE_NOT_FOUND','other owner update is indistinguishable from missing row'); +select throws_ok($q$select public.update_grammar_note('35353535-1111-4111-8111-111111111111',1,pg_temp.grammar_content())$q$,'P0001','GRAMMAR_NOTE_NOT_FOUND','missing row is rejected'); +select lives_ok($q$select public.create_grammar_note('25252525-1111-4111-8111-111111111111',pg_temp.grammar_content('Other owner'))$q$,'request key is scoped to owner'); +select set_config('request.jwt.claim.sub','15151515-1111-4111-8111-111111111111',true); +insert into grammar_test_results values ('second',public.create_grammar_note('25252525-4444-4444-8444-444444444444',pg_temp.grammar_content('Literal %_ title'))); + +-- 정렬 키를 동일하게 고정하여 ID 보조 정렬과 페이지 중복 방지를 검증합니다. +reset role; +update public.grammar_notes set updated_at='2026-10-06T00:00:00Z' where owner_id='15151515-1111-4111-8111-111111111111'; +set local role authenticated; +select is((public.list_grammar_notes(1,1,'')->>'total')::integer,2,'list counts only own matching rows'); +select is(jsonb_array_length(public.list_grammar_notes(1,1,'')->'items'),1,'list applies page size'); +select is(public.list_grammar_notes(1,1,'') #>> '{items,0,id}', + (select id::text from public.grammar_notes order by updated_at desc,id desc limit 1),'equal timestamps use deterministic descending ID'); +select isnt(public.list_grammar_notes(1,1,'') #>> '{items,0,id}',public.list_grammar_notes(2,1,'') #>> '{items,0,id}','consecutive pages do not repeat a note'); +select is(public.list_grammar_notes(3,1,''),'{"items":[],"total":2}'::jsonb,'out-of-range page retains total'); +select is((public.list_grammar_notes(1,20,' eDiTeD ')->>'total')::integer,1,'title search trims and ignores case'); +select is((public.list_grammar_notes(1,20,'DOCTOR')->>'total')::integer,2,'search includes source sentence'); +select is((public.list_grammar_notes(1,20,'%_')->>'total')::integer,1,'percent and underscore are literal search characters'); +select is(public.list_grammar_notes(1,20,'unknown'),'{"items":[],"total":0}'::jsonb,'unmatched search has empty items and zero total'); +select ok(not ((public.list_grammar_notes() #> '{items,0}') ? 'content'),'summary excludes full analysis payload'); +select throws_ok($q$select public.list_grammar_notes(0,20,'')$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','page zero is rejected'); +select throws_ok($q$select public.list_grammar_notes(1,101,'')$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','oversized page is rejected'); +select throws_ok($q$select public.list_grammar_notes(null,20,'')$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','null page is rejected'); +select throws_ok($q$select public.list_grammar_notes(1,20,null)$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','null search is rejected'); +select throws_ok($q$select public.list_grammar_notes(1,20,repeat('x',201))$q$,'P0001','GRAMMAR_NOTE_INVALID_INPUT','oversized query is rejected'); +select is(public.list_grammar_notes(2147483647,100,''),'{"items":[],"total":2}'::jsonb,'large page offset cannot overflow integer'); +reset role; +set local role anon; +select throws_ok($q$select * from public.grammar_notes$q$,'42501',null,'anonymous cannot read notes'); +select throws_ok($q$select public.list_grammar_notes()$q$,'42501',null,'anonymous cannot invoke list RPC'); +select throws_ok($q$select public.create_grammar_note('25252525-5555-4555-8555-555555555555','{}')$q$,'42501',null,'anonymous cannot invoke create RPC'); +select throws_ok($q$select public.update_grammar_note('35353535-1111-4111-8111-111111111111',1,'{}')$q$,'42501',null,'anonymous cannot invoke update RPC'); +reset role; +select * from finish(); +rollback;