@simplysm/orm-common 13.0.98 → 13.0.100

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,8 +1,8 @@
1
1
  # @simplysm/orm-common
2
2
 
3
- ORM Module (common) -- dialect-independent ORM for MySQL, MSSQL, and PostgreSQL.
3
+ Simplysm Package - ORM Module (common)
4
4
 
5
- Provides schema definition, type-safe query building, expression construction, and query rendering without any direct database dependency. Actual database execution is handled by `@simplysm/orm-node`.
5
+ Dialect-independent ORM for MySQL, MSSQL, and PostgreSQL. Provides schema definition, type-safe query building, expression construction, and query rendering without any direct database dependency. Actual database execution is handled by `@simplysm/orm-node`.
6
6
 
7
7
  ## Installation
8
8
 
@@ -10,145 +10,139 @@ Provides schema definition, type-safe query building, expression construction, a
10
10
  npm install @simplysm/orm-common
11
11
  ```
12
12
 
13
- ## API Reference
13
+ ## API Overview
14
14
 
15
15
  ### Core
16
-
17
- Define and create database contexts with connection/transaction management.
18
-
19
- | Export | Kind | Description |
20
- |--------|------|-------------|
21
- | `defineDbContext` | function | Create a DbContext definition (blueprint) from tables, views, procedures, and migrations |
22
- | `createDbContext` | function | Create a runtime DbContext instance from a definition and executor |
23
- | `DbContextBase` | interface | Internal interface used by Queryable/Executable (status, database, schema, executeDefs) |
24
- | `DbContextDef` | interface | DbContext definition holding schema metadata (tables, views, procedures, migrations) |
25
- | `DbContextInstance` | type | Full runtime instance with queryable accessors, DDL methods, and connection management |
26
- | `DbContextStatus` | type | `"ready" \| "connect" \| "transact"` |
27
- | `DbTransactionError` | class | Standardized transaction error with `DbErrorCode` |
28
- | `DbErrorCode` | enum | `NO_ACTIVE_TRANSACTION`, `TRANSACTION_ALREADY_STARTED`, `DEADLOCK`, `LOCK_TIMEOUT` |
29
-
30
- [Detailed documentation](docs/core.md)
16
+ | API | Type | Description |
17
+ |-----|------|-------------|
18
+ | `defineDbContext` | function | Create a DbContext definition (blueprint) |
19
+ | `createDbContext` | function | Create a DbContext instance from definition + executor |
20
+ | `DbContextDef` | interface | DbContext definition (schema metadata, no runtime state) |
21
+ | `DbContextBase` | interface | Internal interface used by Queryable/Executable |
22
+ | `DbContextStatus` | type | Connection status: `"ready" \| "connect" \| "transact"` |
23
+ | `DbContextInstance` | type | Full DbContext instance with accessors and methods |
24
+ | `DbContextConnectionMethods` | interface | connect/connectWithoutTransaction/transaction methods |
25
+ | `DbContextDdlMethods` | interface | DDL execution and QueryDef generation methods |
26
+ | `DbTransactionError` | class | Standardized transaction error with error codes |
27
+ | `DbErrorCode` | enum | Transaction error codes (NO_ACTIVE_TRANSACTION, DEADLOCK, etc.) |
28
+
29
+ -> See [docs/core.md](./docs/core.md) for details.
31
30
 
32
31
  ### Queryable / Executable
33
-
34
- Build and execute SELECT, INSERT, UPDATE, DELETE, and UPSERT queries with full type safety.
35
-
36
- | Export | Kind | Description |
37
- |--------|------|-------------|
38
- | `Queryable` | class | Chaining query builder (select, where, join, include, orderBy, limit, groupBy, etc.) |
39
- | `queryable` | function | Factory that creates a Queryable getter for a table or view |
40
- | `getMatchedPrimaryKeys` | function | Match FK columns to target table PK columns |
32
+ | API | Type | Description |
33
+ |-----|------|-------------|
34
+ | `Queryable` | class | Type-safe query builder (SELECT/INSERT/UPDATE/DELETE) |
35
+ | `queryable` | function | Factory to create Queryable accessor for DbContext |
41
36
  | `Executable` | class | Stored procedure execution wrapper |
42
- | `executable` | function | Factory that creates an Executable getter for a procedure |
43
- | `parseSearchQuery` | function | Parse search text into LIKE patterns (OR / +must / -not) |
44
- | `ParsedSearchQuery` | interface | Result of `parseSearchQuery` with `or`, `must`, `not` arrays |
37
+ | `executable` | function | Factory to create Executable accessor for DbContext |
38
+ | `parseSearchQuery` | function | Parse search query string to SQL LIKE patterns |
39
+ | `ParsedSearchQuery` | interface | Search query parsing result (or/must/not arrays) |
45
40
 
46
- [Detailed documentation](docs/queryable.md)
41
+ -> See [docs/queryable.md](./docs/queryable.md) for details.
47
42
 
48
43
  ### Expression
49
-
50
- Dialect-independent SQL expression builder producing JSON AST.
51
-
52
- | Export | Kind | Description |
53
- |--------|------|-------------|
54
- | `expr` | const | Expression builder with 70+ methods (comparisons, string, math, date, aggregate, window) |
55
- | `ExprUnit` | class | Type-safe expression wrapper tracking return type via generics |
44
+ | API | Type | Description |
45
+ |-----|------|-------------|
46
+ | `expr` | object | Dialect-independent SQL expression builder |
47
+ | `ExprUnit` | class | Type-safe expression wrapper |
56
48
  | `WhereExprUnit` | class | WHERE clause expression wrapper |
57
- | `ExprInput` | type | Accepts `ExprUnit<T>` or literal `T` |
58
- | `SwitchExprBuilder` | interface | CASE WHEN builder returned by `expr.switch()` |
49
+ | `ExprInput` | type | Input type accepting ExprUnit or literal |
50
+ | `SwitchExprBuilder` | interface | CASE/WHEN expression builder |
59
51
 
60
- [Detailed documentation](docs/expression.md)
52
+ -> See [docs/expression.md](./docs/expression.md) for details.
61
53
 
62
54
  ### Schema Builders
63
-
64
- Define tables, views, procedures, columns, indexes, and relations via fluent API.
65
-
66
- | Export | Kind | Description |
67
- |--------|------|-------------|
68
- | `Table` | function | Create a `TableBuilder` for a table |
69
- | `TableBuilder` | class | Fluent builder: `.database()`, `.columns()`, `.primaryKey()`, `.indexes()`, `.relations()` |
70
- | `View` | function | Create a `ViewBuilder` for a view |
71
- | `ViewBuilder` | class | Fluent builder: `.database()`, `.query()`, `.relations()` |
72
- | `Procedure` | function | Create a `ProcedureBuilder` for a stored procedure |
73
- | `ProcedureBuilder` | class | Fluent builder: `.database()`, `.params()`, `.returns()`, `.body()` |
74
- | `ColumnBuilder` | class | Column definition: `.autoIncrement()`, `.nullable()`, `.default()`, `.description()` |
75
- | `createColumnFactory` | function | Returns column type methods (int, bigint, varchar, text, datetime, etc.) |
76
- | `IndexBuilder` | class | Index definition: `.name()`, `.unique()`, `.orderBy()`, `.description()` |
77
- | `createIndexFactory` | function | Returns `{ index(...columns) }` |
78
- | `ForeignKeyBuilder` | class | N:1 FK relation (creates DB constraint) |
79
- | `ForeignKeyTargetBuilder` | class | 1:N FK reverse-reference with `.single()` |
80
- | `RelationKeyBuilder` | class | N:1 logical relation (no DB constraint) |
81
- | `RelationKeyTargetBuilder` | class | 1:N logical reverse-reference with `.single()` |
82
- | `createRelationFactory` | function | Returns FK + RelationKey methods (table gets both, view gets RelationKey only) |
83
- | `_Migration` | const | Built-in system migration table (`_migration` with `code` column) |
84
-
85
- [Detailed documentation](docs/schema-builders.md)
55
+ | API | Type | Description |
56
+ |-----|------|-------------|
57
+ | `Table` | function | Table builder factory |
58
+ | `TableBuilder` | class | Table definition builder (columns, PK, indexes, relations) |
59
+ | `View` | function | View builder factory |
60
+ | `ViewBuilder` | class | View definition builder (query, relations) |
61
+ | `Procedure` | function | Procedure builder factory |
62
+ | `ProcedureBuilder` | class | Stored procedure definition builder |
63
+ | `ColumnBuilder` | class | Column definition builder (type, nullable, default) |
64
+ | `createColumnFactory` | function | Column type factory (int, varchar, datetime, etc.) |
65
+ | `IndexBuilder` | class | Index definition builder |
66
+ | `createIndexFactory` | function | Index factory |
67
+ | `ForeignKeyBuilder` | class | FK relation builder (N:1, creates DB constraint) |
68
+ | `ForeignKeyTargetBuilder` | class | FK reverse-reference builder (1:N) |
69
+ | `RelationKeyBuilder` | class | Logical relation builder (N:1, no DB FK) |
70
+ | `RelationKeyTargetBuilder` | class | Logical reverse-reference builder (1:N, no DB FK) |
71
+ | `createRelationFactory` | function | Relation builder factory |
72
+ | `_Migration` | const | Built-in system migration table |
73
+ | `ColumnBuilderRecord` | type | Column builder record type |
74
+ | `RelationBuilderRecord` | type | Relation builder record type |
75
+ | `InferColumns` | type | Infer value types from column builders |
76
+ | `InferColumnExprs` | type | Infer expression input types |
77
+ | `InferInsertColumns` | type | INSERT type inference |
78
+ | `InferUpdateColumns` | type | UPDATE type inference |
79
+ | `RequiredInsertKeys` | type | Required column keys for INSERT |
80
+ | `OptionalInsertKeys` | type | Optional column keys for INSERT |
81
+ | `DataToColumnBuilderRecord` | type | Data record to column builder record |
82
+ | `InferDeepRelations` | type | Deep relation type inference |
83
+ | `ExtractRelationTarget` | type | Extract N:1 relation target type |
84
+ | `ExtractRelationTargetResult` | type | Extract 1:N relation target type |
85
+
86
+ -> See [docs/schema-builders.md](./docs/schema-builders.md) for details.
86
87
 
87
88
  ### Query Builder
88
-
89
- Render `QueryDef` JSON AST to dialect-specific SQL strings.
90
-
91
- | Export | Kind | Description |
92
- |--------|------|-------------|
93
- | `createQueryBuilder` | function | Create a dialect-specific QueryBuilder (`"mysql"`, `"mssql"`, `"postgresql"`) |
94
- | `QueryBuilderBase` | abstract class | Base class with dispatch and common render methods |
95
- | `ExprRendererBase` | abstract class | Base class for expression-to-SQL rendering |
96
- | `MysqlQueryBuilder` | class | MySQL implementation |
89
+ | API | Type | Description |
90
+ |-----|------|-------------|
91
+ | `createQueryBuilder` | function | Create dialect-specific QueryBuilder |
92
+ | `QueryBuilderBase` | class | Abstract QueryDef-to-SQL renderer |
93
+ | `ExprRendererBase` | class | Abstract expression-to-SQL renderer |
94
+ | `MysqlQueryBuilder` | class | MySQL query builder |
97
95
  | `MysqlExprRenderer` | class | MySQL expression renderer |
98
- | `MssqlQueryBuilder` | class | MSSQL implementation |
96
+ | `MssqlQueryBuilder` | class | MSSQL query builder |
99
97
  | `MssqlExprRenderer` | class | MSSQL expression renderer |
100
- | `PostgresqlQueryBuilder` | class | PostgreSQL implementation |
98
+ | `PostgresqlQueryBuilder` | class | PostgreSQL query builder |
101
99
  | `PostgresqlExprRenderer` | class | PostgreSQL expression renderer |
102
100
 
103
- [Detailed documentation](docs/query-builder.md)
101
+ -> See [docs/query-builder.md](./docs/query-builder.md) for details.
104
102
 
105
103
  ### Types
106
-
107
- TypeScript types for dialects, queries, expressions, columns, and results.
108
-
109
- | Export | Kind | Description |
110
- |--------|------|-------------|
111
- | `Dialect` | type | `"mysql" \| "mssql" \| "postgresql"` |
112
- | `dialects` | const | `["mysql", "mssql", "postgresql"]` |
113
- | `QueryBuildResult` | interface | `{ sql, resultSetIndex?, resultSetStride? }` |
114
- | `IsolationLevel` | type | `"READ_UNCOMMITTED" \| "READ_COMMITTED" \| "REPEATABLE_READ" \| "SERIALIZABLE"` |
115
- | `DataRecord` | type | Recursive record type for query results |
116
- | `DbContextExecutor` | interface | Executor interface (connect, close, beginTransaction, executeDefs, etc.) |
117
- | `ResultMeta` | interface | Metadata for result type transformation and JOIN nesting |
118
- | `Migration` | interface | `{ name, up }` migration definition |
119
- | `DataType` | type | SQL type union (int, bigint, varchar, decimal, datetime, etc.) |
120
- | `ColumnPrimitive` | type | All column value types (string, number, boolean, DateTime, DateOnly, Time, Uuid, Bytes, undefined) |
121
- | `ColumnPrimitiveStr` | type | Type name keys: `"string" \| "number" \| "boolean" \| "DateTime" \| ...` |
122
- | `ColumnMeta` | interface | Column metadata (type, dataType, autoIncrement, nullable, default, description) |
123
- | `Expr` | type | Discriminated union of 40+ expression AST node types |
124
- | `WhereExpr` | type | Subset of Expr for WHERE clauses (comparison + logical) |
125
- | `QueryDef` | type | Union of all query definition types (DML + DDL + Utils + Meta) |
104
+ | API | Type | Description |
105
+ |-----|------|-------------|
106
+ | `Dialect` | type | Database dialect (`"mysql" \| "mssql" \| "postgresql"`) |
107
+ | `dialects` | const | List of all supported dialects |
108
+ | `IsolationLevel` | type | Transaction isolation level |
109
+ | `DataRecord` | type | Query result data record (supports nesting) |
110
+ | `DbContextExecutor` | interface | DB connection and query executor interface |
111
+ | `QueryBuildResult` | interface | Built SQL string + metadata |
112
+ | `ResultMeta` | interface | Result transformation metadata |
113
+ | `Migration` | interface | Database migration definition |
114
+ | `DataType` | type | SQL data type definition (14 variants) |
115
+ | `ColumnPrimitiveMap` | type | TypeScript type name to actual type mapping |
116
+ | `ColumnPrimitiveStr` | type | Column primitive type name |
117
+ | `ColumnPrimitive` | type | All column-storable primitive types |
118
+ | `ColumnMeta` | interface | Column metadata |
119
+ | `DateUnit` | type | Date operation unit |
120
+ | `QueryDefObjectName` | interface | DB object name (database.schema.name) |
121
+ | `QueryDef` | type | All query definition union type |
126
122
  | `SelectQueryDef` | interface | SELECT query definition |
127
123
  | `InsertQueryDef` | interface | INSERT query definition |
128
124
  | `UpdateQueryDef` | interface | UPDATE query definition |
129
125
  | `DeleteQueryDef` | interface | DELETE query definition |
130
126
  | `UpsertQueryDef` | interface | UPSERT query definition |
131
- | `QueryDefObjectName` | interface | `{ database?, schema?, name }` |
132
-
133
- [Detailed documentation](docs/types.md)
134
-
135
- ### Utilities
136
-
137
- Result parsing helpers.
138
-
139
- | Export | Kind | Description |
140
- |--------|------|-------------|
141
- | `parseQueryResult` | function | Transform flat DB results to typed nested objects via `ResultMeta` |
127
+ | `DDL_TYPES` | const | DDL type constants |
128
+ | `Expr` | type | All expression union type |
129
+ | `WhereExpr` | type | WHERE clause expression union type |
130
+ | `WinFn` | type | Window function union type |
131
+ | `WinSpec` | interface | Window specification (OVER clause) |
132
+ | `parseQueryResult` | function | Transform raw DB results to typed objects |
133
+ | `inferColumnPrimitiveStr` | function | Infer ColumnPrimitiveStr from runtime value |
134
+ | `dataTypeStrToColumnPrimitiveStr` | const | SQL type to TypeScript type mapping |
142
135
 
143
- [Detailed documentation](docs/utilities.md)
136
+ -> See [docs/types.md](./docs/types.md) and [docs/utilities.md](./docs/utilities.md) for details.
144
137
 
145
138
  ## Usage Examples
146
139
 
147
- ### 1. Define Schema and DbContext
140
+ ### Define Schema and Query
148
141
 
149
142
  ```typescript
