forge-sql-orm 2.0.30 → 2.1.1
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 +1410 -81
- package/dist/ForgeSQLORM.js +1456 -60
- package/dist/ForgeSQLORM.js.map +1 -1
- package/dist/ForgeSQLORM.mjs +1440 -61
- package/dist/ForgeSQLORM.mjs.map +1 -1
- package/dist/core/ForgeSQLAnalyseOperations.d.ts +1 -1
- package/dist/core/ForgeSQLAnalyseOperations.d.ts.map +1 -1
- package/dist/core/ForgeSQLCacheOperations.d.ts +119 -0
- package/dist/core/ForgeSQLCacheOperations.d.ts.map +1 -0
- package/dist/core/ForgeSQLCrudOperations.d.ts +38 -22
- package/dist/core/ForgeSQLCrudOperations.d.ts.map +1 -1
- package/dist/core/ForgeSQLORM.d.ts +248 -13
- package/dist/core/ForgeSQLORM.d.ts.map +1 -1
- package/dist/core/ForgeSQLQueryBuilder.d.ts +394 -19
- package/dist/core/ForgeSQLQueryBuilder.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/lib/drizzle/extensions/additionalActions.d.ts +90 -0
- package/dist/lib/drizzle/extensions/additionalActions.d.ts.map +1 -0
- package/dist/utils/cacheContextUtils.d.ts +123 -0
- package/dist/utils/cacheContextUtils.d.ts.map +1 -0
- package/dist/utils/cacheUtils.d.ts +56 -0
- package/dist/utils/cacheUtils.d.ts.map +1 -0
- package/dist/utils/sqlUtils.d.ts +8 -0
- package/dist/utils/sqlUtils.d.ts.map +1 -1
- package/dist/webtriggers/clearCacheSchedulerTrigger.d.ts +46 -0
- package/dist/webtriggers/clearCacheSchedulerTrigger.d.ts.map +1 -0
- package/dist/webtriggers/index.d.ts +1 -0
- package/dist/webtriggers/index.d.ts.map +1 -1
- package/package.json +15 -12
- package/src/core/ForgeSQLAnalyseOperations.ts +1 -1
- package/src/core/ForgeSQLCacheOperations.ts +195 -0
- package/src/core/ForgeSQLCrudOperations.ts +49 -40
- package/src/core/ForgeSQLORM.ts +743 -34
- package/src/core/ForgeSQLQueryBuilder.ts +456 -20
- package/src/index.ts +1 -1
- package/src/lib/drizzle/extensions/additionalActions.ts +852 -0
- package/src/lib/drizzle/extensions/types.d.ts +99 -10
- package/src/utils/cacheContextUtils.ts +212 -0
- package/src/utils/cacheUtils.ts +403 -0
- package/src/utils/sqlUtils.ts +42 -0
- package/src/webtriggers/clearCacheSchedulerTrigger.ts +79 -0
- package/src/webtriggers/index.ts +1 -0
- package/dist/lib/drizzle/extensions/selectAliased.d.ts +0 -9
- package/dist/lib/drizzle/extensions/selectAliased.d.ts.map +0 -1
- package/src/lib/drizzle/extensions/selectAliased.ts +0 -72
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
import { DateTime } from "luxon";
|
|
2
|
+
import * as crypto from "crypto";
|
|
3
|
+
import { Query } from "drizzle-orm";
|
|
4
|
+
import { AnyMySqlTable } from "drizzle-orm/mysql-core";
|
|
5
|
+
import { getTableName } from "drizzle-orm/table";
|
|
6
|
+
import { Filter, FilterConditions, kvs, WhereConditions } from "@forge/kvs";
|
|
7
|
+
import { ForgeSqlOrmOptions } from "../core/ForgeSQLQueryBuilder";
|
|
8
|
+
import { cacheApplicationContext, isTableContainsTableInCacheContext } from "./cacheContextUtils";
|
|
9
|
+
|
|
10
|
+
// Constants for better maintainability
|
|
11
|
+
const CACHE_CONSTANTS = {
|
|
12
|
+
BATCH_SIZE: 25,
|
|
13
|
+
MAX_RETRY_ATTEMPTS: 3,
|
|
14
|
+
INITIAL_RETRY_DELAY: 1000,
|
|
15
|
+
RETRY_DELAY_MULTIPLIER: 2,
|
|
16
|
+
DEFAULT_ENTITY_QUERY_NAME: "sql",
|
|
17
|
+
DEFAULT_EXPIRATION_NAME: "expiration",
|
|
18
|
+
DEFAULT_DATA_NAME: "data",
|
|
19
|
+
HASH_LENGTH: 32,
|
|
20
|
+
} as const;
|
|
21
|
+
|
|
22
|
+
// Types for better type safety
|
|
23
|
+
type CacheEntity = {
|
|
24
|
+
[key: string]: string | number;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Gets the current Unix timestamp in seconds.
|
|
29
|
+
*
|
|
30
|
+
* @returns Current timestamp as integer
|
|
31
|
+
*/
|
|
32
|
+
function getCurrentTime(): number {
|
|
33
|
+
const dt = DateTime.now();
|
|
34
|
+
return Math.floor(dt.toSeconds());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Calculates a future timestamp by adding seconds to the current time.
|
|
39
|
+
* Validates that the result is within 32-bit integer range.
|
|
40
|
+
*
|
|
41
|
+
* @param secondsToAdd - Number of seconds to add to current time
|
|
42
|
+
* @returns Future timestamp in seconds
|
|
43
|
+
* @throws Error if the result is out of 32-bit integer range
|
|
44
|
+
*/
|
|
45
|
+
function nowPlusSeconds(secondsToAdd: number): number {
|
|
46
|
+
const dt = DateTime.now().plus({ seconds: secondsToAdd });
|
|
47
|
+
return Math.floor(dt.toSeconds());
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Generates a hash key for a query based on its SQL and parameters.
|
|
52
|
+
*
|
|
53
|
+
* @param query - The Drizzle query object
|
|
54
|
+
* @returns 32-character hexadecimal hash
|
|
55
|
+
*/
|
|
56
|
+
export function hashKey(query: Query): string {
|
|
57
|
+
const h = crypto.createHash("sha256");
|
|
58
|
+
h.update(query.sql.toLowerCase());
|
|
59
|
+
h.update(JSON.stringify(query.params));
|
|
60
|
+
return "CachedQuery_" + h.digest("hex").slice(0, CACHE_CONSTANTS.HASH_LENGTH);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Deletes cache entries in batches to respect Forge limits and timeouts.
|
|
65
|
+
*
|
|
66
|
+
* @param results - Array of cache entries to delete
|
|
67
|
+
* @param cacheEntityName - Name of the cache entity
|
|
68
|
+
* @returns Promise that resolves when all deletions are complete
|
|
69
|
+
*/
|
|
70
|
+
async function deleteCacheEntriesInBatches(
|
|
71
|
+
results: Array<{ key: string }>,
|
|
72
|
+
cacheEntityName: string,
|
|
73
|
+
): Promise<void> {
|
|
74
|
+
for (let i = 0; i < results.length; i += CACHE_CONSTANTS.BATCH_SIZE) {
|
|
75
|
+
const batch = results.slice(i, i + CACHE_CONSTANTS.BATCH_SIZE);
|
|
76
|
+
let transactionBuilder = kvs.transact();
|
|
77
|
+
batch.forEach((result) => {
|
|
78
|
+
transactionBuilder = transactionBuilder.delete(result.key, { entityName: cacheEntityName });
|
|
79
|
+
});
|
|
80
|
+
await transactionBuilder.execute();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Clears cache entries for specific tables using cursor-based pagination.
|
|
86
|
+
*
|
|
87
|
+
* @param tables - Array of table names to clear cache for
|
|
88
|
+
* @param cursor - Pagination cursor for large result sets
|
|
89
|
+
* @param options - ForgeSQL ORM options
|
|
90
|
+
* @returns Total number of deleted cache entries
|
|
91
|
+
*/
|
|
92
|
+
async function clearCursorCache(
|
|
93
|
+
tables: string[],
|
|
94
|
+
cursor: string,
|
|
95
|
+
options: ForgeSqlOrmOptions,
|
|
96
|
+
): Promise<number> {
|
|
97
|
+
const cacheEntityName = options.cacheEntityName;
|
|
98
|
+
if (!cacheEntityName) {
|
|
99
|
+
throw new Error("cacheEntityName is not configured");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const entityQueryName = options.cacheEntityQueryName ?? CACHE_CONSTANTS.DEFAULT_ENTITY_QUERY_NAME;
|
|
103
|
+
let filters = new Filter<{
|
|
104
|
+
[entityQueryName]: string;
|
|
105
|
+
}>();
|
|
106
|
+
|
|
107
|
+
for (const table of tables) {
|
|
108
|
+
const wrapIfNeeded = options.cacheWrapTable ? `\`${table}\`` : table;
|
|
109
|
+
filters.or(entityQueryName, FilterConditions.contains(wrapIfNeeded?.toLowerCase()));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let entityQueryBuilder = kvs
|
|
113
|
+
.entity<{
|
|
114
|
+
[entityQueryName]: string;
|
|
115
|
+
}>(cacheEntityName)
|
|
116
|
+
.query()
|
|
117
|
+
.index(entityQueryName)
|
|
118
|
+
.filters(filters);
|
|
119
|
+
|
|
120
|
+
if (cursor) {
|
|
121
|
+
entityQueryBuilder = entityQueryBuilder.cursor(cursor);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const listResult = await entityQueryBuilder.limit(100).getMany();
|
|
125
|
+
|
|
126
|
+
if (options.logRawSqlQuery) {
|
|
127
|
+
console.warn(`clear cache Records: ${JSON.stringify(listResult.results.map((r) => r.key))}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
await deleteCacheEntriesInBatches(listResult.results, cacheEntityName);
|
|
131
|
+
|
|
132
|
+
if (listResult.nextCursor) {
|
|
133
|
+
return (
|
|
134
|
+
listResult.results.length + (await clearCursorCache(tables, listResult.nextCursor, options))
|
|
135
|
+
);
|
|
136
|
+
} else {
|
|
137
|
+
return listResult.results.length;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Clears expired cache entries using cursor-based pagination.
|
|
143
|
+
*
|
|
144
|
+
* @param cursor - Pagination cursor for large result sets
|
|
145
|
+
* @param options - ForgeSQL ORM options
|
|
146
|
+
* @returns Total number of deleted expired cache entries
|
|
147
|
+
*/
|
|
148
|
+
async function clearExpirationCursorCache(
|
|
149
|
+
cursor: string,
|
|
150
|
+
options: ForgeSqlOrmOptions,
|
|
151
|
+
): Promise<number> {
|
|
152
|
+
const cacheEntityName = options.cacheEntityName;
|
|
153
|
+
if (!cacheEntityName) {
|
|
154
|
+
throw new Error("cacheEntityName is not configured");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const entityExpirationName =
|
|
158
|
+
options.cacheEntityExpirationName ?? CACHE_CONSTANTS.DEFAULT_EXPIRATION_NAME;
|
|
159
|
+
let entityQueryBuilder = kvs
|
|
160
|
+
.entity<{
|
|
161
|
+
[entityExpirationName]: number;
|
|
162
|
+
}>(cacheEntityName)
|
|
163
|
+
.query()
|
|
164
|
+
.index(entityExpirationName)
|
|
165
|
+
.where(WhereConditions.lessThan(Math.floor(DateTime.now().toSeconds())));
|
|
166
|
+
|
|
167
|
+
if (cursor) {
|
|
168
|
+
entityQueryBuilder = entityQueryBuilder.cursor(cursor);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const listResult = await entityQueryBuilder.limit(100).getMany();
|
|
172
|
+
|
|
173
|
+
if (options.logRawSqlQuery) {
|
|
174
|
+
console.warn(`clear expired Records: ${JSON.stringify(listResult.results.map((r) => r.key))}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
await deleteCacheEntriesInBatches(listResult.results, cacheEntityName);
|
|
178
|
+
|
|
179
|
+
if (listResult.nextCursor) {
|
|
180
|
+
return (
|
|
181
|
+
listResult.results.length + (await clearExpirationCursorCache(listResult.nextCursor, options))
|
|
182
|
+
);
|
|
183
|
+
} else {
|
|
184
|
+
return listResult.results.length;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Executes a function with retry logic and exponential backoff.
|
|
190
|
+
*
|
|
191
|
+
* @param operation - Function to execute with retry
|
|
192
|
+
* @param operationName - Name of the operation for logging
|
|
193
|
+
* @param options - ForgeSQL ORM options for logging
|
|
194
|
+
* @returns Promise that resolves to the operation result
|
|
195
|
+
*/
|
|
196
|
+
async function executeWithRetry<T>(operation: () => Promise<T>, operationName: string): Promise<T> {
|
|
197
|
+
let attempt = 0;
|
|
198
|
+
let delay = CACHE_CONSTANTS.INITIAL_RETRY_DELAY;
|
|
199
|
+
|
|
200
|
+
while (attempt < CACHE_CONSTANTS.MAX_RETRY_ATTEMPTS) {
|
|
201
|
+
try {
|
|
202
|
+
return await operation();
|
|
203
|
+
} catch (err: any) {
|
|
204
|
+
console.warn(`Error during ${operationName}: ${err.message}, retry ${attempt}`, err);
|
|
205
|
+
attempt++;
|
|
206
|
+
|
|
207
|
+
if (attempt >= CACHE_CONSTANTS.MAX_RETRY_ATTEMPTS) {
|
|
208
|
+
console.error(`Error during ${operationName}: ${err.message}`, err);
|
|
209
|
+
throw err;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
213
|
+
delay *= CACHE_CONSTANTS.RETRY_DELAY_MULTIPLIER;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
throw new Error(`Maximum retry attempts exceeded for ${operationName}`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Clears cache for a specific table.
|
|
222
|
+
* Uses cache context if available, otherwise clears immediately.
|
|
223
|
+
*
|
|
224
|
+
* @param schema - The table schema to clear cache for
|
|
225
|
+
* @param options - ForgeSQL ORM options
|
|
226
|
+
*/
|
|
227
|
+
export async function clearCache<T extends AnyMySqlTable>(
|
|
228
|
+
schema: T,
|
|
229
|
+
options: ForgeSqlOrmOptions,
|
|
230
|
+
): Promise<void> {
|
|
231
|
+
const tableName = getTableName(schema);
|
|
232
|
+
if (cacheApplicationContext.getStore()) {
|
|
233
|
+
cacheApplicationContext.getStore()?.tables.add(tableName);
|
|
234
|
+
} else {
|
|
235
|
+
await clearTablesCache([tableName], options);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Clears cache for multiple tables with retry logic and performance logging.
|
|
241
|
+
*
|
|
242
|
+
* @param tables - Array of table names to clear cache for
|
|
243
|
+
* @param options - ForgeSQL ORM options
|
|
244
|
+
* @returns Promise that resolves when cache clearing is complete
|
|
245
|
+
*/
|
|
246
|
+
export async function clearTablesCache(
|
|
247
|
+
tables: string[],
|
|
248
|
+
options: ForgeSqlOrmOptions,
|
|
249
|
+
): Promise<void> {
|
|
250
|
+
if (!options.cacheEntityName) {
|
|
251
|
+
throw new Error("cacheEntityName is not configured");
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const startTime = DateTime.now();
|
|
255
|
+
let totalRecords = 0;
|
|
256
|
+
|
|
257
|
+
try {
|
|
258
|
+
totalRecords = await executeWithRetry(
|
|
259
|
+
() => clearCursorCache(tables, "", options),
|
|
260
|
+
"clearing cache",
|
|
261
|
+
);
|
|
262
|
+
} finally {
|
|
263
|
+
if (options.logRawSqlQuery) {
|
|
264
|
+
const duration = DateTime.now().toSeconds() - startTime.toSeconds();
|
|
265
|
+
console.info(`Cleared ${totalRecords} cache records in ${duration} seconds`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Clears expired cache entries with retry logic and performance logging.
|
|
271
|
+
*
|
|
272
|
+
* @param options - ForgeSQL ORM options
|
|
273
|
+
* @returns Promise that resolves when expired cache clearing is complete
|
|
274
|
+
*/
|
|
275
|
+
export async function clearExpiredCache(options: ForgeSqlOrmOptions): Promise<void> {
|
|
276
|
+
if (!options.cacheEntityName) {
|
|
277
|
+
throw new Error("cacheEntityName is not configured");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const startTime = DateTime.now();
|
|
281
|
+
let totalRecords = 0;
|
|
282
|
+
|
|
283
|
+
try {
|
|
284
|
+
totalRecords = await executeWithRetry(
|
|
285
|
+
() => clearExpirationCursorCache("", options),
|
|
286
|
+
"clearing expired cache",
|
|
287
|
+
);
|
|
288
|
+
} finally {
|
|
289
|
+
const duration = DateTime.now().toSeconds() - startTime.toSeconds();
|
|
290
|
+
console.info(`Cleared ${totalRecords} expired cache records in ${duration} seconds`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Retrieves data from cache if it exists and is not expired.
|
|
296
|
+
*
|
|
297
|
+
* @param query - Query object with toSQL method
|
|
298
|
+
* @param options - ForgeSQL ORM options
|
|
299
|
+
* @returns Cached data if found and valid, undefined otherwise
|
|
300
|
+
*/
|
|
301
|
+
export async function getFromCache<T>(
|
|
302
|
+
query: { toSQL: () => Query },
|
|
303
|
+
options: ForgeSqlOrmOptions,
|
|
304
|
+
): Promise<T | undefined> {
|
|
305
|
+
if (!options.cacheEntityName) {
|
|
306
|
+
throw new Error("cacheEntityName is not configured");
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const entityQueryName = options.cacheEntityQueryName ?? CACHE_CONSTANTS.DEFAULT_ENTITY_QUERY_NAME;
|
|
310
|
+
const expirationName =
|
|
311
|
+
options.cacheEntityExpirationName ?? CACHE_CONSTANTS.DEFAULT_EXPIRATION_NAME;
|
|
312
|
+
const dataName = options.cacheEntityDataName ?? CACHE_CONSTANTS.DEFAULT_DATA_NAME;
|
|
313
|
+
|
|
314
|
+
const sqlQuery = query.toSQL();
|
|
315
|
+
const key = hashKey(sqlQuery);
|
|
316
|
+
|
|
317
|
+
// Skip cache if table is in cache context (will be cleared)
|
|
318
|
+
if (await isTableContainsTableInCacheContext(sqlQuery.sql, options)) {
|
|
319
|
+
if (options.logRawSqlQuery) {
|
|
320
|
+
console.warn(`Context contains value to clear. Skip getting from cache`);
|
|
321
|
+
}
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
try {
|
|
326
|
+
const cacheResult = await kvs.entity<CacheEntity>(options.cacheEntityName).get(key);
|
|
327
|
+
|
|
328
|
+
if (
|
|
329
|
+
cacheResult &&
|
|
330
|
+
(cacheResult[expirationName] as number) >= getCurrentTime() &&
|
|
331
|
+
sqlQuery.sql.toLowerCase() === cacheResult[entityQueryName]
|
|
332
|
+
) {
|
|
333
|
+
if (options.logRawSqlQuery) {
|
|
334
|
+
console.warn(`Get value from cache, cacheKey: ${key}`);
|
|
335
|
+
}
|
|
336
|
+
const results = cacheResult[dataName];
|
|
337
|
+
return JSON.parse(results as string);
|
|
338
|
+
}
|
|
339
|
+
} catch (error: any) {
|
|
340
|
+
console.error(`Error getting from cache: ${error.message}`, error);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return undefined;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Stores query results in cache with specified TTL.
|
|
348
|
+
*
|
|
349
|
+
* @param query - Query object with toSQL method
|
|
350
|
+
* @param options - ForgeSQL ORM options
|
|
351
|
+
* @param results - Data to cache
|
|
352
|
+
* @param cacheTtl - Time to live in seconds
|
|
353
|
+
* @returns Promise that resolves when data is stored in cache
|
|
354
|
+
*/
|
|
355
|
+
export async function setCacheResult(
|
|
356
|
+
query: { toSQL: () => Query },
|
|
357
|
+
options: ForgeSqlOrmOptions,
|
|
358
|
+
results: unknown,
|
|
359
|
+
cacheTtl: number,
|
|
360
|
+
): Promise<void> {
|
|
361
|
+
if (!options.cacheEntityName) {
|
|
362
|
+
throw new Error("cacheEntityName is not configured");
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
try {
|
|
366
|
+
const entityQueryName =
|
|
367
|
+
options.cacheEntityQueryName ?? CACHE_CONSTANTS.DEFAULT_ENTITY_QUERY_NAME;
|
|
368
|
+
const expirationName =
|
|
369
|
+
options.cacheEntityExpirationName ?? CACHE_CONSTANTS.DEFAULT_EXPIRATION_NAME;
|
|
370
|
+
const dataName = options.cacheEntityDataName ?? CACHE_CONSTANTS.DEFAULT_DATA_NAME;
|
|
371
|
+
|
|
372
|
+
const sqlQuery = query.toSQL();
|
|
373
|
+
|
|
374
|
+
// Skip cache if table is in cache context (will be cleared)
|
|
375
|
+
if (await isTableContainsTableInCacheContext(sqlQuery.sql, options)) {
|
|
376
|
+
if (options.logRawSqlQuery) {
|
|
377
|
+
console.warn(`Context contains value to clear. Skip setting from cache`);
|
|
378
|
+
}
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const key = hashKey(sqlQuery);
|
|
383
|
+
|
|
384
|
+
await kvs
|
|
385
|
+
.transact()
|
|
386
|
+
.set(
|
|
387
|
+
key,
|
|
388
|
+
{
|
|
389
|
+
[entityQueryName]: sqlQuery.sql.toLowerCase(),
|
|
390
|
+
[expirationName]: nowPlusSeconds(cacheTtl),
|
|
391
|
+
[dataName]: JSON.stringify(results),
|
|
392
|
+
},
|
|
393
|
+
{ entityName: options.cacheEntityName },
|
|
394
|
+
)
|
|
395
|
+
.execute();
|
|
396
|
+
|
|
397
|
+
if (options.logRawSqlQuery) {
|
|
398
|
+
console.warn(`Store value to cache, cacheKey: ${key}`);
|
|
399
|
+
}
|
|
400
|
+
} catch (error: any) {
|
|
401
|
+
console.error(`Error setting cache: ${error.message}`, error);
|
|
402
|
+
}
|
|
403
|
+
}
|
package/src/utils/sqlUtils.ts
CHANGED
|
@@ -74,6 +74,48 @@ export const parseDateTime = (value: string | Date, format: string): Date => {
|
|
|
74
74
|
return result;
|
|
75
75
|
};
|
|
76
76
|
|
|
77
|
+
/**
|
|
78
|
+
* Helper function to validate and format a date-like value using Luxon DateTime.
|
|
79
|
+
* @param value - Date object, ISO/RFC2822/SQL/HTTP string, or timestamp (number|string).
|
|
80
|
+
* @param format - DateTime format string (Luxon format tokens).
|
|
81
|
+
* @returns Formatted date string.
|
|
82
|
+
* @throws Error if value cannot be parsed as a valid date.
|
|
83
|
+
*/
|
|
84
|
+
export function formatDateTime(value: Date | string | number, format: string): string {
|
|
85
|
+
let dt: DateTime|null = null;
|
|
86
|
+
|
|
87
|
+
if (value instanceof Date) {
|
|
88
|
+
dt = DateTime.fromJSDate(value);
|
|
89
|
+
} else if (typeof value === "string") {
|
|
90
|
+
// Перебор парсеров
|
|
91
|
+
for (const parser of [
|
|
92
|
+
DateTime.fromISO,
|
|
93
|
+
DateTime.fromRFC2822,
|
|
94
|
+
DateTime.fromSQL,
|
|
95
|
+
DateTime.fromHTTP,
|
|
96
|
+
]) {
|
|
97
|
+
dt = parser(value);
|
|
98
|
+
if (dt.isValid) break;
|
|
99
|
+
}
|
|
100
|
+
if (!dt?.isValid) {
|
|
101
|
+
const parsed = Number(value);
|
|
102
|
+
if (!isNaN(parsed)) {
|
|
103
|
+
dt = DateTime.fromMillis(parsed);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
} else if (typeof value === "number") {
|
|
107
|
+
dt = DateTime.fromMillis(value);
|
|
108
|
+
} else {
|
|
109
|
+
throw new Error("Unsupported type");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (!dt?.isValid) {
|
|
113
|
+
throw new Error("Invalid Date");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return dt.toFormat(format);
|
|
117
|
+
}
|
|
118
|
+
|
|
77
119
|
/**
|
|
78
120
|
* Gets primary keys from the schema.
|
|
79
121
|
* @template T - The type of the table schema
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { clearExpiredCache } from "../utils/cacheUtils";
|
|
2
|
+
import { ForgeSqlOrmOptions } from "../core/ForgeSQLQueryBuilder";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Scheduler trigger for clearing expired cache entries.
|
|
6
|
+
*
|
|
7
|
+
* This trigger should be configured as a Forge scheduler to automatically
|
|
8
|
+
* clean up expired cache entries based on their TTL (Time To Live).
|
|
9
|
+
*
|
|
10
|
+
* @param options - Optional ForgeSQL ORM configuration. If not provided,
|
|
11
|
+
* uses default cache settings with cacheEntityName: "cache"
|
|
12
|
+
* @returns Promise that resolves to HTTP response object
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* // In your index.ts
|
|
17
|
+
* import { clearCacheSchedulerTrigger } from "forge-sql-orm";
|
|
18
|
+
*
|
|
19
|
+
* export const clearCache = () => {
|
|
20
|
+
* return clearCacheSchedulerTrigger({
|
|
21
|
+
* cacheEntityName: "cache",
|
|
22
|
+
* logRawSqlQuery: true
|
|
23
|
+
* });
|
|
24
|
+
* };
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```yaml
|
|
29
|
+
* # In manifest.yml
|
|
30
|
+
* scheduledTrigger:
|
|
31
|
+
* - key: clear-cache-trigger
|
|
32
|
+
* function: clearCache
|
|
33
|
+
* interval: fiveMinute
|
|
34
|
+
*
|
|
35
|
+
* function:
|
|
36
|
+
* - key: clearCache
|
|
37
|
+
* handler: index.clearCache
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export const clearCacheSchedulerTrigger = async (options?: ForgeSqlOrmOptions) => {
|
|
41
|
+
try {
|
|
42
|
+
const newOptions: ForgeSqlOrmOptions = options ?? {
|
|
43
|
+
logRawSqlQuery: false,
|
|
44
|
+
disableOptimisticLocking: false,
|
|
45
|
+
cacheTTL: 120,
|
|
46
|
+
cacheEntityName: "cache",
|
|
47
|
+
cacheEntityQueryName: "sql",
|
|
48
|
+
cacheEntityExpirationName: "expiration",
|
|
49
|
+
cacheEntityDataName: "data",
|
|
50
|
+
};
|
|
51
|
+
if (!newOptions.cacheEntityName) {
|
|
52
|
+
throw new Error("cacheEntityName is not configured");
|
|
53
|
+
}
|
|
54
|
+
await clearExpiredCache(newOptions);
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
headers: { "Content-Type": ["application/json"] },
|
|
58
|
+
statusCode: 200,
|
|
59
|
+
statusText: "OK",
|
|
60
|
+
body: JSON.stringify({
|
|
61
|
+
success: true,
|
|
62
|
+
message: "Cache cleanup completed successfully",
|
|
63
|
+
timestamp: new Date().toISOString(),
|
|
64
|
+
}),
|
|
65
|
+
};
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.error("Error during cache cleanup: ", JSON.stringify(error));
|
|
68
|
+
return {
|
|
69
|
+
headers: { "Content-Type": ["application/json"] },
|
|
70
|
+
statusCode: 500,
|
|
71
|
+
statusText: "Internal Server Error",
|
|
72
|
+
body: JSON.stringify({
|
|
73
|
+
success: false,
|
|
74
|
+
error: error instanceof Error ? error.message : "Unknown error during cache cleanup",
|
|
75
|
+
timestamp: new Date().toISOString(),
|
|
76
|
+
}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
};
|
package/src/webtriggers/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from "./dropMigrationWebTrigger";
|
|
|
2
2
|
export * from "./applyMigrationsWebTrigger";
|
|
3
3
|
export * from "./fetchSchemaWebTrigger";
|
|
4
4
|
export * from "./dropTablesMigrationWebTrigger";
|
|
5
|
+
export * from "./clearCacheSchedulerTrigger";
|
|
5
6
|
|
|
6
7
|
export interface TriggerResponse<BODY> {
|
|
7
8
|
body?: BODY;
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { MySqlRemoteDatabase } from "drizzle-orm/mysql-proxy";
|
|
2
|
-
import type { SelectedFields } from "drizzle-orm/mysql-core/query-builders/select.types";
|
|
3
|
-
import { MySqlSelectBuilder } from "drizzle-orm/mysql-core";
|
|
4
|
-
import { MySqlRemotePreparedQueryHKT } from "drizzle-orm/mysql-proxy";
|
|
5
|
-
export declare function patchDbWithSelectAliased(db: MySqlRemoteDatabase<any>): MySqlRemoteDatabase<any> & {
|
|
6
|
-
selectAliased: <TSelection extends SelectedFields>(fields: TSelection) => MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT>;
|
|
7
|
-
selectAliasedDistinct: <TSelection extends SelectedFields>(fields: TSelection) => MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT>;
|
|
8
|
-
};
|
|
9
|
-
//# sourceMappingURL=selectAliased.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"selectAliased.d.ts","sourceRoot":"","sources":["../../../../src/lib/drizzle/extensions/selectAliased.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oDAAoD,CAAC;AAEzF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAkDtE,wBAAgB,wBAAwB,CAAC,EAAE,EAAE,mBAAmB,CAAC,GAAG,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,GAAG;IACjG,aAAa,EAAE,CAAC,UAAU,SAAS,cAAc,EAC/C,MAAM,EAAE,UAAU,KACf,kBAAkB,CAAC,UAAU,EAAE,2BAA2B,CAAC,CAAC;IACjE,qBAAqB,EAAE,CAAC,UAAU,SAAS,cAAc,EACvD,MAAM,EAAE,UAAU,KACf,kBAAkB,CAAC,UAAU,EAAE,2BAA2B,CAAC,CAAC;CAClE,CAUA"}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { MySqlRemoteDatabase } from "drizzle-orm/mysql-proxy";
|
|
2
|
-
import type { SelectedFields } from "drizzle-orm/mysql-core/query-builders/select.types";
|
|
3
|
-
import { applyFromDriverTransform, mapSelectFieldsWithAlias } from "../../..";
|
|
4
|
-
import { MySqlSelectBuilder } from "drizzle-orm/mysql-core";
|
|
5
|
-
import { MySqlRemotePreparedQueryHKT } from "drizzle-orm/mysql-proxy";
|
|
6
|
-
|
|
7
|
-
function createAliasedSelectBuilder<TSelection extends SelectedFields>(
|
|
8
|
-
db: MySqlRemoteDatabase<any>,
|
|
9
|
-
fields: TSelection,
|
|
10
|
-
selectFn: (selections: any) => MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT>,
|
|
11
|
-
): MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT> {
|
|
12
|
-
const { selections, aliasMap } = mapSelectFieldsWithAlias(fields);
|
|
13
|
-
const builder = selectFn(selections);
|
|
14
|
-
|
|
15
|
-
const wrapBuilder = (rawBuilder: any): any => {
|
|
16
|
-
return new Proxy(rawBuilder, {
|
|
17
|
-
get(target, prop, receiver) {
|
|
18
|
-
if (prop === "execute") {
|
|
19
|
-
return async (...args: any[]) => {
|
|
20
|
-
const rows = await target.execute(...args);
|
|
21
|
-
return applyFromDriverTransform(rows, selections, aliasMap);
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
if (prop === "then") {
|
|
26
|
-
return (onfulfilled: any, onrejected: any) =>
|
|
27
|
-
target.execute().then((rows: unknown[]) => {
|
|
28
|
-
const transformed = applyFromDriverTransform(rows, selections, aliasMap);
|
|
29
|
-
return onfulfilled?.(transformed);
|
|
30
|
-
}, onrejected);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const value = Reflect.get(target, prop, receiver);
|
|
34
|
-
|
|
35
|
-
if (typeof value === "function") {
|
|
36
|
-
return (...args: any[]) => {
|
|
37
|
-
const result = value.apply(target, args);
|
|
38
|
-
|
|
39
|
-
if (typeof result === "object" && result !== null && "execute" in result) {
|
|
40
|
-
return wrapBuilder(result);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
return result;
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
return value;
|
|
48
|
-
},
|
|
49
|
-
});
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
return wrapBuilder(builder);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export function patchDbWithSelectAliased(db: MySqlRemoteDatabase<any>): MySqlRemoteDatabase<any> & {
|
|
56
|
-
selectAliased: <TSelection extends SelectedFields>(
|
|
57
|
-
fields: TSelection,
|
|
58
|
-
) => MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT>;
|
|
59
|
-
selectAliasedDistinct: <TSelection extends SelectedFields>(
|
|
60
|
-
fields: TSelection,
|
|
61
|
-
) => MySqlSelectBuilder<TSelection, MySqlRemotePreparedQueryHKT>;
|
|
62
|
-
} {
|
|
63
|
-
db.selectAliased = function <TSelection extends SelectedFields>(fields: TSelection) {
|
|
64
|
-
return createAliasedSelectBuilder(db, fields, (selections) => db.select(selections));
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
db.selectAliasedDistinct = function <TSelection extends SelectedFields>(fields: TSelection) {
|
|
68
|
-
return createAliasedSelectBuilder(db, fields, (selections) => db.selectDistinct(selections));
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
return db;
|
|
72
|
-
}
|