Skip to content

Commit efe1777

Browse files
committed
dev
1 parent e3d8232 commit efe1777

File tree

5 files changed

+604
-234
lines changed

5 files changed

+604
-234
lines changed
Lines changed: 167 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,30 @@
1-
# QueryCache DataSource Schema Method
1+
# QueryCache DataSource Metadata Methods
22

3-
This document describes the new `queryDataSourceSchema` method added to the `QueryCache` class, which provides cached and queued access to datasource schema information.
3+
This document describes the datasource metadata query methods added to the `QueryCache` class, which provide cached and queued access to datasource schema, table, and column information.
44

55
## Overview
66

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.
7+
The QueryCache class now includes three main methods for querying datasource metadata:
8+
9+
1. **`queryDataSourceSchema`** - Query available schemas in a datasource
10+
2. **`queryTablesForSchemas`** - Query tables for specific schemas
11+
3. **`queryColumnsForTables`** - Query columns for specific tables
12+
13+
All methods utilize a shared caching and queue infrastructure with automatic cache management, smart refresh, and comprehensive error handling.
814

915
## Features
1016

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
17+
- **Automatic Caching**: Results cached in CubeStore (or memory) with configurable expiration
18+
- **Queue Management**: Uses existing queue system to prevent concurrent identical requests
1319
- **Smart Refresh**: Automatically refreshes expired cache entries
1420
- **Force Refresh**: Option to bypass cache and fetch fresh data
1521
- **Fallback Support**: Returns cached data if refresh fails
16-
- **Cache Management**: Includes method to manually clear cache
22+
- **Cache Management**: Methods to manually clear specific caches
23+
- **DRY Implementation**: Shared generic caching logic to avoid code duplication
1724

18-
## Method Signature
25+
## Method Signatures
26+
27+
### queryDataSourceSchema
1928

2029
```typescript
2130
public async queryDataSourceSchema(
@@ -29,19 +38,50 @@ public async queryDataSourceSchema(
2938
): Promise<QuerySchemasResult[]>
3039
```
3140

41+
### queryTablesForSchemas
42+
43+
```typescript
44+
public async queryTablesForSchemas(
45+
schemas: QuerySchemasResult[],
46+
dataSource: string = 'default',
47+
options: {
48+
requestId?: string;
49+
forceRefresh?: boolean;
50+
renewalThreshold?: number;
51+
expiration?: number;
52+
} = {}
53+
): Promise<QueryTablesResult[]>
54+
```
55+
56+
### queryColumnsForTables
57+
58+
```typescript
59+
public async queryColumnsForTables(
60+
tables: QueryTablesResult[],
61+
dataSource: string = 'default',
62+
options: {
63+
requestId?: string;
64+
forceRefresh?: boolean;
65+
renewalThreshold?: number;
66+
expiration?: number;
67+
} = {}
68+
): Promise<QueryColumnsResult[]>
69+
```
70+
3271
## Parameters
3372

3473
- **dataSource** (string, optional): The datasource name to query. Defaults to 'default'.
74+
- **schemas** (QuerySchemasResult[]): Array of schema objects for table queries
75+
- **tables** (QueryTablesResult[]): Array of table objects for column queries
3576
- **options** (object, optional): Configuration options:
3677
- **requestId** (string, optional): Request ID for logging and tracking
3778
- **forceRefresh** (boolean, optional): If true, bypasses cache and fetches fresh data. Defaults to false.
3879
- **renewalThreshold** (number, optional): Cache refresh threshold in seconds. Defaults to 24 hours (86400).
3980
- **expiration** (number, optional): Cache expiration time in seconds. Defaults to 7 days (604800).
4081

41-
## Return Value
42-
43-
Returns a Promise that resolves to an array of `QuerySchemasResult` objects:
82+
## Return Values
4483

84+
### QuerySchemasResult[]
4585
```typescript
4686
[
4787
{ schema_name: 'public' },
@@ -50,9 +90,38 @@ Returns a Promise that resolves to an array of `QuerySchemasResult` objects:
5090
]
5191
```
5292

