@simplysm/sd-claude 14.0.88 → 14.0.89

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.
Files changed (122) hide show
  1. package/claude/references/sd-simplysm14/README.md +17 -17
  2. package/claude/references/sd-simplysm14/apis/angular/README.md +27 -53
  3. package/claude/references/sd-simplysm14/apis/angular/controls.md +37 -105
  4. package/claude/references/sd-simplysm14/apis/angular/crud.md +46 -43
  5. package/claude/references/sd-simplysm14/apis/angular/directives.md +22 -32
  6. package/claude/references/sd-simplysm14/apis/angular/features.md +40 -55
  7. package/claude/references/sd-simplysm14/apis/angular/infra.md +40 -40
  8. package/claude/references/sd-simplysm14/apis/angular/layout.md +25 -53
  9. package/claude/references/sd-simplysm14/apis/angular/overlay.md +70 -82
  10. package/claude/references/sd-simplysm14/apis/angular/routing-appstructure.md +44 -39
  11. package/claude/references/sd-simplysm14/apis/angular/selection-managers.md +21 -36
  12. package/claude/references/sd-simplysm14/apis/angular/shared-data.md +52 -65
  13. package/claude/references/sd-simplysm14/apis/angular/sheet.md +65 -70
  14. package/claude/references/sd-simplysm14/apis/capacitor-plugin-auto-update/README.md +33 -35
  15. package/claude/references/sd-simplysm14/apis/capacitor-plugin-file-system/README.md +7 -7
  16. package/claude/references/sd-simplysm14/apis/capacitor-plugin-intent/README.md +29 -29
  17. package/claude/references/sd-simplysm14/apis/capacitor-plugin-usb-storage/README.md +45 -50
  18. package/claude/references/sd-simplysm14/apis/core-browser/README.md +42 -55
  19. package/claude/references/sd-simplysm14/apis/core-browser/dom-element.md +62 -0
  20. package/claude/references/sd-simplysm14/apis/core-browser/indexed-db.md +13 -12
  21. package/claude/references/sd-simplysm14/apis/core-common/README.md +222 -98
  22. package/claude/references/sd-simplysm14/apis/core-common/array-ext.md +102 -53
  23. package/claude/references/sd-simplysm14/apis/core-common/async-runtime.md +128 -0
  24. package/claude/references/sd-simplysm14/apis/core-common/datetime.md +98 -64
  25. package/claude/references/sd-simplysm14/apis/core-common/errors.md +91 -0
  26. package/claude/references/sd-simplysm14/apis/core-common/json-transfer.md +34 -28
  27. package/claude/references/sd-simplysm14/apis/core-common/obj.md +104 -40
  28. package/claude/references/sd-simplysm14/apis/core-node/README.md +11 -8
  29. package/claude/references/sd-simplysm14/apis/core-node/consola.md +23 -31
  30. package/claude/references/sd-simplysm14/apis/core-node/cpx.md +33 -22
  31. package/claude/references/sd-simplysm14/apis/core-node/fs-watcher.md +28 -25
  32. package/claude/references/sd-simplysm14/apis/core-node/fsx.md +39 -53
  33. package/claude/references/sd-simplysm14/apis/core-node/pathx.md +26 -29
  34. package/claude/references/sd-simplysm14/apis/core-node/worker.md +27 -29
  35. package/claude/references/sd-simplysm14/apis/excel/README.md +14 -14
  36. package/claude/references/sd-simplysm14/apis/lint/README.md +27 -21
  37. package/claude/references/sd-simplysm14/apis/lint/rules.md +89 -49
  38. package/claude/references/sd-simplysm14/apis/orm-common/README.md +5 -59
  39. package/claude/references/sd-simplysm14/apis/orm-common/db-context.md +98 -67
  40. package/claude/references/sd-simplysm14/apis/orm-common/expr.md +107 -92
  41. package/claude/references/sd-simplysm14/apis/orm-common/queryable.md +99 -65
  42. package/claude/references/sd-simplysm14/apis/orm-common/schema.md +83 -98
  43. package/claude/references/sd-simplysm14/apis/orm-common/types.md +62 -52
  44. package/claude/references/sd-simplysm14/apis/orm-node/README.md +62 -25
  45. package/claude/references/sd-simplysm14/apis/orm-node/db-conn.md +27 -27
  46. package/claude/references/sd-simplysm14/apis/sd-cli/README.md +12 -15
  47. package/claude/references/sd-simplysm14/apis/sd-cli/SdTsCompiler.md +92 -45
  48. package/claude/references/sd-simplysm14/apis/sd-cli/sd-config-types.md +226 -108
  49. package/claude/references/sd-simplysm14/apis/service-client/README.md +84 -86
  50. package/claude/references/sd-simplysm14/apis/service-client/orm.md +14 -11
  51. package/claude/references/sd-simplysm14/apis/service-client/transport.md +33 -10
  52. package/claude/references/sd-simplysm14/apis/service-common/README.md +37 -23
  53. package/claude/references/sd-simplysm14/apis/service-common/app-structure.md +9 -9
  54. package/claude/references/sd-simplysm14/apis/service-common/protocol.md +13 -13
  55. package/claude/references/sd-simplysm14/apis/service-server/README.md +81 -65
  56. package/claude/references/sd-simplysm14/apis/service-server/service-authoring.md +32 -35
  57. package/claude/references/sd-simplysm14/apis/service-server/transport-internals.md +44 -33
  58. package/claude/references/sd-simplysm14/apis/service-server/v1-legacy.md +34 -45
  59. package/claude/references/sd-simplysm14/apis/storage/README.md +24 -18
  60. package/claude/skills/sd-demo/SKILL.md +6 -0
  61. package/claude/skills/sd-impl/SKILL.md +4 -7
  62. package/claude/skills/sd-spec/SKILL.md +31 -858
  63. package/claude/skills/sd-spec/references/spec-authoring.md +519 -0
  64. package/claude/workflows/sd-docs.js +84 -0
  65. package/package.json +1 -1
  66. package/claude/references/sd-simplysm14/apis/orm-common/query-builder.md +0 -29
  67. package/claude/skills/sd-demo/evals/fixtures/inventory-list/.specs/inventory/spec.md +0 -99
  68. package/claude/skills/sd-demo/evals/fixtures/inventory-list/packages/demo-client/package.json +0 -12
  69. package/claude/skills/sd-demo/evals/fixtures/inventory-list/packages/demo-client/src/index.ts +0 -3
  70. package/claude/skills/sd-demo/evals/fixtures/inventory-list/packages/demo-client/src/screens/inbound/inbound.list.ts +0 -150
  71. package/claude/skills/sd-demo/evals/fixtures/inventory-list/packages/demo-client/src/screens/inventory/inventory-master.list.ts +0 -143
  72. package/claude/skills/sd-demo/evals/fixtures/inventory-list/packages/demo-client/src/screens/outbound/outbound.list.ts +0 -150
  73. package/claude/skills/sd-demo/evals/fixtures/inventory-list/pnpm-workspace.yaml +0 -2
  74. package/claude/skills/sd-demo/evals/fixtures/inventory-list/sd.config.ts +0 -12
  75. package/claude/skills/sd-demo/evals/golden.jsonl +0 -1
  76. package/claude/skills/sd-dev/evals/fixtures/minimal-ts-pkg/package.json +0 -8
  77. package/claude/skills/sd-dev/evals/fixtures/minimal-ts-pkg/src/.gitkeep +0 -0
  78. package/claude/skills/sd-dev/evals/fixtures/minimal-ts-pkg/tests/.gitkeep +0 -0
  79. package/claude/skills/sd-dev/evals/fixtures/minimal-ts-pkg/tsconfig.json +0 -10
  80. package/claude/skills/sd-dev/evals/golden.jsonl +0 -1
  81. package/claude/skills/sd-docs/SKILL.md +0 -46
  82. package/claude/skills/sd-docs/evals/fixtures/new-write/.claude/references/sd-simplysm14/README.md +0 -7
  83. package/claude/skills/sd-docs/evals/fixtures/new-write/packages/bar/package.json +0 -5
  84. package/claude/skills/sd-docs/evals/fixtures/new-write/packages/bar/src/index.ts +0 -3
  85. package/claude/skills/sd-docs/evals/fixtures/new-write/packages/baz/package.json +0 -6
  86. package/claude/skills/sd-docs/evals/fixtures/new-write/packages/baz/src/index.ts +0 -1
  87. package/claude/skills/sd-docs/evals/fixtures/new-write/packages/foo/package.json +0 -5
  88. package/claude/skills/sd-docs/evals/fixtures/new-write/packages/foo/src/index.ts +0 -8
  89. package/claude/skills/sd-docs/evals/fixtures/update-mixed/.claude/references/sd-simplysm14/README.md +0 -7
  90. package/claude/skills/sd-docs/evals/fixtures/update-mixed/.claude/references/sd-simplysm14/apis/foo/README.md +0 -3
  91. package/claude/skills/sd-docs/evals/fixtures/update-mixed/packages/bar/package.json +0 -5
  92. package/claude/skills/sd-docs/evals/fixtures/update-mixed/packages/bar/src/index.ts +0 -3
  93. package/claude/skills/sd-docs/evals/fixtures/update-mixed/packages/baz/package.json +0 -6
  94. package/claude/skills/sd-docs/evals/fixtures/update-mixed/packages/baz/src/index.ts +0 -1
  95. package/claude/skills/sd-docs/evals/fixtures/update-mixed/packages/foo/package.json +0 -5
  96. package/claude/skills/sd-docs/evals/fixtures/update-mixed/packages/foo/src/index.ts +0 -8
  97. package/claude/skills/sd-docs/evals/golden.jsonl +0 -2
  98. package/claude/skills/sd-impl/evals/fixtures/case-a-new-screen/.specs/260513120000_warehouse/spec.md +0 -101
  99. package/claude/skills/sd-impl/evals/fixtures/case-b-update-with-demo/.specs/260513120000_warehouse/spec.md +0 -101
  100. package/claude/skills/sd-impl/evals/fixtures/case-b-update-with-demo/packages/app/src/screens/box-register/box-register.view.ts +0 -46
  101. package/claude/skills/sd-impl/evals/fixtures/case-c-new-cross/.specs/260513120000_warehouse/spec.md +0 -89
  102. package/claude/skills/sd-impl/evals/fixtures/case-d-spec-modify/.specs/260513120000_warehouse/spec.md +0 -101
  103. package/claude/skills/sd-impl/evals/golden.jsonl +0 -4
  104. package/claude/skills/sd-manual/evals/fixtures/new-manual/src/notification.ts +0 -25
  105. package/claude/skills/sd-manual/evals/fixtures/update-manual/.claude/references/sd-simplysm14/manuals/notification.md +0 -14
  106. package/claude/skills/sd-manual/evals/fixtures/update-manual/src/notification.ts +0 -37
  107. package/claude/skills/sd-manual/evals/golden.jsonl +0 -2
  108. package/claude/skills/sd-review/evals/fixtures/code-review/src/foo.ts +0 -7
  109. package/claude/skills/sd-review/evals/fixtures/doc-review/docs/foo.md +0 -4
  110. package/claude/skills/sd-review/evals/golden.jsonl +0 -2
  111. package/claude/skills/sd-skill/evals/fixtures/existing-skill/.claude/skills/todo-format/SKILL.md +0 -14
  112. package/claude/skills/sd-skill/evals/fixtures/new-skill/.gitkeep +0 -0
  113. package/claude/skills/sd-skill/evals/golden.jsonl +0 -2
  114. package/claude/skills/sd-spec/evals/fixtures/case-a-split//355/232/214/354/235/230/353/241/235.md +0 -20
  115. package/claude/skills/sd-spec/evals/fixtures/case-b-detail/.specs/260513120000_warehouse/spec.md +0 -95
  116. package/claude/skills/sd-spec/evals/golden.jsonl +0 -2
  117. package/claude/skills/sd-unpack/evals/fixtures/eml-with-text-attachment/meeting.eml +0 -21
  118. package/claude/skills/sd-unpack/evals/fixtures/simple-eml/meeting.eml +0 -10
  119. package/claude/skills/sd-unpack/evals/golden.jsonl +0 -2
  120. package/claude/skills/sd-use/evals/fixtures/empty/.gitkeep +0 -0
  121. package/claude/skills/sd-use/evals/golden.jsonl +0 -6
  122. /package/claude/{skills/sd-docs/references/doc-rules.md → workflows/sd-docs.rules.md} +0 -0
