@simplysm/orm-common 13.0.98 → 13.0.99

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/docs/core.md CHANGED
@@ -1,18 +1,14 @@
1
1
  # Core
2
2
 
3
- Database context definition, creation, and lifecycle management.
3
+ ## `defineDbContext`
4
4
 
5
- Source: `src/define-db-context.ts`, `src/create-db-context.ts`, `src/types/db-context-def.ts`, `src/errors/db-transaction-error.ts`
6
-
7
- ## defineDbContext
8
-
9
- Create a `DbContextDef` blueprint from tables, views, procedures, and migrations. Automatically includes the `_migration` system table.
5
+ Factory function that creates a DbContext definition (blueprint). Takes table, view, procedure builders and migration definitions. Automatically includes the `_migration` system table.
10
6
 
11
7
  ```typescript
12
8
  function defineDbContext<
13
- TTables extends Record<string, TableBuilder<any, any>>,
14
- TViews extends Record<string, ViewBuilder<any, any, any>>,
15
- TProcedures extends Record<string, ProcedureBuilder<any, any>>,
9
+ TTables extends Record<string, TableBuilder<any, any>> = {},
10
+ TViews extends Record<string, ViewBuilder<any, any, any>> = {},
11
+ TProcedures extends Record<string, ProcedureBuilder<any, any>> = {},
16
12
  >(config: {
17
13
  tables?: TTables;
18
14
  views?: TViews;
@@ -21,32 +17,18 @@ function defineDbContext<
21
17
  }): DbContextDef<TTables & { _migration: typeof _Migration }, TViews, TProcedures>;
22
18
  ```
23
19
 
24
- **Example:**
25
-
26
- ```typescript
27
- const MyDb = defineDbContext({
28
- tables: { user: User, post: Post },
29
- views: { userSummary: UserSummary },
30
- procedures: { getUserById: GetUserById },
31
- migrations: [
32
- { name: "20260101_001_init", up: async (db) => { await db.createTable(User); } },
33
- ],
34
- });
35
- ```
20
+ | Parameter | Type | Description |
21
+ |-----------|------|-------------|
22
+ | `config.tables` | `TTables` | Table builder definitions |
23
+ | `config.views` | `TViews` | View builder definitions |
24
+ | `config.procedures` | `TProcedures` | Procedure builder definitions |
25
+ | `config.migrations` | `Migration[]` | Migration definitions |
36
26
 
37
- ## createDbContext
27
+ ## `createDbContext`
38
28
 
39
- Create a runtime `DbContextInstance` from a definition and executor. This is the main entry point for database operations.
29
+ DbContext instance factory. Takes a `DbContextDef` and `DbContextExecutor` and creates a complete DbContext instance with queryable accessors, DDL methods, and connection/transaction management.
40
30
 
41
31
  ```typescript
42
- /**
43
- * @param def - Definition object created by defineDbContext()
44
- * @param executor - Query executor (NodeDbContextExecutor, ServiceDbContextExecutor, etc.)
45
- * @param opt - Database options
46
- * @param opt.database - Database name
47
- * @param opt.schema - Schema name (MSSQL: dbo, PostgreSQL: public)
48
- * @returns A complete DbContext instance
49
- */
50
32
  function createDbContext<TDef extends DbContextDef<any, any, any>>(
51
33
  def: TDef,
52
34
  executor: DbContextExecutor,
@@ -54,27 +36,42 @@ function createDbContext<TDef extends DbContextDef<any, any, any>>(
54
36
  ): DbContextInstance<TDef>;
55
37
  ```
56
38
 
57
- The returned instance provides:
39
+ | Parameter | Type | Description |
40
+ |-----------|------|-------------|
41
+ | `def` | `TDef` | Definition object created by `defineDbContext()` |
42
+ | `executor` | `DbContextExecutor` | Query executor implementation |
43
+ | `opt.database` | `string` | Database name |
44
+ | `opt.schema` | `string` | Schema name (MSSQL: dbo, PostgreSQL: public) |
58
45
 
59
- - **Queryable accessors** -- one per table/view (e.g., `db.user()` returns a `Queryable`)
60
- - **Executable accessors** -- one per procedure (e.g., `db.getUserById()` returns an `Executable`)
61
- - **Connection management** -- `connect()`, `connectWithoutTransaction()`, `transaction()`
62
- - **DDL methods** -- `createTable()`, `dropTable()`, `addColumn()`, `addIndex()`, etc.
63
- - **Initialization** -- `initialize()` to run migrations
46
+ ## `DbContextDef`
64
47
 
