@simplysm/orm-common 14.0.4 → 14.0.6

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,135 +1,163 @@
1
1
  # @simplysm/orm-common
2
2
 
3
- Database-independent ORM providing schema builders, a type-safe query builder, an expression DSL, and multi-dialect support (MySQL, MSSQL, PostgreSQL).
3
+ Platform-neutral ORM module for the Simplysm framework. Provides type-safe query building, schema definition, expression building, and DDL generation for MySQL, MSSQL, and PostgreSQL.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
8
  npm install @simplysm/orm-common
9
+ # or
10
+ pnpm add @simplysm/orm-common
9
11
  ```
10
12
 
11
- ## API Reference
12
-
13
- | Category | Document | Key Exports |
14
- |---|---|---|
15
- | Core | [docs/core.md](docs/core.md) | `defineDbContext`, `createDbContext`, `DbContextDef`, `DbContextInstance`, `DbContextBase`, `DbContextStatus`, `DbContextConnectionMethods`, `DbContextDdlMethods`, `DbTransactionError`, `DbErrorCode` |
16
- | Queryable | [docs/queryable.md](docs/queryable.md) | `Queryable`, `QueryableRecord`, `QueryableWriteRecord`, `NullableQueryableRecord`, `getMatchedPrimaryKeys`, `Executable`, `executable`, `ParsedSearchQuery`, `parseSearchQuery` |
17
- | Expression | [docs/expression.md](docs/expression.md) | `expr`, `SwitchExprBuilder`, `ExprUnit`, `WhereExprUnit`, `ExprInput` |
18
- | Schema Builders | [docs/schema-builders.md](docs/schema-builders.md) | `Table`, `TableBuilder`, `View`, `ViewBuilder`, `Procedure`, `ProcedureBuilder`, `ColumnBuilder`, `createColumnFactory`, `IndexBuilder`, `createIndexFactory`, relation builders, type utilities |
19
- | Query Builder | [docs/query-builder.md](docs/query-builder.md) | `createQueryBuilder`, `QueryBuilderBase`, `ExprRendererBase`, `MysqlQueryBuilder`, `MssqlQueryBuilder`, `PostgresqlQueryBuilder` + renderers |
20
- | Types | [docs/types.md](docs/types.md) | `Dialect`, `IsolationLevel`, `DataRecord`, `DbContextExecutor`, `ResultMeta`, `Migration`, `QueryBuildResult`, `ColumnMeta`, `DataType`, column primitives, QueryDef types, Expr types, `parseQueryResult`, `_Migration` |
21
-
22
- ## Quick Start
23
-
24
- ### Define Schema
13
+ ## API Overview
14
+
15
+ ### Core
16
+
17
+ | Export | Type | Description |
18
+ |--------|------|-------------|
19
+ | [`defineDbContext`](./docs/core.md#definedbcontext) | Function | Create a DbContext definition (blueprint) with tables, views, procedures, and migrations |
20
+ | [`createDbContext`](./docs/core.md#createdbcontext) | Function | Create a DbContext instance from a definition and executor |
21
+ | [`DbTransactionError`](./docs/core.md#dbtransactionerror) | Class | Standardized database transaction error with DBMS-independent error codes |
22
+ | [`DbErrorCode`](./docs/core.md#dberrorcode) | Enum | Transaction error codes |
23
+ | [`_Migration`](./docs/core.md#_migration) | Constant | System migration table definition (TableBuilder) |
24
+
25
+ ### Queryable / Executable
26
+
27
+ | Export | Type | Description |
28
+ |--------|------|-------------|
29
+ | [`Queryable`](./docs/queryable.md#queryable) | Class | Fluent query builder for SELECT, INSERT, UPDATE, DELETE, UPSERT |
30
+ | [`queryable`](./docs/queryable.md#queryable-factory) | Function | Factory to create Queryable accessors for tables/views |
31
+ | [`Executable`](./docs/queryable.md#executable) | Class | Stored procedure execution wrapper |
32
+ | [`executable`](./docs/queryable.md#executable-factory) | Function | Factory to create Executable accessors for procedures |
33
+ | [`parseSearchQuery`](./docs/queryable.md#parsesearchquery) | Function | Parse search query string into SQL LIKE patterns |
34
+ | [`ParsedSearchQuery`](./docs/queryable.md#parsedsearchquery) | Interface | Parsed search query result |
35
+ | [`getMatchedPrimaryKeys`](./docs/queryable.md#getmatchedprimarykeys) | Function | Match FK columns with target table PK columns |
36
+ | [`QueryableRecord`](./docs/queryable.md#queryablerecord) | Type | Maps DataRecord fields to ExprUnit proxies |
37
+ | [`QueryableWriteRecord`](./docs/queryable.md#queryablewriterecord) | Type | Maps DataRecord fields to ExprInput for writes |
38
+ | [`NullableQueryableRecord`](./docs/queryable.md#nullablequeryablerecord) | Type | QueryableRecord with nullable primitives (for LEFT JOIN) |
39
+ | [`UnwrapQueryableRecord`](./docs/queryable.md#unwrapqueryablerecord) | Type | Reverse-map QueryableRecord to DataRecord |
40
+ | [`PathProxy`](./docs/queryable.md#pathproxy) | Type | Type-safe path proxy for `include()` |
41
+
42
+ ### Expression Builder
43
+
44
+ | Export | Type | Description |
45
+ |--------|------|-------------|
46
+ | [`expr`](./docs/expression.md#expr-object) | Object | Dialect-independent SQL expression builder (100+ methods) |
47
+ | [`ExprUnit`](./docs/expression.md#exprunit) | Class | Type-safe expression wrapper |
48
+ | [`WhereExprUnit`](./docs/expression.md#whereexprunit) | Class | WHERE clause expression wrapper |
49
+ | [`ExprInput`](./docs/expression.md#exprinput) | Type | Union of ExprUnit or literal values |
50
+ | [`SwitchExprBuilder`](./docs/expression.md#switchexprbuilder) | Interface | CASE WHEN builder (fluent API) |
51
+
52
+ ### Schema Builders
53
+
54
+ | Export | Type | Description |
55
+ |--------|------|-------------|
56
+ | [`Table`](./docs/schema-builders.md#table-function) | Function | Create a TableBuilder |
57
+ | [`TableBuilder`](./docs/schema-builders.md#tablebuilder) | Class | Fluent API for table definitions |
58
+ | [`View`](./docs/schema-builders.md#view-function) | Function | Create a ViewBuilder |
59
+ | [`ViewBuilder`](./docs/schema-builders.md#viewbuilder) | Class | Fluent API for view definitions |
60
+ | [`Procedure`](./docs/schema-builders.md#procedure-function) | Function | Create a ProcedureBuilder |
61
+ | [`ProcedureBuilder`](./docs/schema-builders.md#procedurebuilder) | Class | Fluent API for stored procedure definitions |
62
+ | [`ColumnBuilder`](./docs/schema-builders.md#columnbuilder) | Class | Column definition builder |
63
+ | [`createColumnFactory`](./docs/schema-builders.md#createcolumnfactory) | Function | Column type factory |
64
+ | [`IndexBuilder`](./docs/schema-builders.md#indexbuilder) | Class | Index definition builder |
65
+ | [`createIndexFactory`](./docs/schema-builders.md#createindexfactory) | Function | Index factory |
66
+ | [`ForeignKeyBuilder`](./docs/schema-builders.md#foreignkeybuilder) | Class | FK relation builder (N:1) |
67
+ | [`ForeignKeyTargetBuilder`](./docs/schema-builders.md#foreignkeytargetbuilder) | Class | FK reverse-reference builder (1:N/1:1) |
68
+ | [`RelationKeyBuilder`](./docs/schema-builders.md#relationkeybuilder) | Class | Logical relation builder (no DB FK) |
69
+ | [`RelationKeyTargetBuilder`](./docs/schema-builders.md#relationkeytargetbuilder) | Class | Logical reverse-reference builder |
70
+ | [`createRelationFactory`](./docs/schema-builders.md#createrelationfactory) | Function | Relation factory |
71
+
72
+ ### Query Builder & Result Parsing
73
+
74
+ | Export | Type | Description |
75
+ |--------|------|-------------|
76
+ | [`createQueryBuilder`](./docs/query-builder.md#createquerybuilder) | Function | Create a dialect-specific QueryBuilder |
77
+ | [`QueryBuilderBase`](./docs/query-builder.md#querybuilderbase) | Abstract Class | Base for QueryDef to SQL rendering |
78
+ | [`MysqlQueryBuilder`](./docs/query-builder.md#dialect-specific-query-builders) | Class | MySQL query builder |
79
+ | [`MssqlQueryBuilder`](./docs/query-builder.md#dialect-specific-query-builders) | Class | MSSQL query builder |
80
+ | [`PostgresqlQueryBuilder`](./docs/query-builder.md#dialect-specific-query-builders) | Class | PostgreSQL query builder |
81
+ | [`ExprRendererBase`](./docs/query-builder.md#exprrendererbase) | Abstract Class | Base for Expr to SQL rendering |
82
+ | [`MysqlExprRenderer`](./docs/query-builder.md#dialect-specific-expression-renderers) | Class | MySQL expression renderer |
83
+ | [`MssqlExprRenderer`](./docs/query-builder.md#dialect-specific-expression-renderers) | Class | MSSQL expression renderer |
84
+ | [`PostgresqlExprRenderer`](./docs/query-builder.md#dialect-specific-expression-renderers) | Class | PostgreSQL expression renderer |
85
+ | [`parseQueryResult`](./docs/query-builder.md#parsequeryresult) | Function | Parse raw DB results into typed objects |
86
+
87
+ ### Types
88
+
89
+ See [Types documentation](./docs/types.md) for all type exports including:
90
+ - Database: `Dialect`, `dialects`, `IsolationLevel`, `DataRecord`, `DbContextExecutor`, `ResultMeta`, `Migration`, `QueryBuildResult`
91
+ - DbContext: `DbContextDef`, `DbContextBase`, `DbContextStatus`, `DbContextInstance`, `DbContextConnectionMethods`, `DbContextDdlMethods`
92
+ - Column: `DataType`, `ColumnPrimitive`, `ColumnPrimitiveStr`, `ColumnPrimitiveMap`, `ColumnMeta`, `dataTypeStrToColumnPrimitiveStr`, `inferColumnPrimitiveStr`, `InferColumnPrimitiveFromDataType`
93
+ - Column Builder: `ColumnBuilderRecord`, `InferColumns`, `InferColumnExprs`, `InferInsertColumns`, `InferUpdateColumns`, `RequiredInsertKeys`, `OptionalInsertKeys`, `DataToColumnBuilderRecord`
94
+ - Relation: `RelationBuilderRecord`, `InferDeepRelations`, `ExtractRelationTarget`, `ExtractRelationTargetResult`
95
+ - Expression: `Expr` (50+ variants), `WhereExpr`, `DateUnit`, `WinFn`, `WinSpec`, all `Expr*` interfaces
96
+ - QueryDef: `QueryDef` (30+ variants), `QueryDefObjectName`, `DDL_TYPES`, `DdlType`, all `*QueryDef` interfaces
97
+
98
+ ## Usage Examples
99
+
100
+ ### Define Schema and DbContext
25
101
 
26
102
  ```typescript