@@ -1,90 +1,130 @@
1
1
  # @simplysm/lint — rules
2
2
 
3
- `eslint-plugin` 이 노출하는 커스텀 ESLint 규칙 9종. 규칙 ID 는 등록 시 `@simplysm/<name>`. 개별 규칙을 켜거나 lint 위반 메시지·autofix·옵션 의미를 파악할 때 읽음. 옵션 없는 규칙은 `schema: []`. autofix 는 `fixable: "code"` 표시 규칙만 제공. 모든 규칙은 `createRule`(= `ESLintUtils.RuleCreator`)로 생성되어 문서 URL 이 자동 부여됨.
3
+ `eslint-plugin` 이 노출하는 커스텀 ESLint 규칙 9종. 규칙 id 는 등록 시 `@simplysm/<name>`. 개별 규칙을 켜거나 lint 위반 메시지·autofix·옵션 의미를 파악할 때 읽음. 모든 규칙은 `createRule`(= `ESLintUtils.RuleCreator`, `src/utils/create-rule.ts`)로 생성되어 문서 URL 이 자동 부여됨. 옵션 없는 규칙은 `schema: []`. autofix 는 아래 "autofix" 표기 규칙만 제공.
4
4
 
5
- ## ng-no-async-effect
5
+ ## no-hard-private
6
6
 
7
- `type: problem`, autofix 없음. `@angular/core` 의 `effect()` 인자로 async 함수(화살표/함수표현식이며 `async` 플래그)를 직접 전달하는 것을 금지. `await` 이후 읽은 signal 반응형 컨텍스트를 벗어나 의존성 추적에서 빠지는 버그, 그리고 반환값이 `Promise<void>` 가 되어 cleanup 등록이 막히는 문제를 방지.
7
+ ECMAScript hard private(`#field`) 사용을 금지하고 TypeScript `private _` 스타일을 강제. `type: "problem"`, autofix 있음, 옵션 없음. JS·TS 양쪽에서 동작.
8
8
 
9
- - 감지 범위: named import(`effect`), aliased import(`effect as ngEffect`), namespace import(`ng.effect(...)`). `@angular/core` 아닌 모듈·로컬 선언 `effect` 는 무시(스코프·import 정의를 추적해 판별).
10
- - `noAsyncEffect` — async 직접 전달 금지 메시지. 비동기 작업은 `void untracked(async () => { ... })` 안에서 수행하라고 안내.
9
+ 검사 대상: 클래스 필드 선언(`#field`), 메서드 선언(`#method()`), 접근자 선언(`accessor #field`), 멤버 접근 표현식(`this.#field`).
11
10
 
