@simplysm/orm-node 13.0.100 → 14.0.4

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @simplysm/orm-node
2
2
 
3
- Simplysm package - ORM module (node). Provides database connection implementations for MySQL, MSSQL, and PostgreSQL, plus a high-level ORM factory for managing DbContext instances with transaction support.
3
+ Node.js ORM runtime providing database connections for MySQL, MSSQL, and PostgreSQL with typed query execution.
4
4
 
5
5
  ## Installation
6
6
 
@@ -8,220 +8,247 @@ Simplysm package - ORM module (node). Provides database connection implementatio
8
8
  npm install @simplysm/orm-node
9
9
  ```
10
10
 
11
- Database drivers are loaded lazily. Install only the driver(s) you need:
11
+ Peer dependencies (install the driver for your database):
12
+ - MySQL: `mysql2`
13
+ - MSSQL: `tedious`
14
+ - PostgreSQL: `pg`, `pg-copy-streams`
12
15
 
13
- ```bash
14
- npm install mysql2 # for MySQL
15
- npm install tedious # for MSSQL / Azure SQL
16
- npm install pg pg-copy-streams # for PostgreSQL
17
- ```
16
+ ## Quick Start
18
17
 
19
- ## API Overview
18
+ ```typescript
19
+ import { defineDbContext, Table, expr } from "@simplysm/orm-common";
20
+ import { createOrm } from "@simplysm/orm-node";
20
21
 
21
- ### Types
22
+ const User = Table("User")
23
+ .columns((c) => ({
24
+ id: c.bigint().autoIncrement(),
25
+ name: c.varchar(100),
26
+ email: c.varchar(200).nullable(),
27
+ }))
28
+ .primaryKey("id");
22
29
 
23
- | API | Type | Description |
24
- |-----|------|-------------|
25
- | `DbConn` | interface | Low-level DB connection interface |
26
- | `DbConnConfig` | type | Union of all connection config types |
27
- | `MysqlDbConnConfig` | interface | MySQL connection configuration |
28
- | `MssqlDbConnConfig` | interface | MSSQL connection configuration |
29
- | `PostgresqlDbConnConfig` | interface | PostgreSQL connection configuration |
30
- | `DB_CONN_CONNECT_TIMEOUT` | const | Connection timeout (10 seconds) |
31
- | `DB_CONN_DEFAULT_TIMEOUT` | const | Query default timeout (10 minutes) |
32
- | `DB_CONN_ERRORS` | const | Error message constants |
33
- | `getDialectFromConfig` | function | Extract Dialect from DbConnConfig |
30
+ const MyDb = defineDbContext({
31
+ tables: { user: User },
32
+ });
34
33
 
35
- ### Connections
34
+ const orm = createOrm(MyDb, {
35
+ dialect: "mysql",
36
+ host: "localhost",
37
+ port: 3306,
38
+ username: "root",
39
+ password: "password",
40
+ database: "mydb",
41
+ });
36
42
 
37
- | API | Type | Description |
38
- |-----|------|-------------|
39
- | `MysqlDbConn` | class | MySQL connection (uses mysql2/promise) |
40
- | `MssqlDbConn` | class | MSSQL/Azure SQL connection (uses tedious) |
41
- | `PostgresqlDbConn` | class | PostgreSQL connection (uses pg) |
42
- | `createDbConn` | function | DB connection factory function |
43
+ // With transaction
44
+ await orm.connect(async (db) => {
45
+ await db.user().insert([{ name: "Gildong Hong" }]);
46
+ const users = await db.user().execute();
47
+ return users;
48
+ });
43
49
 