27
- import { Table, defineDbContext, expr } from "@simplysm/orm-common";
103
+ import { Table, defineDbContext, createDbContext, expr } from "@simplysm/orm-common";
28
104
 
29
- // Define tables
30
105
  const User = Table("User")
31
106
  .database("mydb")
32
107
  .columns((c) => ({
33
108
  id: c.bigint().autoIncrement(),
34
109
  name: c.varchar(100),
35
110
  email: c.varchar(200).nullable(),
36
- status: c.varchar(20).default("active"),
37
- createdAt: c.datetime(),
38
- }))
39
- .primaryKey("id")
40
- .indexes((i) => [i.index("email").unique()]);
41
-
42
- const Post = Table("Post")
43
- .database("mydb")
44
- .columns((c) => ({
45
- id: c.bigint().autoIncrement(),
46
- authorId: c.bigint(),
47
- title: c.varchar(200),
48
- content: c.text(),
111
+ companyId: c.bigint(),
49
112
  }))
50
113
  .primaryKey("id")
114
+ .indexes((i) => [i.index("email").unique()])
51
115
  .relations((r) => ({
52
- author: r.foreignKey(["authorId"], () => User),
116
+ company: r.foreignKey(["companyId"], () => Company),
117
+ posts: r.foreignKeyTarget(() => Post, "author"),
53
118
  }));
