forge-sql-orm 2.0.9 → 2.0.11

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 (41) hide show
  1. package/README.md +67 -42
  2. package/dist/ForgeSQLORM.js +162 -16
  3. package/dist/ForgeSQLORM.js.map +1 -1
  4. package/dist/ForgeSQLORM.mjs +165 -19
  5. package/dist/ForgeSQLORM.mjs.map +1 -1
  6. package/dist/core/ForgeSQLCrudOperations.d.ts.map +1 -1
  7. package/dist/core/ForgeSQLORM.d.ts.map +1 -1
  8. package/dist/core/ForgeSQLQueryBuilder.d.ts +32 -0
  9. package/dist/core/ForgeSQLQueryBuilder.d.ts.map +1 -1
  10. package/dist/core/SystemTables.d.ts +8 -6
  11. package/dist/core/SystemTables.d.ts.map +1 -1
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/lib/drizzle/extensions/selectAliased.d.ts +9 -0
  15. package/dist/lib/drizzle/extensions/selectAliased.d.ts.map +1 -0
  16. package/dist/utils/sqlUtils.d.ts +8 -4
  17. package/dist/utils/sqlUtils.d.ts.map +1 -1
  18. package/dist/webtriggers/applyMigrationsWebTrigger.d.ts +23 -0
  19. package/dist/webtriggers/applyMigrationsWebTrigger.d.ts.map +1 -1
  20. package/dist/webtriggers/dropMigrationWebTrigger.d.ts +20 -4
  21. package/dist/webtriggers/dropMigrationWebTrigger.d.ts.map +1 -1
  22. package/dist/webtriggers/fetchSchemaWebTrigger.d.ts +28 -0
  23. package/dist/webtriggers/fetchSchemaWebTrigger.d.ts.map +1 -0
  24. package/dist/webtriggers/index.d.ts +1 -0
  25. package/dist/webtriggers/index.d.ts.map +1 -1
  26. package/dist-cli/cli.js +5 -0
  27. package/dist-cli/cli.js.map +1 -1
  28. package/dist-cli/cli.mjs +8 -3
  29. package/dist-cli/cli.mjs.map +1 -1
  30. package/package.json +10 -10
  31. package/src/core/ForgeSQLCrudOperations.ts +0 -425
  32. package/src/core/ForgeSQLORM.ts +0 -228
  33. package/src/core/ForgeSQLQueryBuilder.ts +0 -319
  34. package/src/core/ForgeSQLSelectOperations.ts +0 -93
  35. package/src/core/SystemTables.ts +0 -7
  36. package/src/index.ts +0 -10
  37. package/src/utils/forgeDriver.ts +0 -39
  38. package/src/utils/sqlUtils.ts +0 -306
  39. package/src/webtriggers/applyMigrationsWebTrigger.ts +0 -26
  40. package/src/webtriggers/dropMigrationWebTrigger.ts +0 -35
  41. package/src/webtriggers/index.ts +0 -25