44
- ### Core
50
+ // Without transaction (for DDL or read-only)
51
+ await orm.connectWithoutTransaction(async (db) => {
52
+ await db.initialize();
53
+ const users = await db.user().execute();
54
+ return users;
55
+ });
56
+ ```
57
+
58
+ ## API Reference
45
59
 
46
- | API | Type | Description |
47
- |-----|------|-------------|
48
- | `NodeDbContextExecutor` | class | DbContextExecutor for Node.js |
49
- | `createOrm` | function | ORM factory function |
50
- | `Orm` | interface | ORM instance type |
51
- | `OrmOptions` | interface | ORM options (database/schema override) |
60
+ ### Types
52
61
 
53
- ---
62
+ #### DbConn (interface)
54
63
 
55
- ### `DbConnConfig`
64
+ Low-level database connection interface. Extends `EventEmitter<{ close: void }>`.
65
+
66
+ | Field / Method | Type | Description |
67
+ |---|---|---|
68
+ | `config` | `DbConnConfig` | Connection configuration |
69
+ | `isConnected` | `boolean` | Whether the connection is active |
70
+ | `isInTransaction` | `boolean` | Whether a transaction is in progress |
71
+ | `connect()` | `Promise<void>` | Establish connection |
72
+ | `close()` | `Promise<void>` | Close connection |
73
+ | `beginTransaction(isolationLevel?)` | `Promise<void>` | Start transaction |
74
+ | `commitTransaction()` | `Promise<void>` | Commit transaction |
75
+ | `rollbackTransaction()` | `Promise<void>` | Rollback transaction |
76
+ | `execute(queries: string[])` | `Promise<Record<string, unknown>[][]>` | Execute SQL query array |
77
+ | `executeParametrized(query, params?)` | `Promise<Record<string, unknown>[][]>` | Execute parameterized query |
78
+ | `bulkInsert(tableName, columnMetas, records)` | `Promise<void>` | Native bulk insert (MSSQL: BulkLoad, MySQL: LOAD DATA, PostgreSQL: COPY) |
79
+
80
+ #### DbConnConfig (type)
56
81
 
57
82
  ```typescript
58
83
  type DbConnConfig = MysqlDbConnConfig | MssqlDbConnConfig | PostgresqlDbConnConfig;