93+
### QueryTablesResult[]
94+
```typescript
95+
[
96+
{ schema_name: 'public', table_name: 'users' },
97+
{ schema_name: 'public', table_name: 'orders' },
98+
{ schema_name: 'analytics', table_name: 'events' }
99+
]
100+
```
101+
102+
### QueryColumnsResult[]
103+
```typescript
104+
[
105+
{
106+
schema_name: 'public',
107+
table_name: 'users',
108+
column_name: 'id',
109+
data_type: 'integer',
110+
attributes?: string[],
111+
foreign_keys?: ForeignKey[]
112+
},
113+
{
114+
schema_name: 'public',
115+
table_name: 'users',
116+
column_name: 'name',
117+
data_type: 'text'
118+
}
119+
]
120+
```
121+
53122
## Usage Examples
54123

55-
### Basic Usage
124+
### Basic Schema Query
56125

57126
```typescript
58127
const queryCache = new QueryCache(/* ... */);
@@ -62,38 +131,71 @@ const schemas = await queryCache.queryDataSourceSchema();
62131
console.log('Available schemas:', schemas);
63132
```
64133

65-
### With Request ID
134+
### Full Metadata Discovery Chain
66135

67136
```typescript
137+
// Get all schemas
68138
const schemas = await queryCache.queryDataSourceSchema('default', {
69-
requestId: 'my-request-123'
139+
requestId: 'metadata-discovery'
140+
});
141+
142+
// Get all tables for those schemas
143+
const tables = await queryCache.queryTablesForSchemas(schemas, 'default', {
144+
requestId: 'metadata-discovery'
70145
});
146+
147+
// Get all columns for those tables
148+
const columns = await queryCache.queryColumnsForTables(tables, 'default', {
149+
requestId: 'metadata-discovery'
150+
});
151+
152+
console.log(`Found ${schemas.length} schemas, ${tables.length} tables, ${columns.length} columns`);
71153
```
72154

73-
### Force Refresh Cache
155+
### Selective Metadata Queries
74156

75157
```typescript
76-
const freshSchemas = await queryCache.queryDataSourceSchema('analytics', {
77-
forceRefresh: true,
78-
requestId: 'force-refresh-request'
79-
});
158+
// Get specific schemas only
159+
const publicSchema = [{ schema_name: 'public' }];
160+
const publicTables = await queryCache.queryTablesForSchemas(publicSchema, 'default');
161+
162+
// Get columns for specific tables only
163+
const userTable = [{ schema_name: 'public', table_name: 'users' }];
164+
const userColumns = await queryCache.queryColumnsForTables(userTable, 'default');
80165
```
81166

82-
### Custom Cache Settings
167+
### Force Refresh Examples
83168

84169
```typescript
85-
const schemas = await queryCache.queryDataSourceSchema('reporting', {
170+
// Force refresh schemas
171+
const freshSchemas = await queryCache.queryDataSourceSchema('analytics', {
172+
forceRefresh: true,
173+
requestId: 'force-refresh-schemas'
174+
});
175+
176+
// Force refresh tables with custom cache settings
177+
const freshTables = await queryCache.queryTablesForSchemas(freshSchemas, 'analytics', {
178+
forceRefresh: true,
86179
renewalThreshold: 60 * 60, // 1 hour
87-
expiration: 3 * 24 * 60 * 60, // 3 days
88-
requestId: 'custom-cache-request'
180+
expiration: 2 * 24 * 60 * 60, // 2 days
181+
requestId: 'force-refresh-tables'
89182
});
90183
```
91184

92-
### Clear Cache
185+
### Cache Management
93186

94187
```typescript
95-
// Clear cache for specific datasource
188+
// Clear individual caches
96189
await queryCache.clearDataSourceSchemaCache('default');
190+
191+
const schemas = [{ schema_name: 'public' }, { schema_name: 'analytics' }];
192+
await queryCache.clearTablesForSchemasCache(schemas, 'default');
193+
194+
const tables = [
195+
{ schema_name: 'public', table_name: 'users' },
196+
{ schema_name: 'public', table_name: 'orders' }
197+
];
198+
await queryCache.clearColumnsForTablesCache(tables, 'default');
97199
```
98200