12
- ```ts
13
- // 위반
14
- effect(async () => { await load(); });
15
- // 권장
16
- effect(() => { sig(); void untracked(async () => { await load(); }); });
11
+ 메시지:
12
+ - `preferSoftPrivate` — hard private(#) 금지, `private _` 스타일 사용 안내. autofix 는 `#name` → `_name` 으로 치환하고, 선언부에 접근제어자가 없으면 `private ` 를 앞에 삽입(데코레이터·`static`·`async`·`readonly` 순서를 보존해 그 뒤 삽입). 토큰 계산 실패 시 이름만 바뀌는 불완전 수정을 막기 위해 수정 전체를 건너뜀.
13
+ - `nameConflict` `#{{name}}` `_{{name}}` 으로 바꿀 수 없음(동일 이름 멤버가 클래스에 이미 존재). 이 경우 보고만 하고 autofix 안 함. 중첩 클래스는 스택으로 각 클래스 멤버 집합을 관리.
14
+
15
+ ```typescript
16
+ class A { #count = 0; inc() { this.#count++; } }
17
+ // → private _count = 0; inc() { this._count++; }
17
18
  ```
18
19
 
19
- ## no-hard-private
20
+ ## no-subpath-imports-from-simplysm
20
21
 
21
- `type: problem`, autofix 있음. ECMAScript hard private(`#field`) 금지, TypeScript `private _` 스타일 강제.
22
+ `@simplysm/*` 패키지의 `src` 하위 경로 import 를 금지(빌드 산출물 export 경유를 강제). `type: "problem"`, autofix 있음, 옵션 없음. JS·TS 양쪽에서 동작.
22
23
 
23
- - 감지: 필드 선언 `#field`, 메서드 선언 `#method()`, 접근자 선언 `accessor #field`, 사용처 `this.#field`. 중첩 클래스도 스택으로 추적.
24
- - autofix: `#a` → `_a` 이름 변경 + 선언부 앞에 `private ` 삽입(데코레이터·`static`·`async`·`readonly` 순서 보존; 사용처 `this.#a` → `this._a`). 단, 같은 클래스에 `_a` 멤버가 이미 있으면 충돌로 변환 불가 → 보고만 하고 autofix 안 함.
25
- - `preferSoftPrivate` — hard private 금지(이름 변경 가능 시 적용되는 일반 메시지).
26
- - `nameConflict` — `_{{name}}` 멤버가 이미 존재해 변환 불가. `{{name}}` 치환.
24
+ 검사 대상: 정적 import(`import ... from`), 동적 import(`import("...")`), 재내보내기(`export { x } from`), 전체 재내보내기(`export * from`). import 경로를 `/` 로 분리해 3번째 세그먼트가 `src` 인 경우(`@simplysm/pkg/src`, `@simplysm/pkg/src/xxx`)만 위반. `@simplysm/pkg`·`@simplysm/pkg/xxx`(src 아닌 subpath)는 허용.
27
25
 
28
- ## no-subpath-imports-from-simplysm
26
+ 메시지:
27
+ - `noSubpathImport` — `'@simplysm/{{pkg}}'` 에서 `src` 하위 경로 import 불가. autofix 는 경로를 `@simplysm/<pkg>`(원래 따옴표 유지)로 치환.
28
+
29
+ ```typescript
30
+ import { x } from "@simplysm/core-common/src/x"; // → "@simplysm/core-common"
31
+ ```
32
+
33
+ ## ng-no-async-effect
34
+
35
+ Angular `@angular/core` 의 `effect()` 에 async 함수를 직접 전달하는 것을 금지. `type: "problem"`, autofix 없음, 옵션 없음. `await` 이후 signal read 가 reactive 의존성으로 추적되지 않고 반환값이 `Promise<void>` 가 되어 cleanup 등록이 막히는 문제 방지.
29
36
 
30
- `type: problem`, autofix 있음. `@simplysm/<pkg>/src/...` 형태의 `src` 하위 경로 import 금지(`@simplysm/<pkg>` `src` 아닌 하위 경로는 허용).
37
+ 검사 대상: `effect(...)` 호출의 인자가 async ArrowFunction/FunctionExpression 인 경우. `effect` 식별자가 `@angular/core` 에서 import 되었는지 스코프로 검증 — named(`import { effect }`)·aliased(`effect as ngEffect`)·namespace(`import * as ng` → `ng.effect(...)`) import 만 인정. 다른 모듈 또는 로컬 선언 `effect` 는 무시.
31
38
 
32
- - 감지: 정적 `import ... from '...'`, 동적 `import('...')`, 재내보내기 `export { ... } from '...'`, 전체 재내보내기 `export * from '...'`. 경로를 `/` 로 분해해 3번째 세그먼트가 `src` 인 경우만 위반.
33
- - autofix: `@simplysm/pkg/src/x` `@simplysm/pkg` 치환(원본 따옴표 종류 유지).
34
- - `noSubpathImport` — `{{pkg}}`(패키지명)·`{{importPath}}`(원본 경로) 치환.
39
+ 메시지:
40
+ - `noAsyncEffect` async 함수 직접 전달 금지. 비동기는 `void untracked(async () => { ... })` 내부에서 수행하라고 안내. 보고 위치는 첫 인자(콜백) 노드.
41
+
42
+ ```typescript
43
+ effect(() => { this.sig(); void untracked(async () => { await this.load(); }); });
44
+ ```
35
45
 
36
46
  ## ts-no-throw-not-implemented-error
37
47
 
38
- `type: suggestion`, autofix 없음, recommended 에서 `warn`(테스트에서는 off). `@simplysm/core-common` 의 `NotImplementedError` 를 `new` 로 생성하는 코드를 감지해 미구현 코드의 프로덕션 유입을 경고.
48
+ `@simplysm/core-common` 의 `NotImplementedError` 를 `new` 로 인스턴스화하는 코드를 감지(미구현 코드의 프로덕션 유입 방지). `type: "suggestion"`, autofix 없음, 옵션 없음. recommended 에서 `warn`(테스트 파일은 `off`).
49
+
50
+ 검사 대상: `new NotImplementedError(...)`(named/aliased import), `new CC.NotImplementedError(...)`(namespace import). 식별자가 `@simplysm/core-common` 에서 import 되었는지 스코프로 검증. 동적 import(`await import(...)`)는 감지 안 함.
39
51
 
40
- - 감지: named/aliased import(`NotImplementedError`, `NotImplementedError as NIE`), namespace import(`new CC.NotImplementedError()`). import 소스가 `@simplysm/core-common` 인지 스코프로 검증. 동적 import 는 무시.
41
- - `noThrowNotImplementedError` — `{{text}}` 치환. `new` 첫 인자가 비어있지 않은 문자열 리터럴이면 그 문자열을, 아니면 `"미구현"` 을 그대로 출력.
52
+ 메시지:
53
+ - `noThrowNotImplementedError` — 메시지 본문은 `{{text}}` 치환. 첫 인자가 비어있지 않은 문자열 리터럴이면 그 값을, 아니면 `"미구현"` 을 출력.
42
54
 
