|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#29364] The delegated fallback face (`FallbackDelegateStrategy`) refuses a |
| 5 | + * date bucket over a field that is not a date or a datetime, as the engine face |
| 6 | + * refuses it, field for field. |
| 7 | + * |
| 8 | + * ## The shape this closes |
| 9 | + * |
| 10 | + * `FallbackDelegateStrategy` hands a cube query to the host's fallback |
| 11 | + * `IAnalyticsService` (`MemoryAnalyticsService` from `@objectstack/driver-memory` |
| 12 | + * is the in-repo one), which folds a bucketed time dimension itself and reads |
| 13 | + * no field type. Measured on `origin/main` `aca58cdb` with |
| 14 | + * `MemoryAnalyticsService` as the delegate, a month bucket over: |
| 15 | + * |
| 16 | + * | field | the fallback face answered | |
| 17 | + * |:--|:--| |
| 18 | + * | `formula` (virtual: no stored column) | 200, one `null` group holding every row | |
| 19 | + * | `text` | 200, a `null` group beside whatever text parsed as a date | |
| 20 | + * | `datetime` (the control) | 200, the right buckets | |
| 21 | + * |
| 22 | + * while the engine face (the default composition: real ObjectQL + SqlDriver on |
| 23 | + * SQLite) refused the first two with `INVALID_FIELD` / 400 at |
| 24 | + * `groupBy.N.dateGranularity`. No shipped composition reaches this face; the |
| 25 | + * public construction paths do, and both are pinned below: |
| 26 | + * `new AnalyticsService({ fallbackService })`, and `AnalyticsServicePlugin` |
| 27 | + * capturing a pre-registered analytics service under a `queryCapabilities` |
| 28 | + * override with `objectqlAggregate: false`. |
| 29 | + * |
| 30 | + * The delegate here is a recording double: the pin is the service's face (the |
| 31 | + * refusal, and that the delegate was never called), not the delegate's fold. |
| 32 | + */ |
| 33 | + |
| 34 | +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; |
| 35 | +import { ObjectQL } from '@objectstack/objectql'; |
| 36 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 37 | +import type { Cube } from '@objectstack/spec/data'; |
| 38 | +import type { AnalyticsResult, IAnalyticsService } from '@objectstack/spec/contracts'; |
| 39 | +import { AnalyticsService } from '../analytics-service.js'; |
| 40 | +import { AnalyticsServicePlugin } from '../plugin.js'; |
| 41 | +import { installDefaultOrganization } from './default-organization.testkit.js'; |
| 42 | + |
| 43 | +const DEAL = 'os29364_deal'; |
| 44 | +const CUBE = 'os29364_cube'; |
| 45 | + |
| 46 | +const CUBES = [ |
| 47 | + { |
| 48 | + name: CUBE, |
| 49 | + title: 'Fallback date bucket cube', |
| 50 | + sql: DEAL, |
| 51 | + public: true, |
| 52 | + measures: { amount_sum: { type: 'sum', sql: 'amount', label: 'Amount' } }, |
| 53 | + dimensions: { |
| 54 | + calc: { type: 'time', sql: 'calc', label: 'Calc' }, |
| 55 | + region: { type: 'time', sql: 'region', label: 'Region' }, |
| 56 | + closed_at: { type: 'time', sql: 'closed_at', label: 'Closed at' }, |
| 57 | + }, |
| 58 | + }, |
| 59 | +] as unknown as Cube[]; |
| 60 | + |
| 61 | +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; |
| 62 | + |
| 63 | +type Query = Record<string, unknown>; |
| 64 | +const bucket = (...dims: Array<[dimension: string, granularity: string]>): Query => ({ |
| 65 | + cube: CUBE, |
| 66 | + measures: [`${CUBE}.amount_sum`], |
| 67 | + timeDimensions: dims.map(([d, granularity]) => ({ dimension: `${CUBE}.${d}`, granularity })), |
| 68 | +}); |
| 69 | + |
| 70 | +/** The rows and statement the recording delegate answers with. */ |
| 71 | +const DELEGATED: AnalyticsResult = { |
| 72 | + rows: [{ [`${CUBE}.closed_at`]: '2026-03', [`${CUBE}.amount_sum`]: 10 }], |
| 73 | + fields: [{ name: `${CUBE}.closed_at`, type: 'string' }, { name: `${CUBE}.amount_sum`, type: 'number' }], |
| 74 | +}; |
| 75 | +const DELEGATED_SQL = { sql: 'SELECT 1 -- delegated', params: [] as unknown[] }; |
| 76 | + |
| 77 | +function recordingDelegate() { |
| 78 | + return { |
| 79 | + query: vi.fn(async () => DELEGATED), |
| 80 | + generateSql: vi.fn(async () => DELEGATED_SQL), |
| 81 | + getMeta: vi.fn(async () => []), |
| 82 | + }; |
| 83 | +} |
| 84 | + |
| 85 | +/** The refusal `p` rejects with, as the keys a caller reads; a resolution fails the case. */ |
| 86 | +const refusalOf = async (face: string, p: Promise<unknown>) => { |
| 87 | + const err = (await p.then( |
| 88 | + () => { throw new Error(`${face}: expected a refusal, but it resolved`); }, |
| 89 | + (e: unknown) => e, |
| 90 | + )) as Error & Record<string, unknown>; |
| 91 | + return { |
| 92 | + message: err.message, code: err.code, status: err.status, httpStatus: err.httpStatus, |
| 93 | + object: err.object, param: err.param, path: err.path, field: err.field, fields: err.fields, |
| 94 | + }; |
| 95 | +}; |
| 96 | + |
| 97 | +describe('[#29364] the fallback face refuses a date bucket over a field that is not a date, as the engine face does', () => { |
| 98 | + let engine: ObjectQL; |
| 99 | + /** The engine face: the default composition, no `queryCapabilities` override. */ |
| 100 | + let engineFace: AnalyticsService; |
| 101 | + |
| 102 | + /** A field's declaration on the engine, as the plugin's `sourceFieldMeta` reads it. */ |
| 103 | + const fieldMeta = (object: string, field: string) => { |
| 104 | + const f = (engine as unknown as { getObject(o: string): { fields?: Record<string, { type?: string }> } | undefined }) |
| 105 | + .getObject(object)?.fields?.[field]; |
| 106 | + return f ? { type: f.type } : undefined; |
| 107 | + }; |
| 108 | + |
| 109 | + beforeAll(async () => { |
| 110 | + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); |
| 111 | + engine = new ObjectQL({ logger: quiet } as never); |
| 112 | + engine.registerDriver(driver as never, true); |
| 113 | + await engine.init(); |
| 114 | + engine.registry.registerObject({ |
| 115 | + name: DEAL, |
| 116 | + label: 'Deal', |
| 117 | + fields: { |
| 118 | + region: { name: 'region', type: 'text' }, |
| 119 | + amount: { name: 'amount', type: 'number' }, |
| 120 | + closed_at: { name: 'closed_at', type: 'datetime' }, |
| 121 | + closed_on: { name: 'closed_on', type: 'date' }, |
| 122 | + // A formula the table stores no column for, whose result is a date. |
| 123 | + calc: { name: 'calc', type: 'formula', expression: 'closed_on', returnType: 'date' }, |
| 124 | + }, |
| 125 | + } as never); |
| 126 | + await engine.syncSchemas(); |
| 127 | + await installDefaultOrganization(engine as never); |
| 128 | + await engine.insert(DEAL, { |
| 129 | + id: 'd1', region: 'amer', amount: 10, closed_at: '2026-03-01T00:00:00.000Z', closed_on: '2026-03-02', |
| 130 | + } as never); |
| 131 | + |
| 132 | + const registered: Record<string, unknown> = {}; |
| 133 | + await new AnalyticsServicePlugin({ cubes: CUBES } as never).init({ |
| 134 | + getService: (name: string) => (name === 'data' ? engine : registered[name]), |
| 135 | + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 136 | + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 137 | + hook: () => {}, |
| 138 | + logger: quiet, |
| 139 | + } as never); |
| 140 | + engineFace = registered.analytics as AnalyticsService; |
| 141 | + }); |
| 142 | + |
| 143 | + afterAll(async () => { |
| 144 | + try { await engine?.destroy(); } catch { /* noop */ } |
| 145 | + }); |
| 146 | + |
| 147 | + /** `new AnalyticsService({ fallbackService })` with the host's field types. */ |
| 148 | + const constructedFace = () => { |
| 149 | + const delegate = recordingDelegate(); |
| 150 | + const face = new AnalyticsService({ |
| 151 | + cubes: CUBES, |
| 152 | + logger: quiet as never, |
| 153 | + fallbackService: delegate as unknown as IAnalyticsService, |
| 154 | + sourceFieldMeta: fieldMeta, |
| 155 | + } as never); |
| 156 | + return { face, delegate }; |
| 157 | + }; |
| 158 | + |
| 159 | + /** `AnalyticsServicePlugin` capturing a pre-registered analytics service, `objectqlAggregate: false`. */ |
| 160 | + const pluginFace = async () => { |
| 161 | + const delegate = recordingDelegate(); |
| 162 | + const registered: Record<string, unknown> = { analytics: delegate }; |
| 163 | + await new AnalyticsServicePlugin({ |
| 164 | + cubes: CUBES, |
| 165 | + queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: false, inMemory: false }), |
| 166 | + } as never).init({ |
| 167 | + getService: (name: string) => (name === 'data' ? engine : registered[name]), |
| 168 | + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 169 | + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 170 | + hook: () => {}, |
| 171 | + logger: quiet, |
| 172 | + } as never); |
| 173 | + return { face: registered.analytics as AnalyticsService, delegate }; |
| 174 | + }; |
| 175 | + |
| 176 | + const FACES = [ |
| 177 | + ['new AnalyticsService({ fallbackService })', constructedFace], |
| 178 | + ['AnalyticsServicePlugin, objectqlAggregate: false', pluginFace], |
| 179 | + ] as const; |
| 180 | + |
| 181 | + const REFUSED: Array<[label: string, query: Query, field: string, path: string]> = [ |
| 182 | + ['a formula by month', bucket(['calc', 'month']), 'calc', 'groupBy.0.dateGranularity'], |
| 183 | + ['a text column by month', bucket(['region', 'month']), 'region', 'groupBy.0.dateGranularity'], |
| 184 | + ['a formula after a datetime bucket', bucket(['closed_at', 'year'], ['calc', 'month']), 'calc', 'groupBy.1.dateGranularity'], |
| 185 | + ]; |
| 186 | + |
| 187 | + for (const [faceLabel, makeFace] of FACES) { |
| 188 | + describe(faceLabel, () => { |
| 189 | + it.each(REFUSED)('refuses %s with the engine face\'s refusal, on the query and the dry run, and never calls the delegate', async (_l, query, field, path) => { |
| 190 | + const { face, delegate } = await makeFace(); |
| 191 | + const asEngine = await refusalOf('engine', engineFace.query({ ...query } as never)); |
| 192 | + // The engine face's own refusal, so a reader can see what is being matched. |
| 193 | + expect(asEngine).toMatchObject({ code: 'INVALID_FIELD', status: 400, object: DEAL, param: 'groupBy', path, field, fields: [field] }); |
| 194 | + |
| 195 | + expect(await refusalOf('fallback query', face.query({ ...query } as never)), 'the fallback query vs the engine face').toEqual(asEngine); |
| 196 | + expect(await refusalOf('fallback sql', face.generateSql({ ...query } as never)), 'the fallback dry run vs the engine face').toEqual(asEngine); |
| 197 | + expect(delegate.query).not.toHaveBeenCalled(); |
| 198 | + expect(delegate.generateSql).not.toHaveBeenCalled(); |
| 199 | + }); |
| 200 | + |
| 201 | + it('serves a datetime bucket through the delegate, as before (the control)', async () => { |
| 202 | + const { face, delegate } = await makeFace(); |
| 203 | + const query = bucket(['closed_at', 'month']); |
| 204 | + const result = await face.query({ ...query } as never); |
| 205 | + expect(delegate.query).toHaveBeenCalledTimes(1); |
| 206 | + expect(result.rows).toEqual(DELEGATED.rows); |
| 207 | + expect(await face.generateSql({ ...query } as never)).toEqual(DELEGATED_SQL); |
| 208 | + expect(delegate.generateSql).toHaveBeenCalledTimes(1); |
| 209 | + }); |
| 210 | + }); |
| 211 | + } |
| 212 | + |
| 213 | + it('does not judge a bucket the host gave no field type for (no sourceFieldMeta), as the preview and the dry run', async () => { |
| 214 | + const delegate = recordingDelegate(); |
| 215 | + const face = new AnalyticsService({ |
| 216 | + cubes: CUBES, |
| 217 | + logger: quiet as never, |
| 218 | + fallbackService: delegate as unknown as IAnalyticsService, |
| 219 | + } as never); |
| 220 | + await face.query({ ...bucket(['calc', 'month']) } as never); |
| 221 | + expect(delegate.query).toHaveBeenCalledTimes(1); |
| 222 | + }); |
| 223 | +}); |
0 commit comments