99201
## Cache Behavior
@@ -106,51 +208,77 @@ await queryCache.clearDataSourceSchemaCache('default');
106208

107209
## Implementation Details
108210

109-
### Queue Handler
211+
### Queue Handlers
110212

111-
The method adds a new `getSchemas` handler to the QueryQueue:
213+
The methods add three new handlers to the QueryQueue:
112214

113215
```typescript
114216
getSchemas: async (req) => {
115217
const client = await clientFactory();
116218
return client.getSchemas();
117219
}
220+
221+
getTablesForSchemas: async (req) => {
222+
const client = await clientFactory();
223+
return client.getTablesForSpecificSchemas(req.schemas);
224+
}
225+
226+
getColumnsForTables: async (req) => {
227+
const client = await clientFactory();
228+
return client.getColumnsForSpecificTables(req.tables);
229+
}
118230
```
119231

120232
### Cache Key Structure
121233

122-
Cache keys use the format: `['DATASOURCE_SCHEMA', dataSource]`
234+
- **Schemas**: `['DATASOURCE_SCHEMA', dataSource]`
235+
- **Tables**: `['DATASOURCE_TABLES', '${dataSource}:${schemaNames}']`
236+
- **Columns**: `['DATASOURCE_COLUMNS', '${dataSource}:${tableNames}']`
237+
238+
### DRY Implementation
239+
240+
All methods use a shared generic `queryDataSourceMetadata<T>()` method that handles:
241+
- Cache key generation
242+
- Queue execution
243+
- Cache retrieval and updating
244+
- Error handling and fallbacks
245+
- Logging
246+
247+
This eliminates code duplication and ensures consistent behavior across all methods.
123248

124249
### Logging
125250

126-
The method provides comprehensive logging for:
251+
Comprehensive logging includes:
127252
- Cache hits and misses
128253
- Fresh data fetching
129254
- Cache updates
130255
- Error conditions
256+
- Metadata about schemas/tables/columns being queried
131257

132258
## Error Handling
133259

134260
- Network errors during refresh fall back to cached data if available
135261
- Missing cache triggers fresh data fetch
136262
- All errors are properly logged with context
137-
- TypeScript types ensure type safety
263+
- TypeScript types ensure type safety throughout
138264

139265
## Performance Considerations
140266

141267
- Default 24-hour cache renewal threshold balances freshness with performance
142268
- Queue system prevents duplicate concurrent requests
143-
- In-memory caching disabled for schema queries to prevent memory issues
269+
- Cache keys include sorted parameter lists for consistency
144270
- CubeStore provides persistent, scalable caching
271+
- Intelligent cache key construction prevents cache pollution
145272

146273
## Testing
147274

148-
A test suite is provided in `test/datasource-schema.test.ts` that validates:
149-
- Cache miss behavior
150-
- Cache hit behavior
275+
A comprehensive test suite is provided in `test/datasource-schema.test.ts` that validates:
276+
- All three metadata query methods
277+
- Cache miss and hit behavior
151278
- Force refresh functionality
152-
- Cache clearing
153-
- Error handling
279+
- Cache clearing for all types
280+
- Full metadata discovery chains
281+
- Error handling scenarios
154282

155283
Run the test with:
156284
```bash
@@ -159,8 +287,9 @@ ts-node test/datasource-schema.test.ts
159287

160288
## Integration
161289

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
290+
These methods integrate seamlessly with the existing QueryCache infrastructure:
291+
- Use the same queue system as other operations
292+
- Follow the same caching patterns
165293
- Compatible with all supported cache drivers (memory, CubeStore)
166294
- Consistent logging and error handling
295+
- Proper TypeScript typing throughout

0 commit comments

Comments
 (0)