Skip to content

Commit e3d8232

Browse files
committed
dev
1 parent c388350 commit e3d8232

File tree

4 files changed

+529
-0
lines changed

4 files changed

+529
-0
lines changed
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
# QueryCache DataSource Schema Method
2+
3+
This document describes the new `queryDataSourceSchema` method added to the `QueryCache` class, which provides cached and queued access to datasource schema information.
4+
5+
## Overview
6+
7+
The `queryDataSourceSchema` method allows you to query the available schemas in a datasource with automatic caching and queue management. This is particularly useful for applications that need to frequently access schema information without overwhelming the database with repeated queries.
8+
9+
## Features
10+
11+
- **Automatic Caching**: Results are cached in CubeStore (or memory) with configurable expiration
12+
- **Queue Management**: Uses the existing queue system to prevent concurrent identical requests
13+
- **Smart Refresh**: Automatically refreshes expired cache entries
14+
- **Force Refresh**: Option to bypass cache and fetch fresh data
15+
- **Fallback Support**: Returns cached data if refresh fails
16+
- **Cache Management**: Includes method to manually clear cache
17+
18+
## Method Signature
19+
20+
```typescript
21+
public async queryDataSourceSchema(
22+
dataSource: string = 'default',
23+
options: {
24+
requestId?: string;
25+
forceRefresh?: boolean;
26+
renewalThreshold?: number;
27+
expiration?: number;
28+
} = {}
29+
): Promise<QuerySchemasResult[]>
30+
```
31+
32+
## Parameters
33+
34+
- **dataSource** (string, optional): The datasource name to query. Defaults to 'default'.
35+
- **options** (object, optional): Configuration options:
36+
- **requestId** (string, optional): Request ID for logging and tracking
37+
- **forceRefresh** (boolean, optional): If true, bypasses cache and fetches fresh data. Defaults to false.
38+
- **renewalThreshold** (number, optional): Cache refresh threshold in seconds. Defaults to 24 hours (86400).
39+
- **expiration** (number, optional): Cache expiration time in seconds. Defaults to 7 days (604800).
40+
41+
## Return Value
42+
43+
Returns a Promise that resolves to an array of `QuerySchemasResult` objects:
44+
45+
```typescript
46+
[
47+
{ schema_name: 'public' },
48+
{ schema_name: 'analytics' },
49+
{ schema_name: 'reporting' }
50+
]
51+
```
52+
53+
## Usage Examples
54+
55+
### Basic Usage
56+
57+
```typescript
58+
const queryCache = new QueryCache(/* ... */);
59+
60+
// Get schemas for default datasource
61+
const schemas = await queryCache.queryDataSourceSchema();
62+
console.log('Available schemas:', schemas);
63+
```
64+
65+
### With Request ID
66+
67+
```typescript
68+
const schemas = await queryCache.queryDataSourceSchema('default', {
69+
requestId: 'my-request-123'
70+
});
71+
```
72+
73+
### Force Refresh Cache
74+
75+
```typescript
76+
const freshSchemas = await queryCache.queryDataSourceSchema('analytics', {
77+
forceRefresh: true,
78+
requestId: 'force-refresh-request'
79+
});
80+
```
81+
82+
### Custom Cache Settings
83+
84+
```typescript
85+
const schemas = await queryCache.queryDataSourceSchema('reporting', {
86+
renewalThreshold: 60 * 60, // 1 hour
87+
expiration: 3 * 24 * 60 * 60, // 3 days
88+
requestId: 'custom-cache-request'
89+
});
90+
```
91+
92+
### Clear Cache
93+
94+
```typescript
95+
// Clear cache for specific datasource
96+
await queryCache.clearDataSourceSchemaCache('default');
97+
```
98+
99+
## Cache Behavior
100+
101+
1. **First Call**: Fetches data from datasource and caches it
102+
2. **Subsequent Calls**: Returns cached data if within renewal threshold
103+
3. **Expired Cache**: Automatically fetches fresh data and updates cache
104+
4. **Failed Refresh**: Returns cached data as fallback if refresh fails
105+
5. **Force Refresh**: Always fetches fresh data and updates cache
106+
107+
## Implementation Details
108+
109+
### Queue Handler
110+
111+
The method adds a new `getSchemas` handler to the QueryQueue:
112+
113+
```typescript
114+
getSchemas: async (req) => {
115+
const client = await clientFactory();
116+
return client.getSchemas();
117+
}
118+
```
119+
120+
### Cache Key Structure
121+
122+
Cache keys use the format: `['DATASOURCE_SCHEMA', dataSource]`
123+
124+
### Logging
125+
126+
The method provides comprehensive logging for:
127+
- Cache hits and misses
128+
- Fresh data fetching
129+
- Cache updates
130+
- Error conditions
131+
132+
## Error Handling
133+
134+
- Network errors during refresh fall back to cached data if available
135+
- Missing cache triggers fresh data fetch
136+
- All errors are properly logged with context
137+
- TypeScript types ensure type safety
138+
139+
## Performance Considerations
140+
141+
- Default 24-hour cache renewal threshold balances freshness with performance
142+
- Queue system prevents duplicate concurrent requests
143+
- In-memory caching disabled for schema queries to prevent memory issues
144+
- CubeStore provides persistent, scalable caching
145+
146+
## Testing
147+
148+
A test suite is provided in `test/datasource-schema.test.ts` that validates:
149+
- Cache miss behavior
150+
- Cache hit behavior
151+
- Force refresh functionality
152+
- Cache clearing
153+
- Error handling
154+
155+
Run the test with:
156+
```bash
157+
ts-node test/datasource-schema.test.ts
158+
```
159+
160+
## Integration
161+
162+
This method integrates seamlessly with the existing QueryCache infrastructure:
163+
- Uses the same queue system as other operations
164+
- Follows the same caching patterns
165+
- Compatible with all supported cache drivers (memory, CubeStore)
166+
- Consistent logging and error handling
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* Example usage of the queryDataSourceSchema method
3+
*/
4+
5+
import { QueryCache } from '../src/orchestrator/QueryCache';
6+
7+
// Example usage of the new queryDataSourceSchema method
8+
async function exampleUsage() {
9+
// Assuming you have a QueryCache instance
10+
const queryCache = new QueryCache(
11+
'example',
12+
(_dataSource) => {
13+
// Your driver factory implementation
14+
throw new Error('Driver factory not implemented in example');
15+
},
16+
(msg, params) => console.log(msg, params), // logger
17+
{
18+
cacheAndQueueDriver: 'cubestore', // Use CubeStore for caching
19+
cubeStoreDriverFactory: async () => {
20+
// Your CubeStore driver factory implementation
21+
throw new Error('CubeStore driver factory not implemented in example');
22+
}
23+
}
24+
);
25+
26+
try {
27+
// Query datasource schema with default options (24h cache)
28+
const schemas = await queryCache.queryDataSourceSchema('default', {
29+
requestId: 'example-request-1'
30+
});
31+
32+
console.log('Available schemas:', schemas);
33+
34+
// Force refresh the schema cache
35+
const freshSchemas = await queryCache.queryDataSourceSchema('default', {
36+
requestId: 'example-request-2',
37+
forceRefresh: true
38+
});
39+
40+
console.log('Fresh schemas:', freshSchemas);
41+
42+
// Query with custom cache settings (1 hour cache, 3 days expiration)
43+
const schemasCustomCache = await queryCache.queryDataSourceSchema('analytics', {
44+
requestId: 'example-request-3',
45+
renewalThreshold: 60 * 60, // 1 hour
46+
expiration: 3 * 24 * 60 * 60 // 3 days
47+
});
48+
49+
console.log('Analytics schemas:', schemasCustomCache);
50+
51+
// Clear cache for a specific datasource
52+
await queryCache.clearDataSourceSchemaCache('default');
53+
console.log('Cache cleared for default datasource');
54+
} catch (error) {
55+
console.error('Error querying datasource schema:', error);
56+
}
57+
}
58+
59+
// The method returns an array of QuerySchemasResult objects:
60+
// [
61+
// { schema_name: 'public' },
62+
// { schema_name: 'analytics' },
63+
// { schema_name: 'reporting' }
64+
// ]
65+
66+
export { exampleUsage };

0 commit comments

Comments
 (0)