@objectstack/service-analytics 4.0.4 → 4.1.0

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.
@@ -1,469 +0,0 @@
1
- // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2
-
3
- import { describe, it, expect, vi, beforeEach } from 'vitest';
4
- import type { Cube } from '@objectstack/spec/data';
5
- import type { AnalyticsQuery, AnalyticsResult, IAnalyticsService } from '@objectstack/spec/contracts';
6
- import { AnalyticsService } from '../analytics-service.js';
7
- import { CubeRegistry } from '../cube-registry.js';
8
- import { NativeSQLStrategy } from '../strategies/native-sql-strategy.js';
9
- import { ObjectQLStrategy } from '../strategies/objectql-strategy.js';
10
- import type { DriverCapabilities } from '../strategies/types.js';
11
-
12
- // ─────────────────────────────────────────────────────────────────
13
- // Test fixtures
14
- // ─────────────────────────────────────────────────────────────────
15
-
16
- const ordersCube: Cube = {
17
- name: 'orders',
18
- title: 'Orders',
19
- sql: 'orders',
20
- measures: {
21
- count: { name: 'count', label: 'Count', type: 'count', sql: '*' },
22
- total_amount: { name: 'total_amount', label: 'Total Amount', type: 'sum', sql: 'amount' },
23
- avg_amount: { name: 'avg_amount', label: 'Avg Amount', type: 'avg', sql: 'amount' },
24
- },
25
- dimensions: {
26
- status: { name: 'status', label: 'Status', type: 'string', sql: 'status' },
27
- created_at: {
28
- name: 'created_at',
29
- label: 'Created At',
30
- type: 'time',
31
- sql: 'created_at',
32
- granularities: ['day', 'week', 'month'],
33
- },
34
- },
35
- public: false,
36
- };
37
-
38
- const baseQuery: AnalyticsQuery = {
39
- cube: 'orders',
40
- measures: ['orders.count', 'orders.total_amount'],
41
- dimensions: ['orders.status'],
42
- };
43
-
44
- // Suppress logger output in tests
45
- const silentLogger = {
46
- info: vi.fn(),
47
- debug: vi.fn(),
48
- warn: vi.fn(),
49
- error: vi.fn(),
50
- child: vi.fn().mockReturnThis(),
51
- } as any;
52
-
53
- // ─────────────────────────────────────────────────────────────────
54
- // CubeRegistry
55
- // ─────────────────────────────────────────────────────────────────
56
-
57
- describe('CubeRegistry', () => {
58
- let registry: CubeRegistry;
59
-
60
- beforeEach(() => {
61
- registry = new CubeRegistry();
62
- });
63
-
64
- it('should register and retrieve a cube', () => {
65
- registry.register(ordersCube);
66
- expect(registry.get('orders')).toEqual(ordersCube);
67
- expect(registry.has('orders')).toBe(true);
68
- expect(registry.size).toBe(1);
69
- });
70
-
71
- it('should register multiple cubes at once', () => {
72
- const cube2: Cube = { ...ordersCube, name: 'products', sql: 'products' };
73
- registry.registerAll([ordersCube, cube2]);
74
- expect(registry.size).toBe(2);
75
- expect(registry.names()).toEqual(['orders', 'products']);
76
- });
77
-
78
- it('should return undefined for unknown cube', () => {
79
- expect(registry.get('nonexistent')).toBeUndefined();
80
- expect(registry.has('nonexistent')).toBe(false);
81
- });
82
-
83
- it('should clear all cubes', () => {
84
- registry.register(ordersCube);
85
- registry.clear();
86
- expect(registry.size).toBe(0);
87
- });
88
-
89
- it('should infer a cube from object fields', () => {
90
- const cube = registry.inferFromObject('tasks', [
91
- { name: 'title', type: 'text', label: 'Title' },
92
- { name: 'hours', type: 'number', label: 'Hours' },
93
- { name: 'due_date', type: 'date', label: 'Due Date' },
94
- { name: 'active', type: 'boolean', label: 'Active' },
95
- ]);
96
-
97
- expect(cube.name).toBe('tasks');
98
- expect(cube.measures.count).toBeDefined();
99
- expect(cube.measures.hours_sum).toBeDefined();
100
- expect(cube.measures.hours_avg).toBeDefined();
101
- expect(cube.dimensions.title.type).toBe('string');
102
- expect(cube.dimensions.hours.type).toBe('number');
103
- expect(cube.dimensions.due_date.type).toBe('time');
104
- expect(cube.dimensions.active.type).toBe('boolean');
105
-
106
- // Should also be registered automatically
107
- expect(registry.get('tasks')).toBe(cube);
108
- });
109
- });
110
-
111
- // ─────────────────────────────────────────────────────────────────
112
- // NativeSQLStrategy
113
- // ─────────────────────────────────────────────────────────────────
114
-
115
- describe('NativeSQLStrategy', () => {
116
- const strategy = new NativeSQLStrategy();
117
-
118
- it('should have correct name and priority', () => {
119
- expect(strategy.name).toBe('NativeSQLStrategy');
120
- expect(strategy.priority).toBe(10);
121
- });
122
-
123
- it('should handle when nativeSql capability is true', () => {
124
- const ctx = {
125
- getCube: () => ordersCube,
126
- queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }),
127
- executeRawSql: vi.fn(),
128
- };
129
- expect(strategy.canHandle(baseQuery, ctx)).toBe(true);
130
- });
131
-
132
- it('should not handle when nativeSql is false', () => {
133
- const ctx = {
134
- getCube: () => ordersCube,
135
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }),
136
- };
137
- expect(strategy.canHandle(baseQuery, ctx)).toBe(false);
138
- });
139
-
140
- it('should not handle when cube is missing', () => {
141
- const ctx = {
142
- getCube: () => ordersCube,
143
- queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }),
144
- executeRawSql: vi.fn(),
145
- };
146
- expect(strategy.canHandle({ measures: ['count'] }, ctx)).toBe(false);
147
- });
148
-
149
- it('should generate SQL with dimensions, measures, and filters', async () => {
150
- const ctx = {
151
- getCube: () => ordersCube,
152
- queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }),
153
- executeRawSql: vi.fn(),
154
- };
155
-
156
- const query: AnalyticsQuery = {
157
- cube: 'orders',
158
- measures: ['orders.count', 'orders.total_amount'],
159
- dimensions: ['orders.status'],
160
- filters: [{ member: 'orders.status', operator: 'equals', values: ['completed'] }],
161
- limit: 10,
162
- };
163
-
164
- const { sql, params } = await strategy.generateSql(query, ctx);
165
-
166
- expect(sql).toContain('SELECT');
167
- expect(sql).toContain('COUNT(*)');
168
- expect(sql).toContain('SUM(amount)');
169
- expect(sql).toContain('GROUP BY');
170
- expect(sql).toContain('LIMIT 10');
171
- expect(params).toContain('completed');
172
- });
173
-
174
- it('should execute query and return structured result', async () => {
175
- const mockRows = [
176
- { 'orders.status': 'completed', 'orders.count': 5, 'orders.total_amount': 500 },
177
- ];
178
- const executeRawSql = vi.fn().mockResolvedValue(mockRows);
179
-
180
- const ctx = {
181
- getCube: () => ordersCube,
182
- queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }),
183
- executeRawSql,
184
- };
185
-
186
- const result = await strategy.execute(baseQuery, ctx);
187
-
188
- expect(executeRawSql).toHaveBeenCalled();
189
- expect(result.rows).toEqual(mockRows);
190
- expect(result.fields).toHaveLength(3); // 1 dimension + 2 measures
191
- expect(result.sql).toBeDefined();
192
- });
193
- });
194
-
195
- // ─────────────────────────────────────────────────────────────────
196
- // ObjectQLStrategy
197
- // ─────────────────────────────────────────────────────────────────
198
-
199
- describe('ObjectQLStrategy', () => {
200
- const strategy = new ObjectQLStrategy();
201
-
202
- it('should have correct name and priority', () => {
203
- expect(strategy.name).toBe('ObjectQLStrategy');
204
- expect(strategy.priority).toBe(20);
205
- });
206
-
207
- it('should handle when objectqlAggregate capability is true', () => {
208
- const ctx = {
209
- getCube: () => ordersCube,
210
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }),
211
- executeAggregate: vi.fn(),
212
- };
213
- expect(strategy.canHandle(baseQuery, ctx)).toBe(true);
214
- });
215
-
216
- it('should not handle without executeAggregate', () => {
217
- const ctx = {
218
- getCube: () => ordersCube,
219
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }),
220
- };
221
- expect(strategy.canHandle(baseQuery, ctx)).toBe(false);
222
- });
223
-
224
- it('should execute an aggregate query', async () => {
225
- const mockRows = [
226
- { status: 'pending', 'orders.count': 3, 'orders.total_amount': 150 },
227
- ];
228
- const executeAggregate = vi.fn().mockResolvedValue(mockRows);
229
-
230
- const ctx = {
231
- getCube: () => ordersCube,
232
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }),
233
- executeAggregate,
234
- };
235
-
236
- const result = await strategy.execute(baseQuery, ctx);
237
-
238
- expect(executeAggregate).toHaveBeenCalledWith('orders', expect.objectContaining({
239
- groupBy: ['status'],
240
- aggregations: expect.arrayContaining([
241
- expect.objectContaining({ method: 'count' }),
242
- expect.objectContaining({ method: 'sum' }),
243
- ]),
244
- }));
245
- expect(result.rows).toHaveLength(1);
246
- expect(result.fields).toHaveLength(3);
247
- });
248
-
249
- it('should generate representative SQL', async () => {
250
- const ctx = {
251
- getCube: () => ordersCube,
252
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }),
253
- executeAggregate: vi.fn(),
254
- };
255
-
256
- const { sql } = await strategy.generateSql(baseQuery, ctx);
257
- expect(sql).toContain('SELECT');
258
- expect(sql).toContain('COUNT(*)');
259
- expect(sql).toContain('GROUP BY');
260
- });
261
- });
262
-
263
- // ─────────────────────────────────────────────────────────────────
264
- // FallbackDelegateStrategy (internal, tested via AnalyticsService)
265
- // ─────────────────────────────────────────────────────────────────
266
-
267
- describe('FallbackDelegateStrategy (via AnalyticsService)', () => {
268
- it('should auto-add FallbackDelegateStrategy when fallbackService is configured', async () => {
269
- const mockResult: AnalyticsResult = { rows: [{ count: 10 }], fields: [{ name: 'count', type: 'number' }] };
270
- const fallback: IAnalyticsService = {
271
- query: vi.fn().mockResolvedValue(mockResult),
272
- getMeta: vi.fn().mockResolvedValue([]),
273
- };
274
-
275
- const service = new AnalyticsService({
276
- cubes: [ordersCube],
277
- logger: silentLogger,
278
- fallbackService: fallback,
279
- });
280
-
281
- const result = await service.query(baseQuery);
282
- expect(fallback.query).toHaveBeenCalledWith(baseQuery);
283
- expect(result).toEqual(mockResult);
284
- });
285
-
286
- it('should NOT add FallbackDelegateStrategy when no fallbackService', async () => {
287
- const service = new AnalyticsService({
288
- cubes: [ordersCube],
289
- logger: silentLogger,
290
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: false, inMemory: false }),
291
- });
292
-
293
- await expect(service.query(baseQuery)).rejects.toThrow('No strategy can handle');
294
- });
295
-
296
- it('should delegate generateSql to fallback service', async () => {
297
- const fallback: IAnalyticsService = {
298
- query: vi.fn(),
299
- getMeta: vi.fn(),
300
- generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT 1', params: [] }),
301
- };
302
-
303
- const service = new AnalyticsService({
304
- cubes: [ordersCube],
305
- logger: silentLogger,
306
- fallbackService: fallback,
307
- });
308
-
309
- const { sql } = await service.generateSql(baseQuery);
310
- expect(sql).toBe('SELECT 1');
311
- });
312
-
313
- it('should return placeholder SQL when fallback has no generateSql', async () => {
314
- const fallback: IAnalyticsService = {
315
- query: vi.fn().mockResolvedValue({ rows: [], fields: [] }),
316
- getMeta: vi.fn(),
317
- };
318
-
319
- const service = new AnalyticsService({
320
- cubes: [ordersCube],
321
- logger: silentLogger,
322
- fallbackService: fallback,
323
- });
324
-
325
- const { sql } = await service.generateSql(baseQuery);
326
- expect(sql).toContain('FallbackDelegateStrategy');
327
- });
328
- });
329
-
330
- // ─────────────────────────────────────────────────────────────────
331
- // AnalyticsService (Orchestrator)
332
- // ─────────────────────────────────────────────────────────────────
333
-
334
- describe('AnalyticsService', () => {
335
- it('should use NativeSQLStrategy when driver supports native SQL', async () => {
336
- const mockRows = [{ count: 42 }];
337
- const service = new AnalyticsService({
338
- cubes: [ordersCube],
339
- logger: silentLogger,
340
- queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: true, inMemory: false }),
341
- executeRawSql: vi.fn().mockResolvedValue(mockRows),
342
- });
343
-
344
- const result = await service.query(baseQuery);
345
- expect(result.rows).toEqual(mockRows);
346
- expect(result.sql).toBeDefined(); // NativeSQL always includes sql
347
- });
348
-
349
- it('should fall back to ObjectQLStrategy when nativeSql is false', async () => {
350
- const mockRows = [{ status: 'pending', 'orders.count': 3, 'orders.total_amount': 100 }];
351
- const service = new AnalyticsService({
352
- cubes: [ordersCube],
353
- logger: silentLogger,
354
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }),
355
- executeAggregate: vi.fn().mockResolvedValue(mockRows),
356
- });
357
-
358
- const result = await service.query(baseQuery);
359
- expect(result.rows).toHaveLength(1);
360
- });
361
-
362
- it('should fall back to FallbackDelegateStrategy with fallback service', async () => {
363
- const mockResult: AnalyticsResult = {
364
- rows: [{ count: 100 }],
365
- fields: [{ name: 'count', type: 'number' }],
366
- };
367
- const fallback: IAnalyticsService = {
368
- query: vi.fn().mockResolvedValue(mockResult),
369
- getMeta: vi.fn().mockResolvedValue([]),
370
- };
371
-
372
- const service = new AnalyticsService({
373
- cubes: [ordersCube],
374
- logger: silentLogger,
375
- fallbackService: fallback,
376
- });
377
-
378
- const result = await service.query(baseQuery);
379
- expect(result).toEqual(mockResult);
380
- expect(fallback.query).toHaveBeenCalled();
381
- });
382
-
383
- it('should throw when no strategy can handle the query', async () => {
384
- const service = new AnalyticsService({
385
- cubes: [ordersCube],
386
- logger: silentLogger,
387
- queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: false, inMemory: false }),
388
- });
389
-
390
- await expect(service.query(baseQuery)).rejects.toThrow('No strategy can handle');
391
- });
392
-
393
- it('should throw when cube name is missing', async () => {
394
- const service = new AnalyticsService({ logger: silentLogger });
395
- await expect(service.query({ measures: ['count'] })).rejects.toThrow('Cube name is required');
396
- });
397
-
398
- it('should return cube metadata via getMeta()', async () => {
399
- const service = new AnalyticsService({
400
- cubes: [ordersCube],
401
- logger: silentLogger,
402
- });
403
-
404
- const meta = await service.getMeta();
405
- expect(meta).toHaveLength(1);
406
- expect(meta[0].name).toBe('orders');
407
- expect(meta[0].measures.length).toBeGreaterThan(0);
408
- expect(meta[0].dimensions.length).toBeGreaterThan(0);
409
- });
410
-
411
- it('should filter getMeta() by cube name', async () => {
412
- const service = new AnalyticsService({
413
- cubes: [ordersCube],
414
- logger: silentLogger,
415
- });
416
-
417
- const meta = await service.getMeta('orders');
418
- expect(meta).toHaveLength(1);
419
- expect(meta[0].name).toBe('orders');
420
-
421
- const empty = await service.getMeta('nonexistent');
422
- expect(empty).toHaveLength(0);
423
- });
424
-
425
- it('should generate SQL via generateSql()', async () => {
426
- const service = new AnalyticsService({
427
- cubes: [ordersCube],
428
- logger: silentLogger,
429
- queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }),
430
- executeRawSql: vi.fn(),
431
- });
432
-
433
- const { sql } = await service.generateSql(baseQuery);
434
- expect(sql).toContain('SELECT');
435
- expect(sql).toContain('COUNT(*)');
436
- });
437
-
438
- it('should expose cubeRegistry for external cube registration', () => {
439
- const service = new AnalyticsService({ logger: silentLogger });
440
- expect(service.cubeRegistry).toBeInstanceOf(CubeRegistry);
441
- expect(service.cubeRegistry.size).toBe(0);
442
-
443
- service.cubeRegistry.register(ordersCube);
444
- expect(service.cubeRegistry.size).toBe(1);
445
- });
446
-
447
- it('should support strategy priority ordering', async () => {
448
- // Custom strategy at priority 5 (before NativeSQL at 10)
449
- const customStrategy = {
450
- name: 'CustomStrategy',
451
- priority: 5,
452
- canHandle: () => true,
453
- execute: vi.fn().mockResolvedValue({ rows: [{ custom: true }], fields: [] }),
454
- generateSql: vi.fn().mockResolvedValue({ sql: 'CUSTOM', params: [] }),
455
- };
456
-
457
- const service = new AnalyticsService({
458
- cubes: [ordersCube],
459
- logger: silentLogger,
460
- strategies: [customStrategy],
461
- queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: true, inMemory: false }),
462
- executeRawSql: vi.fn(),
463
- });
464
-
465
- const result = await service.query(baseQuery);
466
- expect(customStrategy.execute).toHaveBeenCalled();
467
- expect(result.rows[0]).toEqual({ custom: true });
468
- });
469
- });
@@ -1,231 +0,0 @@
1
- // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2
-
3
- import type {
4
- IAnalyticsService,
5
- AnalyticsQuery,
6
- AnalyticsResult,
7
- CubeMeta,
8
- } from '@objectstack/spec/contracts';
9
- import type { Cube } from '@objectstack/spec/data';
10
- import type { Logger } from '@objectstack/spec/contracts';
11
- import { createLogger } from '@objectstack/core';
12
- import { CubeRegistry } from './cube-registry.js';
13
- import type { AnalyticsStrategy, DriverCapabilities, StrategyContext } from './strategies/types.js';
14
- import { NativeSQLStrategy } from './strategies/native-sql-strategy.js';
15
- import { ObjectQLStrategy } from './strategies/objectql-strategy.js';
16
-
17
- /**
18
- * Configuration for AnalyticsService.
19
- */
20
- export interface AnalyticsServiceConfig {
21
- /** Pre-defined cube definitions (from manifest). */
22
- cubes?: Cube[];
23
- /** Logger instance. */
24
- logger?: Logger;
25
- /**
26
- * Probe driver capabilities for the object that backs a cube.
27
- * The service calls this function to decide which strategy can handle a query.
28
- */
29
- queryCapabilities?: (cubeName: string) => DriverCapabilities;
30
- /**
31
- * Execute raw SQL on the driver for a given object.
32
- * Required for NativeSQLStrategy.
33
- */
34
- executeRawSql?: (objectName: string, sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
35
- /**
36
- * Execute an ObjectQL aggregate query.
37
- * Required for ObjectQLStrategy.
38
- */
39
- executeAggregate?: (objectName: string, options: {
40
- groupBy?: string[];
41
- aggregations?: Array<{ field: string; method: string; alias: string }>;
42
- filter?: Record<string, unknown>;
43
- }) => Promise<Record<string, unknown>[]>;
44
- /**
45
- * Fallback IAnalyticsService (e.g. MemoryAnalyticsService).
46
- * Used by InMemoryStrategy.
47
- */
48
- fallbackService?: IAnalyticsService;
49
- /**
50
- * Custom strategies to add/replace the defaults.
51
- * They are merged with the built-in strategies and sorted by priority.
52
- */
53
- strategies?: AnalyticsStrategy[];
54
- }
55
-
56
- /**
57
- * Default capabilities when probing is not configured — assumes in-memory only.
58
- */
59
- const DEFAULT_CAPABILITIES: DriverCapabilities = {
60
- nativeSql: false,
61
- objectqlAggregate: false,
62
- inMemory: true,
63
- };
64
-
65
- /**
66
- * AnalyticsService — Multi-driver analytics orchestrator.
67
- *
68
- * Implements `IAnalyticsService` by delegating to a priority-ordered
69
- * strategy chain:
70
- *
71
- * | Priority | Strategy | Condition |
72
- * |:---:|:---|:---|
73
- * | P1 (10) | NativeSQLStrategy | Driver supports raw SQL |
74
- * | P2 (20) | ObjectQLStrategy | Driver supports aggregate AST |
75
- * | P3 (30) | (custom / InMemoryStrategy from driver-memory) | Injected by user |
76
- *
77
- * When `fallbackService` is configured, an internal delegate strategy
78
- * is automatically appended at priority 30 as a safety net.
79
- *
80
- * The service also owns a `CubeRegistry` for metadata discovery and
81
- * auto-inference from object schemas.
82
- */
83
- export class AnalyticsService implements IAnalyticsService {
84
- private readonly strategies: AnalyticsStrategy[];
85
- private readonly strategyCtx: StrategyContext;
86
- readonly cubeRegistry: CubeRegistry;
87
- private readonly logger: Logger;
88
-
89
- constructor(config: AnalyticsServiceConfig = {}) {
90
- this.logger = config.logger || createLogger({ level: 'info', format: 'pretty' });
91
- this.cubeRegistry = new CubeRegistry();
92
-
93
- // Register pre-defined cubes
94
- if (config.cubes) {
95
- this.cubeRegistry.registerAll(config.cubes);
96
- }
97
-
98
- // Build strategy context
99
- this.strategyCtx = {
100
- getCube: (name) => this.cubeRegistry.get(name),
101
- queryCapabilities: config.queryCapabilities || (() => DEFAULT_CAPABILITIES),
102
- executeRawSql: config.executeRawSql,
103
- executeAggregate: config.executeAggregate,
104
- fallbackService: config.fallbackService,
105
- };
106
-
107
- // Build strategy chain (built-in + custom, sorted by priority)
108
- // InMemoryStrategy is NOT built-in — it lives in @objectstack/driver-memory
109
- // and should be passed via config.strategies when needed.
110
- // When fallbackService is configured, an internal delegate is added at P3.
111
- const builtIn: AnalyticsStrategy[] = [
112
- new NativeSQLStrategy(),
113
- new ObjectQLStrategy(),
114
- ];
115
-
116
- // Auto-add fallback delegate when fallbackService is provided
117
- if (config.fallbackService) {
118
- builtIn.push(new FallbackDelegateStrategy());
119
- }
120
-
121
- const custom = config.strategies || [];
122
- this.strategies = [...builtIn, ...custom].sort((a, b) => a.priority - b.priority);
123
-
124
- this.logger.info(
125
- `[Analytics] Initialized with ${this.cubeRegistry.size} cubes, ` +
126
- `${this.strategies.length} strategies: ${this.strategies.map(s => s.name).join(' → ')}`,
127
- );
128
- }
129
-
130
- /**
131
- * Execute an analytical query by delegating to the first capable strategy.
132
- */
133
- async query(query: AnalyticsQuery): Promise<AnalyticsResult> {
134
- if (!query.cube) {
135
- throw new Error('Cube name is required in analytics query');
136
- }
137
-
138
- const strategy = this.resolveStrategy(query);
139
- this.logger.debug(`[Analytics] Query on cube "${query.cube}" → ${strategy.name}`);
140
-
141
- return strategy.execute(query, this.strategyCtx);
142
- }
143
-
144
- /**
145
- * Get cube metadata for discovery.
146
- */
147
- async getMeta(cubeName?: string): Promise<CubeMeta[]> {
148
- // If a fallback service is configured, merge its metadata with the registry
149
- const cubes = cubeName
150
- ? [this.cubeRegistry.get(cubeName)].filter(Boolean) as Cube[]
151
- : this.cubeRegistry.getAll();
152
-
153
- return cubes.map(cube => ({
154
- name: cube.name,
155
- title: cube.title,
156
- measures: Object.entries(cube.measures).map(([key, measure]) => ({
157
- name: `${cube.name}.${key}`,
158
- type: measure.type,
159
- title: measure.label,
160
- })),
161
- dimensions: Object.entries(cube.dimensions).map(([key, dimension]) => ({
162
- name: `${cube.name}.${key}`,
163
- type: dimension.type,
164
- title: dimension.label,
165
- })),
166
- }));
167
- }
168
-
169
- /**
170
- * Generate SQL for a query without executing it (dry-run).
171
- */
172
- async generateSql(query: AnalyticsQuery): Promise<{ sql: string; params: unknown[] }> {
173
- if (!query.cube) {
174
- throw new Error('Cube name is required for SQL generation');
175
- }
176
-
177
- const strategy = this.resolveStrategy(query);
178
- this.logger.debug(`[Analytics] generateSql on cube "${query.cube}" → ${strategy.name}`);
179
-
180
- return strategy.generateSql(query, this.strategyCtx);
181
- }
182
-
183
- // ── Internal ─────────────────────────────────────────────────────
184
-
185
- /**
186
- * Walk the strategy chain and return the first strategy that can handle the query.
187
- */
188
- private resolveStrategy(query: AnalyticsQuery): AnalyticsStrategy {
189
- for (const strategy of this.strategies) {
190
- if (strategy.canHandle(query, this.strategyCtx)) {
191
- return strategy;
192
- }
193
- }
194
- throw new Error(
195
- `[Analytics] No strategy can handle query for cube "${query.cube}". ` +
196
- `Checked: ${this.strategies.map(s => s.name).join(', ')}. ` +
197
- 'Ensure a compatible driver is configured or a fallback service is registered.',
198
- );
199
- }
200
- }
201
-
202
- /**
203
- * FallbackDelegateStrategy — Internal strategy for fallback service delegation.
204
- *
205
- * Automatically added to the strategy chain when `fallbackService` is configured.
206
- * Not exported — consumers who need explicit in-memory support should use
207
- * `InMemoryStrategy` from `@objectstack/driver-memory`.
208
- */
209
- class FallbackDelegateStrategy implements AnalyticsStrategy {
210
- readonly name = 'FallbackDelegateStrategy';
211
- readonly priority = 30;
212
-
213
- canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {
214
- if (!query.cube) return false;
215
- return !!ctx.fallbackService;
216
- }
217
-
218
- async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise<AnalyticsResult> {
219
- return ctx.fallbackService!.query(query);
220
- }
221
-
222
- async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {
223
- if (ctx.fallbackService?.generateSql) {
224
- return ctx.fallbackService.generateSql(query);
225
- }
226
- return {
227
- sql: `-- FallbackDelegateStrategy: SQL generation not supported for cube "${query.cube}"`,
228
- params: [],
229
- };
230
- }
231
- }