43
- ```ts
44
- throw new NotImplementedError("결제 모듈 미구현"); // → "결제 모듈 미구현" 경고
55
+ ```typescript
56
+ import { NotImplementedError } from "@simplysm/core-common";
57
+ new NotImplementedError("결제 연동"); // → "결제 연동" 경고
45
58
  ```
46
59
 
47
60
  ## ts-no-unused-injects
48
61
 
49
- `type: problem`, autofix 있음. 클래스 내 `inject()` 호출로 초기화된 프로퍼티 같은 클래스 어디에서도 참조되지 않는 필드를 보고.
62
+ 미사용 Angular `inject()` 필드를 감지. `type: "problem"`, autofix 있음, 옵션 없음.
50
63
 
51
- - 감지: `PropertyDefinition` 값이 `inject(...)` 호출이고 key 식별자인 필드. 클래스 본문 전체를 재귀 순회해 필드명과 동일한 식별자(자기 key 제외)가 하나도 없으면 미사용으로 판정.
52
- - autofix: 해당 필드 제거(앞 토큰 끝 ~ 뒤 토큰 사이 range 삭제).
53
- - `unusedInject` — `inject() field "{{name}}" is never used.`
64
+ 검사 대상: 클래스 본문에서 `inject(...)` 호출로 초기화된 PropertyDefinition(키가 Identifier). 같은 클래스 본문 전체를 순회해 필드명과 동일한 Identifier 참조(필드 자신 제외)가 0개면 미사용으로 판정. 클래스 내부 참조만 검사 — 템플릿 사용 여부는 보지 않음.
65
+
66
+ 메시지:
67
+ - `unusedInject` — `inject() field "{{name}}" is never used.` autofix 는 해당 필드 선언을 앞 토큰 끝부터 제거(뒤 토큰이 있으면 필드 끝까지).
68
+
69
+ ```typescript
70
+ class C { private _svc = inject(MyService); } // _svc 미참조 시 제거
71
+ ```
54
72
 
55
73
  ## ts-no-unused-protected-readonly
56
74
 
57
- `type: problem`, autofix 있음. `@Component` 데코레이터가 달린 클래스에서 `protected readonly`(non-static) 필드가 인라인 `template` 클래스 본문 어디에서도 참조되지 않으면 보고.
75
+ Angular `@Component` 인라인 템플릿·클래스 본문 어디에서도 쓰이는 `protected readonly` 필드를 감지. `type: "problem"`, autofix 있음, 옵션 없음.
76
+
77
+ 검사 대상: `@Component` 데코레이터가 있고 그 첫 인자 객체에 `template` 속성(문자열 리터럴 또는 템플릿 리터럴)이 있는 클래스. 그 클래스의 `protected readonly` 비-static 필드(키가 Identifier)가 ① 인라인 템플릿에서 미참조 ② 클래스 본문 다른 멤버에서 미참조 둘 다일 때 보고. 템플릿 식별자는 `@angular/compiler` 의 `parseTemplate` 으로 AST 파싱 후 `ImplicitReceiver`/`ThisReceiver` 위 `PropertyRead`(클래스 필드 참조)만 수집하며, `*ngFor` 로컬·`@let`·`@if ... as`·`@for` item/별칭 등 스코프 로컬 변수는 제외. `@if`/`@switch`/`@for`/`@defer` 블록, 입력/이벤트/구조 디렉티브 바인딩까지 순회. `templateUrl`(외부 템플릿)은 대상 아님(`template` 문자열만).
58
78
 
59
- - 동작: `@Component({ template: ... })` 의 인라인 템플릿 문자열(템플릿 리터럴/문자열 리터럴)을 `@angular/compiler` 의 `parseTemplate` 으로 파싱해 바인딩 식별자를 수집. `@for` item·context 변수, `@if (...; as alias)`, `@let` 선언, 구조 디렉티브(`*ngFor` 등) 로컬 변수는 스코프에서 제외(오탐 방지). 템플릿·클래스 양쪽 모두 미사용일 때만 보고. `template` prop 이 없거나 빈 문자열이면 검사하지 않음(외부 `templateUrl` 미지원).
60
- - autofix: 필드 선언 라인 제거(앞 들여쓰기·뒤 세미콜론/개행 포함).
61
- - `unusedField` — `Protected readonly field "{{name}}" is not used in class or template.`
79
+ 메시지:
80
+ - `unusedField` — `Protected readonly field "{{name}}" is not used in class or template.` autofix 필드 선언과 앞 들여쓰기·뒤 `;`·개행을 함께 제거.
81
+
82
+ ```typescript
83
+ @Component({ template: `<div>{{title}}</div>` })
84
+ class C { protected readonly title = "x"; protected readonly unused = 1; } // unused 제거
85
+ ```
62
86
 
63
87
  ## ng-template-no-strict-null-check
64
88
 
65
- `type: problem`, autofix 없음(인라인 템플릿 offset 매핑 문제로 미제공). Angular 템플릿 바인딩에서 `=== null`/`undefined`, `!== null`/`undefined` 금지, `== null`/`!= null` 강제.
89
+ Angular HTML 템플릿에서 엄격 비교(`=== null`, `!== null`, `=== undefined`, `!== undefined`)를 금지하고 `== null`/`!= null` 로 통일하도록 강제. `type: "problem"`, autofix 없음(인라인 템플릿 offset 매핑 문제로 미제공), 옵션 없음. HTML 파일 대상.
90
+
91
+ 검사 대상: 템플릿 표현식의 `Binary` 노드 중 연산자가 `===`/`!==` 이고 양변 중 하나가 nil 리터럴(value 가 null/undefined)인 경우.
66
92
 
67
- - 감지: `===`/`!==` 이항 연산의 한쪽 피연산자가 `null`/`undefined` 리터럴(value 가 nil)인 경우.
68
- - `noStrictNullCheck` — `{{actual}}`(원본 표현식)·`{{replacement}}`(권장 표현식, `x == null`/`x != null`) 치환.
93
+ 메시지:
94
+ - `noStrictNullCheck` — `{{actual}}`(예: `x === null`) 사용 금지, `{{replacement}}`(예: `x == null`) 사용 안내. `===`→`==`, `!==`→`!=` 로 변환한 권장 표현을 제시.
95
+
96
+ ```html
97
+ @if (user !== null) {} <!-- user != null 사용하라고 보고 -->
98
+ ```
69
99
 
70
100
  ## ng-template-no-todo-comments
71
101
 
72
- `type: problem`, autofix 없음, recommended 에서 `warn`. HTML 템플릿의 `<!-- TODO: ... -->` 주석을 감지. AST visitor 아니라 raw 텍스트 정규식으로 처리(visitor 객체 반환).
102
+ Angular HTML 템플릿 `<!-- TODO: ... -->` 주석을 경고. `type: "problem"`, autofix 없음, 옵션 없음. recommended 에서 `warn`. HTML 파일 대상.
73
103
 
74
- - 감지: HTML 주석(`<!-- ... -->`) 내부에 `TODO:` 가 포함된 경우. 메시지에는 `TODO:` 이후를 trim 한 본문을 그대로 출력.
75
- - `noTodo` — `{{content}}` 치환(주석에 적힌 TODO 내용).
104
+ 동작: raw 텍스트를 `<!--...-->` 정규식으로 훑어 주석 내용에 `TODO:` 가 있으면 보고(AST 방문자 없이 빈 객체 반환). 메시지 본문은 `TODO:` trim 한 내용.
105
+
106
+ 메시지:
107
+ - `noTodo` — 본문은 `{{content}}`(TODO 뒤 텍스트) 그대로 출력.
108
+
109
+ ```html
110
+ <!-- TODO: 페이징 추가 --> <!-- "페이징 추가" 경고 -->
111
+ ```
76
112
 
77
113
  ## ng-template-sd-require-binding-attrs
78
114
 
79
- `type: problem`, autofix 있음, 옵션 있음. `sd-` 접두사 컴포넌트에서 허용 목록 밖 plain attribute 사용을 금지하고 Angular property binding(`[attr]="..."`)을 강제.
115
+ `sd-*` 접두사 커스텀 컴포넌트에서 허용목록 밖 plain attribute 사용을 금지하고 Angular property binding(`[attr]="..."`)을 강제. `type: "problem"`, autofix 있음. HTML 파일 대상. **유일하게 옵션 있는 규칙**.
116
+
117
+ 옵션(`RuleOptions`, 모두 선택):
118
+ - `selectorPrefixes: string[]` — 검사 대상 요소 태그 접두사. 미지정 시 `["sd-"]`. 태그명을 소문자로 비교. 다른 디자인 시스템 접두사를 검사하려면 지정.
119
+ - `allowAttributes: string[]` — plain attribute 로 허용할 정확한 이름 목록. 미지정 시 `["id","class","style","title","tabindex","role"]`. 소문자 비교. 추가로 허용할 표준 속성을 늘릴 때.
120
+ - `allowAttributePrefixes: string[]` — plain attribute 로 허용할 접두사 목록. 미지정 시 `["aria-","data-","sd-"]`. 소문자 비교. 접두사 기반(aria/data 등) 속성군을 통째 허용할 때.
121
+
122
+ 동작: 대상 태그(접두사 매칭) 요소의 attribute 중 `allowAttributes`(정확 일치)·`allowAttributePrefixes`(접두사 일치) 어디에도 안 드는 것을 보고.
80
123
 
81
- - 옵션(객체 1개, 모든 키 선택):
82
- - `selectorPrefixes: string[]` — 검사 대상 엘리먼트 태그 접두사. 기본 `["sd-"]`. 접두사로 시작하는 태그만 검사. 다른 디자인 시스템 접두사를 쓰면 값으로 교체.
83
- - `allowAttributes: string[]` — plain 으로 허용할 attribute 이름. 기본 `["id","class","style","title","tabindex","role"]`. 대소문자 무시. 표준 전역 속성을 추가 허용할 때 확장.
84
- - `allowAttributePrefixes: string[]` — plain 으로 허용할 attribute 접두사. 기본 `["aria-","data-","sd-"]`. 접근성·데이터 속성군을 통째로 허용.
85
- - autofix: 값 없는 attr → `[attr]="true"`, 값 있는 attr → `[attr]="'<escaped>'"`(`\`·`'` 이스케이프). 빈 span 이면 fix 생략.
86
- - `requireBindingForAttribute` — `{{attrName}}`·`{{elementName}}` 치환.
124
+ 메시지:
125
+ - `requireBindingForAttribute` — `"{{attrName}}"` `"{{elementName}}"` plain attribute 로 불가, property binding 사용 안내. autofix 는 값이 빈 문자열이면 `[attr]="true"`, 값이 있으면 `\` `'` 이스케이프해 `[attr]="'값'"` 치환(span start≥end 면 수정 안 함).
87
126
 