54
119
 
55
- // Define DbContext
56
- const MyDb = defineDbContext({
57
- tables: { user: User, post: Post },
58
- migrations: [
59
- {
60
- name: "20260105_001_init",
61
- up: async (db) => {
62
- await db.createTable(User);
63
- await db.createTable(Post);
64
- },
65
- },
66
- ],
67
- });
120
+ const MyDb = defineDbContext({ tables: { user: User, post: Post, company: Company } });
121
+ const db = createDbContext(MyDb, executor, { database: "mydb" });
68
122
  ```
69
123
 
70
124
  ### Query Data
71
125
 
72
126
  ```typescript
73
- // Assume db is a DbContextInstance created via createDbContext()
74
-
75
- // SELECT with WHERE
76
- const activeUsers = await db.user()
77
- .where((u) => [expr.eq(u.status, "active")])
78
- .orderBy((u) => u.name)
79
- .execute();
80
-
81
- // JOIN
82
- const postsWithAuthor = await db.post()
83
- .include((p) => p.author)
84
- .execute();
85
-
86
- // Aggregate
87
- const userPostCount = await db.user()
88
- .select((u) => ({
89
- name: u.name,
90
- postCount: expr.count(),
91
- }))
92
- .joinSingle("latestPost", (qr, u) =>
93
- qr.from(Post).where((p) => [expr.eq(p.authorId, u.id)])
94
- )
95
- .groupBy((u) => [u.name])
96
- .execute();
97
-
98
- // INSERT
99
- await db.user().insert([
100
- { name: "Gildong Hong", email: "hong@test.com", createdAt: DateTime.now() },
101
- ]);
102
-
103
- // UPDATE
104
- await db.user()
105
- .where((u) => [expr.eq(u.id, 1)])
106
- .update(() => ({
107
- name: expr.val("string", "New Name"),
108
- }));
127
+ await db.connect(async () => {
128
+ const users = await db.user()
129
+ .where((u) => [expr.eq(u.status, "active")])
130
+ .orderBy((u) => u.name)
131
+ .execute();
109
132
 
110
- // DELETE
111
- await db.user()
112
- .where((u) => [expr.eq(u.status, "deleted")])
113
- .delete();
114
- ```
133
+ const posts = await db.post().include((p) => p.author).execute();
115
134
 
116
- ### Search
135
+ await db.user().insert([{ name: "New User", companyId: 1 }]);
117
136
 
118
- ```typescript
119
- // Text search with operators
120
- const results = await db.user()
121
- .search((u) => [u.name, u.email], "+admin -deleted")
122
- .execute();
137
+ await db.user()
138
+ .where((u) => [expr.eq(u.id, 1)])
139
+ .update(() => ({ name: expr.val("string", "Updated") }));
140
+ });
123
141
  ```
124
142
 
125
- ### Recursive CTE
143
+ ### Expression Builder
126
144
 
127
145
  ```typescript
