@simplysm/orm-node 13.0.95 → 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.
Files changed (2) hide show
  1. package/package.json +4 -4
  2. package/README.md +0 -276
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplysm/orm-node",
3
- "version": "13.0.95",
3
+ "version": "13.0.97",
4
4
  "description": "Simplysm package - ORM module (node)",
5
5
  "author": "simplysm",
6
6
  "license": "Apache-2.0",
@@ -20,13 +20,13 @@
20
20
  "sideEffects": false,
21
21
  "dependencies": {
22
22
  "consola": "^3.4.2",
23
- "@simplysm/core-common": "13.0.95",
24
- "@simplysm/orm-common": "13.0.95"
23
+ "@simplysm/core-common": "13.0.97",
24
+ "@simplysm/orm-common": "13.0.97"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/pg": "^8.18.0",
28
28
  "@types/pg-copy-streams": "^1.2.5",
29
- "mysql2": "^3.19.1",
29
+ "mysql2": "^3.20.0",
30
30
  "pg": "^8.20.0",
31
31
  "pg-copy-streams": "^7.0.0",
32
32
  "tedious": "^19.2.1"
package/README.md DELETED
@@ -1,276 +0,0 @@
1
- # @simplysm/orm-node
2
-
3
- Node.js용 ORM 모듈. MySQL, PostgreSQL, MSSQL(Azure 포함) 데이터베이스를 지원한다.
4
-
5
- ## 설치
6
-
7
- ```bash
8
- npm install @simplysm/orm-node
9
- ```
10
-
11
- 사용하는 DB에 따라 드라이버를 추가로 설치한다 (모두 optional peerDependency):
12
-
13
- ```bash
14
- npm install mysql2 # MySQL
15
- npm install pg pg-copy-streams # PostgreSQL
16
- npm install tedious # MSSQL / Azure SQL
17
- ```
18
-
19
- **의존성:** `@simplysm/core-common`, `@simplysm/orm-common`, `consola`
20
-
21
- ## 아키텍처 개요
22
-
23
- ```
24
- createOrm() -- 최상위 팩토리 (ORM 인스턴스)
25
- └─ NodeDbContextExecutor -- DbContextExecutor 구현체
26
- └─ createDbConn() -- DB 연결 생성
27
- └─ MysqlDbConn / PostgresqlDbConn / MssqlDbConn -- 실제 연결
28
- ```
29
-
30
- - `createOrm` -- `@simplysm/orm-common`의 `DbContext`와 DB 연결을 결합하는 고수준 API
31
- - `NodeDbContextExecutor` -- `QueryDef` → SQL 변환 및 실행을 담당하는 어댑터
32
- - `createDbConn` -- DB 연결 인스턴스를 생성
33
- - `MysqlDbConn` / `PostgresqlDbConn` / `MssqlDbConn` -- 각 DBMS별 실제 연결 구현
34
-
35
- ## 주요 사용법
36
-
37
- ### ORM 인스턴스 생성 및 트랜잭션
38
-
39
- ```typescript
40
- import { createOrm } from "@simplysm/orm-node";
41
- import { defineDbContext, Table } from "@simplysm/orm-common";
42
-
43
- // 1. 테이블 및 DbContext 정의 (orm-common)
44
- const User = Table("user")
45
- .columns((c) => ({ id: c.int().autoIncrement(), name: c.varchar(100) }))
46
- .primaryKey("id");
47
-
48
- const Order = Table("order")
49
- .columns((c) => ({ id: c.int().autoIncrement(), userId: c.int(), amount: c.decimal(10, 2) }))
50
- .primaryKey("id");
51
-
52
- const MyDb = defineDbContext({
53
- tables: { user: User, order: Order },
54
- });
55
-
56
- // 2. ORM 인스턴스 생성
57
- const orm = createOrm(MyDb, {
58
- dialect: "mysql",
59
- host: "localhost",
60
- port: 3306,
61
- username: "root",
62
- password: "password",
63
- database: "mydb",
64
- });
65
-
66
- // 3-a. 자동 트랜잭션 (commit/rollback 자동 처리)
67
- const result = await orm.connect(async (db) => {
68
- const users = await db.user().execute();
69
- await db.user().insert([{ name: "Alice" }]);
70
- return users;
71
- });
72
-
73
- // 3-b. 트랜잭션 없이 실행
74
- const users = await orm.connectWithoutTransaction(async (db) => {
75
- return await db.user().execute();
76
- });
77
-
78
- // 3-c. 격리 수준 지정
79
- await orm.connect(async (db) => {
80
- /* ... */
81
- }, "SERIALIZABLE");
82
- ```
83
-
84
- ### OrmOptions로 database/schema 오버라이드
85
-
86
- ```typescript
87
- const orm = createOrm(MyDb, config, {
88
- database: "other_db", // config.database 대신 사용
89
- schema: "custom_schema", // config.schema 대신 사용
90
- });
91
- ```
92
-
93
- ### 저수준 DB 연결
94
-
95
- ```typescript
96
- import { createDbConn } from "@simplysm/orm-node";
97
-
98
- const conn = await createDbConn(config);
99
- await conn.connect();
100
-
101
- await conn.beginTransaction();
102
- try {
103
- const rows = await conn.execute(["SELECT * FROM users"]);
104
- await conn.executeParametrized("INSERT INTO users (name) VALUES (?)", ["Alice"]);
105
- await conn.commitTransaction();
106
- } catch {
107
- await conn.rollbackTransaction();
108
- }
109
-
110
- await conn.close();
111
- ```
112
-
113
- ### 벌크 인서트
114
-
115
- 각 DBMS의 네이티브 벌크 API를 사용하여 최적 성능을 제공한다.
116
-
117
- ```typescript
118
- await conn.bulkInsert("users", columnMetas, records);
119
- ```
120
-
121
- | DBMS | 방식 |
122
- |------|------|
123
- | MySQL | `LOAD DATA LOCAL INFILE` (임시 CSV 파일) |
124
- | PostgreSQL | `COPY FROM STDIN` (스트림 기반 CSV) |
125
- | MSSQL | tedious `BulkLoad` API (네이티브) |
126
-
127
- ## API 레퍼런스
128
-
129
- ### `createOrm(dbContextDef, config, options?): Orm`
130
-
131
- ORM 인스턴스 팩토리. `defineDbContext`로 정의한 DbContext 정의와 연결 설정을 결합한다.
132
-
133
- ```typescript
134
- function createOrm<TDef extends DbContextDef<any, any, any>>(
135
- dbContextDef: TDef,
136
- config: DbConnConfig,
137
- options?: OrmOptions,
138
- ): Orm<TDef>;
139
- ```
140
-
141
- **`Orm<TDef>` 인터페이스:**
142
-
143
- | 속성/메서드 | 타입 | 설명 |
144
- |---|---|---|
145
- | `dbContextDef` | `TDef` (readonly) | DbContext 정의 |
146
- | `config` | `DbConnConfig` (readonly) | 연결 설정 |
147
- | `options` | `OrmOptions` (readonly, optional) | 옵션 |
148
- | `connect(callback, isolationLevel?)` | `Promise<R>` | 트랜잭션 내에서 콜백 실행 |
149
- | `connectWithoutTransaction(callback)` | `Promise<R>` | 트랜잭션 없이 콜백 실행 |
150
-
151
- **`OrmOptions` 인터페이스:**
152
-
153
- | 필드 | 타입 | 설명 |
154
- |---|---|---|
155
- | `database?` | `string` | config.database 대신 사용할 DB 이름 |
156
- | `schema?` | `string` | config.schema 대신 사용할 스키마 이름 |
157
-
158
- ### `createDbConn(config): Promise<DbConn>`
159
-
160
- DB 연결 인스턴스를 생성하여 반환한다. 반환된 객체에 `connect()`를 호출해야 실제 연결이 수립된다.
161
-
162
- ```typescript
163
- function createDbConn(config: DbConnConfig): Promise<DbConn>;
164
- ```
165
-
166
- ### `DbConn` 인터페이스
167
-
168
- 모든 DB 연결 구현체의 공통 인터페이스. `EventEmitter<{ close: void }>`를 상속한다.
169
-
170
- ```typescript
171
- interface DbConn extends EventEmitter<{ close: void }> {
172
- config: DbConnConfig;
173
- isConnected: boolean;
174
- isInTransaction: boolean;
175
-
176
- connect(): Promise<void>;
177
- close(): Promise<void>;
178
- beginTransaction(isolationLevel?: IsolationLevel): Promise<void>;
179
- commitTransaction(): Promise<void>;
180
- rollbackTransaction(): Promise<void>;
181
- execute(queries: string[]): Promise<Record<string, unknown>[][]>;
182
- executeParametrized(query: string, params?: unknown[]): Promise<Record<string, unknown>[][]>;
183
- bulkInsert(
184
- tableName: string,
185
- columnMetas: Record<string, ColumnMeta>,
186
- records: Record<string, unknown>[],
187
- ): Promise<void>;
188
- }
189
- ```
190
-
191
- ### `DbConnConfig` 타입
192
-
193
- `dialect` 필드로 분기되는 유니온 타입이다.
194
-
195
- ```typescript
196
- type DbConnConfig = MysqlDbConnConfig | MssqlDbConnConfig | PostgresqlDbConnConfig;
197
- ```
198
-
199
- **공통 필드:**
200
-
201
- | 필드 | 타입 | 설명 |
202
- |---|---|---|
203
- | `dialect` | `"mysql"` \| `"mssql"` \| `"mssql-azure"` \| `"postgresql"` | DBMS 종류 |
204
- | `host` | `string` | 호스트 |
205
- | `port?` | `number` | 포트 |
206
- | `username` | `string` | 사용자명 |
207
- | `password` | `string` | 비밀번호 |
208
- | `database?` | `string` | 데이터베이스명 |
209
- | `defaultIsolationLevel?` | `IsolationLevel` | 기본 격리 수준 |
210
- **MSSQL/PostgreSQL 전용:**
211
-
212
- | 필드 | 타입 | 설명 |
213
- |---|---|---|
214
- | `schema?` | `string` | 스키마 (MSSQL 기본: `dbo`, PostgreSQL 기본: `public`) |
215
-
216
- **MSSQL 특수 dialect:**
217
- - `"mssql-azure"`: Azure SQL용. `encrypt: true`가 자동 적용됨.
218
-
219
- ### `NodeDbContextExecutor`
220
-
221
- `@simplysm/orm-common`의 `DbContextExecutor` 인터페이스 구현체. `DbContext`가 내부적으로 사용한다.
222
-
223
- ```typescript
224
- class NodeDbContextExecutor implements DbContextExecutor {
225
- constructor(config: DbConnConfig);
226
-
227
- connect(): Promise<void>;
228
- close(): Promise<void>;
229
- beginTransaction(isolationLevel?: IsolationLevel): Promise<void>;
230
- commitTransaction(): Promise<void>;
231
- rollbackTransaction(): Promise<void>;
232
- executeParametrized(query: string, params?: unknown[]): Promise<Record<string, unknown>[][]>;
233
- bulkInsert(tableName: string, columnMetas: Record<string, ColumnMeta>, records: DataRecord[]): Promise<void>;
234
- executeDefs<T = DataRecord>(defs: QueryDef[], resultMetas?: (ResultMeta | undefined)[]): Promise<T[][]>;
235
- }
236
- ```
237
-
238
- **`executeDefs` 동작:**
239
- - `QueryDef`를 dialect에 맞는 SQL로 변환 (`createQueryBuilder`)
240
- - `resultMetas`가 모두 `undefined`이면 → 결과 없는 쿼리로 판단하여 단일 배치 실행
241
- - `ResultMeta`가 있으면 → `parseQueryResult`로 타입 변환 적용
242
-
243
- ### DB 연결 구현 클래스
244
-
245
- | 클래스 | 드라이버 | dialect |
246
- |---|---|---|
247
- | `MysqlDbConn` | `mysql2/promise` | `"mysql"` |
248
- | `PostgresqlDbConn` | `pg` + `pg-copy-streams` | `"postgresql"` |
249
- | `MssqlDbConn` | `tedious` | `"mssql"`, `"mssql-azure"` |
250
-
251
- 모두 `EventEmitter<{ close: void }>`를 상속하고 `DbConn`을 구현한다. 드라이버 모듈은 `createDbConn` 호출 시 lazy import된다.
252
-
253
- ### `getDialectFromConfig(config): Dialect`
254
-
255
- config에서 `Dialect`를 추출한다. `"mssql-azure"` → `"mssql"`로 변환된다.
256
-
257
- ```typescript
258
- function getDialectFromConfig(config: DbConnConfig): Dialect;
259
- ```
260
-
261
- ### 상수
262
-
263
- | 상수 | 값 | 설명 |
264
- |---|---|---|
265
- | `DB_CONN_CONNECT_TIMEOUT` | 10초 (10,000ms) | 연결 타임아웃 |
266
- | `DB_CONN_DEFAULT_TIMEOUT` | 10분 (600,000ms) | 쿼리 기본 타임아웃 |
267
- | `DB_CONN_ERRORS.NOT_CONNECTED` | `"'Connection' is not connected."` | 미연결 에러 메시지 |
268
- | `DB_CONN_ERRORS.ALREADY_CONNECTED` | `"'Connection' is already connected."` | 중복 연결 에러 메시지 |
269
-
270
- ### IsolationLevel 타입
271
-
272
- `@simplysm/orm-common`에서 제공하는 트랜잭션 격리 수준이다.
273
-
274
- ```typescript
275
- type IsolationLevel = "READ_UNCOMMITTED" | "READ_COMMITTED" | "REPEATABLE_READ" | "SERIALIZABLE";
276
- ```