88
- ```js
89
- { "@simplysm/ng-template-sd-require-binding-attrs": ["error", { allowAttributes: ["id", "for"] }] }
127
+ ```html
128
+ <sd-button myattr="hello"></sd-button> <!-- <sd-button [myattr]="'hello'"></sd-button> -->
129
+ <sd-button disabled></sd-button> <!-- → <sd-button [disabled]="true"></sd-button> -->
90
130
  ```
@@ -1,67 +1,13 @@
1
1
  # @simplysm/orm-common
2
2
 
3
- Dialect 독립 ORM 코어. 테이블/뷰/프로시저를 빌더로 정의하고, `DbContext` 클래스에 등록한 뒤, 체이닝 `Queryable` 로 타입 안전한 SELECT/CUD 쿼리를 JSON AST(`QueryDef`/`Expr`)로 조립한다. 실제 SQL 변환·DB 연결은 dialect QueryBuilder(이 패키지) + `@simplysm/orm-node` 등 executor 담당.
3
+ Dialect 독립 ORM 코어. 테이블/뷰/프로시저를 fluent builder 로 정의하고, `DbContext` 클래스에 등록한 뒤, 체이닝 `Queryable` 로 타입 안전한 SELECT/CUD 쿼리를 JSON AST(`QueryDef`/`Expr`)로 조립한다. 실제 SQL 변환은 패키지의 dialect QueryBuilder(MySQL/MSSQL/PostgreSQL)가, DB 연결·실행은 `DbContextExecutor` 구현체(`@simplysm/orm-node` 등)담당한다.
4
4
 
5
5
  ## 사용 트리거 인덱스
6
6
 
7
7
  - **스키마 정의 (Table/View/Procedure/Column/Index/Relation 빌더)** — DB 객체를 fluent 빌더로 선언하고 column·PK·index·FK 관계를 잡을 때. 자세히: [schema.md](./schema.md)
8
- - **DbContext (연결·트랜잭션·DDL·마이그레이션·초기화)** — 빌더들을 한 컨텍스트에 등록하고 `connect`/`transaction` 으로 실행, DDL·migration·`initialize` 를 돌릴 때. 자세히: [db-context.md](./db-context.md)
9
- - **Queryable (SELECT/JOIN/INSERT/UPDATE/DELETE/UPSERT 체이닝)** — `db.user()` 로 받은 쿼리 빌더에 where/orderBy/join/include/group/recursive/union 을 걸고 execute/single/count/insert/update/delete/upsert 호출할 때. 자세히: [queryable.md](./queryable.md)
8
+ - **DbContext (연결·트랜잭션·DDL·마이그레이션·초기화·트랜잭션 에러)** — 빌더들을 한 컨텍스트에 등록하고 `connect`/`transaction` 으로 실행, DDL·migration·`initialize` 를 돌리거나 `DbTransactionError` 를 처리할 때. 자세히: [db-context.md](./db-context.md)
9
+ - **Queryable (SELECT/JOIN/CUD 체이닝 · 프로시저 실행 · 검색 파서)** — `db.user()` 로 받은 쿼리 빌더에 where/orderBy/join/include/group/recursive/union 을 걸고 execute/single/count/insert/update/delete/upsert 하거나, `Executable` 로 프로시저를 실행하고 `search()` 텍스트 검색을 쓸 때. 자세히: [queryable.md](./queryable.md)
10
10
  - **expr (SQL 표현식 빌더)** — where/select/orderBy 콜백 안에서 비교·문자열·숫자·날짜·집계·조건·window·서브쿼리 표현식을 만들 때. 자세히: [expr.md](./expr.md)
11
- - **QueryDef / Expr / Column 타입** — executor·QueryBuilder 를 직접 구현하거나 AST·결과 메타를 다룰 참조하는 타입군. 자세히: [types.md](./types.md)
12
- - **QueryBuilder (dialect SQL 렌더러)** — QueryDef 를 mysql/mssql/postgresql SQL 로 변환하는 클래스. executor 구현체가 사용. 자세히: [query-builder.md](./query-builder.md)
13
- - **결과 파싱 유틸 / 검색 파서 / 프로시저 실행 / 에러** — 아래 인라인 섹션 참조.
11
+ - **타입·실행 엔진 내부 (QueryDef/Expr/Column 타입 · dialect QueryBuilder · 결과 파서)** — executor·QueryBuilder 를 직접 구현하거나 AST·결과 메타를 다루고, QueryDef SQL 로 렌더링하거나 raw 결과를 환원할 때. 자세히: [types.md](./types.md)
14
12
 
15
- ## Executable / executable (프로시저 실행)
16
-
17
- 저장 프로시저를 `DbContext.executable(Procedure)` 로 등록하면 `() => Executable` 팩토리가 반환된다. `Executable` 은 프로시저 실행 래퍼.
18
-
19
- - `executable(db: DbContextBase, builder: ProcedureBuilder): () => Executable` — DbContext 내부에서 프로시저 getter 를 만드는 팩토리. 보통 `DbContext.executable()` 보호 메서드가 대신 호출.
20
- - `Executable.execute(params): Promise<TReturns[][]>` — 프로시저 실행. `params` 는 `ProcedureBuilder.params()` 로 정의한 키별 값(리터럴 또는 ExprUnit). 결과는 결과셋 배열의 배열.
21
- - `Executable.getExecProcQueryDef(params?)` — 실행용 `ExecProcQueryDef` 생성. 파라미터 미정의 프로시저에 값 전달 시 throw.
22
-
23
- ```typescript
24
- const result = await db.getUserById().execute({ userId: 1 });
25
- ```
26
-
27
- ## 결과 파싱 유틸
28
-
29
- executor 가 DB raw 결과를 TS 객체로 환원할 때 쓰는 유틸. 일반 사용자는 직접 호출하지 않음.
30
-
31
- - `parseQueryResult<T>(rawResults, meta: ResultMeta): Promise<T[] | undefined>` — flat raw 행 배열을 `meta.columns`(키→타입) 로 타입 변환하고 `meta.joins`(키→`{isSingle}`) 로 중첩 그룹핑. 입력이 비었거나 파싱 후 전부 빈 객체면 undefined. async 전용(100행마다 이벤트 루프 양보). `isSingle:true` 관계에 서로 다른 다건이 매칭되면 throw.
32
- - `pickResultSets<T>(rawResults: T[][], buildResult): T[]` — 다중 결과셋에서 필요분 추출. `resultSetIndex` 없으면 첫 셋, `resultSetStride` 없으면 해당 인덱스 셋, 있으면 인덱스부터 stride 간격으로 concat(MySQL 배치 INSERT 의 SELECT 결과만 모을 때).
33
-
34
- ## 검색 파서
35
-
36
- `Queryable.search()` 내부에서 쓰이며, 검색 문법 문자열을 SQL LIKE 패턴으로 변환.
37
-
38
- - `parseSearchQuery(searchText: string): ParsedSearchQuery` — 검색 문자열 파싱. 반환 `{ or, must, not }` 각각 LIKE 패턴 배열.
39
- - `or: string[]` — 공백 구분 일반 토큰(OR, 하나 이상 일치). 와일드카드 없는 토큰은 `%토큰%`(부분 일치).
40
- - `must: string[]` — `+토큰` 또는 `"정확한 구문"`(AND, 필수 포함).
41
- - `not: string[]` — `-토큰`(NOT, 제외).
42
- - 문법: `term1 term2`(OR), `+term`(필수), `-term`(제외), `"구문"`(정확·필수), `*`(와일드카드→`%`). 이스케이프 `\\ \* \% \" \+ \-`. 닫히지 않은 따옴표는 일반 텍스트.
43
- - `interface ParsedSearchQuery` — 위 `or`/`must`/`not` 세 LIKE 패턴 배열을 담는 타입.
44
-
45
- ## 에러 (DbTransactionError / DbErrorCode)
46
-
47
- DBMS 네이티브 트랜잭션 에러를 표준 코드로 래핑. `connect`/`transaction` 의 롤백 경로에서 발생.
48
-
49
- - `class DbTransactionError extends Error` — 표준화된 트랜잭션 에러.
50
- - `code: DbErrorCode` — 표준 에러 코드.
51
- - `message: string` — 에러 메시지(생성자 2번째 인자).
52
- - `originalError?: unknown` — 원본 DBMS 에러(디버깅용).
53
- - `name` — 항상 `"DbTransactionError"`.
54
- - `enum DbErrorCode` — 표준 트랜잭션 에러 코드.
55
- - `NO_ACTIVE_TRANSACTION` — 활성 트랜잭션 없는데 ROLLBACK 시도. 롤백 중 이 코드면 `connect`/`transaction` 이 무시(원 에러 보존).
56
- - `TRANSACTION_ALREADY_STARTED` — 이미 트랜잭션 시작됨.
57
- - `DEADLOCK` — 데드락 발생.
58
- - `LOCK_TIMEOUT` — 잠금 타임아웃.
59
-
60
- ```typescript
61
- try {
62
- await db.rollbackTransaction();
63
- } catch (err) {
64
- if (err instanceof DbTransactionError && err.code === DbErrorCode.NO_ACTIVE_TRANSACTION) return;
65
- throw err;
66
- }
67
- ```
13
+ 모든 군이 별도 파일로 분할되어 있다. README 인라인 섹션은 두지 않는다.
@@ -1,80 +1,111 @@
1
- # @simplysm/orm-common — DbContext / 연결·DDL·마이그레이션
1
+ # @simplysm/orm-common — DbContext / 연결·트랜잭션·DDL·마이그레이션
2
2
 