128
- const hierarchy = await db.employee()
129
- .where((e) => [expr.null(e.managerId)])
130
- .recursive((cte) =>
131
- cte.from(Employee)
132
- .where((e) => [expr.eq(e.managerId, e.self[0].id)])
133
- )
134
- .execute();
146
+ // Window functions
147
+ db.order().select((o) => ({
148
+ ...o,
149
+ rowNum: expr.rowNumber({ partitionBy: [o.userId], orderBy: [[o.createdAt, "DESC"]] }),
150
+ }));
151
+
152
+ // CASE WHEN
153
+ db.user().select((u) => ({
154
+ grade: expr.switch<string>()
155
+ .case(expr.gte(u.score, 90), "A")
156
+ .default("C"),
157
+ }));
158
+
159
+ // Raw SQL
160
+ db.user().select((u) => ({
161
+ data: expr.raw("string")`JSON_EXTRACT(${u.metadata}, '$.email')`,
162
+ }));
135
163
  ```
package/docs/core.md CHANGED
@@ -4,32 +4,32 @@ DbContext definition, creation, and lifecycle management.
4
4
 
5
5
  ## defineDbContext
6
6
 
7
- Factory function that creates a `DbContextDef` blueprint from tables, views, procedures, and migrations. Automatically adds a `_migration` system table.
8
-
9
7
  ```typescript