65
- **Example:**
48
+ DbContext definition (blueprint). Created by `defineDbContext()`. Contains schema metadata but no runtime state.
66
49
 
67
50
  ```typescript
68
- const db = createDbContext(MyDb, executor, { database: "mydb" });
69
-
70
- await db.connect(async () => {
71
- const users = await db.user().execute();
72
- });
51
+ interface DbContextDef<
52
+ TTables extends Record<string, TableBuilder<any, any>>,
53
+ TViews extends Record<string, ViewBuilder<any, any, any>>,
54
+ TProcedures extends Record<string, ProcedureBuilder<any, any>> = {},
55
+ > {
56
+ readonly meta: {
57
+ readonly tables: TTables;
58
+ readonly views: TViews;
59
+ readonly procedures: TProcedures;
60
+ readonly migrations: Migration[];
61
+ };
62
+ }
73
63
  ```
74
64
 
75
- ## DbContextBase
65
+ | Field | Type | Description |
66
+ |-------|------|-------------|
67
+ | `meta.tables` | `TTables` | Table builder definitions |
68
+ | `meta.views` | `TViews` | View builder definitions |
69
+ | `meta.procedures` | `TProcedures` | Procedure builder definitions |
70
+ | `meta.migrations` | `Migration[]` | Migration definitions |
71
+
72
+ ## `DbContextBase`
76
73
 
77
- Internal interface satisfied by the DbContext instance. Used by `Queryable`, `Executable`, and `ViewBuilder`.
74
+ Internal interface used by Queryable, Executable, and ViewBuilder.
78
75
 
79
76
  ```typescript
80
77
  interface DbContextBase {
@@ -94,28 +91,28 @@ interface DbContextBase {
94
91
  }
95
92
  ```
96
93
 
97
- ## DbContextDef
94
+ | Field | Type | Description |
95
+ |-------|------|-------------|
96
+ | `status` | `DbContextStatus` | Current connection status |
97
+ | `database` | `string \| undefined` | Database name |
98
+ | `schema` | `string \| undefined` | Schema name |
99
+ | `getNextAlias()` | `() => string` | Generate next table alias |
100
+ | `resetAliasCounter()` | `() => void` | Reset alias counter |
101
+ | `executeDefs()` | `(defs, resultMetas?) => Promise<T[][]>` | Execute query definitions |
102
+ | `getQueryDefObjectName()` | `(tableOrView) => QueryDefObjectName` | Get qualified object name |
103
+ | `switchFk()` | `(table, enabled) => Promise<void>` | Enable/disable FK constraints |
98
104
 
99
- Definition (blueprint) created by `defineDbContext()`. Contains schema metadata but no runtime state.
105
+ ## `DbContextStatus`
106
+
107
+ Connection status type.
100
108
 
101
109
  ```typescript
102
- interface DbContextDef<
103
- TTables extends Record<string, TableBuilder<any, any>>,
104
- TViews extends Record<string, ViewBuilder<any, any, any>>,
105
- TProcedures extends Record<string, ProcedureBuilder<any, any>>,
106
- > {
107
- readonly meta: {
108
- readonly tables: TTables;
109
- readonly views: TViews;
110
- readonly procedures: TProcedures;
111
- readonly migrations: Migration[];
112
- };
113
- }
110
+ type DbContextStatus = "ready" | "connect" | "transact";
114
111
  ```
115
112
 
116
- ## DbContextInstance
113
+ ## `DbContextInstance`
117
114
 
118
- Full runtime type created by `createDbContext`. Combines `DbContextBase`, connection methods, DDL methods, and auto-mapped queryable/executable accessors.
115
+ Full DbContext instance type created by `createDbContext`. Extends `DbContextBase` with queryable accessors for tables/views, executable accessors for procedures, DDL methods, and connection/transaction management.
119
116
 
120
117
  ```typescript
121
118
  type DbContextInstance<TDef extends DbContextDef<any, any, any>> = DbContextBase &
@@ -132,64 +129,84 @@ type DbContextInstance<TDef extends DbContextDef<any, any, any>> = DbContextBase
132
129
  };
133
130
  ```
134
131
 
135
- ### Connection Methods
132
+ ## `DbContextConnectionMethods`
133
+
134
+ Connection and transaction management methods.
136
135
 