59
84
  ```
60
85
 
61
- ### `MysqlDbConnConfig`
86
+ #### MysqlDbConnConfig (interface)
87
+
88
+ | Field | Type | Required | Description |
89
+ |---|---|---|---|
90
+ | `dialect` | `"mysql"` | Yes | Dialect identifier |
91
+ | `host` | `string` | Yes | Server hostname |
92
+ | `port` | `number` | No | Server port |
93
+ | `username` | `string` | Yes | Login username |
94
+ | `password` | `string` | Yes | Login password |
95
+ | `database` | `string` | No | Default database |
96
+ | `defaultIsolationLevel` | `IsolationLevel` | No | Default transaction isolation level |
97
+
98
+ #### MssqlDbConnConfig (interface)
99
+
100
+ | Field | Type | Required | Description |
101
+ |---|---|---|---|
102
+ | `dialect` | `"mssql" \| "mssql-azure"` | Yes | Dialect identifier |
103
+ | `host` | `string` | Yes | Server hostname |
104
+ | `port` | `number` | No | Server port |
105
+ | `username` | `string` | Yes | Login username |
106
+ | `password` | `string` | Yes | Login password |
107
+ | `database` | `string` | No | Default database |
108
+ | `schema` | `string` | No | Default schema (default: dbo) |
109
+ | `defaultIsolationLevel` | `IsolationLevel` | No | Default transaction isolation level |
110
+
111
+ #### PostgresqlDbConnConfig (interface)
112
+
113
+ | Field | Type | Required | Description |
114
+ |---|---|---|---|
115
+ | `dialect` | `"postgresql"` | Yes | Dialect identifier |
116
+ | `host` | `string` | Yes | Server hostname |
117
+ | `port` | `number` | No | Server port |
118
+ | `username` | `string` | Yes | Login username |
119
+ | `password` | `string` | Yes | Login password |
120
+ | `database` | `string` | No | Default database |
121
+ | `schema` | `string` | No | Default schema (default: public) |
122
+ | `defaultIsolationLevel` | `IsolationLevel` | No | Default transaction isolation level |
123
+
124
+ #### getDialectFromConfig
125
+
126
+ Extracts the `Dialect` from a `DbConnConfig`. Maps `"mssql-azure"` to `"mssql"`.
62
127
 
63
- | Field | Type | Description |
64
- |-------|------|-------------|
65
- | `dialect` | `"mysql"` | Dialect identifier |
66
- | `host` | `string` | Server hostname |
67
- | `port` | `number?` | Server port |
68
- | `username` | `string` | Username |
69
- | `password` | `string` | Password |
70
- | `database` | `string?` | Database name |
71
- | `defaultIsolationLevel` | `IsolationLevel?` | Default transaction isolation level |
128
+ ```typescript
129
+ function getDialectFromConfig(config: DbConnConfig): Dialect;
130
+ ```
72
131
 
73
- ### `MssqlDbConnConfig`
132
+ #### Constants
74
133
 
75
- | Field | Type | Description |
76
- |-------|------|-------------|
77
- | `dialect` | `"mssql" \| "mssql-azure"` | Dialect identifier |
78
- | `host` | `string` | Server hostname |
79
- | `port` | `number?` | Server port |
80
- | `username` | `string` | Username |
81
- | `password` | `string` | Password |
82
- | `database` | `string?` | Database name |
83
- | `schema` | `string?` | Schema name |
84
- | `defaultIsolationLevel` | `IsolationLevel?` | Default transaction isolation level |
85
-
86
- ### `PostgresqlDbConnConfig`
134
+ | Constant | Value | Description |
135
+ |---|---|---|
136
+ | `DB_CONN_CONNECT_TIMEOUT` | `10000` | Connection establishment timeout (10 seconds) |
137
+ | `DB_CONN_DEFAULT_TIMEOUT` | `600000` | Default query timeout (10 minutes) |
138
+ | `DB_CONN_ERRORS` | `{ NOT_CONNECTED, ALREADY_CONNECTED }` | Standard error messages |
87
139
 
88
- | Field | Type | Description |
89
- |-------|------|-------------|
90
- | `dialect` | `"postgresql"` | Dialect identifier |
91
- | `host` | `string` | Server hostname |
92
- | `port` | `number?` | Server port |
93
- | `username` | `string` | Username |
94
- | `password` | `string` | Password |
95
- | `database` | `string?` | Database name |
96
- | `schema` | `string?` | Schema name |
97
- | `defaultIsolationLevel` | `IsolationLevel?` | Default transaction isolation level |
98
-
99
- ### `DbConn`
100
-
101
- Interface extending `EventEmitter<{ close: void }>`. Implemented by `MysqlDbConn`, `MssqlDbConn`, and `PostgresqlDbConn`.
102
-
103
- | Property/Method | Signature | Description |
104
- |-----------------|-----------|-------------|
105
- | `config` | `DbConnConfig` | Connection configuration |
106
- | `isConnected` | `boolean` | Whether connected |
107
- | `isInTransaction` | `boolean` | Whether transaction is in progress |
108
- | `connect` | `() => Promise<void>` | Establish DB connection |
109
- | `close` | `() => Promise<void>` | Close DB connection |
110
- | `beginTransaction` | `(isolationLevel?: IsolationLevel) => Promise<void>` | Begin transaction |
111
- | `commitTransaction` | `() => Promise<void>` | Commit transaction |
112
- | `rollbackTransaction` | `() => Promise<void>` | Rollback transaction |
113
- | `execute` | `(queries: string[]) => Promise<Record<string, unknown>[][]>` | Execute SQL query array |
114
- | `executeParametrized` | `(query: string, params?: unknown[]) => Promise<Record<string, unknown>[][]>` | Execute parameterized query |
115
- | `bulkInsert` | `(tableName: string, columnMetas: Record<string, ColumnMeta>, records: Record<string, unknown>[]) => Promise<void>` | Bulk INSERT using native API |
116
-
117
- ### `createDbConn`
140
+ ### Connections
141
+
142
+ #### MssqlDbConn (class)
143
+
144
+ Implements `DbConn` using the `tedious` driver for Microsoft SQL Server.
118
145
 
119
146
  ```typescript
120
- function createDbConn(config: DbConnConfig): Promise<DbConn>
147
+ class MssqlDbConn implements DbConn {
148
+ constructor(tedious: typeof import("tedious"), config: MssqlDbConnConfig);
149
+ }
121
150
  ```
122
151
 
123
- Factory function that creates a DB connection instance. The returned connection is **not yet connected** -- call `connect()` separately. Database drivers are lazily loaded.
152
+ #### MysqlDbConn (class)
124
153
 
125
- ### `getDialectFromConfig`
154
+ Implements `DbConn` using the `mysql2/promise` driver for MySQL.
126
155
 
127
156
  ```typescript
