@simplysm/orm-common 13.0.96 → 13.0.97
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/README.md +0 -112
- package/docs/ddl.md +0 -300
- package/docs/query.md +0 -644
- package/docs/schema.md +0 -325
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplysm/orm-common",
|
|
3
|
-
"version": "13.0.
|
|
3
|
+
"version": "13.0.97",
|
|
4
4
|
"description": "Simplysm Package - ORM Module (common)",
|
|
5
5
|
"author": "simplysm",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -20,6 +20,6 @@
|
|
|
20
20
|
],
|
|
21
21
|
"sideEffects": false,
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@simplysm/core-common": "13.0.
|
|
23
|
+
"@simplysm/core-common": "13.0.97"
|
|
24
24
|
}
|
|
25
25
|
}
|
package/README.md
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
# @simplysm/orm-common
|
|
2
|
-
|
|
3
|
-
플랫폼 중립적인 ORM 핵심 모듈. 스키마 정의, 타입 안전한 쿼리 빌더, DDL 관리, MySQL/PostgreSQL/MSSQL 방언 지원.
|
|
4
|
-
|
|
5
|
-
## 설치
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
npm install @simplysm/orm-common
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
**의존성:** `@simplysm/core-common`
|
|
12
|
-
|
|
13
|
-
## 문서
|
|
14
|
-
|
|
15
|
-
| 카테고리 | 설명 |
|
|
16
|
-
|---------|------|
|
|
17
|
-
| [스키마 정의](docs/schema.md) | Table, View, Procedure, Column, Relation, Index 빌더 |
|
|
18
|
-
| [쿼리 & 표현식](docs/query.md) | Queryable, Executable, expr 표현식 빌더 |
|
|
19
|
-
| [DDL & 초기화](docs/ddl.md) | DDL 메서드, 스키마 초기화, 마이그레이션 |
|
|
20
|
-
|
|
21
|
-
## 빠른 시작
|
|
22
|
-
|
|
23
|
-
### DbContext 정의
|
|
24
|
-
|
|
25
|
-
```typescript
|
|
26
|
-
import { defineDbContext, createDbContext, Table, expr } from "@simplysm/orm-common";
|
|
27
|
-
|
|
28
|
-
// 테이블 정의
|
|
29
|
-
const User = Table("user")
|
|
30
|
-
.columns((c) => ({
|
|
31
|
-
id: c.int().autoIncrement(),
|
|
32
|
-
name: c.varchar(100),
|
|
33
|
-
email: c.varchar(200).nullable(),
|
|
34
|
-
createdAt: c.datetime(),
|
|
35
|
-
}))
|
|
36
|
-
.primaryKey("id")
|
|
37
|
-
.indexes((i) => [i.index("email").unique()]);
|
|
38
|
-
|
|
39
|
-
const Order = Table("order")
|
|
40
|
-
.columns((c) => ({
|
|
41
|
-
id: c.int().autoIncrement(),
|
|
42
|
-
userId: c.int(),
|
|
43
|
-
amount: c.decimal(10, 2),
|
|
44
|
-
}))
|
|
45
|
-
.primaryKey("id")
|
|
46
|
-
.relations((r) => ({
|
|
47
|
-
user: r.foreignKey(["userId"], () => User),
|
|
48
|
-
}));
|
|
49
|
-
|
|
50
|
-
// DbContext 정의 (스키마 블루프린트)
|
|
51
|
-
const MyDb = defineDbContext({
|
|
52
|
-
tables: { user: User, order: Order },
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
// DbContext 인스턴스 생성 (런타임)
|
|
56
|
-
const db = createDbContext(MyDb, executor, { database: "mydb" });
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
### 쿼리 실행
|
|
60
|
-
|
|
61
|
-
```typescript
|
|
62
|
-
await db.connect(async () => {
|
|
63
|
-
// SELECT
|
|
64
|
-
const users = await db.user()
|
|
65
|
-
.where((c) => [expr.eq(c.name, "Alice")])
|
|
66
|
-
.orderBy((c) => c.createdAt, "DESC")
|
|
67
|
-
.execute();
|
|
68
|
-
|
|
69
|
-
// JOIN (관계 기반)
|
|
70
|
-
const orders = await db.order()
|
|
71
|
-
.include((c) => c.user)
|
|
72
|
-
.where((c) => [expr.gt(c.amount, 100)])
|
|
73
|
-
.execute();
|
|
74
|
-
|
|
75
|
-
// 집계
|
|
76
|
-
const stats = await db.order()
|
|
77
|
-
.select((c) => ({
|
|
78
|
-
userId: c.userId,
|
|
79
|
-
total: expr.sum(c.amount),
|
|
80
|
-
count: expr.count(),
|
|
81
|
-
}))
|
|
82
|
-
.groupBy((c) => [c.userId])
|
|
83
|
-
.execute();
|
|
84
|
-
|
|
85
|
-
// INSERT
|
|
86
|
-
await db.user().insert([{ name: "Bob", email: "bob@example.com", createdAt: new DateTime() }]);
|
|
87
|
-
|
|
88
|
-
// INSERT 후 ID 반환
|
|
89
|
-
const [inserted] = await db.user().insert(
|
|
90
|
-
[{ name: "Charlie", createdAt: new DateTime() }],
|
|
91
|
-
["id"],
|
|
92
|
-
);
|
|
93
|
-
|
|
94
|
-
// UPDATE
|
|
95
|
-
await db.user()
|
|
96
|
-
.where((c) => [expr.eq(c.id, 1)])
|
|
97
|
-
.update((c) => ({ name: expr.val("string", "Alice2") }));
|
|
98
|
-
|
|
99
|
-
// DELETE
|
|
100
|
-
await db.user()
|
|
101
|
-
.where((c) => [expr.eq(c.id, 1)])
|
|
102
|
-
.delete();
|
|
103
|
-
});
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
### 지원 방언
|
|
107
|
-
|
|
108
|
-
| 방언 | 값 | 최소 버전 |
|
|
109
|
-
|------|-----|----------|
|
|
110
|
-
| MySQL | `"mysql"` | 8.0.14+ |
|
|
111
|
-
| MSSQL | `"mssql"` | 2012+ |
|
|
112
|
-
| PostgreSQL | `"postgresql"` | 9.0+ |
|
package/docs/ddl.md
DELETED
|
@@ -1,300 +0,0 @@
|
|
|
1
|
-
# DDL & 초기화
|
|
2
|
-
|
|
3
|
-
`createDbContext()`로 생성된 DbContext 인스턴스에서 사용하는 DDL 메서드.
|
|
4
|
-
|
|
5
|
-
**중요:** DDL 연산은 트랜잭션 내에서 실행할 수 없다. `connectWithoutTransaction()` 내에서 사용해야 한다.
|
|
6
|
-
|
|
7
|
-
## 스키마 초기화
|
|
8
|
-
|
|
9
|
-
```typescript
|
|
10
|
-
await db.connectWithoutTransaction(async () => {
|
|
11
|
-
// 정의된 모든 테이블/뷰/프로시저 자동 생성
|
|
12
|
-
await db.initialize();
|
|
13
|
-
|
|
14
|
-
// 기존 스키마 삭제 후 재생성
|
|
15
|
-
await db.initialize({ force: true });
|
|
16
|
-
|
|
17
|
-
// 특정 DB만 초기화
|
|
18
|
-
await db.initialize({ dbs: ["mydb"] });
|
|
19
|
-
});
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
### initialize API
|
|
23
|
-
|
|
24
|
-
```
|
|
25
|
-
db.initialize(options?: {
|
|
26
|
-
dbs?: string[]; // 초기화할 DB 목록 (생략 시 전체)
|
|
27
|
-
force?: boolean; // true이면 기존 스키마 삭제 후 재생성
|
|
28
|
-
}): Promise<void>
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
## 테이블 DDL
|
|
32
|
-
|
|
33
|
-
```typescript
|
|
34
|
-
// 테이블 생성 (TableBuilder 전달)
|
|
35
|
-
await db.createTable(User);
|
|
36
|
-
|
|
37
|
-
// 테이블 삭제 (QueryDefObjectName 전달)
|
|
38
|
-
await db.dropTable({ name: "user", database: "mydb" });
|
|
39
|
-
|
|
40
|
-
// 테이블 이름 변경
|
|
41
|
-
await db.renameTable({ name: "user" }, "users_v2");
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
## 컬럼 DDL
|
|
45
|
-
|
|
46
|
-
```typescript
|
|
47
|
-
import { createColumnFactory } from "@simplysm/orm-common";
|
|
48
|
-
const c = createColumnFactory();
|
|
49
|
-
|
|
50
|
-
// 컬럼 추가
|
|
51
|
-
await db.addColumn({ name: "user" }, "phone", c.varchar(20).nullable());
|
|
52
|
-
|
|
53
|
-
// 컬럼 수정
|
|
54
|
-
await db.modifyColumn({ name: "user" }, "phone", c.varchar(50).nullable());
|
|
55
|
-
|
|
56
|
-
// 컬럼 이름 변경
|
|
57
|
-
await db.renameColumn({ name: "user" }, "phone", "phoneNumber");
|
|
58
|
-
|
|
59
|
-
// 컬럼 삭제
|
|
60
|
-
await db.dropColumn({ name: "user" }, "phone");
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
## 키/인덱스 DDL
|
|
64
|
-
|
|
65
|
-
```typescript
|
|
66
|
-
// PK
|
|
67
|
-
await db.addPrimaryKey({ name: "user" }, ["id"]);
|
|
68
|
-
await db.dropPrimaryKey({ name: "user" });
|
|
69
|
-
|
|
70
|
-
// FK
|
|
71
|
-
await db.addForeignKey({ name: "order" }, "user", userRelationDef);
|
|
72
|
-
await db.dropForeignKey({ name: "order" }, "user");
|
|
73
|
-
|
|
74
|
-
// 인덱스
|
|
75
|
-
await db.addIndex({ name: "user" }, indexBuilder);
|
|
76
|
-
await db.dropIndex({ name: "user" }, ["email"]);
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
## 뷰/프로시저 DDL
|
|
80
|
-
|
|
81
|
-
```typescript
|
|
82
|
-
await db.createView(UserSummary);
|
|
83
|
-
await db.dropView({ name: "user_summary" });
|
|
84
|
-
|
|
85
|
-
await db.createProc(GetUserOrders);
|
|
86
|
-
await db.dropProc({ name: "get_user_orders" });
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
## 스키마 관리
|
|
90
|
-
|
|
91
|
-
```typescript
|
|
92
|
-
// 스키마 존재 여부
|
|
93
|
-
const exists = await db.schemaExists("mydb", "dbo");
|
|
94
|
-
|
|
95
|
-
// 스키마 내 모든 테이블 삭제
|
|
96
|
-
await db.clearSchema({ database: "mydb", schema: "dbo" });
|
|
97
|
-
|
|
98
|
-
// 테이블 TRUNCATE
|
|
99
|
-
await db.truncate({ name: "user" });
|
|
100
|
-
|
|
101
|
-
// FK 제약조건 토글
|
|
102
|
-
await db.switchFk({ name: "user" }, false); // FK 비활성화
|
|
103
|
-
// ... 벌크 작업 ...
|
|
104
|
-
await db.switchFk({ name: "user" }, true); // FK 활성화
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
## DDL 메서드 API
|
|
108
|
-
|
|
109
|
-
### 테이블/뷰/프로시저
|
|
110
|
-
|
|
111
|
-
| 메서드 | 시그니처 | 설명 |
|
|
112
|
-
|--------|---------|------|
|
|
113
|
-
| `createTable` | `(table: TableBuilder) => Promise<void>` | 테이블 생성 |
|
|
114
|
-
| `dropTable` | `(table: QueryDefObjectName) => Promise<void>` | 테이블 삭제 |
|
|
115
|
-
| `renameTable` | `(table: QueryDefObjectName, newName: string) => Promise<void>` | 테이블 이름 변경 |
|
|
116
|
-
| `createView` | `(view: ViewBuilder) => Promise<void>` | 뷰 생성 |
|
|
117
|
-
| `dropView` | `(view: QueryDefObjectName) => Promise<void>` | 뷰 삭제 |
|
|
118
|
-
| `createProc` | `(proc: ProcedureBuilder) => Promise<void>` | 프로시저 생성 |
|
|
119
|
-
| `dropProc` | `(proc: QueryDefObjectName) => Promise<void>` | 프로시저 삭제 |
|
|
120
|
-
|
|
121
|
-
### 컬럼
|
|
122
|
-
|
|
123
|
-
| 메서드 | 시그니처 | 설명 |
|
|
124
|
-
|--------|---------|------|
|
|
125
|
-
| `addColumn` | `(table, columnName, column: ColumnBuilder) => Promise<void>` | 컬럼 추가 |
|
|
126
|
-
| `dropColumn` | `(table, column: string) => Promise<void>` | 컬럼 삭제 |
|
|
127
|
-
| `modifyColumn` | `(table, columnName, column: ColumnBuilder) => Promise<void>` | 컬럼 수정 |
|
|
128
|
-
| `renameColumn` | `(table, column, newName) => Promise<void>` | 컬럼 이름 변경 |
|
|
129
|
-
|
|
130
|
-
### 키/인덱스
|
|
131
|
-
|
|
132
|
-
| 메서드 | 시그니처 | 설명 |
|
|
133
|
-
|--------|---------|------|
|
|
134
|
-
| `addPrimaryKey` | `(table, columns: string[]) => Promise<void>` | PK 추가 |
|
|
135
|
-
| `dropPrimaryKey` | `(table) => Promise<void>` | PK 삭제 |
|
|
136
|
-
| `addForeignKey` | `(table, relationName, relationDef) => Promise<void>` | FK 추가 |
|
|
137
|
-
| `dropForeignKey` | `(table, relationName) => Promise<void>` | FK 삭제 |
|
|
138
|
-
| `addIndex` | `(table, indexBuilder) => Promise<void>` | 인덱스 추가 |
|
|
139
|
-
| `dropIndex` | `(table, columns: string[]) => Promise<void>` | 인덱스 삭제 |
|
|
140
|
-
|
|
141
|
-
### 스키마
|
|
142
|
-
|
|
143
|
-
| 메서드 | 시그니처 | 설명 |
|
|
144
|
-
|--------|---------|------|
|
|
145
|
-
| `schemaExists` | `(database, schema?) => Promise<boolean>` | 스키마 존재 여부 |
|
|
146
|
-
| `clearSchema` | `(params: { database, schema? }) => Promise<void>` | 스키마 내 모든 테이블 삭제 |
|
|
147
|
-
| `truncate` | `(table) => Promise<void>` | 테이블 TRUNCATE |
|
|
148
|
-
| `switchFk` | `(table, enabled: boolean) => Promise<void>` | FK 제약조건 on/off |
|
|
149
|
-
|
|
150
|
-
## 연결 & 트랜잭션
|
|
151
|
-
|
|
152
|
-
```typescript
|
|
153
|
-
// 자동 트랜잭션 (connect -> begin -> callback -> commit/rollback -> close)
|
|
154
|
-
const result = await db.connect(async () => {
|
|
155
|
-
await db.user().insert([{ name: "Alice", createdAt: new DateTime() }]);
|
|
156
|
-
return await db.user().execute();
|
|
157
|
-
}, "SERIALIZABLE"); // 격리 수준 선택
|
|
158
|
-
|
|
159
|
-
// 트랜잭션 없이 연결 (DDL 작업 등)
|
|
160
|
-
await db.connectWithoutTransaction(async () => {
|
|
161
|
-
await db.initialize();
|
|
162
|
-
});
|
|
163
|
-
|
|
164
|
-
// 수동 트랜잭션 (connectWithoutTransaction 내에서)
|
|
165
|
-
await db.connectWithoutTransaction(async () => {
|
|
166
|
-
// DDL 먼저 실행 (트랜잭션 밖)
|
|
167
|
-
await db.createTable(NewTable);
|
|
168
|
-
|
|
169
|
-
// 이후 트랜잭션 내에서 DML 실행
|
|
170
|
-
await db.transaction(async () => {
|
|
171
|
-
await db.user().insert([{ name: "Bob", createdAt: new DateTime() }]);
|
|
172
|
-
});
|
|
173
|
-
});
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
### 연결 API
|
|
177
|
-
|
|
178
|
-
| 메서드 | 시그니처 | 설명 |
|
|
179
|
-
|--------|---------|------|
|
|
180
|
-
| `connect` | `(fn, isolationLevel?) => Promise<T>` | 자동 트랜잭션 (connect -> begin -> fn -> commit/rollback -> close) |
|
|
181
|
-
| `connectWithoutTransaction` | `(fn) => Promise<T>` | 트랜잭션 없이 연결 (DDL용) |
|
|
182
|
-
| `transaction` | `(fn, isolationLevel?) => Promise<T>` | 수동 트랜잭션 (connectWithoutTransaction 내에서) |
|
|
183
|
-
|
|
184
|
-
격리 수준: `"READ_UNCOMMITTED"`, `"READ_COMMITTED"`, `"REPEATABLE_READ"`, `"SERIALIZABLE"`
|
|
185
|
-
|
|
186
|
-
## DbContextExecutor 인터페이스
|
|
187
|
-
|
|
188
|
-
Node.js(`@simplysm/orm-node`)나 서비스 클라이언트(`@simplysm/service-client`)에서 구현.
|
|
189
|
-
|
|
190
|
-
```typescript
|
|
191
|
-
interface DbContextExecutor {
|
|
192
|
-
connect(): Promise<void>;
|
|
193
|
-
close(): Promise<void>;
|
|
194
|
-
beginTransaction(isolationLevel?: IsolationLevel): Promise<void>;
|
|
195
|
-
commitTransaction(): Promise<void>;
|
|
196
|
-
rollbackTransaction(): Promise<void>;
|
|
197
|
-
executeDefs<T>(defs: QueryDef[], resultMetas?: (ResultMeta | undefined)[]): Promise<T[][]>;
|
|
198
|
-
}
|
|
199
|
-
```
|
|
200
|
-
|
|
201
|
-
## 마이그레이션
|
|
202
|
-
|
|
203
|
-
`defineDbContext`의 `migrations` 옵션으로 스키마 변경사항을 관리한다. `initialize()` 호출 시 아직 실행되지 않은 마이그레이션만 실행된다.
|
|
204
|
-
|
|
205
|
-
```typescript
|
|
206
|
-
const MyDb = defineDbContext({
|
|
207
|
-
tables: { user: User },
|
|
208
|
-
migrations: [
|
|
209
|
-
{
|
|
210
|
-
name: "20260105_001_create_user_table",
|
|
211
|
-
up: async (db) => {
|
|
212
|
-
await db.createTable(User);
|
|
213
|
-
},
|
|
214
|
-
},
|
|
215
|
-
{
|
|
216
|
-
name: "20260106_001_add_email_column",
|
|
217
|
-
up: async (db) => {
|
|
218
|
-
const c = createColumnFactory();
|
|
219
|
-
await db.addColumn({ name: "user" }, "email", c.varchar(200).nullable());
|
|
220
|
-
},
|
|
221
|
-
},
|
|
222
|
-
],
|
|
223
|
-
});
|
|
224
|
-
```
|
|
225
|
-
|
|
226
|
-
### Migration 인터페이스
|
|
227
|
-
|
|
228
|
-
```typescript
|
|
229
|
-
interface Migration {
|
|
230
|
-
name: string;
|
|
231
|
-
up: (db: DbContextBase & DbContextDdlMethods) => Promise<void>;
|
|
232
|
-
}
|
|
233
|
-
```
|
|
234
|
-
|
|
235
|
-
실행된 마이그레이션은 `_migration` 테이블에 기록된다.
|
|
236
|
-
|
|
237
|
-
```typescript
|
|
238
|
-
// 마이그레이션 코드 조회
|
|
239
|
-
const migrations = await db._migration().execute();
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
## DbTransactionError
|
|
243
|
-
|
|
244
|
-
트랜잭션 관련 에러를 DBMS 독립적으로 처리하기 위한 에러 클래스.
|
|
245
|
-
|
|
246
|
-
```typescript
|
|
247
|
-
import { DbTransactionError, DbErrorCode } from "@simplysm/orm-common";
|
|
248
|
-
|
|
249
|
-
// DbErrorCode:
|
|
250
|
-
// - NO_ACTIVE_TRANSACTION: 활성 트랜잭션 없음
|
|
251
|
-
// - TRANSACTION_ALREADY_STARTED: 트랜잭션 이미 시작됨
|
|
252
|
-
// - DEADLOCK: 데드락 발생
|
|
253
|
-
// - LOCK_TIMEOUT: 잠금 타임아웃
|
|
254
|
-
```
|
|
255
|
-
|
|
256
|
-
### DbTransactionError API
|
|
257
|
-
|
|
258
|
-
```typescript
|
|
259
|
-
class DbTransactionError extends Error {
|
|
260
|
-
readonly name: "DbTransactionError";
|
|
261
|
-
readonly code: DbErrorCode;
|
|
262
|
-
readonly originalError?: unknown;
|
|
263
|
-
constructor(code: DbErrorCode, message: string, originalError?: unknown);
|
|
264
|
-
}
|
|
265
|
-
```
|
|
266
|
-
|
|
267
|
-
## QueryDef 생성기
|
|
268
|
-
|
|
269
|
-
DDL 메서드 외에도 `get*QueryDef()` 메서드로 QueryDef만 생성할 수 있다 (직접 실행하지 않음).
|
|
270
|
-
|
|
271
|
-
```typescript
|
|
272
|
-
const def = db.getCreateTableQueryDef(User);
|
|
273
|
-
const def2 = db.getAddColumnQueryDef({ name: "user" }, "phone", c.varchar(20));
|
|
274
|
-
// ... 등. 모든 DDL 메서드에 대응하는 get*QueryDef() 메서드가 있다.
|
|
275
|
-
```
|
|
276
|
-
|
|
277
|
-
| 생성기 | 대응 DDL 메서드 |
|
|
278
|
-
|--------|---------------|
|
|
279
|
-
| `getCreateTableQueryDef` | `createTable` |
|
|
280
|
-
| `getCreateViewQueryDef` | `createView` |
|
|
281
|
-
| `getCreateProcQueryDef` | `createProc` |
|
|
282
|
-
| `getCreateObjectQueryDef` | Table/View/Procedure 자동 판별 |
|
|
283
|
-
| `getDropTableQueryDef` | `dropTable` |
|
|
284
|
-
| `getRenameTableQueryDef` | `renameTable` |
|
|
285
|
-
| `getDropViewQueryDef` | `dropView` |
|
|
286
|
-
| `getDropProcQueryDef` | `dropProc` |
|
|
287
|
-
| `getAddColumnQueryDef` | `addColumn` |
|
|
288
|
-
| `getDropColumnQueryDef` | `dropColumn` |
|
|
289
|
-
| `getModifyColumnQueryDef` | `modifyColumn` |
|
|
290
|
-
| `getRenameColumnQueryDef` | `renameColumn` |
|
|
291
|
-
| `getAddPrimaryKeyQueryDef` | `addPrimaryKey` |
|
|
292
|
-
| `getDropPrimaryKeyQueryDef` | `dropPrimaryKey` |
|
|
293
|
-
| `getAddForeignKeyQueryDef` | `addForeignKey` |
|
|
294
|
-
| `getAddIndexQueryDef` | `addIndex` |
|
|
295
|
-
| `getDropForeignKeyQueryDef` | `dropForeignKey` |
|
|
296
|
-
| `getDropIndexQueryDef` | `dropIndex` |
|
|
297
|
-
| `getClearSchemaQueryDef` | `clearSchema` |
|
|
298
|
-
| `getSchemaExistsQueryDef` | `schemaExists` |
|
|
299
|
-
| `getTruncateQueryDef` | `truncate` |
|
|
300
|
-
| `getSwitchFkQueryDef` | `switchFk` |
|
package/docs/query.md
DELETED
|
@@ -1,644 +0,0 @@
|
|
|
1
|
-
# 쿼리 & 표현식
|
|
2
|
-
|
|
3
|
-
## Queryable -- SELECT 쿼리 빌더
|
|
4
|
-
|
|
5
|
-
### 기본 조회
|
|
6
|
-
|
|
7
|
-
```typescript
|
|
8
|
-
// 전체 조회
|
|
9
|
-
const users = await db.user().execute();
|
|
10
|
-
|
|
11
|
-
// 단건 조회 (2건 이상이면 throw)
|
|
12
|
-
const user = await db.user()
|
|
13
|
-
.where((c) => [expr.eq(c.id, 1)])
|
|
14
|
-
.single();
|
|
15
|
-
|
|
16
|
-
// 첫 번째 결과 (여러 건이어도 첫 번째만 반환)
|
|
17
|
-
const latest = await db.user()
|
|
18
|
-
.orderBy((c) => c.createdAt, "DESC")
|
|
19
|
-
.first();
|
|
20
|
-
|
|
21
|
-
// 행 수
|
|
22
|
-
const count = await db.user()
|
|
23
|
-
.where((c) => [expr.eq(c.isActive, true)])
|
|
24
|
-
.count();
|
|
25
|
-
|
|
26
|
-
// 존재 여부
|
|
27
|
-
const hasAdmin = await db.user()
|
|
28
|
-
.where((c) => [expr.eq(c.role, "admin")])
|
|
29
|
-
.exists();
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
### Queryable API
|
|
33
|
-
|
|
34
|
-
#### 실행 메서드
|
|
35
|
-
|
|
36
|
-
| 메서드 | 시그니처 | 설명 |
|
|
37
|
-
|--------|---------|------|
|
|
38
|
-
| `execute` | `() => Promise<TData[]>` | SELECT 실행, 결과 배열 반환 |
|
|
39
|
-
| `single` | `() => Promise<TData \| undefined>` | 단건 반환 (2건 이상이면 throw) |
|
|
40
|
-
| `first` | `() => Promise<TData \| undefined>` | 첫 번째 결과 반환 |
|
|
41
|
-
| `count` | `(fn?) => Promise<number>` | 행 수 반환. distinct/groupBy 이후에는 wrap() 필요 |
|
|
42
|
-
| `exists` | `() => Promise<boolean>` | 데이터 존재 여부 |
|
|
43
|
-
|
|
44
|
-
#### 조건 메서드 (체이닝)
|
|
45
|
-
|
|
46
|
-
| 메서드 | 시그니처 | 설명 |
|
|
47
|
-
|--------|---------|------|
|
|
48
|
-
| `where` | `(fn: (cols) => WhereExprUnit[]) => Queryable` | WHERE 조건 (여러 번 호출 시 AND 결합) |
|
|
49
|
-
| `search` | `(fn: (cols) => ExprUnit[], text: string) => Queryable` | 텍스트 검색 |
|
|
50
|
-
| `orderBy` | `(fn: (cols) => ExprUnit, dir?) => Queryable` | 정렬 (기본 ASC, 여러 번 호출 가능) |
|
|
51
|
-
| `top` | `(count: number) => Queryable` | 상위 N건 (ORDER BY 없이 사용 가능) |
|
|
52
|
-
| `limit` | `(skip: number, take: number) => Queryable` | 페이징 (ORDER BY 필수) |
|
|
53
|
-
| `select` | `(fn: (cols) => Record) => Queryable` | 컬럼 선택/변환 |
|
|
54
|
-
| `distinct` | `() => Queryable` | 중복 제거 |
|
|
55
|
-
| `lock` | `() => Queryable` | FOR UPDATE 잠금 |
|
|
56
|
-
| `groupBy` | `(fn: (cols) => ExprUnit[]) => Queryable` | 그룹화 |
|
|
57
|
-
| `having` | `(fn: (cols) => WhereExprUnit[]) => Queryable` | 그룹 필터링 |
|
|
58
|
-
|
|
59
|
-
#### JOIN 메서드
|
|
60
|
-
|
|
61
|
-
| 메서드 | 시그니처 | 설명 |
|
|
62
|
-
|--------|---------|------|
|
|
63
|
-
| `join` | `(as, fn: (qr, cols) => Queryable) => Queryable` | LEFT JOIN (1:N, 배열) |
|
|
64
|
-
| `joinSingle` | `(as, fn: (qr, cols) => Queryable) => Queryable` | LEFT JOIN (N:1, 단일 객체) |
|
|
65
|
-
| `include` | `(fn: (item) => PathProxy) => Queryable` | 관계 기반 자동 JOIN |
|
|
66
|
-
|
|
67
|
-
#### 서브쿼리/유틸리티
|
|
68
|
-
|
|
69
|
-
| 메서드 | 시그니처 | 설명 |
|
|
70
|
-
|--------|---------|------|
|
|
71
|
-
| `wrap` | `() => Queryable` | 서브쿼리로 래핑 |
|
|
72
|
-
| `Queryable.union` | `(...queries) => Queryable` | UNION (최소 2개) |
|
|
73
|
-
| `recursive` | `(fn: (cte) => Queryable) => Queryable` | 재귀 CTE |
|
|
74
|
-
|
|
75
|
-
#### CUD 메서드
|
|
76
|
-
|
|
77
|
-
| 메서드 | 시그니처 | 설명 |
|
|
78
|
-
|--------|---------|------|
|
|
79
|
-
| `insert` | `(records, outputColumns?) => Promise` | INSERT (1000건 단위 자동 분할) |
|
|
80
|
-
| `insertIfNotExists` | `(record, outputColumns?) => Promise` | 조건부 INSERT |
|
|
81
|
-
| `insertInto` | `(targetTable, outputColumns?) => Promise` | INSERT INTO ... SELECT |
|
|
82
|
-
| `update` | `(fn: (cols) => Record, outputColumns?) => Promise` | UPDATE |
|
|
83
|
-
| `delete` | `(outputColumns?) => Promise` | DELETE |
|
|
84
|
-
| `upsert` | `(updateFn, insertFn?, outputColumns?) => Promise` | UPSERT (UPDATE or INSERT) |
|
|
85
|
-
| `switchFk` | `(enabled: boolean) => Promise<void>` | FK 제약조건 on/off |
|
|
86
|
-
|
|
87
|
-
### 필터링 (WHERE)
|
|
88
|
-
|
|
89
|
-
```typescript
|
|
90
|
-
db.user()
|
|
91
|
-
.where((c) => [
|
|
92
|
-
expr.eq(c.name, "Alice"), // name = 'Alice'
|
|
93
|
-
expr.gt(c.score, 80), // score > 80
|
|
94
|
-
expr.between(c.createdAt, from, to), // BETWEEN
|
|
95
|
-
expr.like(c.email, "%@gmail.com"), // LIKE
|
|
96
|
-
expr.in(c.role, ["admin", "user"]), // IN
|
|
97
|
-
expr.null(c.deletedAt), // IS NULL
|
|
98
|
-
])
|
|
99
|
-
// 배열은 자동 AND 결합. OR는 명시적으로:
|
|
100
|
-
.where((c) => [
|
|
101
|
-
expr.or([
|
|
102
|
-
expr.eq(c.role, "admin"),
|
|
103
|
-
expr.gt(c.score, 90),
|
|
104
|
-
]),
|
|
105
|
-
])
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
where()를 여러 번 호출하면 AND로 결합된다.
|
|
109
|
-
|
|
110
|
-
### 텍스트 검색 (search)
|
|
111
|
-
|
|
112
|
-
```typescript
|
|
113
|
-
// 여러 컬럼에서 텍스트 검색
|
|
114
|
-
db.user()
|
|
115
|
-
.search((c) => [c.name, c.email], "John +admin -withdrawn")
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
검색 문법: `term`(OR), `+term`(AND 필수), `-term`(NOT 제외), `"exact"`(정확히 + 필수), `wild*`(접두사). 내부적으로 `parseSearchQuery()`를 사용하여 SQL LIKE 패턴으로 변환한다.
|
|
119
|
-
|
|
120
|
-
### 정렬 (ORDER BY)
|
|
121
|
-
|
|
122
|
-
```typescript
|
|
123
|
-
// orderBy는 컬럼 하나씩, 여러 번 호출 가능
|
|
124
|
-
db.user()
|
|
125
|
-
.orderBy((c) => c.createdAt, "DESC")
|
|
126
|
-
.orderBy((c) => c.name) // 기본: ASC
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
### 페이징
|
|
130
|
-
|
|
131
|
-
```typescript
|
|
132
|
-
// top: ORDER BY 없이도 사용 가능
|
|
133
|
-
db.user().top(10)
|
|
134
|
-
|
|
135
|
-
// limit: ORDER BY 필수 (skip, take)
|
|
136
|
-
db.user()
|
|
137
|
-
.orderBy((c) => c.createdAt, "DESC")
|
|
138
|
-
.limit(20, 10) // 20건 건너뛰고 10건 가져오기
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
### 컬럼 선택 (SELECT)
|
|
142
|
-
|
|
143
|
-
```typescript
|
|
144
|
-
db.user()
|
|
145
|
-
.select((c) => ({
|
|
146
|
-
id: c.id,
|
|
147
|
-
upperName: expr.upper(c.name),
|
|
148
|
-
emailDomain: expr.right(c.email, 10),
|
|
149
|
-
}))
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
### 그룹화 (GROUP BY)
|
|
153
|
-
|
|
154
|
-
```typescript
|
|
155
|
-
db.order()
|
|
156
|
-
.select((c) => ({
|
|
157
|
-
userId: c.userId,
|
|
158
|
-
total: expr.sum(c.amount),
|
|
159
|
-
count: expr.count(),
|
|
160
|
-
avg: expr.avg(c.amount),
|
|
161
|
-
}))
|
|
162
|
-
.groupBy((c) => [c.userId])
|
|
163
|
-
.having((c) => [expr.gt(expr.count(), 5)])
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
### JOIN
|
|
167
|
-
|
|
168
|
-
```typescript
|
|
169
|
-
// LEFT JOIN (1:N, 배열로 결과에 추가)
|
|
170
|
-
db.user()
|
|
171
|
-
.join("posts", (qr, u) =>
|
|
172
|
-
qr.from(Post)
|
|
173
|
-
.where((p) => [expr.eq(p.userId, u.id)])
|
|
174
|
-
)
|
|
175
|
-
// 결과: { id, name, posts: [{ id, title }, ...] }
|
|
176
|
-
|
|
177
|
-
// LEFT JOIN SINGLE (N:1, 단일 객체로 결과에 추가)
|
|
178
|
-
db.order()
|
|
179
|
-
.joinSingle("user", (qr, o) =>
|
|
180
|
-
qr.from(User)
|
|
181
|
-
.where((u) => [expr.eq(u.id, o.userId)])
|
|
182
|
-
)
|
|
183
|
-
// 결과: { id, amount, user: { id, name } | undefined }
|
|
184
|
-
|
|
185
|
-
// 관계 자동 로드 (include) -- 정의된 관계 기반 자동 JOIN
|
|
186
|
-
db.order()
|
|
187
|
-
.include((c) => c.user) // N:1 관계 로드
|
|
188
|
-
.include((c) => c.user.company) // 중첩 관계
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
### 서브쿼리
|
|
192
|
-
|
|
193
|
-
```typescript
|
|
194
|
-
// 스칼라 서브쿼리
|
|
195
|
-
db.user().select((c) => ({
|
|
196
|
-
name: c.name,
|
|
197
|
-
orderCount: expr.subquery("number",
|
|
198
|
-
db.order()
|
|
199
|
-
.where((o) => [expr.eq(o.userId, c.id)])
|
|
200
|
-
.select(() => ({ cnt: expr.count() }))
|
|
201
|
-
),
|
|
202
|
-
}))
|
|
203
|
-
|
|
204
|
-
// IN 서브쿼리
|
|
205
|
-
db.user().where((c) => [
|
|
206
|
-
expr.inQuery(c.id,
|
|
207
|
-
db.order()
|
|
208
|
-
.where((o) => [expr.gt(o.amount, 1000)])
|
|
209
|
-
.select((o) => ({ userId: o.userId }))
|
|
210
|
-
),
|
|
211
|
-
])
|
|
212
|
-
|
|
213
|
-
// EXISTS
|
|
214
|
-
db.user().where((c) => [
|
|
215
|
-
expr.exists(db.order().where((o) => [expr.eq(o.userId, c.id)])),
|
|
216
|
-
])
|
|
217
|
-
```
|
|
218
|
-
|
|
219
|
-
### 잠금 (FOR UPDATE)
|
|
220
|
-
|
|
221
|
-
```typescript
|
|
222
|
-
await db.connect(async () => {
|
|
223
|
-
const user = await db.user()
|
|
224
|
-
.where((c) => [expr.eq(c.id, 1)])
|
|
225
|
-
.lock()
|
|
226
|
-
.single();
|
|
227
|
-
});
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
### DISTINCT
|
|
231
|
-
|
|
232
|
-
```typescript
|
|
233
|
-
db.user().select((c) => ({ role: c.role })).distinct()
|
|
234
|
-
```
|
|
235
|
-
|
|
236
|
-
### 서브쿼리 래핑 (wrap)
|
|
237
|
-
|
|
238
|
-
DISTINCT나 GROUP BY 이후 count() 등을 사용하려면 wrap()으로 서브쿼리화해야 한다.
|
|
239
|
-
|
|
240
|
-
```typescript
|
|
241
|
-
const count = await db.user()
|
|
242
|
-
.select((c) => ({ name: c.name }))
|
|
243
|
-
.distinct()
|
|
244
|
-
.wrap()
|
|
245
|
-
.count();
|
|
246
|
-
```
|
|
247
|
-
|
|
248
|
-
### UNION
|
|
249
|
-
|
|
250
|
-
```typescript
|
|
251
|
-
const combined = Queryable.union(
|
|
252
|
-
db.user().where((c) => [expr.eq(c.type, "admin")]),
|
|
253
|
-
db.user().where((c) => [expr.eq(c.type, "manager")]),
|
|
254
|
-
);
|
|
255
|
-
```
|
|
256
|
-
|
|
257
|
-
### 재귀 쿼리 (CTE)
|
|
258
|
-
|
|
259
|
-
```typescript
|
|
260
|
-
// 계층 데이터 조회 (조직도, 카테고리 트리 등)
|
|
261
|
-
db.employee()
|
|
262
|
-
.where((e) => [expr.null(e.managerId)]) // 루트 노드
|
|
263
|
-
.recursive((cte) =>
|
|
264
|
-
cte.from(Employee)
|
|
265
|
-
.where((e) => [expr.eq(e.managerId, e.self[0].id)])
|
|
266
|
-
)
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
---
|
|
270
|
-
|
|
271
|
-
## CUD 연산
|
|
272
|
-
|
|
273
|
-
`select()`, `groupBy()`, `join()` 이후에는 CUD 불가 (타입 레벨에서 차단).
|
|
274
|
-
|
|
275
|
-
### INSERT
|
|
276
|
-
|
|
277
|
-
```typescript
|
|
278
|
-
// 기본 삽입
|
|
279
|
-
await db.user().insert([
|
|
280
|
-
{ name: "Alice", email: "alice@example.com", createdAt: new DateTime() },
|
|
281
|
-
{ name: "Bob", createdAt: new DateTime() },
|
|
282
|
-
]);
|
|
283
|
-
|
|
284
|
-
// INSERT 후 컬럼 반환 (OUTPUT)
|
|
285
|
-
const [inserted] = await db.user().insert(
|
|
286
|
-
[{ name: "Alice", createdAt: new DateTime() }],
|
|
287
|
-
["id"], // 반환받을 컬럼
|
|
288
|
-
);
|
|
289
|
-
// inserted.id -> 자동 생성된 ID
|
|
290
|
-
|
|
291
|
-
// 조건부 INSERT (WHERE 조건에 맞는 데이터가 없을 때만)
|
|
292
|
-
await db.user()
|
|
293
|
-
.where((c) => [expr.eq(c.email, "test@test.com")])
|
|
294
|
-
.insertIfNotExists({ name: "testing", email: "test@test.com", createdAt: new DateTime() });
|
|
295
|
-
|
|
296
|
-
// INSERT INTO ... SELECT
|
|
297
|
-
await db.user()
|
|
298
|
-
.select((c) => ({ name: c.name, createdAt: c.createdAt }))
|
|
299
|
-
.where((c) => [expr.eq(c.isArchived, false)])
|
|
300
|
-
.insertInto(ArchivedUser);
|
|
301
|
-
```
|
|
302
|
-
|
|
303
|
-
### UPDATE
|
|
304
|
-
|
|
305
|
-
```typescript
|
|
306
|
-
await db.user()
|
|
307
|
-
.where((c) => [expr.eq(c.id, 1)])
|
|
308
|
-
.update((c) => ({ name: expr.val("string", "Alice2") }));
|
|
309
|
-
|
|
310
|
-
// 기존 값 참조
|
|
311
|
-
await db.product()
|
|
312
|
-
.update((p) => ({
|
|
313
|
-
price: expr.mul(p.price, expr.val("number", 1.1)),
|
|
314
|
-
}));
|
|
315
|
-
|
|
316
|
-
// OUTPUT으로 변경된 데이터 반환
|
|
317
|
-
const updated = await db.user()
|
|
318
|
-
.where((c) => [expr.eq(c.id, 1)])
|
|
319
|
-
.update(
|
|
320
|
-
(c) => ({ name: expr.val("string", "Alice2") }),
|
|
321
|
-
["id", "name"],
|
|
322
|
-
);
|
|
323
|
-
```
|
|
324
|
-
|
|
325
|
-
### DELETE
|
|
326
|
-
|
|
327
|
-
```typescript
|
|
328
|
-
await db.user()
|
|
329
|
-
.where((c) => [expr.eq(c.id, 1)])
|
|
330
|
-
.delete();
|
|
331
|
-
|
|
332
|
-
// OUTPUT으로 삭제된 데이터 반환
|
|
333
|
-
const deleted = await db.user()
|
|
334
|
-
.where((c) => [expr.eq(c.isExpired, true)])
|
|
335
|
-
.delete(["id", "name"]);
|
|
336
|
-
```
|
|
337
|
-
|
|
338
|
-
### UPSERT (UPDATE or INSERT)
|
|
339
|
-
|
|
340
|
-
```typescript
|
|
341
|
-
// 동일 데이터로 UPDATE/INSERT
|
|
342
|
-
await db.user()
|
|
343
|
-
.where((c) => [expr.eq(c.email, "test@test.com")])
|
|
344
|
-
.upsert(() => ({
|
|
345
|
-
name: expr.val("string", "testing"),
|
|
346
|
-
email: expr.val("string", "test@test.com"),
|
|
347
|
-
}));
|
|
348
|
-
|
|
349
|
-
// UPDATE/INSERT 데이터가 다른 경우
|
|
350
|
-
await db.user()
|
|
351
|
-
.where((c) => [expr.eq(c.email, "test@test.com")])
|
|
352
|
-
.upsert(
|
|
353
|
-
() => ({ loginCount: expr.val("number", 1) }), // UPDATE용
|
|
354
|
-
(update) => ({ ...update, email: expr.val("string", "test@test.com") }), // INSERT용
|
|
355
|
-
);
|
|
356
|
-
```
|
|
357
|
-
|
|
358
|
-
### FK 토글
|
|
359
|
-
|
|
360
|
-
```typescript
|
|
361
|
-
// Queryable에서 직접 FK on/off
|
|
362
|
-
await db.user().switchFk(false); // FK 비활성화
|
|
363
|
-
// ... 벌크 작업 ...
|
|
364
|
-
await db.user().switchFk(true); // FK 활성화
|
|
365
|
-
```
|
|
366
|
-
|
|
367
|
-
---
|
|
368
|
-
|
|
369
|
-
## Executable -- 프로시저 실행
|
|
370
|
-
|
|
371
|
-
```typescript
|
|
372
|
-
const MyDb = defineDbContext({
|
|
373
|
-
tables: { user: User },
|
|
374
|
-
procedures: { getUserOrders: GetUserOrders },
|
|
375
|
-
});
|
|
376
|
-
|
|
377
|
-
const db = createDbContext(MyDb, executor, { database: "mydb" });
|
|
378
|
-
|
|
379
|
-
await db.connect(async () => {
|
|
380
|
-
const results = await db.getUserOrders().execute({ userId: 1 });
|
|
381
|
-
});
|
|
382
|
-
```
|
|
383
|
-
|
|
384
|
-
### Executable API
|
|
385
|
-
|
|
386
|
-
| 메서드 | 시그니처 | 설명 |
|
|
387
|
-
|--------|---------|------|
|
|
388
|
-
| `execute` | `(params) => Promise<TReturns[][]>` | 프로시저 실행 |
|
|
389
|
-
| `getExecProcQueryDef` | `(params?) => QueryDef` | QueryDef만 생성 (실행 안 함) |
|
|
390
|
-
|
|
391
|
-
---
|
|
392
|
-
|
|
393
|
-
## expr -- 표현식 빌더
|
|
394
|
-
|
|
395
|
-
방언 독립적인 SQL 표현식을 생성한다. JSON AST(Expr)를 생성하며, QueryBuilder가 각 DBMS(MySQL, MSSQL, PostgreSQL)에 맞게 변환한다.
|
|
396
|
-
|
|
397
|
-
### 값/조건
|
|
398
|
-
|
|
399
|
-
| 함수 | 설명 |
|
|
400
|
-
|------|------|
|
|
401
|
-
| `expr.val(type, value)` | 리터럴 값 |
|
|
402
|
-
| `expr.col(type, alias, key)` | 컬럼 참조 |
|
|
403
|
-
| `expr.raw(type)\`sql\`` | Raw SQL (태그 템플릿) |
|
|
404
|
-
| `expr.eq(a, b)` | `=` (NULL 안전) |
|
|
405
|
-
| `expr.gt(a, b)` | `>` |
|
|
406
|
-
| `expr.lt(a, b)` | `<` |
|
|
407
|
-
| `expr.gte(a, b)` | `>=` |
|
|
408
|
-
| `expr.lte(a, b)` | `<=` |
|
|
409
|
-
| `expr.between(src, from?, to?)` | BETWEEN |
|
|
410
|
-
| `expr.null(src)` | IS NULL |
|
|
411
|
-
| `expr.like(src, pattern)` | LIKE |
|
|
412
|
-
| `expr.regexp(src, pattern)` | 정규식 매칭 |
|
|
413
|
-
| `expr.in(src, values)` | IN (값 목록) |
|
|
414
|
-
| `expr.inQuery(src, query)` | IN (서브쿼리) |
|
|
415
|
-
| `expr.exists(query)` | EXISTS |
|
|
416
|
-
| `expr.not(cond)` | NOT |
|
|
417
|
-
| `expr.and(conds)` | AND |
|
|
418
|
-
| `expr.or(conds)` | OR |
|
|
419
|
-
|
|
420
|
-
### 문자열 함수
|
|
421
|
-
|
|
422
|
-
| 함수 | 설명 |
|
|
423
|
-
|------|------|
|
|
424
|
-
| `expr.concat(...args)` | 연결 (NULL=빈문자열) |
|
|
425
|
-
| `expr.left(src, len)` | 왼쪽 N자 |
|
|
426
|
-
| `expr.right(src, len)` | 오른쪽 N자 |
|
|
427
|
-
| `expr.substring(src, start, len?)` | 부분 문자열 (1-based) |
|
|
428
|
-
| `expr.trim(src)` | 양쪽 공백 제거 |
|
|
429
|
-
| `expr.padStart(src, len, fill)` | 왼쪽 패딩 (LPAD) |
|
|
430
|
-
| `expr.replace(src, from, to)` | 치환 |
|
|
431
|
-
| `expr.upper(src)` / `expr.lower(src)` | 대/소문자 |
|
|
432
|
-
| `expr.length(src)` | 문자 길이 (CHAR_LENGTH) |
|
|
433
|
-
| `expr.byteLength(src)` | 바이트 길이 (LENGTH/DATALENGTH) |
|
|
434
|
-
| `expr.indexOf(src, search)` | 위치 (1-based, 0=없음) |
|
|
435
|
-
|
|
436
|
-
### 수학 함수
|
|
437
|
-
|
|
438
|
-
| 함수 | 설명 |
|
|
439
|
-
|------|------|
|
|
440
|
-
| `expr.abs(src)` | 절대값 |
|
|
441
|
-
| `expr.round(src, digits)` | 반올림 |
|
|
442
|
-
| `expr.ceil(src)` / `expr.floor(src)` | 올림/내림 |
|
|
443
|
-
|
|
444
|
-
### 날짜 함수
|
|
445
|
-
|
|
446
|
-
| 함수 | 설명 |
|
|
447
|
-
|------|------|
|
|
448
|
-
| `expr.year(src)` / `expr.month(src)` / `expr.day(src)` | 연/월/일 추출 |
|
|
449
|
-
| `expr.hour(src)` / `expr.minute(src)` / `expr.second(src)` | 시/분/초 추출 |
|
|
450
|
-
| `expr.dateDiff(unit, from, to)` | 날짜 차이 |
|
|
451
|
-
| `expr.dateAdd(unit, src, value)` | 날짜 더하기 |
|
|
452
|
-
| `expr.formatDate(src, format)` | 날짜 포맷 (FORMAT/DATE_FORMAT) |
|
|
453
|
-
| `expr.isoWeek(src)` | ISO 주차 |
|
|
454
|
-
| `expr.isoWeekStartDate(src)` | ISO 주 시작일 |
|
|
455
|
-
| `expr.isoYearMonth(src)` | ISO 연월 (YYYYMM 형식) |
|
|
456
|
-
|
|
457
|
-
단위(`DateUnit`): `"year"`, `"month"`, `"day"`, `"hour"`, `"minute"`, `"second"`
|
|
458
|
-
|
|
459
|
-
### 집계 함수
|
|
460
|
-
|
|
461
|
-
| 함수 | 설명 |
|
|
462
|
-
|------|------|
|
|
463
|
-
| `expr.count(arg?, distinct?)` | 행 수 |
|
|
464
|
-
| `expr.sum(arg)` | 합계 |
|
|
465
|
-
| `expr.avg(arg)` | 평균 |
|
|
466
|
-
| `expr.max(arg)` / `expr.min(arg)` | 최대/최소 |
|
|
467
|
-
|
|
468
|
-
### 조건 함수
|
|
469
|
-
|
|
470
|
-
```typescript
|
|
471
|
-
// CASE WHEN
|
|
472
|
-
expr.switch<string>()
|
|
473
|
-
.case(expr.gt(c.score, 90), "A")
|
|
474
|
-
.case(expr.gt(c.score, 80), "B")
|
|
475
|
-
.default("C")
|
|
476
|
-
|
|
477
|
-
// IF (단순 삼항)
|
|
478
|
-
expr.if(expr.gt(c.score, 60), "pass", "fail")
|
|
479
|
-
|
|
480
|
-
// WHERE -> boolean 컬럼
|
|
481
|
-
expr.is(expr.gt(c.score, 80)) // true/false
|
|
482
|
-
|
|
483
|
-
// NULLIF (source === value이면 NULL 반환)
|
|
484
|
-
expr.nullIf(c.status, "unknown")
|
|
485
|
-
```
|
|
486
|
-
|
|
487
|
-
### 윈도우 함수
|
|
488
|
-
|
|
489
|
-
```typescript
|
|
490
|
-
// 순위
|
|
491
|
-
expr.rowNumber({ partitionBy: [c.dept], orderBy: [[c.score, "DESC"]] })
|
|
492
|
-
expr.rank({ orderBy: [[c.score, "DESC"]] })
|
|
493
|
-
expr.denseRank({ orderBy: [[c.score, "DESC"]] })
|
|
494
|
-
expr.ntile(4, { orderBy: [[c.score, "DESC"]] })
|
|
495
|
-
|
|
496
|
-
// 탐색
|
|
497
|
-
expr.lag(c.score, 1, 0, { orderBy: [[c.createdAt, "ASC"]] })
|
|
498
|
-
expr.lead(c.score, 1, undefined, { orderBy: [[c.createdAt, "ASC"]] })
|
|
499
|
-
expr.firstValue(c.score, { orderBy: [[c.createdAt, "ASC"]] })
|
|
500
|
-
expr.lastValue(c.score, { orderBy: [[c.createdAt, "ASC"]] })
|
|
501
|
-
|
|
502
|
-
// 윈도우 집계
|
|
503
|
-
expr.sumOver(c.amount, { partitionBy: [c.dept] })
|
|
504
|
-
expr.avgOver(c.amount, { partitionBy: [c.dept] })
|
|
505
|
-
expr.countOver({ partitionBy: [c.dept] })
|
|
506
|
-
expr.minOver(c.amount, { partitionBy: [c.dept] })
|
|
507
|
-
expr.maxOver(c.amount, { partitionBy: [c.dept] })
|
|
508
|
-
```
|
|
509
|
-
|
|
510
|
-
### 기타
|
|
511
|
-
|
|
512
|
-
| 함수 | 설명 |
|
|
513
|
-
|------|------|
|
|
514
|
-
| `expr.cast(src, targetType)` | 타입 변환 |
|
|
515
|
-
| `expr.greatest(...args)` | 최대값 |
|
|
516
|
-
| `expr.least(...args)` | 최소값 |
|
|
517
|
-
| `expr.rowNum()` | 행 번호 (전체) |
|
|
518
|
-
| `expr.random()` | 랜덤 0~1 |
|
|
519
|
-
| `expr.subquery(type, queryable)` | 스칼라 서브쿼리 |
|
|
520
|
-
|
|
521
|
-
---
|
|
522
|
-
|
|
523
|
-
## ExprUnit / WhereExprUnit
|
|
524
|
-
|
|
525
|
-
Queryable 콜백에서 컬럼 참조 시 자동으로 `ExprUnit`으로 래핑된다.
|
|
526
|
-
|
|
527
|
-
```typescript
|
|
528
|
-
// ExprUnit<TPrimitive> -- 타입 안전한 표현식 래퍼
|
|
529
|
-
class ExprUnit<TPrimitive extends ColumnPrimitive> {
|
|
530
|
-
readonly dataType: ColumnPrimitiveStr;
|
|
531
|
-
readonly expr: Expr;
|
|
532
|
-
get n(): ExprUnit<NonNullable<TPrimitive>>; // nullable 제거
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// WhereExprUnit -- WHERE 절용 표현식 래퍼
|
|
536
|
-
class WhereExprUnit {
|
|
537
|
-
readonly expr: WhereExpr;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// ExprInput -- ExprUnit 또는 리터럴 값을 받는 입력 타입
|
|
541
|
-
type ExprInput<TPrimitive> = ExprUnit<TPrimitive> | TPrimitive;
|
|
542
|
-
```
|
|
543
|
-
|
|
544
|
-
---
|
|
545
|
-
|
|
546
|
-
## 검색 파서
|
|
547
|
-
|
|
548
|
-
사용자 검색 문법을 SQL LIKE 패턴으로 변환.
|
|
549
|
-
|
|
550
|
-
```typescript
|
|
551
|
-
import { parseSearchQuery } from "@simplysm/orm-common";
|
|
552
|
-
|
|
553
|
-
parseSearchQuery('apple +fruit -rotten "green apple" wild*');
|
|
554
|
-
// {
|
|
555
|
-
// or: ["%apple%", "wild%"],
|
|
556
|
-
// must: ["%green apple%", "%fruit%"],
|
|
557
|
-
// not: ["%rotten%"],
|
|
558
|
-
// }
|
|
559
|
-
```
|
|
560
|
-
|
|
561
|
-
### parseSearchQuery API
|
|
562
|
-
|
|
563
|
-
```
|
|
564
|
-
parseSearchQuery(searchText: string): ParsedSearchQuery
|
|
565
|
-
|
|
566
|
-
interface ParsedSearchQuery {
|
|
567
|
-
or: string[]; // OR 조건 (LIKE 패턴)
|
|
568
|
-
must: string[]; // AND 필수 조건 (LIKE 패턴)
|
|
569
|
-
not: string[]; // NOT 제외 조건 (LIKE 패턴)
|
|
570
|
-
}
|
|
571
|
-
```
|
|
572
|
-
|
|
573
|
-
문법: `term`(OR), `+term`(AND 필수), `-term`(NOT 제외), `"exact"`(정확히 + 필수), `wild*`(접두사)
|
|
574
|
-
|
|
575
|
-
이스케이프: `\\` (리터럴 `\`), `\*` (리터럴 `*`), `\%` (리터럴 `%`), `\"` (리터럴 `"`), `\+` (리터럴 `+`), `\-` (리터럴 `-`)
|
|
576
|
-
|
|
577
|
-
---
|
|
578
|
-
|
|
579
|
-
## QueryBuilder
|
|
580
|
-
|
|
581
|
-
QueryDef(JSON AST)를 DBMS별 SQL 문자열로 변환한다.
|
|
582
|
-
|
|
583
|
-
```typescript
|
|
584
|
-
import { createQueryBuilder } from "@simplysm/orm-common";
|
|
585
|
-
import type { Dialect } from "@simplysm/orm-common";
|
|
586
|
-
|
|
587
|
-
const builder = createQueryBuilder("mysql"); // "mysql" | "mssql" | "postgresql"
|
|
588
|
-
const result = builder.build(queryDef);
|
|
589
|
-
// result.sql -> SQL 문자열
|
|
590
|
-
```
|
|
591
|
-
|
|
592
|
-
### createQueryBuilder API
|
|
593
|
-
|
|
594
|
-
```
|
|
595
|
-
createQueryBuilder(dialect: Dialect): QueryBuilderBase
|
|
596
|
-
```
|
|
597
|
-
|
|
598
|
-
| 방언 | 구현 클래스 |
|
|
599
|
-
|------|-----------|
|
|
600
|
-
| `"mysql"` | `MysqlQueryBuilder` |
|
|
601
|
-
| `"mssql"` | `MssqlQueryBuilder` |
|
|
602
|
-
| `"postgresql"` | `PostgresqlQueryBuilder` |
|
|
603
|
-
|
|
604
|
-
---
|
|
605
|
-
|
|
606
|
-
## parseQueryResult
|
|
607
|
-
|
|
608
|
-
DB 쿼리 결과를 ResultMeta 기반으로 TypeScript 객체로 변환한다. 타입 파싱과 JOIN 결과 중첩을 처리한다.
|
|
609
|
-
|
|
610
|
-
```typescript
|
|
611
|
-
import { parseQueryResult } from "@simplysm/orm-common";
|
|
612
|
-
|
|
613
|
-
// 단순 타입 파싱
|
|
614
|
-
const raw = [{ id: "1", createdAt: "2026-01-07T10:00:00.000Z" }];
|
|
615
|
-
const meta = { columns: { id: "number", createdAt: "DateTime" }, joins: {} };
|
|
616
|
-
const result = await parseQueryResult(raw, meta);
|
|
617
|
-
// [{ id: 1, createdAt: DateTime(...) }]
|
|
618
|
-
|
|
619
|
-
// JOIN 결과 중첩
|
|
620
|
-
const raw2 = [
|
|
621
|
-
{ id: 1, name: "User1", "posts.id": 10, "posts.title": "Post1" },
|
|
622
|
-
{ id: 1, name: "User1", "posts.id": 11, "posts.title": "Post2" },
|
|
623
|
-
];
|
|
624
|
-
const meta2 = {
|
|
625
|
-
columns: { id: "number", name: "string", "posts.id": "number", "posts.title": "string" },
|
|
626
|
-
joins: { posts: { isSingle: false } },
|
|
627
|
-
};
|
|
628
|
-
const result2 = await parseQueryResult(raw2, meta2);
|
|
629
|
-
// [{ id: 1, name: "User1", posts: [{ id: 10, title: "Post1" }, { id: 11, title: "Post2" }] }]
|
|
630
|
-
```
|
|
631
|
-
|
|
632
|
-
### parseQueryResult API
|
|
633
|
-
|
|
634
|
-
```
|
|
635
|
-
parseQueryResult<TRecord>(
|
|
636
|
-
rawResults: Record<string, unknown>[],
|
|
637
|
-
meta: ResultMeta,
|
|
638
|
-
): Promise<TRecord[] | undefined>
|
|
639
|
-
|
|
640
|
-
interface ResultMeta {
|
|
641
|
-
columns: Record<string, ColumnPrimitiveStr>;
|
|
642
|
-
joins: Record<string, { isSingle: boolean }>;
|
|
643
|
-
}
|
|
644
|
-
```
|
package/docs/schema.md
DELETED
|
@@ -1,325 +0,0 @@
|
|
|
1
|
-
# 스키마 정의
|
|
2
|
-
|
|
3
|
-
## Table
|
|
4
|
-
|
|
5
|
-
불변 빌더 패턴으로 테이블을 정의한다. 모든 메서드는 새 인스턴스를 반환한다.
|
|
6
|
-
|
|
7
|
-
```typescript
|
|
8
|
-
import { Table } from "@simplysm/orm-common";
|
|
9
|
-
|
|
10
|
-
const User = Table("user")
|
|
11
|
-
.description("사용자 테이블")
|
|
12
|
-
.database("mydb") // 선택
|
|
13
|
-
.schema("dbo") // MSSQL/PostgreSQL, 선택
|
|
14
|
-
.columns((c) => ({
|
|
15
|
-
id: c.int().autoIncrement(),
|
|
16
|
-
name: c.varchar(100),
|
|
17
|
-
email: c.varchar(200).nullable(),
|
|
18
|
-
role: c.varchar(20).default("user"),
|
|
19
|
-
bio: c.text().nullable(),
|
|
20
|
-
avatar: c.binary().nullable(),
|
|
21
|
-
score: c.decimal(10, 2).nullable(),
|
|
22
|
-
active: c.boolean().default(true),
|
|
23
|
-
birthday: c.date().nullable(),
|
|
24
|
-
loginTime: c.time().nullable(),
|
|
25
|
-
createdAt: c.datetime(),
|
|
26
|
-
externalId: c.uuid().nullable(),
|
|
27
|
-
}))
|
|
28
|
-
.primaryKey("id") // 복합 PK 지원: .primaryKey("col1", "col2")
|
|
29
|
-
.indexes((i) => [
|
|
30
|
-
i.index("email").unique(),
|
|
31
|
-
i.index("name", "role").orderBy("ASC", "DESC"),
|
|
32
|
-
i.index("createdAt").name("ix_created"),
|
|
33
|
-
])
|
|
34
|
-
.relations((r) => ({
|
|
35
|
-
orders: r.foreignKeyTarget(() => Order, "user"), // 1:N
|
|
36
|
-
profile: r.foreignKeyTarget(() => Profile, "user").single(), // 1:1
|
|
37
|
-
}));
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
### Table API
|
|
41
|
-
|
|
42
|
-
```
|
|
43
|
-
Table(name: string): TableBuilder
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
| 메서드 | 시그니처 | 설명 |
|
|
47
|
-
|--------|---------|------|
|
|
48
|
-
| `description` | `(desc: string) => TableBuilder` | 테이블 설명 (DDL 코멘트) |
|
|
49
|
-
| `database` | `(db: string) => TableBuilder` | 데이터베이스 이름 |
|
|
50
|
-
| `schema` | `(schema: string) => TableBuilder` | 스키마 이름 (MSSQL: dbo, PostgreSQL: public) |
|
|
51
|
-
| `columns` | `(fn: (c) => Record) => TableBuilder` | 컬럼 정의 |
|
|
52
|
-
| `primaryKey` | `(...columns: string[]) => TableBuilder` | PK 설정 (복합 PK 지원) |
|
|
53
|
-
| `indexes` | `(fn: (i) => IndexBuilder[]) => TableBuilder` | 인덱스 정의 |
|
|
54
|
-
| `relations` | `(fn: (r) => Record) => TableBuilder` | 관계 정의 |
|
|
55
|
-
|
|
56
|
-
### 컬럼 타입
|
|
57
|
-
|
|
58
|
-
| 메서드 | SQL 타입 | TypeScript 타입 |
|
|
59
|
-
|--------|---------|----------------|
|
|
60
|
-
| `c.int()` | INT | `number` |
|
|
61
|
-
| `c.bigint()` | BIGINT | `number` |
|
|
62
|
-
| `c.float()` | FLOAT | `number` |
|
|
63
|
-
| `c.double()` | DOUBLE | `number` |
|
|
64
|
-
| `c.decimal(p, s?)` | DECIMAL(p,s) | `number` |
|
|
65
|
-
| `c.varchar(len)` | VARCHAR(len) | `string` |
|
|
66
|
-
| `c.char(len)` | CHAR(len) | `string` |
|
|
67
|
-
| `c.text()` | LONGTEXT/TEXT | `string` |
|
|
68
|
-
| `c.boolean()` | BIT/TINYINT(1) | `boolean` |
|
|
69
|
-
| `c.datetime()` | DATETIME | `DateTime` |
|
|
70
|
-
| `c.date()` | DATE | `DateOnly` |
|
|
71
|
-
| `c.time()` | TIME | `Time` |
|
|
72
|
-
| `c.binary()` | LONGBLOB/VARBINARY/BYTEA | `Bytes` |
|
|
73
|
-
| `c.uuid()` | UNIQUEIDENTIFIER/UUID | `Uuid` |
|
|
74
|
-
|
|
75
|
-
### 컬럼 수정자
|
|
76
|
-
|
|
77
|
-
```typescript
|
|
78
|
-
c.int().autoIncrement() // 자동 증가 (INSERT 시 선택적)
|
|
79
|
-
c.varchar(100).nullable() // NULL 허용 (타입에 undefined 추가)
|
|
80
|
-
c.varchar(20).default("x") // 기본값 (INSERT 시 선택적)
|
|
81
|
-
c.varchar(100).description("설명")
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
### 타입 추론
|
|
85
|
-
|
|
86
|
-
```typescript
|
|
87
|
-
User.$inferSelect // { id: number; name: string; email: string | undefined; ... }
|
|
88
|
-
User.$inferInsert // { name: string; createdAt: DateTime; } & { id?: number; email?: string; ... }
|
|
89
|
-
User.$inferUpdate // { id?: number; name?: string; ... } (모든 필드 선택적)
|
|
90
|
-
User.$inferColumns // { id: number; name: string; email: string | undefined; ... } (관계 제외)
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
---
|
|
94
|
-
|
|
95
|
-
## 관계 (Relation)
|
|
96
|
-
|
|
97
|
-
### foreignKey -- N:1 (DB FK 생성)
|
|
98
|
-
|
|
99
|
-
```typescript
|
|
100
|
-
const Order = Table("order")
|
|
101
|
-
.columns((c) => ({
|
|
102
|
-
id: c.int().autoIncrement(),
|
|
103
|
-
userId: c.int(),
|
|
104
|
-
}))
|
|
105
|
-
.primaryKey("id")
|
|
106
|
-
.relations((r) => ({
|
|
107
|
-
user: r.foreignKey(["userId"], () => User), // Order.userId -> User.id
|
|
108
|
-
}));
|
|
109
|
-
```
|
|
110
|
-
|
|
111
|
-
### foreignKeyTarget -- 1:N / 1:1 (역참조)
|
|
112
|
-
|
|
113
|
-
```typescript
|
|
114
|
-
const User = Table("user")
|
|
115
|
-
.columns((c) => ({ id: c.int().autoIncrement(), name: c.varchar(100) }))
|
|
116
|
-
.primaryKey("id")
|
|
117
|
-
.relations((r) => ({
|
|
118
|
-
orders: r.foreignKeyTarget(() => Order, "user"), // 1:N (배열)
|
|
119
|
-
profile: r.foreignKeyTarget(() => Profile, "user").single(), // 1:1 (단일 객체)
|
|
120
|
-
}));
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
### relationKey / relationKeyTarget -- 논리적 관계 (DB FK 없음)
|
|
124
|
-
|
|
125
|
-
View에서도 사용 가능. DB에 FK 제약조건을 생성하지 않는다.
|
|
126
|
-
|
|
127
|
-
```typescript
|
|
128
|
-
.relations((r) => ({
|
|
129
|
-
category: r.relationKey(["categoryId"], () => Category),
|
|
130
|
-
items: r.relationKeyTarget(() => Item, "parent"),
|
|
131
|
-
}))
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
### 관계 빌더 API
|
|
135
|
-
|
|
136
|
-
| 빌더 | 용도 | DB FK 생성 |
|
|
137
|
-
|------|------|----------|
|
|
138
|
-
| `ForeignKeyBuilder` | N:1 관계 (FK 컬럼 소유) | O |
|
|
139
|
-
| `ForeignKeyTargetBuilder` | 1:N / 1:1 역참조 | O (대상 테이블) |
|
|
140
|
-
| `RelationKeyBuilder` | N:1 논리적 관계 | X |
|
|
141
|
-
| `RelationKeyTargetBuilder` | 1:N / 1:1 논리적 역참조 | X |
|
|
142
|
-
|
|
143
|
-
공통 메서드:
|
|
144
|
-
|
|
145
|
-
| 메서드 | 설명 |
|
|
146
|
-
|--------|------|
|
|
147
|
-
| `.description(desc)` | 관계 설명 |
|
|
148
|
-
| `.single()` | 1:1 관계 (ForeignKeyTargetBuilder, RelationKeyTargetBuilder만 해당) |
|
|
149
|
-
|
|
150
|
-
---
|
|
151
|
-
|
|
152
|
-
## View
|
|
153
|
-
|
|
154
|
-
```typescript
|
|
155
|
-
import { View, expr } from "@simplysm/orm-common";
|
|
156
|
-
|
|
157
|
-
const UserSummary = View("user_summary")
|
|
158
|
-
.database("mydb")
|
|
159
|
-
.query<typeof MyDb>((db) =>
|
|
160
|
-
db.user()
|
|
161
|
-
.select((c) => ({
|
|
162
|
-
userId: c.id,
|
|
163
|
-
userName: c.name,
|
|
164
|
-
orderCount: expr.count(),
|
|
165
|
-
totalAmount: expr.sum(c.amount),
|
|
166
|
-
}))
|
|
167
|
-
.groupBy((c) => [c.id, c.name])
|
|
168
|
-
)
|
|
169
|
-
.relations((r) => ({
|
|
170
|
-
user: r.relationKey(["userId"], () => User),
|
|
171
|
-
}));
|
|
172
|
-
```
|
|
173
|
-
|
|
174
|
-
### View API
|
|
175
|
-
|
|
176
|
-
```
|
|
177
|
-
View(name: string): ViewBuilder
|
|
178
|
-
```
|
|
179
|
-
|
|
180
|
-
| 메서드 | 시그니처 | 설명 |
|
|
181
|
-
|--------|---------|------|
|
|
182
|
-
| `description` | `(desc: string) => ViewBuilder` | 뷰 설명 |
|
|
183
|
-
| `database` | `(db: string) => ViewBuilder` | 데이터베이스 이름 |
|
|
184
|
-
| `schema` | `(schema: string) => ViewBuilder` | 스키마 이름 |
|
|
185
|
-
| `query` | `(viewFn: (db) => Queryable) => ViewBuilder` | 뷰 쿼리 정의 |
|
|
186
|
-
| `relations` | `(fn: (r) => Record) => ViewBuilder` | 관계 정의 (relationKey만 가능) |
|
|
187
|
-
|
|
188
|
-
**DbContext 등록:**
|
|
189
|
-
|
|
190
|
-
```typescript
|
|
191
|
-
const MyDb = defineDbContext({
|
|
192
|
-
tables: { user: User },
|
|
193
|
-
views: { userSummary: UserSummary },
|
|
194
|
-
});
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
---
|
|
198
|
-
|
|
199
|
-
## Procedure
|
|
200
|
-
|
|
201
|
-
```typescript
|
|
202
|
-
import { Procedure } from "@simplysm/orm-common";
|
|
203
|
-
|
|
204
|
-
const GetUserOrders = Procedure("get_user_orders")
|
|
205
|
-
.database("mydb")
|
|
206
|
-
.params((c) => ({
|
|
207
|
-
userId: c.int(),
|
|
208
|
-
fromDate: c.date().nullable(),
|
|
209
|
-
}))
|
|
210
|
-
.returns((c) => ({
|
|
211
|
-
orderId: c.int(),
|
|
212
|
-
amount: c.decimal(10, 2),
|
|
213
|
-
createdAt: c.datetime(),
|
|
214
|
-
}))
|
|
215
|
-
.body(`
|
|
216
|
-
SELECT id AS orderId, amount, created_at AS createdAt
|
|
217
|
-
FROM orders
|
|
218
|
-
WHERE user_id = userId AND created_at >= COALESCE(fromDate, '1900-01-01')
|
|
219
|
-
`);
|
|
220
|
-
```
|
|
221
|
-
|
|
222
|
-
### Procedure API
|
|
223
|
-
|
|
224
|
-
```
|
|
225
|
-
Procedure(name: string): ProcedureBuilder
|
|
226
|
-
```
|
|
227
|
-
|
|
228
|
-
| 메서드 | 시그니처 | 설명 |
|
|
229
|
-
|--------|---------|------|
|
|
230
|
-
| `description` | `(desc: string) => ProcedureBuilder` | 프로시저 설명 |
|
|
231
|
-
| `database` | `(db: string) => ProcedureBuilder` | 데이터베이스 이름 |
|
|
232
|
-
| `schema` | `(schema: string) => ProcedureBuilder` | 스키마 이름 |
|
|
233
|
-
| `params` | `(fn: (c) => Record) => ProcedureBuilder` | 파라미터 정의 |
|
|
234
|
-
| `returns` | `(fn: (c) => Record) => ProcedureBuilder` | 반환 타입 정의 |
|
|
235
|
-
| `body` | `(sql: string) => ProcedureBuilder` | 프로시저 본문 SQL |
|
|
236
|
-
|
|
237
|
-
**DbContext 등록:**
|
|
238
|
-
|
|
239
|
-
```typescript
|
|
240
|
-
const MyDb = defineDbContext({
|
|
241
|
-
tables: { user: User },
|
|
242
|
-
procedures: { getUserOrders: GetUserOrders },
|
|
243
|
-
});
|
|
244
|
-
```
|
|
245
|
-
|
|
246
|
-
MSSQL은 파라미터에 `@` 접두사 필요: `@userId`, `@fromDate`
|
|
247
|
-
|
|
248
|
-
---
|
|
249
|
-
|
|
250
|
-
## Index
|
|
251
|
-
|
|
252
|
-
```typescript
|
|
253
|
-
.indexes((i) => [
|
|
254
|
-
i.index("email").unique(), // UNIQUE INDEX
|
|
255
|
-
i.index("name", "role").orderBy("ASC", "DESC"), // 정렬 방향 지정
|
|
256
|
-
i.index("createdAt").name("ix_custom_name"), // 커스텀 이름
|
|
257
|
-
i.index("code").description("코드 인덱스"),
|
|
258
|
-
])
|
|
259
|
-
```
|
|
260
|
-
|
|
261
|
-
### IndexBuilder API
|
|
262
|
-
|
|
263
|
-
| 메서드 | 시그니처 | 설명 |
|
|
264
|
-
|--------|---------|------|
|
|
265
|
-
| `index` | `(...columns: string[]) => IndexBuilder` | 인덱스 생성 (단일/복합) |
|
|
266
|
-
| `unique` | `() => IndexBuilder` | 유니크 인덱스 설정 |
|
|
267
|
-
| `orderBy` | `(...dirs: ("ASC"\|"DESC")[]) => IndexBuilder` | 컬럼별 정렬 방향 |
|
|
268
|
-
| `name` | `(name: string) => IndexBuilder` | 커스텀 인덱스 이름 |
|
|
269
|
-
| `description` | `(desc: string) => IndexBuilder` | 인덱스 설명 |
|
|
270
|
-
|
|
271
|
-
---
|
|
272
|
-
|
|
273
|
-
## defineDbContext / createDbContext
|
|
274
|
-
|
|
275
|
-
### defineDbContext -- 스키마 블루프린트
|
|
276
|
-
|
|
277
|
-
```typescript
|
|
278
|
-
import { defineDbContext } from "@simplysm/orm-common";
|
|
279
|
-
|
|
280
|
-
const MyDb = defineDbContext({
|
|
281
|
-
tables: { user: User, order: Order },
|
|
282
|
-
views: { userSummary: UserSummary },
|
|
283
|
-
procedures: { getUserOrders: GetUserOrders },
|
|
284
|
-
migrations: [
|
|
285
|
-
{
|
|
286
|
-
name: "20260105_001_add_phone",
|
|
287
|
-
up: async (db) => {
|
|
288
|
-
const c = createColumnFactory();
|
|
289
|
-
await db.addColumn({ name: "user" }, "phone", c.varchar(20).nullable());
|
|
290
|
-
},
|
|
291
|
-
},
|
|
292
|
-
],
|
|
293
|
-
});
|
|
294
|
-
```
|
|
295
|
-
|
|
296
|
-
`_migration` 테이블이 자동으로 포함된다.
|
|
297
|
-
|
|
298
|
-
### createDbContext -- 런타임 인스턴스 생성
|
|
299
|
-
|
|
300
|
-
```typescript
|
|
301
|
-
import { createDbContext } from "@simplysm/orm-common";
|
|
302
|
-
|
|
303
|
-
const db = createDbContext(MyDb, executor, {
|
|
304
|
-
database: "mydb",
|
|
305
|
-
schema: "dbo", // MSSQL/PostgreSQL 선택
|
|
306
|
-
});
|
|
307
|
-
```
|
|
308
|
-
|
|
309
|
-
```
|
|
310
|
-
createDbContext(
|
|
311
|
-
def: DbContextDef,
|
|
312
|
-
executor: DbContextExecutor,
|
|
313
|
-
opt: { database: string; schema?: string },
|
|
314
|
-
): DbContextInstance
|
|
315
|
-
```
|
|
316
|
-
|
|
317
|
-
`executor`는 `DbContextExecutor` 인터페이스를 구현해야 한다 (`@simplysm/orm-node`의 `NodeDbContextExecutor` 등).
|
|
318
|
-
|
|
319
|
-
생성된 인스턴스는 다음을 포함한다:
|
|
320
|
-
- 등록된 테이블/뷰에 대한 `Queryable` 접근자 (예: `db.user()`, `db.order()`)
|
|
321
|
-
- 등록된 프로시저에 대한 `Executable` 접근자 (예: `db.getUserOrders()`)
|
|
322
|
-
- 연결/트랜잭션 관리 메서드
|
|
323
|
-
- DDL 실행 메서드
|
|
324
|
-
- `initialize()` 메서드
|
|
325
|
-
- `_migration()` 시스템 테이블 접근자
|