3
- 테이블/뷰/프로시저 빌더를 class 프로퍼티로 등록하고, 연결·트랜잭션·DDL·초기화·마이그레이션을 제공하는 추상 클래스. 서브클래스로 확장해 사용. 실제 DB I/O 생성자에 주입한 `DbContextExecutor` 담당.
3
+ `DbContext` 추상 클래스를 상속해 테이블·뷰·프로시저를 프로퍼티로 등록하고, 연결·트랜잭션·DDL·마이그레이션을 실행하는 묶음. executor(`DbContextExecutor`) 구현체와 `{ database, schema? }` 옵션을 생성자로 주입한다. 트랜잭션 롤백 에러는 `DbTransactionError` 표준화된다.
4
4
 
5
- ## DbContext (추상 클래스)
5
+ ## DbContext (정의·등록)
6
6
 
7
- - `new DbContext(executor: DbContextExecutor, opt: { database: string; schema? })` — 생성자(서브클래스가 호출). `executor` DB I/O 구현, `opt.database`/`opt.schema` 기본 네임스페이스.
8
- - `status: DbContextStatus` — 현재 상태(`"ready"`|`"connect"`|`"transact"`). 연결/트랜잭션 가드에 사용.
9
- - `database` / `schema` — 주입한 기본 database/schema.
10
- - 등록 메서드(protected, 서브클래스 프로퍼티 초기화에서 호출):
11
- - `queryable(builder): () => Queryable` — Table/View 빌더를 Queryable 팩토리로 등록. 호출할 때마다 새 alias 부여.
12
- - `executable(builder): () => Executable` — Procedure 빌더를 Executable 팩토리로 등록.
13
- - `migrations: Migration[]` — 마이그레이션 정의(서브클래스에서 오버라이드). 기본 배열.
7
+ `abstract class DbContext implements DbContextBase`. 서브클래스에서 `this.queryable(...)`/`this.executable(...)` 멤버를 만들고 `migrations` 오버라이드한다.
8
+
9
+ - `constructor(executor: DbContextExecutor, opt: { database: string; schema?: string })` — executor 대상 DB 옵션 주입.
10
+ - `protected queryable(builder): () => Queryable` — Table/View 빌더를 Queryable 팩토리로 등록. 호출 시마다 새 alias 부여(View 는 viewFn 실행). 반환 함수에 `SD_BUILDER` 심볼로 원본 빌더를 부착.
11
+ - `protected executable(builder): () => Executable` — Procedure 빌더를 Executable 팩토리로 등록. 마찬가지로 `SD_BUILDER` 부착.
12
+ - `migrations: Migration[]` — 마이그레이션 정의 배열. 서브클래스에서 오버라이드. `initialize()` 가 미적용분만 순서대로 실행.
13
+ - `_migration` — 내부 시스템 마이그레이션 테이블(`_Migration`) Queryable. 적용 이력 저장용.
14
14
 