128
- function getDialectFromConfig(config: DbConnConfig): Dialect
157
+ class MysqlDbConn implements DbConn {
158
+ constructor(mysql: typeof import("mysql2/promise"), config: MysqlDbConnConfig);
159
+ }
129
160
  ```
130
161
 
131
- Extracts the `Dialect` from a config. Maps `"mssql-azure"` to `"mssql"`.
162
+ #### PostgresqlDbConn (class)
132
163
 
133
- ### `OrmOptions`
164
+ Implements `DbConn` using `pg` and `pg-copy-streams` drivers for PostgreSQL.
134
165
 
135
- | Field | Type | Description |
136
- |-------|------|-------------|
137
- | `database` | `string?` | Database name (overrides DbConnConfig's database) |
138
- | `schema` | `string?` | Schema name (MSSQL: dbo, PostgreSQL: public) |
166
+ ```typescript
167
+ class PostgresqlDbConn implements DbConn {
168
+ constructor(
169
+ pg: typeof import("pg"),
170
+ pgCopyStreams: typeof import("pg-copy-streams"),
171
+ config: PostgresqlDbConnConfig,
172
+ );
173
+ }
174
+ ```
139
175
 
140
- ### `Orm<TDef>`
176
+ ### Core
141
177
 
142
- | Property/Method | Signature | Description |
143
- |-----------------|-----------|-------------|
144
- | `dbContextDef` | `TDef` | DbContext definition |
145
- | `config` | `DbConnConfig` | Connection configuration |
146
- | `options` | `OrmOptions?` | ORM options |
147
- | `connect` | `<R>(callback: (conn: DbContextInstance<TDef>) => Promise<R>, isolationLevel?: IsolationLevel) => Promise<R>` | Execute callback within a transaction |
148
- | `connectWithoutTransaction` | `<R>(callback: (conn: DbContextInstance<TDef>) => Promise<R>) => Promise<R>` | Execute callback without a transaction |
178
+ #### createDbConn
149
179
 
150
- ### `createOrm`
180
+ Factory function that creates a `DbConn` instance with lazy-loaded drivers. The connection is NOT established -- call `connect()` separately.
151
181
 
152
182
  ```typescript
153
- function createOrm<TDef extends DbContextDef<any, any, any>>(
154
- dbContextDef: TDef,
155
- config: DbConnConfig,
156
- options?: OrmOptions,
157
- ): Orm<TDef>
183
+ async function createDbConn(config: DbConnConfig): Promise<DbConn>;
158
184
  ```
159
185
 
160
- ### `NodeDbContextExecutor`
161
-
162
- | Method | Signature | Description |
163
- |--------|-----------|-------------|
164
- | `constructor` | `(config: DbConnConfig)` | Create executor with connection config |
165
- | `connect` | `() => Promise<void>` | Establish DB connection |
166
- | `close` | `() => Promise<void>` | Close DB connection |
167
- | `beginTransaction` | `(isolationLevel?: IsolationLevel) => Promise<void>` | Begin transaction |
168
- | `commitTransaction` | `() => Promise<void>` | Commit transaction |
169
- | `rollbackTransaction` | `() => Promise<void>` | Rollback transaction |
170
- | `executeParametrized` | `(query: string, params?: unknown[]) => Promise<Record<string, unknown>[][]>` | Execute parameterized query |
171
- | `bulkInsert` | `(tableName: string, columnMetas: Record<string, ColumnMeta>, records: DataRecord[]) => Promise<void>` | Bulk insert |
172
- | `executeDefs` | `<T>(defs: QueryDef[], resultMetas?: (ResultMeta \| undefined)[]) => Promise<T[][]>` | Execute QueryDef array |
173
-
174
- ## Usage Examples
186
+ #### NodeDbContextExecutor (class)
175
187
 
176
- ### Using createOrm (recommended)
188
+ Implements `DbContextExecutor` for Node.js. Bridges `DbConn` with the ORM's `QueryDef` system.
177
189
 
178
190
  ```typescript