150
143
  import { Table, defineDbContext, createDbContext, expr } from "@simplysm/orm-common";
151
144
 
145
+ // Define tables
152
146
  const User = Table("User")
153
147
  .database("mydb")
154
148
  .columns((c) => ({
@@ -156,7 +150,6 @@ const User = Table("User")
156
150
  name: c.varchar(100),
157
151
  email: c.varchar(200).nullable(),
158
152
  status: c.varchar(20).default("active"),
159
- createdAt: c.datetime(),
160
153
  }))
161
154
  .primaryKey("id")
162
155
  .indexes((i) => [i.index("email").unique()]);
@@ -167,101 +160,33 @@ const Post = Table("Post")
167
160
  id: c.bigint().autoIncrement(),
168
161
  authorId: c.bigint(),
169
162
  title: c.varchar(200),
170
- content: c.text(),
171
163
  }))
172
164
  .primaryKey("id")
173
165
  .relations((r) => ({
174
166
  author: r.foreignKey(["authorId"], () => User),
175
167
  }));
176
168
 
169
+ // Define DbContext
177
170
  const MyDb = defineDbContext({
178
171
  tables: { user: User, post: Post },
179
172
  });
180
173
 
181
- // createDbContext requires an executor (from @simplysm/orm-node or service-client)
174
+ // Create instance and query
182
175
  const db = createDbContext(MyDb, executor, { database: "mydb" });