10
- function defineDbContext<TTables, TViews, TProcedures>(config: {
8
+ function defineDbContext<
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>> = {},
12
+ >(config: {
11
13
  tables?: TTables;
12
14
  views?: TViews;
13
15
  procedures?: TProcedures;
14
16
  migrations?: Migration[];
15
- }): DbContextDef<TTables & { _migration: typeof _Migration }, TViews, TProcedures>;
17
+ }): DbContextDef<TTables & { _migration: typeof _Migration }, TViews, TProcedures>
16
18
  ```
17
19
 
18
- **Parameters:**
20
+ Creates a DbContext definition (blueprint) containing schema metadata. Automatically adds the `_migration` system table. The definition itself has no runtime state.
19
21
 
20
22
  | Parameter | Type | Description |
21
- |---|---|---|
23
+ |-----------|------|-------------|
22
24
  | `config.tables` | `Record<string, TableBuilder>` | Table definitions |
23
25
  | `config.views` | `Record<string, ViewBuilder>` | View definitions |
24
26
  | `config.procedures` | `Record<string, ProcedureBuilder>` | Procedure definitions |
25
27
  | `config.migrations` | `Migration[]` | Migration definitions |
26
28
 
27
- **Example:**
28
-
29
29
  ```typescript
30
30
  const MyDb = defineDbContext({
31
31
  tables: { user: User, post: Post },
32
- views: { userSummary: UserSummary },
32
+ views: { activeUsers: ActiveUsersView },
33
33
  procedures: { getUserById: GetUserById },
34
34
  migrations: [
35
35
  { name: "20260101_001_init", up: async (db) => { await db.createTable(User); } },
@@ -39,161 +39,97 @@ const MyDb = defineDbContext({
39
39
 
40
40
  ## createDbContext
41
41
 
42
- Factory that creates a complete `DbContextInstance` from a `DbContextDef` and a `DbContextExecutor`. The returned instance includes queryable accessors for all tables/views, executable accessors for procedures, connection/transaction management, and DDL methods.
43
-
44
42
  ```typescript
45
43
  function createDbContext<TDef extends DbContextDef<any, any, any>>(
46
44
  def: TDef,
47
45
  executor: DbContextExecutor,
48
46
  opt: { database: string; schema?: string },
49
- ): DbContextInstance<TDef>;
47
+ ): DbContextInstance<TDef>
50
48
  ```
51
49
 
52
- **Parameters:**
50
+ Creates a full DbContext instance from a definition and executor. The returned object provides:
51
+
52
+ - **Queryable accessors** for each table/view (e.g., `db.user()` returns a `Queryable`)
53
+ - **Executable accessors** for each procedure (e.g., `db.getUserById()` returns an `Executable`)
54
+ - **Connection management**: `connect()`, `connectWithoutTransaction()`, `transaction()`
55
+ - **DDL methods**: `createTable()`, `dropTable()`, `addColumn()`, etc. (see `DbContextDdlMethods`)
56
+ - **DDL QueryDef generators**: `getCreateTableQueryDef()`, etc.
57
+ - **Initialize**: `initialize()` runs migrations
53
58
 
54
59
  | Parameter | Type | Description |
55
- |---|---|---|
56
- | `def` | `DbContextDef` | Definition created by `defineDbContext()` |
57
- | `executor` | `DbContextExecutor` | Query executor (e.g., `NodeDbContextExecutor`) |
60
+ |-----------|------|-------------|
61
+ | `def` | `DbContextDef` | Definition from `defineDbContext()` |
62
+ | `executor` | `DbContextExecutor` | Query execution engine (e.g., `NodeDbContextExecutor`) |
58
63
  | `opt.database` | `string` | Database name |
59
- | `opt.schema` | `string` | Schema name (MSSQL: dbo, PostgreSQL: public) |
64
+ | `opt.schema` | `string?` | Schema name (MSSQL: dbo, PostgreSQL: public) |
60
65
 
61
- **Example:**
66
+ ### Connection Methods
62
67
 
63
- ```typescript
64
- const db = createDbContext(MyDb, executor, { database: "mydb" });
65
-
66
- await db.connect(async () => {
67
- const users = await db.user().execute();
68
- });
69
- ```
70
-
71
- ## DbContextDef
72
-
73
- Blueprint interface created by `defineDbContext()`. Contains only schema metadata, no runtime state.
74
-
75
- ```typescript
76
- interface DbContextDef<TTables, TViews, TProcedures> {
77
- readonly meta: {
78
- readonly tables: TTables;
79
- readonly views: TViews;
80
- readonly procedures: TProcedures;
81
- readonly migrations: Migration[];
82
- };
83
- }
84
- ```
85
-
86
- ## DbContextInstance
87
-
88
- Full DbContext instance type returned by `createDbContext()`. Extends `DbContextBase` with queryable accessors, DDL methods, and connection management.
89
-
90
- ```typescript
91
- type DbContextInstance<TDef> = DbContextBase
92
- & DbContextConnectionMethods
93
- & DbContextDdlMethods
94
- & { [K in keyof TDef["meta"]["tables"]]: () => Queryable<...> }
95
- & { [K in keyof TDef["meta"]["views"]]: () => Queryable<...> }
96
- & { [K in keyof TDef["meta"]["procedures"]]: () => Executable<...> }
97
- & {
98
- _migration: () => Queryable<{ code: string }, any>;
99
- initialize(options?: { dbs?: string[]; force?: boolean }): Promise<void>;
100
- };
101
- ```
102
-
103
- ## DbContextBase
104
-
105
- Core interface used internally by Queryable, Executable, and ViewBuilder.
106
-
107
- ```typescript
108
- interface DbContextBase {
109
- status: DbContextStatus;
110
- readonly database: string | undefined;
111
- readonly schema: string | undefined;
112
- getNextAlias(): string;
113
- resetAliasCounter(): void;
114
- executeDefs<T = DataRecord>(defs: QueryDef[], resultMetas?: (ResultMeta | undefined)[]): Promise<T[][]>;
115
- getQueryDefObjectName(tableOrView: TableBuilder | ViewBuilder): QueryDefObjectName;
116
- switchFk(table: QueryDefObjectName, enabled: boolean): Promise<void>;
117
- }
118
- ```
119
-
120
- ## DbContextStatus
121
-
122
- ```typescript
123
- type DbContextStatus = "ready" | "connect" | "transact";
124
- ```
125
-
126
- | Value | Description |
127
- |---|---|
128
- | `"ready"` | Not connected |
129
- | `"connect"` | Connected, no active transaction |
130
- | `"transact"` | Inside a transaction |
131
-
132
- ## DbContextConnectionMethods
68
+ | Method | Signature | Description |
69
+ |--------|-----------|-------------|
70
+ | `connect` | `<R>(fn: () => Promise<R>, isolationLevel?: IsolationLevel) => Promise<R>` | Connect, begin transaction, execute callback, commit (auto-rollback on error) |
71
+ | `connectWithoutTransaction` | `<R>(fn: () => Promise<R>) => Promise<R>` | Connect without transaction, execute callback, close |
72
+ | `transaction` | `<R>(fn: () => Promise<R>, isolationLevel?: IsolationLevel) => Promise<R>` | Begin transaction within existing connection (for use inside `connectWithoutTransaction`) |
73
+
74
+ ### DDL Execution Methods
75
+
76
+ | Method | Signature |
77
+ |--------|-----------|
78
+ | `createTable` | `(table: TableBuilder) => Promise<void>` |
79
+ | `dropTable` | `(table: QueryDefObjectName) => Promise<void>` |
80
+ | `renameTable` | `(table: QueryDefObjectName, newName: string) => Promise<void>` |
81
+ | `createView` | `(view: ViewBuilder) => Promise<void>` |
82
+ | `dropView` | `(view: QueryDefObjectName) => Promise<void>` |
83
+ | `createProc` | `(procedure: ProcedureBuilder) => Promise<void>` |
84
+ | `dropProc` | `(procedure: QueryDefObjectName) => Promise<void>` |
85
+ | `addColumn` | `(table: QueryDefObjectName, columnName: string, column: ColumnBuilder) => Promise<void>` |
86
+ | `dropColumn` | `(table: QueryDefObjectName, column: string) => Promise<void>` |
87
+ | `modifyColumn` | `(table: QueryDefObjectName, columnName: string, column: ColumnBuilder) => Promise<void>` |
88
+ | `renameColumn` | `(table: QueryDefObjectName, column: string, newName: string) => Promise<void>` |
89
+ | `addPrimaryKey` | `(table: QueryDefObjectName, columns: string[]) => Promise<void>` |
90
+ | `dropPrimaryKey` | `(table: QueryDefObjectName) => Promise<void>` |
91
+ | `addForeignKey` | `(table: QueryDefObjectName, relationName: string, relationDef: ForeignKeyBuilder) => Promise<void>` |
92
+ | `addIndex` | `(table: QueryDefObjectName, indexBuilder: IndexBuilder) => Promise<void>` |
93
+ | `dropForeignKey` | `(table: QueryDefObjectName, relationName: string) => Promise<void>` |
94
+ | `dropIndex` | `(table: QueryDefObjectName, columns: string[]) => Promise<void>` |
95
+ | `clearSchema` | `(params: { database: string; schema?: string }) => Promise<void>` |
96
+ | `schemaExists` | `(database: string, schema?: string) => Promise<boolean>` |
97
+ | `truncate` | `(table: QueryDefObjectName) => Promise<void>` |
98
+ | `switchFk` | `(table: QueryDefObjectName, enabled: boolean) => Promise<void>` |
99
+
100
+ ### DDL QueryDef Generators
101
+
102
+ Each DDL method has a corresponding `get*QueryDef` method that returns a `QueryDef` without executing it. For example: `getCreateTableQueryDef(table)`, `getDropTableQueryDef(table)`, etc.
103
+
104
+ ### Initialize
133
105
 
134
106
  ```typescript
135
- interface DbContextConnectionMethods {
136
- connect<TResult>(fn: () => Promise<TResult>, isolationLevel?: IsolationLevel): Promise<TResult>;
137
- connectWithoutTransaction<TResult>(callback: () => Promise<TResult>): Promise<TResult>;
138
- transaction<TResult>(fn: () => Promise<TResult>, isolationLevel?: IsolationLevel): Promise<TResult>;
139
- }
107
+ async initialize(options?: { dbs?: string[]; force?: boolean }): Promise<void>
140
108
  ```
141
109
 
142
- | Method | Description |
143
- |---|---|
144
- | `connect(fn, isolationLevel?)` | Connect, begin transaction, execute `fn`, commit. Auto-rollback on error. |
145
- | `connectWithoutTransaction(fn)` | Connect and execute `fn` without a transaction. For DDL or read-only operations. |
146
- | `transaction(fn, isolationLevel?)` | Begin a nested transaction within an existing connection. Use inside `connectWithoutTransaction`. |
147
-
148
- ## DbContextDdlMethods
149
-
150
- DDL execution methods and QueryDef generators on `DbContextInstance`.
151
-
152
- ### Execution Methods
153
-
154
- | Method | Signature | Description |
155
- |---|---|---|
156
- | `createTable` | `(table: TableBuilder) => Promise<void>` | Create a table |
157
- | `dropTable` | `(table: QueryDefObjectName) => Promise<void>` | Drop a table |
158
- | `renameTable` | `(table: QueryDefObjectName, newName: string) => Promise<void>` | Rename a table |
159
- | `createView` | `(view: ViewBuilder) => Promise<void>` | Create a view |
160
- | `dropView` | `(view: QueryDefObjectName) => Promise<void>` | Drop a view |
161
- | `createProc` | `(procedure: ProcedureBuilder) => Promise<void>` | Create a stored procedure |
162
- | `dropProc` | `(procedure: QueryDefObjectName) => Promise<void>` | Drop a stored procedure |
163
- | `addColumn` | `(table, columnName, column: ColumnBuilder) => Promise<void>` | Add a column |
164
- | `dropColumn` | `(table, column: string) => Promise<void>` | Drop a column |
165
- | `modifyColumn` | `(table, columnName, column: ColumnBuilder) => Promise<void>` | Modify a column |
166
- | `renameColumn` | `(table, column, newName) => Promise<void>` | Rename a column |
167
- | `addPrimaryKey` | `(table, columns: string[]) => Promise<void>` | Add primary key |
168
- | `dropPrimaryKey` | `(table) => Promise<void>` | Drop primary key |
169
- | `addForeignKey` | `(table, relationName, relationDef: ForeignKeyBuilder) => Promise<void>` | Add foreign key |
170
- | `addIndex` | `(table, indexBuilder: IndexBuilder) => Promise<void>` | Add index |
171
- | `dropForeignKey` | `(table, relationName) => Promise<void>` | Drop foreign key |
172
- | `dropIndex` | `(table, columns: string[]) => Promise<void>` | Drop index |
173
- | `clearSchema` | `(params: { database; schema? }) => Promise<void>` | Clear all objects in schema |
174
- | `schemaExists` | `(database, schema?) => Promise<boolean>` | Check if schema exists |
175
- | `truncate` | `(table) => Promise<void>` | Truncate table |
176
- | `switchFk` | `(table, enabled: boolean) => Promise<void>` | Enable/disable FK constraints |
177
-
178
- ### QueryDef Generator Methods
179
-
180
- Each DDL execution method has a corresponding `get*QueryDef` method (e.g., `getCreateTableQueryDef`, `getDropTableQueryDef`) that returns a `QueryDef` without executing it. These are useful for building migration scripts or batching DDL operations.
110
+ Runs pending migrations. If `force` is true, drops and recreates the schema.
181
111
 
182
112
  ## DbTransactionError
183
113
 
184
- Standardized transaction error that wraps DBMS-native errors with a `DbErrorCode`.
185
-
186
114
  ```typescript
187
115
  class DbTransactionError extends Error {
188
116
  readonly name = "DbTransactionError";
189
117
  constructor(
190
- readonly code: DbErrorCode,
118
+ public readonly code: DbErrorCode,
191
119
  message: string,
192
- readonly originalError?: unknown,
193
- );
120
+ public readonly originalError?: unknown,
121
+ )
194
122
  }
195
123
  ```
196
124
 
125
+ Wraps DBMS-native transaction errors into standardized error codes.
126
+
127
+ | Field | Type | Description |
128
+ |-------|------|-------------|
129
+ | `code` | `DbErrorCode` | Standardized error code |
130
+ | `message` | `string` | Error message |
131
+ | `originalError` | `unknown?` | Original DBMS error (for debugging) |
132
+
197
133
  ## DbErrorCode
198
134
 
199
135
  ```typescript
@@ -204,3 +140,18 @@ enum DbErrorCode {
204
140
  LOCK_TIMEOUT = "LOCK_TIMEOUT",
205
141
  }
206
142
  ```
143
+
144
+ | Value | Description |
145
+ |-------|-------------|
146
+ | `NO_ACTIVE_TRANSACTION` | No active transaction (e.g., rollback when no transaction) |
147
+ | `TRANSACTION_ALREADY_STARTED` | Transaction already started |
148
+ | `DEADLOCK` | Deadlock detected |
149
+ | `LOCK_TIMEOUT` | Lock timeout exceeded |
150
+
151
+ ## _Migration
152
+
153
+ ```typescript
154
+ const _Migration: TableBuilder<{ code: ColumnBuilder<string, ...> }, {}>
155
+ ```
156
+
157
+ System migration tracking table. Automatically added to every DbContext via `defineDbContext()`. Has a single `code` column (VARCHAR(255)) as primary key, storing executed migration names.