179
- import { createOrm } from "@simplysm/orm-node";
180
- import { defineDbContext, queryable } from "@simplysm/orm-common";
181
-
182
- const MyDb = defineDbContext({
183
- user: (db) => queryable(db, User),
184
- });
191
+ class NodeDbContextExecutor implements DbContextExecutor {
192
+ constructor(config: DbConnConfig);
193
+
194
+ connect(): Promise<void>;
195
+ close(): Promise<void>;
196
+ beginTransaction(isolationLevel?: IsolationLevel): Promise<void>;
197
+ commitTransaction(): Promise<void>;
198
+ rollbackTransaction(): Promise<void>;
199
+ executeParametrized(query: string, params?: unknown[]): Promise<Record<string, unknown>[][]>;
200
+ bulkInsert(tableName: string, columnMetas: Record<string, ColumnMeta>, records: DataRecord[]): Promise<void>;
201
+ executeDefs<T = DataRecord>(defs: QueryDef[], resultMetas?: (ResultMeta | undefined)[]): Promise<T[][]>;
202
+ }
203
+ ```
185
204
 
186
- const orm = createOrm(MyDb, {
187
- dialect: "mysql",
188
- host: "localhost",
189
- port: 3306,
190
- username: "root",
191
- password: "password",
192
- database: "mydb",
193
- });
205
+ #### createOrm
194
206
 
195
- // Execute within a transaction
196
- await orm.connect(async (db) => {
197
- const users = await db.user().execute();
198
- return users;
199
- });
207
+ Main factory function. Creates an `Orm` instance that manages `DbContext` creation and connection lifecycle.
200
208
 
201
- // Execute without a transaction
202
- await orm.connectWithoutTransaction(async (db) => {
203
- const users = await db.user().execute();
204
- return users;
205
- });
209
+ ```typescript
210
+ function createOrm<TDef extends DbContextDef<any, any, any>>(
211
+ dbContextDef: TDef,
212
+ config: DbConnConfig,
213
+ options?: OrmOptions,
214
+ ): Orm<TDef>;
206
215
  ```
207
216
 
208
- ### Using low-level connection
217
+ **Parameters:**
209
218
 
210
- ```typescript
211
- import { createDbConn } from "@simplysm/orm-node";
219
+ | Parameter | Type | Description |
220
+ |---|---|---|
221
+ | `dbContextDef` | `DbContextDef` | Definition from `defineDbContext()` |
222
+ | `config` | `DbConnConfig` | Database connection configuration |
223
+ | `options` | `OrmOptions` | Optional overrides for database/schema |
212
224
 
213
- const conn = await createDbConn({
214
- dialect: "postgresql",
215
- host: "localhost",
216
- username: "admin",
217
- password: "secret",
218
- database: "testdb",
219
- });
225
+ #### Orm (interface)
220
226
 
221
- await conn.connect();
222
- try {
223
- const results = await conn.execute(["SELECT * FROM users"]);
224
- } finally {
225
- await conn.close();
227
+ ```typescript
228
+ interface Orm<TDef extends DbContextDef<any, any, any>> {
229
+ readonly dbContextDef: TDef;
230
+ readonly config: DbConnConfig;
231
+ readonly options?: OrmOptions;
232
+
233
+ connect<R>(
234
+ callback: (conn: DbContextInstance<TDef>) => Promise<R>,
235
+ isolationLevel?: IsolationLevel,
236
+ ): Promise<R>;
237
+
238
+ connectWithoutTransaction<R>(
239
+ callback: (conn: DbContextInstance<TDef>) => Promise<R>,
240
+ ): Promise<R>;
226
241
  }
227
242
  ```
243
+
244
+ | Method | Description |
245
+ |---|---|
246
+ | `connect(callback, isolationLevel?)` | Create a new DbContext, connect with transaction, execute callback, auto-commit/rollback, close. |
247
+ | `connectWithoutTransaction(callback)` | Create a new DbContext, connect without transaction, execute callback, close. |
248
+
249
+ #### OrmOptions (interface)
250
+
251
+ | Field | Type | Description |
252
+ |---|---|---|
253
+ | `database` | `string` | Override database name from config |
254
+ | `schema` | `string` | Override schema name from config |
@@ -2,9 +2,9 @@ import { EventEmitter } from "@simplysm/core-common";
2
2
  import type { ColumnMeta, IsolationLevel } from "@simplysm/orm-common";
3
3
  import { type DbConn, type MssqlDbConnConfig } from "../types/db-conn";
4
4
  /**
5
- * MSSQL database connection class
5
+ * MSSQL 데이터베이스 연결 클래스
6
6
  *
7
- * Manages MSSQL/Azure SQL connections using the tedious library.
7
+ * tedious 라이브러리를 사용하여 MSSQL/Azure SQL 연결을 관리한다.
8
8
  */
9
9
  export declare class MssqlDbConn extends EventEmitter<{
10
10
  close: void;
@@ -34,10 +34,10 @@ export declare class MssqlDbConn extends EventEmitter<{
34
34
  private _convertColumnMetaToTediousBulkColumnDef;
35
35
  private _convertDataTypeToTediousBulkColumnType;
36
36
  /**
37
- * Infer the type of a value and return Tedious data type
37
+ * 값의 타입을 추론하여 Tedious 데이터 타입을 반환한다
38
38
  *
39
- * @param value - Value whose type is to be inferred (error if null/undefined is passed)
40
- * @throws Error if null/undefined is passed
39
+ * @param value - 타입을 추론할 (null/undefined 전달 시 오류 발생)
40
+ * @throws null/undefined 전달 시 오류
41
41
  */
42
42
  private _guessTediousType;
43
43
  }