183
- ```
184
-
185
- ### 2. Query with Filters, Joins, and Aggregation
186
176
 
187
- ```typescript
188
177
  await db.connect(async () => {
189
- // Basic query with WHERE
178
+ // SELECT with WHERE
190
179
  const activeUsers = await db.user()
191
180
  .where((u) => [expr.eq(u.status, "active")])
192
181
  .orderBy((u) => u.name)
193
182
  .execute();
194
183
 
184
+ // INSERT
185
+ await db.user().insert([{ name: "John", email: "john@test.com" }]);
186
+
195
187
  // JOIN with include
196
- const postsWithAuthor = await db.post()
188
+ const posts = await db.post()
197
189
  .include((p) => p.author)
198
190
  .execute();
199
-
200
- // Aggregation
201
- const stats = await db.post()
202
- .select((p) => ({
203
- authorId: p.authorId,
204
- postCount: expr.count(p.id),
205
- }))
206
- .groupBy((p) => [p.authorId])
207
- .execute();
208
- });
209
- ```
210
-
211
- ### 3. Insert, Update, Delete
212
-
213
- ```typescript
214
- await db.connect(async () => {
215
- // Insert with output
216
- const [inserted] = await db.user().insert(
217
- [{ name: "Alice", createdAt: DateTime.now() }],
218
- ["id"],
219
- );
220
-
221
- // Update
222
- await db.user()
223
- .where((u) => [expr.eq(u.id, inserted.id)])
224
- .update((u) => ({
225
- status: expr.val("string", "verified"),
226
- }));
227
-
228
- // Delete
229
- await db.user()
230
- .where((u) => [expr.eq(u.status, "deleted")])
231
- .delete();
232
-
233
- // Upsert
234
- await db.user()
235
- .where((u) => [expr.eq(u.email, "alice@test.com")])
236
- .upsert(() => ({
237
- name: expr.val("string", "Alice"),
238
- email: expr.val("string", "alice@test.com"),
239
- createdAt: expr.val("DateTime", DateTime.now()),
240
- }));
241
- });
242
- ```
243
-
244
- ### 4. Text Search
245
-
246
- ```typescript
247
- await db.connect(async () => {
248
- // Search with OR, +must, -exclude syntax
249
- const results = await db.user()
250
- .search((u) => [u.name, u.email], "alice +active -deleted")
251
- .execute();
252
- });
253
- ```
254
-
255
- ### 5. Recursive CTE
256
-
257
- ```typescript
258
- await db.connect(async () => {
259
- const hierarchy = await db.employee()
260
- .where((e) => [expr.null(e.managerId)])
261
- .recursive((cte) =>
262
- cte.from(Employee)
263
- .where((e) => [expr.eq(e.managerId, e.self![0].id)])
264
- )
265
- .execute();
266
191
  });
267
192
  ```