137
136
  ```typescript
138
137
  interface DbContextConnectionMethods {
139
- /** Execute within a transaction (auto commit/rollback) */
140
138
  connect<TResult>(fn: () => Promise<TResult>, isolationLevel?: IsolationLevel): Promise<TResult>;
141
-
142
- /** Connect without transaction (for DDL or read-only operations) */
143
139
  connectWithoutTransaction<TResult>(callback: () => Promise<TResult>): Promise<TResult>;
144
-
145
- /** Start a transaction within an already-connected state */
146
140
  transaction<TResult>(fn: () => Promise<TResult>, isolationLevel?: IsolationLevel): Promise<TResult>;
147
141
  }
148
142
  ```
149
143
 
150
- ### DDL Methods
151
-
152
- The instance exposes DDL execution methods and their corresponding QueryDef generators:
153
-
154
144
  | Method | Description |
155
145
  |--------|-------------|
156
- | `createTable(table)` | CREATE TABLE |
157
- | `dropTable(table)` | DROP TABLE |
158
- | `renameTable(table, newName)` | RENAME TABLE |
159
- | `createView(view)` | CREATE VIEW |
160
- | `dropView(view)` | DROP VIEW |
161
- | `createProc(procedure)` | CREATE PROCEDURE |
162
- | `dropProc(procedure)` | DROP PROCEDURE |
163
- | `addColumn(table, name, column)` | ADD COLUMN |
164
- | `dropColumn(table, column)` | DROP COLUMN |
165
- | `modifyColumn(table, name, column)` | MODIFY COLUMN |
166
- | `renameColumn(table, column, newName)` | RENAME COLUMN |
167
- | `addPrimaryKey(table, columns)` | ADD PRIMARY KEY |
168
- | `dropPrimaryKey(table)` | DROP PRIMARY KEY |
169
- | `addForeignKey(table, name, def)` | ADD FOREIGN KEY |
170
- | `dropForeignKey(table, name)` | DROP FOREIGN KEY |
171
- | `addIndex(table, indexBuilder)` | CREATE INDEX |
172
- | `dropIndex(table, columns)` | DROP INDEX |
173
- | `clearSchema(params)` | Clear all objects in schema |
174
- | `schemaExists(database, schema?)` | Check schema existence |
175
- | `truncate(table)` | TRUNCATE TABLE |
176
- | `switchFk(table, enabled)` | Enable/disable FK constraints |
177
-
178
- ## DbContextStatus
146
+ | `connect()` | Execute callback within a transaction (auto commit/rollback) |
147
+ | `connectWithoutTransaction()` | Connect without transaction, execute callback, auto-close |
148
+ | `transaction()` | Start transaction in already-connected state (auto commit/rollback) |
149
+
150
+ ## `DbContextDdlMethods`
151
+
152
+ DDL execution methods and QueryDef generators for tables, views, procedures, columns, indexes, foreign keys, and schema operations.
179
153
 