@@ -1,319 +0,0 @@
1
- import { UpdateQueryResponse } from "@forge/sql";
2
- import { SqlParameters } from "@forge/sql/out/sql-statement";
3
- import {
4
- AnyMySqlSelectQueryBuilder,
5
- AnyMySqlTable,
6
- customType,
7
- MySqlSelectBuilder,
8
- } from "drizzle-orm/mysql-core";
9
- import {
10
- MySqlSelectDynamic,
11
- type SelectedFields,
12
- } from "drizzle-orm/mysql-core/query-builders/select.types";
13
- import { InferInsertModel, SQL } from "drizzle-orm";
14
- import moment from "moment/moment";
15
- import { parseDateTime } from "../utils/sqlUtils";
16
- import { MySqlRemoteDatabase, MySqlRemotePreparedQueryHKT } from "drizzle-orm/mysql-proxy/index";
17
-
18
- // ============= Core Types =============
19
-
20
- /**
21
- * Interface representing the main ForgeSQL operations.
22
- * Provides access to CRUD operations and schema-level SQL operations.
23
- */
24
- export interface ForgeSqlOperation extends QueryBuilderForgeSql {
25
- /**
26
- * Provides CRUD (Create, Read, Update, Delete) operations.
27
- * @returns {CRUDForgeSQL} Interface for performing CRUD operations
28
- */
29
- crud(): CRUDForgeSQL;
30
-
31
- /**
32
- * Provides schema-level SQL fetch operations.
33
- * @returns {SchemaSqlForgeSql} Interface for executing schema-bound SQL queries
34
- */
35
- fetch(): SchemaSqlForgeSql;
36
- }
37
-
38
- /**
39
- * Interface for Query Builder operations.
40
- * Provides access to the underlying Drizzle ORM query builder.
41
- */
42
- export interface QueryBuilderForgeSql {
43
- /**
44
- * Creates a new query builder for the given entity.
45
- * @returns {MySql2Database<Record<string, unknown>>} The Drizzle database instance for building queries
46
- */
47
- getDrizzleQueryBuilder(): MySqlRemoteDatabase<Record<string, unknown>>;
48
-
49
- select<TSelection extends SelectedFields>(
50
- fields: TSelection,
51
- ): MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT>;
52
-
53
- selectDistinct<TSelection extends SelectedFields>(
54
- fields: TSelection,
55
- ): MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT>;
56
- }
57
-
58
- // ============= CRUD Operations =============
59
-
60
- /**
61
- * Interface for CRUD (Create, Read, Update, Delete) operations.
62
- * Provides methods for basic database operations with support for optimistic locking.
63
- */
64
- export interface CRUDForgeSQL {
65
- /**
66
- * Inserts multiple records into the database.
67
- * @template T - The type of the table schema
68
- * @param {T} schema - The entity schema
69
- * @param {Partial<InferInsertModel<T>>[]} models - The list of entities to insert
70
- * @param {boolean} [updateIfExists] - Whether to update the row if it already exists (default: false)
71
- * @returns {Promise<number>} The number of inserted rows
72
- * @throws {Error} If the insert operation fails
73
- */
74
- insert<T extends AnyMySqlTable>(
75
- schema: T,
76
- models: Partial<InferInsertModel<T>>[],
77
- updateIfExists?: boolean,
78
- ): Promise<number>;
79
-
80
- /**
81
- * Deletes a record by its ID.
82
- * @template T - The type of the table schema
83
- * @param {unknown} id - The ID of the record to delete
84
- * @param {T} schema - The entity schema
85
- * @returns {Promise<number>} The number of rows affected
86
- * @throws {Error} If the delete operation fails
87
- */
88
- deleteById<T extends AnyMySqlTable>(id: unknown, schema: T): Promise<number>;
89
-
90
- /**
91
- * Updates a record by its ID with optimistic locking support.
92
- * If a version field is defined in the schema, versioning is applied:
93
- * - the current record version is retrieved
94
- * - checked for concurrent modifications
95
- * - and then incremented
96
- *
97
- * @template T - The type of the table schema
98
- * @param {Partial<InferInsertModel<T>>} entity - The entity with updated values
99
- * @param {T} schema - The entity schema
100
- * @returns {Promise<number>} The number of rows affected
101
- * @throws {Error} If the primary key is not included in the update fields
102
- * @throws {Error} If optimistic locking check fails
103
- */
104
- updateById<T extends AnyMySqlTable>(
105
- entity: Partial<InferInsertModel<T>>,
106
- schema: T,
107
- ): Promise<number>;
108
-
109
- /**
110
- * Updates specified fields of records based on provided conditions.
111
- * If the "where" parameter is not provided, the WHERE clause is built from the entity fields
112
- * that are not included in the list of fields to update.
113
- *
114
- * @template T - The type of the table schema
115
- * @param {Partial<InferInsertModel<T>>} updateData - The object containing values to update
116
- * @param {T} schema - The entity schema
117
- * @param {SQL<unknown>} [where] - Optional filtering conditions for the WHERE clause
118
- * @returns {Promise<number>} The number of affected rows
119
- * @throws {Error} If no filtering criteria are provided
120
- * @throws {Error} If the update operation fails
121
- */
122
- updateFields<T extends AnyMySqlTable>(
123
- updateData: Partial<InferInsertModel<T>>,
124
- schema: T,
125
- where?: SQL<unknown>,
126
- ): Promise<number>;
127
- }
128
-
129
- // ============= Schema SQL Operations =============
130
-
131
- /**
132
- * Interface for schema-level SQL operations.
133
- * Provides methods for executing SQL queries with schema binding and type safety.
134
- */
135
- export interface SchemaSqlForgeSql {
136
- /**
137
- * Executes a Drizzle query and returns a single result.
138
- * @template T - The type of the query builder
139
- * @param {T} query - The Drizzle query to execute
140
- * @returns {Promise<Awaited<T> extends Array<any> ? Awaited<T>[number] | undefined : Awaited<T> | undefined>} A single result object or undefined
141
- * @throws {Error} If more than one record is returned
142
- * @throws {Error} If the query execution fails
143
- */
144
- executeQueryOnlyOne<T extends MySqlSelectDynamic<AnyMySqlSelectQueryBuilder>>(
145
- query: T,
146
- ): Promise<
147
- Awaited<T> extends Array<any> ? Awaited<T>[number] | undefined : Awaited<T> | undefined
148
- >;
149
-
150
- /**
151
- * Executes a raw SQL query and returns the results.
152
- * @template T - The type of the result objects
153
- * @param {string} query - The raw SQL query
154
- * @param {SqlParameters[]} [params] - Optional SQL parameters
155
- * @returns {Promise<T[]>} A list of results as objects
156
- * @throws {Error} If the query execution fails
157
- */
158
- executeRawSQL<T extends object | unknown>(query: string, params?: SqlParameters[]): Promise<T[]>;
159
-
160
- /**
161
- * Executes a raw SQL update query.
162
- * @param {string} query - The raw SQL update query
163
- * @param {SqlParameters[]} [params] - Optional SQL parameters
164
- * @returns {Promise<UpdateQueryResponse>} The update response containing affected rows
165
- * @throws {Error} If the update operation fails
166
- */
167
- executeRawUpdateSQL(query: string, params?: unknown[]): Promise<UpdateQueryResponse>;
168
- }
169
-
170
- // ============= Configuration Types =============
171
-
172
- /**
173
- * Interface for version field metadata.
174
- * Defines the configuration for optimistic locking version fields.
175
- */
176
- export interface VersionFieldMetadata {
177
- /** Name of the version field */
178
- fieldName: string;
179
- }
180
-
181
- /**
182
- * Interface for table metadata.
183
- * Defines the configuration for a specific table.
184
- */
185
- export interface TableMetadata {
186
- /** Name of the table */
187
- tableName: string;
188
- /** Version field configuration for optimistic locking */
189
- versionField: VersionFieldMetadata;
190
- }
191
-
192
- /**
193
- * Type for additional metadata configuration.
194
- * Maps table names to their metadata configuration.
195
- */
196
- export type AdditionalMetadata = Record<string, TableMetadata>;
197
-
198
- /**
199
- * Options for configuring ForgeSQL ORM behavior.
200
- */
201
- export interface ForgeSqlOrmOptions {
202
- /**
203
- * Enables logging of raw SQL queries in the Atlassian Forge Developer Console.
204
- * Useful for debugging and monitoring SQL operations.
205
- * @default false
206
- */
207
- logRawSqlQuery?: boolean;
208
-
209
- /**
210
- * Disables optimistic locking for all operations.
211
- * When enabled, version checks are skipped during updates.
212
- * @default false
213
- */
214
- disableOptimisticLocking?: boolean;
215
-
216
- /**
217
- * Additional metadata for table configuration.
218
- * Allows specifying table-specific settings and behaviors.
219
- * @example
220
- * ```typescript
221
- * {
222
- * users: {
223
- * tableName: "users",
224
- * versionField: {
225
- * fieldName: "updatedAt",
226
- * type: "datetime",
227
- * nullable: false
228
- * }
229
- * }
230
- * }
231
- * ```
232
- */
233
- additionalMetadata?: AdditionalMetadata;
234
- }
235
-
236
- // ============= Custom Types =============
237
-
238
- /**
239
- * Custom type for MySQL datetime fields.
240
- * Handles conversion between JavaScript Date objects and MySQL datetime strings.
241
- */
242
- export const forgeDateTimeString = customType<{
243
- data: Date;
244
- driver: string;
245
- config: { format?: string };
246
- }>({
247
- dataType() {
248
- return "datetime";
249
- },
250
- toDriver(value: Date) {
251
- return moment(value as Date).format("YYYY-MM-DDTHH:mm:ss.SSS");
252
- },
253
- fromDriver(value: unknown) {
254
- const format = "YYYY-MM-DDTHH:mm:ss.SSS";
255
- return parseDateTime(value as string, format);
256
- },
257
- });
258
-
259
- /**
260
- * Custom type for MySQL timestamp fields.
261
- * Handles conversion between JavaScript Date objects and MySQL timestamp strings.
262
- */
263
- export const forgeTimestampString = customType<{
264
- data: Date;
265
- driver: string;
266
- config: { format?: string };
267
- }>({
268
- dataType() {
269
- return "timestamp";
270
- },
271
- toDriver(value: Date) {
272
- return moment(value as Date).format("YYYY-MM-DDTHH:mm:ss.SSS");
273
- },
274
- fromDriver(value: unknown) {
275
- const format = "YYYY-MM-DDTHH:mm:ss.SSS";
276
- return parseDateTime(value as string, format);
277
- },
278
- });
279
-
280
- /**
281
- * Custom type for MySQL date fields.
282
- * Handles conversion between JavaScript Date objects and MySQL date strings.
283
- */
284
- export const forgeDateString = customType<{
285
- data: Date;
286
- driver: string;
287
- config: { format?: string };
288
- }>({
289
- dataType() {
290
- return "date";
291
- },
292
- toDriver(value: Date) {
293
- return moment(value as Date).format("YYYY-MM-DD");
294
- },
295
- fromDriver(value: unknown) {
296
- const format = "YYYY-MM-DD";
297
- return parseDateTime(value as string, format);
298
- },
299
- });
300
-
301
- /**
302
- * Custom type for MySQL time fields.
303
- * Handles conversion between JavaScript Date objects and MySQL time strings.
304
- */
305
- export const forgeTimeString = customType<{
306
- data: Date;
307
- driver: string;
308
- config: { format?: string };
309
- }>({
310
- dataType() {
311
- return "time";
312
- },
313
- toDriver(value: Date) {
314
- return moment(value as Date).format("HH:mm:ss.SSS");
315
- },
316
- fromDriver(value: unknown) {
317
- return parseDateTime(value as string, "HH:mm:ss.SSS");
318
- },
319
- });
@@ -1,93 +0,0 @@
1
- import { sql, UpdateQueryResponse } from "@forge/sql";
2
- import { ForgeSqlOrmOptions, SchemaSqlForgeSql } from "./ForgeSQLQueryBuilder";
3
- import {
4
- AnyMySqlSelectQueryBuilder,
5
- MySqlSelectDynamic,
6
- } from "drizzle-orm/mysql-core/query-builders/select.types";
7
-
8
- /**
9
- * Class implementing SQL select operations for ForgeSQL ORM.
10
- * Provides methods for executing queries and mapping results to entity types.
11
- */
12
- export class ForgeSQLSelectOperations implements SchemaSqlForgeSql {
13
- private readonly options: ForgeSqlOrmOptions;
14
-
15
- /**
16
- * Creates a new instance of ForgeSQLSelectOperations.
17
- * @param {ForgeSqlOrmOptions} options - Configuration options for the ORM
18
- */
19
- constructor(options: ForgeSqlOrmOptions) {
20
- this.options = options;
21
- }
22
-
23
- /**
24
- * Executes a Drizzle query and returns a single result.
25
- * Throws an error if more than one record is returned.
26
- *
27
- * @template T - The type of the query builder
28
- * @param {T} query - The Drizzle query to execute
29
- * @returns {Promise<Awaited<T> extends Array<any> ? Awaited<T>[number] | undefined : Awaited<T> | undefined>} A single result object or undefined
30
- * @throws {Error} If more than one record is returned
31
- */
32
- async executeQueryOnlyOne<T extends MySqlSelectDynamic<AnyMySqlSelectQueryBuilder>>(
33
- query: T,
34
- ): Promise<
35
- Awaited<T> extends Array<any> ? Awaited<T>[number] | undefined : Awaited<T> | undefined
36
- > {
37
- const results: Awaited<T> = await query;
38
- const datas = results as unknown[];
39
- if (!datas.length) {
40
- return undefined;
41
- }
42
- if (datas.length > 1) {
43
- throw new Error(`Expected 1 record but returned ${datas.length}`);
44
- }
45
-
46
- return datas[0] as Awaited<T> extends Array<any> ? Awaited<T>[number] : Awaited<T>;
47
- }
48
-
49
- /**
50
- * Executes a raw SQL query and returns the results.
51
- * Logs the query if logging is enabled.
52
- *
53
- * @template T - The type of the result objects
54
- * @param {string} query - The raw SQL query to execute
55
- * @param {SqlParameters[]} [params] - Optional SQL parameters
56
- * @returns {Promise<T[]>} A list of results as objects
57
- */
58
- async executeRawSQL<T extends object | unknown>(query: string, params?: unknown[]): Promise<T[]> {
59
- if (this.options.logRawSqlQuery) {
60
- console.debug(
61
- `Executing with SQL ${query}` + params ? `, with params: ${JSON.stringify(params)}` : "",
62
- );
63
- }
64
- const sqlStatement = sql.prepare<T>(query);
65
- if (params) {
66
- sqlStatement.bindParams(...params);
67
- }
68
- const result = await sqlStatement.execute();
69
- return result.rows as T[];
70
- }
71
-
72
- /**
73
- * Executes a raw SQL update query.
74
- * @param {string} query - The raw SQL update query
75
- * @param {SqlParameters[]} [params] - Optional SQL parameters
76
- * @returns {Promise<UpdateQueryResponse>} The update response containing affected rows
77
- */
78
- async executeRawUpdateSQL(query: string, params?: unknown[]): Promise<UpdateQueryResponse> {
79
- const sqlStatement = sql.prepare<UpdateQueryResponse>(query);
80
- if (params) {
81
- sqlStatement.bindParams(...params);
82
- }
83
- if (this.options.logRawSqlQuery) {
84
- console.debug(
85
- `Executing Update with SQL ${query}` + params
86
- ? `, with params: ${JSON.stringify(params)}`
87
- : "",
88
- );
89
- }
90
- const updateQueryResponseResults = await sqlStatement.execute();
91
- return updateQueryResponseResults.rows;
92
- }
93
- }
@@ -1,7 +0,0 @@
1
- import { int, mysqlTable, timestamp, varchar } from "drizzle-orm/mysql-core/index";
2
-
3
- export const migrations = mysqlTable("__migrations", {
4
- id: int("id").primaryKey().autoincrement(),
5
- name: varchar("name", { length: 255 }).notNull(),
6
- created_at: timestamp("created_at").defaultNow().notNull(),
7
- });
package/src/index.ts DELETED
@@ -1,10 +0,0 @@
1
- import ForgeSQLORM from "./core/ForgeSQLORM";
2
-
3
- export * from "./core/ForgeSQLQueryBuilder";
4
- export * from "./core/ForgeSQLCrudOperations";
5
- export * from "./core/ForgeSQLSelectOperations";
6
- export * from "./utils/sqlUtils";
7
- export * from "./utils/forgeDriver";
8
- export * from "./webtriggers";
9
-
10
- export default ForgeSQLORM;
@@ -1,39 +0,0 @@
1
- import { sql, UpdateQueryResponse } from "@forge/sql";
2
-
3
- interface ForgeSQLResult {
4
- rows: Record<string, unknown>[] | Record<string, unknown>;
5
- }
6
-
7
- export const forgeDriver = async (
8
- query: string,
9
- params: any[],
10
- method: "all" | "execute",
11
- ): Promise<{
12
- rows: any[];
13
- insertId?: number;
14
- affectedRows?: number;
15
- }> => {
16
- try {
17
- if (method == "execute") {
18
- const sqlStatement = sql.prepare<UpdateQueryResponse>(query);
19
- if (params) {
20
- sqlStatement.bindParams(...params);
21
- }
22
- const updateQueryResponseResults = await sqlStatement.execute();
23
- let result = updateQueryResponseResults.rows as any;
24
- return { ...result, rows: [result] };
25
- } else {
26
- const sqlStatement = await sql.prepare<unknown>(query);
27
- if (params) {
28
- await sqlStatement.bindParams(...params);
29
- }
30
- const result = (await sqlStatement.execute()) as ForgeSQLResult;
31
- let rows;
32
- rows = (result.rows as any[]).map((r) => Object.values(r as Record<string, unknown>));
33
- return { rows: rows };
34
- }
35
- } catch (error) {
36
- console.error("SQL Error:", JSON.stringify(error));
37
- throw error;
38
- }
39
- };