15
15
  ```typescript
16
16
  class MainDb extends DbContext {
17
17
  user = this.queryable(User);
18
18
  post = this.queryable(Post);
19
19
  getUserById = this.executable(GetUserById);
20
- migrations = [{ name: "001", up: async (db) => { await db.createTable(User); } }];
20
+ override migrations = [{ name: "001", up: async (db) => { await db.createTable(User); } }];
21
21
  }
22
22
  const db = new MainDb(executor, { database: "mydb" });
23
- await db.connect(async () => { await db.user().execute(); });
24
23
  ```
25
24
 
26
- ## 연결 / 트랜잭션
27
-
28
- - `connect<T>(fn, isolationLevel?): Promise<T>` 연결 + 트랜잭션 1개를 감싸 `fn` 실행. 성공 시 commit, 예외 시 rollback 후 throw, 종료 시 항상 close. `ready` 아니면 throw. 최초 호출 관계 정합성 검증. `isolationLevel` 은 격리 수준(선택).
29
- - `connectWithoutTransaction<T>(callback): Promise<T>` — 트랜잭션 없이 연결만 잡고 `callback` 실행, 종료 시 close. 내부에서 별도 `transaction()` 을 직접 호출할 때 사용.
30
- - `transaction<T>(fn, isolationLevel?): Promise<T>`이미 연결된 상태에서 트랜잭션만 시작/commit/rollback. `transact` 상태면 throw. (DDL 은 transact 상태에서 실행 불가 — `executeDefs` 가 throw)
31
-
32
- ## DbContextBase 내부 인터페이스 메서드
33
-
34
- executor·Queryable 의존하는 저수준 메서드(직접 호출은 드묾):
35
- - `getNextAlias(): string` — 다음 테이블 alias(`T1`, `T2`...) 발급.
36
- - `resetAliasCounter(): void`alias 카운터 초기화(연결 시작 시 호출).
37
- - `executeDefs<T>(defs: QueryDef[], resultMetas?): Promise<T[][]>` — QueryDef 배열을 executor 로 실행. transact 상태에서 DDL 포함 시 throw.
38
- - `getQueryDefObjectName(tableOrView): QueryDefObjectName` 빌더 DB 객체 이름(database/schema/name) 해석.
39
- - `switchFk(table, enabled): Promise<void>` — FK 제약 활성/비활성(트랜잭션 내 가능).
40
-
41
- ## DDL 실행 메서드 (await 후 즉시 실행)
42
-
43
- 각각 해당 DDL `executeDefs` 즉시 실행. `table`/`view`/`procedure` 인자는 `QueryDefObjectName` 또는 빌더.
44
- - `createTable(table)` / `dropTable(table)` / `renameTable(table, newName)` 테이블 생성/삭제/이름변경.
45
- - `createView(view)` / `dropView(view)` 생성/삭제.
46
- - `createProc(procedure)` / `dropProc(procedure)` — 프로시저 생성/삭제.
47
- - `addColumn(table, columnName, column)` column 추가(`column` `ColumnBuilder`).
48
- - `dropColumn(table, column)` — column 삭제.
49
- - `modifyColumn(table, columnName, column)` — column 타입/속성 변경.
50
- - `renameColumn(table, column, newName)` column 이름 변경.
51
- - `addPrimaryKey(table, columns)` / `dropPrimaryKey(table)` PK 추가/삭제.
52
- - `addForeignKey(table, relationName, relationDef)` FK 추가(`relationDef` `ForeignKeyBuilder`).
53
- - `dropForeignKey(table, relationName)` — FK 삭제.
54
- - `addIndex(table, indexBuilder)` / `dropIndex(table, columns)` — index 추가/삭제.
55
- - `clearSchema(params: { database; schema? })` — 스키마 내 모든 객체 삭제.
56
- - `schemaExists(database, schema?): Promise<boolean>` — 스키마 존재 확인.
57
- - `truncate(table)` — 테이블 비우기.
58
-
59
- ## DDL QueryDef 생성기 (실행 없이 def 만 반환)
60
-
61
- DDL 들의 `get*QueryDef(...)` 버전. 즉시 실행하지 않고 `QueryDef` 만 반환해 배치·검사용으로 모을 때 사용. 예: `getCreateTableQueryDef(table)`, `getDropTableQueryDef(table)`, `getAddColumnQueryDef(table, columnName, column)`, `getAddForeignKeyQueryDef(...)`, `getTruncateQueryDef(table)`, `getSwitchFkQueryDef(table, enabled)` 등. `getCreateObjectQueryDef(builder)` 는 Table/View/Procedure 중 무엇이든 받아 알맞은 CREATE def 반환.
62
-
63
- ## 초기화 / 마이그레이션
64
-
65
- - `initialize(options?: { dbs?: string[]; force?: boolean }): Promise<boolean>` 스키마 동기화/마이그레이션 실행.
66
- - `dbs?: string[]` 대상 database 한정(미지정 전체).
67
- - `force?: boolean` — true 면 기존 스키마를 강제 재생성. 운영 데이터 손실 위험이 있어 개발/초기 셋업에서만.
68
- - 반환 boolean초기화 수행 여부.
69
- - `interface Migration`마이그레이션 1건.
70
- - `name: string`고유 이름(타임스탬프 권장, 적용 여부 추적 키).
71
- - `up: (db) => Promise<void>` — 적용 함수. `db` 는 DDL 메서드를 갖춘 컨텍스트.
72
-
73
- ## 관련 타입
74
-
75
- - `type DbContextStatus = "ready" | "connect" | "transact"`.
76
- - `interface DbContextBase`Queryable/Executable/ViewBuilder 의존하는 핵심 인터페이스(위 저수준 메서드 + database/schema/status).
77
- - `interface DbContextDdlMethods` — DDL 실행+생성기 메서드 시그니처 모음(Migration.up db 타입).
78
- - `interface DbContextExecutor` — 주입할 실행기 인터페이스. `connect()`/`close()`/`beginTransaction(isolationLevel?)`/`commitTransaction()`/`rollbackTransaction()`/`executeDefs(defs, resultMetas?)`.
79
- - `const SD_BUILDER: symbol` — 등록된 팩토리 함수에 원본 빌더를 매달아두는 심볼 키(내부 메타 조회용).
80
- - `_Migration` — 시스템 마이그레이션 테이블 빌더(`_migration`, PK `code: varchar(255)`). initialize 가 적용 이력 저장에 사용.
25
+ ## 상태·내부 (DbContextBase / DbContextStatus)
26
+
27
+ `interface DbContextBase` — Queryable/Executable/View 의존하는 핵심 면. DbContext구현. executor·어댑터 작성참조.
28
+
29
+ - `status: DbContextStatus``"ready"`(미연결) / `"connect"`(연결됨, 트랜잭션 밖) / `"transact"`(트랜잭션 중). `transact` 상태에서 DDL 실행 throw.
30
+ - `readonly database` / `readonly schema` — 주입된 옵션 값(`string | undefined`).
31
+ - `getNextAlias(): string` 다음 테이블 alias(`T1`, `T2`...) 발급. 카운터 증가.
32
+ - `resetAliasCounter(): void` — alias 카운터 0 으로. connect 시작 시 호출됨.
33
+ - `executeDefs<T>(defs, resultMetas?): Promise<T[][]>` QueryDef 배열 실행 위임. `transact` 중 DDL 포함 시 throw. 모든 쿼리 실행의 단일 통로.
34
+ - `getQueryDefObjectName(tableOrView): QueryDefObjectName` — 빌더에서 `{database, schema, name}` 추출.
35
+ - `switchFk(table, enabled): Promise<void>`FK 제약 on/off(트랜잭션 허용).
36
+
37
+ `type DbContextStatus = "ready" | "connect" | "transact"`. `interface DbContextDdlMethods` 아래 DDL 메서드들의 시그니처 모음(`Migration.up` 의 인자 타입).
38
+
39
+ ## 연결·트랜잭션
40
+
41
+ - `connect<T>(fn, isolationLevel?): Promise<T>` — 연결+트랜잭션으로 `fn` 실행. 최초 1회 관계 검증(`validateRelations`) 후 alias 리셋, beginTransaction → fn → commit, 예외 시 rollback 후 rethrow, 끝에 항상 close. `ready` 상태 아니면 throw. 일반적인 "한 작업=한 트랜잭션" 경로.
42
+ - `connectWithoutTransaction<T>(callback): Promise<T>` 연결만(트랜잭션 없이) `callback` 실행 close. DDL·여러 독립 트랜잭션을 안에서 직접 열 때.
43
+ - `transaction<T>(fn, isolationLevel?): Promise<T>` 이미 연결된 상태에서 트랜잭션 1개 실행(begin→fn→commit, 실패 시 rollback). `transact` 재호출하면 throw. `connectWithoutTransaction` 안에서 트랜잭션을 나눠 쓸 때.
44
+ - `isolationLevel` `"READ_UNCOMMITTED"|"READ_COMMITTED"|"REPEATABLE_READ"|"SERIALIZABLE"`. 미지정 DB 기본값. 동시성 요구에 따라 선택.
45
+
46
+ 롤백 중 발생한 에러가 `DbTransactionError` 이고 코드가 `NO_ACTIVE_TRANSACTION` 이면 무시( 에러 보존), 외엔 원 에러의 `cause` 부착.
47
+
48
+ ```typescript
49
+ await db.connect(async () => {
50
+ const user = await db.user().where((u) => [expr.eq(u.id, 1)]).lock().single();
51
+ await db.user().where((u) => [expr.eq(u.id, 1)]).update((u) => ({ name: expr.val("string", "X") }));
52
+ }, "REPEATABLE_READ");
53
+ ```
54
+
55
+ ## DDL 실행 메서드
56
+
57
+ 각 메서드는 해당 QueryDef 1개를 `executeDefs` 로 실행한다(`transact` 중 호출 시 throw). 대상 `table`/`view`/`procedure` 인자는 빌더 또는 `QueryDefObjectName`.
58
+
59
+ - `createTable(table)` / `dropTable(table)` / `renameTable(table, newName)` — 테이블 생성·삭제·이름변경.
60
+ - `createView(view)` / `dropView(view)` 생성·삭제.
61
+ - `createProc(procedure)` / `dropProc(procedure)` — 프로시저 생성·삭제.
62
+ - `addColumn(table, columnName, column)` / `dropColumn(table, column)` / `modifyColumn(table, columnName, column)` / `renameColumn(table, column, newName)` — 컬럼 추가·삭제·변경·이름변경. `column` 은 `ColumnBuilder`.
63
+ - `addPrimaryKey(table, columns)` / `dropPrimaryKey(table)` — PK 추가·삭제.
64
+ - `addForeignKey(table, relationName, relationDef)` / `dropForeignKey(table, relationName)`FK 추가·삭제. `relationDef` 는 `ForeignKeyBuilder`.
65
+ - `addIndex(table, indexBuilder)` / `dropIndex(table, columns)` 인덱스 추가·삭제.
66
+ - `truncate(table)` — 데이터 전체 삭제(DDL 취급).
67
+ - `clearSchema(params: { database, schema? })` 스키마 모든 객체 삭제. 초기화·테스트 정리에.
68
+ - `schemaExists(database, schema?): Promise<boolean>` 스키마 존재 여부.
69
+ - `switchFk(table, enabled): Promise<void>`FK 제약 일시 on/off(트랜잭션 허용, DDL 아님).
70
+
71
+ `get...QueryDef(...)` 형태의 생성기(`getCreateTableQueryDef` 등 위 메서드 1:1 대응 + `getCreateObjectQueryDef`)는 실행 없이 `QueryDef` 만 반환 — 여러 DDL 을 모아 한 번에 실행하거나 SQL 을 미리 확인할 때.
72
+
73
+ ## 초기화 / Migration
74
+
75
+ - `initialize(options?: { dbs?: string[]; force?: boolean }): Promise<boolean>` 스키마·마이그레이션 적용. `dbs`=대상 DB 한정, `force`=강제 재생성. 적용 여부 반환.
76
+ - `interface Migration` — `{ name: string; up: (db: DbContextBase & DbContextDdlMethods) => Promise<void> }`. `name` 은 고유(타임스탬프 권장), `up` 안에서 DDL 호출. `initialize` 가 미적용 `name` 만 순서대로 실행.
77
+
78
+ ```typescript
79
+ override migrations: Migration[] = [
80
+ { name: "20260105_001_create_user", up: async (db) => { await db.createTable(User); } },
81
+ { name: "20260105_002_add_email", up: async (db) => { await db.addColumn(User, "email", c.varchar(200).nullable()); } },
82
+ ];
83
+ ```
84
+
85
+ ## 트랜잭션 에러 (DbTransactionError / DbErrorCode)
86
+
87
+ DBMS 네이티브 트랜잭션 에러를 표준 코드로 래핑. `connect`/`transaction` 의 롤백 경로에서 던져진다(주로 executor 구현이 생성).
88
+
89
+ - `class DbTransactionError extends Error`
90
+ - `code: DbErrorCode` — 표준 에러 코드(생성자 1번째 인자).
91
+ - `message: string` — 메시지(생성자 2번째 인자).
92
+ - `originalError?: unknown` — 원본 DBMS 에러(생성자 3번째, 디버깅용).
93
+ - `name` — 항상 `"DbTransactionError"`.
94
+ - `enum DbErrorCode` (문자열 값)
95
+ - `NO_ACTIVE_TRANSACTION` — 활성 트랜잭션 없는데 ROLLBACK 시도. 롤백 중 이 코드면 컨텍스트가 무시하고 원 에러를 보존.
96
+ - `TRANSACTION_ALREADY_STARTED` — 이미 트랜잭션 시작됨.
97
+ - `DEADLOCK` — 데드락.
98
+ - `LOCK_TIMEOUT` — 잠금 타임아웃.
99
+
100
+ ```typescript
101
+ try {
102
+ await db.rollbackTransaction();
103
+ } catch (err) {
104
+ if (err instanceof DbTransactionError && err.code === DbErrorCode.NO_ACTIVE_TRANSACTION) return;
105
+ throw err;
106
+ }
107
+ ```
108
+
109
+ ## SD_BUILDER
110
+
111
+ - `const SD_BUILDER: unique symbol` — `queryable()`/`executable()` 가 반환한 팩토리 함수에 원본 빌더(TableBuilder/ViewBuilder/ProcedureBuilder)를 부착하는 심볼 키. 컨텍스트 멤버에서 정의 빌더를 역으로 꺼낼 때(예: 전체 테이블 순회·DDL 자동화) 사용.