180
154
  ```typescript
181
- type DbContextStatus = "ready" | "connect" | "transact";
155
+ interface DbContextDdlMethods {
156
+ createTable(table: TableBuilder<any, any>): Promise<void>;
157
+ dropTable(table: QueryDefObjectName): Promise<void>;
158
+ renameTable(table: QueryDefObjectName, newName: string): Promise<void>;
159
+ createView(view: ViewBuilder<any, any, any>): Promise<void>;
160
+ dropView(view: QueryDefObjectName): Promise<void>;
161
+ createProc(procedure: ProcedureBuilder<any, any>): Promise<void>;
162
+ dropProc(procedure: QueryDefObjectName): Promise<void>;
163
+ addColumn(table: QueryDefObjectName, columnName: string, column: ColumnBuilder<any, any>): Promise<void>;
164
+ dropColumn(table: QueryDefObjectName, column: string): Promise<void>;
165
+ modifyColumn(table: QueryDefObjectName, columnName: string, column: ColumnBuilder<any, any>): Promise<void>;
166
+ renameColumn(table: QueryDefObjectName, column: string, newName: string): Promise<void>;
167
+ addPrimaryKey(table: QueryDefObjectName, columns: string[]): Promise<void>;
168
+ dropPrimaryKey(table: QueryDefObjectName): Promise<void>;
169
+ addForeignKey(table: QueryDefObjectName, relationName: string, relationDef: ForeignKeyBuilder<any, any>): Promise<void>;
170
+ addIndex(table: QueryDefObjectName, indexBuilder: IndexBuilder<string[]>): Promise<void>;
171
+ dropForeignKey(table: QueryDefObjectName, relationName: string): Promise<void>;
172
+ dropIndex(table: QueryDefObjectName, columns: string[]): Promise<void>;
173
+ clearSchema(params: { database: string; schema?: string }): Promise<void>;
174
+ schemaExists(database: string, schema?: string): Promise<boolean>;
175
+ truncate(table: QueryDefObjectName): Promise<void>;
176
+ switchFk(table: QueryDefObjectName, enabled: boolean): Promise<void>;
177
+ // QueryDef generators (get*QueryDef methods for each DDL operation)
178
+ getCreateTableQueryDef(table: TableBuilder<any, any>): QueryDef;
179
+ getCreateViewQueryDef(view: ViewBuilder<any, any, any>): QueryDef;
180
+ getCreateProcQueryDef(procedure: ProcedureBuilder<any, any>): QueryDef;
181
+ getCreateObjectQueryDef(builder: TableBuilder | ViewBuilder | ProcedureBuilder): QueryDef;
182
+ getDropTableQueryDef(table: QueryDefObjectName): QueryDef;
183
+ getRenameTableQueryDef(table: QueryDefObjectName, newName: string): QueryDef;
184
+ getDropViewQueryDef(view: QueryDefObjectName): QueryDef;
185
+ getDropProcQueryDef(procedure: QueryDefObjectName): QueryDef;
186
+ getAddColumnQueryDef(table: QueryDefObjectName, columnName: string, column: ColumnBuilder<any, any>): QueryDef;
187
+ getDropColumnQueryDef(table: QueryDefObjectName, column: string): QueryDef;
188
+ getModifyColumnQueryDef(table: QueryDefObjectName, columnName: string, column: ColumnBuilder<any, any>): QueryDef;
189
+ getRenameColumnQueryDef(table: QueryDefObjectName, column: string, newName: string): QueryDef;
190
+ getAddPrimaryKeyQueryDef(table: QueryDefObjectName, columns: string[]): QueryDef;
191
+ getDropPrimaryKeyQueryDef(table: QueryDefObjectName): QueryDef;
192
+ getAddForeignKeyQueryDef(table: QueryDefObjectName, relationName: string, relationDef: ForeignKeyBuilder<any, any>): QueryDef;
193
+ getAddIndexQueryDef(table: QueryDefObjectName, indexBuilder: IndexBuilder<string[]>): QueryDef;
194
+ getDropForeignKeyQueryDef(table: QueryDefObjectName, relationName: string): QueryDef;
195
+ getDropIndexQueryDef(table: QueryDefObjectName, columns: string[]): QueryDef;
196
+ getClearSchemaQueryDef(params: { database: string; schema?: string }): QueryDef;
197
+ getSchemaExistsQueryDef(database: string, schema?: string): QueryDef;
198
+ getTruncateQueryDef(table: QueryDefObjectName): QueryDef;
199
+ getSwitchFkQueryDef(table: QueryDefObjectName, enabled: boolean): QueryDef;
200
+ }
182
201
  ```
183
202
 
184
- Lifecycle: `ready` -> `connect` -> `transact` -> `connect` -> `ready`
185
-
186
- ## DbTransactionError
203
+ ## `DbTransactionError`
187
204
 
188
- Standardized transaction error wrapping DBMS-specific native errors.
205
+ Database transaction error with standardized error codes for DBMS-independent error handling.
189
206
 
190
207
  ```typescript
191
208
  class DbTransactionError extends Error {
192
- readonly name = "DbTransactionError";
209
+ override readonly name = "DbTransactionError";
193
210
  constructor(
194
211
  public readonly code: DbErrorCode,
195
212
  message: string,
@@ -198,7 +215,14 @@ class DbTransactionError extends Error {
198
215
  }
199
216
  ```
200
217
 
201
- ## DbErrorCode
218
+ | Property | Type | Description |
219
+ |----------|------|-------------|
220
+ | `code` | `DbErrorCode` | Standardized error code |
221
+ | `originalError` | `unknown` | Original DBMS error (for debugging) |
222
+
223
+ ## `DbErrorCode`
224
+
225
+ Transaction-related error codes.
202
226
 
203
227
  ```typescript
204
228
  enum DbErrorCode {
@@ -208,18 +232,3 @@ enum DbErrorCode {
208
232
  LOCK_TIMEOUT = "LOCK_TIMEOUT",
209
233
  }
210
234
  ```
211
-
212
- **Example:**
213
-
214
- ```typescript
215
- try {
216
- await executor.rollbackTransaction();
217
- } catch (err) {
218
- if (err instanceof DbTransactionError) {
219
- if (err.code === DbErrorCode.NO_ACTIVE_TRANSACTION) {
220
- return; // Already rolled back
221
- }
222
- }
223
- throw err;
224
- }
225
- ```