|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#28977] The `/analytics/sql` dry run refuses a date bucket over a column |
| 5 | + * declared neither a date nor a datetime, as `/analytics/query` does, on real |
| 6 | + * SQLite (the #28841 harness: real ObjectQL + SqlDriver, the default |
| 7 | + * composition). |
| 8 | + * |
| 9 | + * ## The shape this closes |
| 10 | + * |
| 11 | + * The query hands `engine.aggregate` the keys the ObjectQL strategy builds |
| 12 | + * (native declines every bucketed selection to it), and the engine refuses a |
| 13 | + * bucket over any other declared type: `INVALID_FIELD` / 400 at |
| 14 | + * `groupBy.N.dateGranularity`. The dry run rendered the bucket without reading |
| 15 | + * the column's type, so on `main` `ab085a04` it printed a statement for each: |
| 16 | + * |
| 17 | + * | selection | the dry run rendered | |
| 18 | + * |:--|:--| |
| 19 | + * | text `region` by month | `strftime('%Y-%m', \`region\`)` | |
| 20 | + * | select, number, boolean, `time` | the same over that column | |
| 21 | + * | `account.name` beside a text bucket (the cross-object path) | the join and the bucket | |
| 22 | + * | a cube dimension over `region` declaring one granularity, asked raw | the bucket | |
| 23 | + * | text `region` by month at `America/New_York` | `NOT_IMPLEMENTED` / 501 saying the query is served | |
| 24 | + * |
| 25 | + * It now judges the keys `execute()` hands the engine with the service's one |
| 26 | + * reading of it (`dataset-date-bucket-door.ts`, #28852), after the `dateRange` |
| 27 | + * read and the column-asked-twice door as `query()` refuses, so it answers the |
| 28 | + * query's refusal field for field. A date and a datetime bucket still render |
| 29 | + * byte for byte (pinned below). |
| 30 | + */ |
| 31 | + |
| 32 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 33 | +import { ObjectQL } from '@objectstack/objectql'; |
| 34 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 35 | +import type { Cube } from '@objectstack/spec/data'; |
| 36 | +import type { AnalyticsService } from '../analytics-service.js'; |
| 37 | +import { AnalyticsServicePlugin } from '../plugin.js'; |
| 38 | +import { installDefaultOrganization } from './default-organization.testkit.js'; |
| 39 | + |
| 40 | +const DEAL = 'os28977_deal'; |
| 41 | +const ACCOUNT = 'os28977_account'; |
| 42 | +const CUBE = 'os28977_cube'; |
| 43 | + |
| 44 | +const CUBES = [ |
| 45 | + { |
| 46 | + name: CUBE, |
| 47 | + title: 'Date bucket cube', |
| 48 | + sql: DEAL, |
| 49 | + public: true, |
| 50 | + measures: { amount_sum: { type: 'sum', sql: 'amount', label: 'Amount' } }, |
| 51 | + dimensions: { |
| 52 | + region: { type: 'string', sql: 'region', label: 'Region' }, |
| 53 | + // A time dimension over a text column, declaring one granularity: asked |
| 54 | + // raw, it is bucketed by that granularity (`withDeclaredGranularityDefaults`). |
| 55 | + region_month: { type: 'time', sql: 'region', label: 'Region month', granularities: ['month'] }, |
| 56 | + }, |
| 57 | + }, |
| 58 | +] as unknown as Cube[]; |
| 59 | + |
| 60 | +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; |
| 61 | + |
| 62 | +type Query = Record<string, unknown>; |
| 63 | +const td = (dimension: string, granularity: string, extra: Query = {}) => ({ dimension, granularity, ...extra }); |
| 64 | +/** The inferred cube over the deal object, which serves a lookup path as a cross-object dimension. */ |
| 65 | +const onObject = (extra: Query): Query => ({ cube: DEAL, measures: ['amount_sum'], ...extra }); |
| 66 | +const onCube = (extra: Query): Query => ({ cube: CUBE, measures: ['amount_sum'], ...extra }); |
| 67 | + |
| 68 | +/** The engine's refusal for a bucket over `field`, declared `type`, at `path`. */ |
| 69 | +const refusalFor = (field: string, type: string, granularity: string, path: string) => ({ |
| 70 | + message: |
| 71 | + `aggregate('${DEAL}'): ${path} buckets '${field}' by '${granularity}', but '${field}' is a ` |
| 72 | + + `declared ${type} field — only a date or datetime field can be date-bucketed. The query was NOT run. Group by ` |
| 73 | + + `'${field}' without 'dateGranularity', or bucket a date or datetime field. A value that is not a date has no ` |
| 74 | + + 'calendar position: every row fell into one null bucket (or, for a number, an epoch bucket) while the answer ' |
| 75 | + + 'looked served.', |
| 76 | + code: 'INVALID_FIELD', status: 400, httpStatus: 400, |
| 77 | + object: DEAL, param: 'groupBy', path, field, fields: [field], |
| 78 | +}); |
| 79 | + |
| 80 | +describe('[#28977] the /analytics/sql dry run refuses a date bucket over a column that is not a date, as the query does', () => { |
| 81 | + let engine: ObjectQL; |
| 82 | + let analytics: AnalyticsService; |
| 83 | + |
| 84 | + beforeAll(async () => { |
| 85 | + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); |
| 86 | + engine = new ObjectQL({ logger: quiet } as never); |
| 87 | + engine.registerDriver(driver as never, true); |
| 88 | + await engine.init(); |
| 89 | + engine.registry.registerObject({ name: ACCOUNT, label: 'Account', fields: { name: { name: 'name', type: 'text' } } } as never); |
| 90 | + engine.registry.registerObject({ |
| 91 | + name: DEAL, |
| 92 | + label: 'Deal', |
| 93 | + fields: { |
| 94 | + region: { name: 'region', type: 'text' }, |
| 95 | + stage: { name: 'stage', type: 'select', options: [{ label: 'Won', value: 'won' }, { label: 'Lost', value: 'lost' }] }, |
| 96 | + amount: { name: 'amount', type: 'number' }, |
| 97 | + flag: { name: 'flag', type: 'boolean' }, |
| 98 | + opened_time: { name: 'opened_time', type: 'time' }, |
| 99 | + closed_at: { name: 'closed_at', type: 'datetime' }, |
| 100 | + closed_on: { name: 'closed_on', type: 'date' }, |
| 101 | + account: { name: 'account', type: 'lookup', reference: ACCOUNT }, |
| 102 | + }, |
| 103 | + } as never); |
| 104 | + await engine.syncSchemas(); |
| 105 | + await installDefaultOrganization(engine as never); |
| 106 | + await engine.insert(ACCOUNT, { id: 'a1', name: 'Acme' } as never); |
| 107 | + await engine.insert(DEAL, { |
| 108 | + id: 'd1', region: 'amer', stage: 'won', amount: 10, flag: true, opened_time: '10:00', |
| 109 | + closed_at: '2026-03-01T00:00:00.000Z', closed_on: '2026-03-02', account: 'a1', |
| 110 | + } as never); |
| 111 | + |
| 112 | + // The default composition: no `queryCapabilities` override. |
| 113 | + const registered: Record<string, unknown> = {}; |
| 114 | + await new AnalyticsServicePlugin({ cubes: CUBES, debugSql: true } as never).init({ |
| 115 | + getService: (name: string) => (name === 'data' ? engine : registered[name]), |
| 116 | + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 117 | + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 118 | + hook: () => {}, |
| 119 | + logger: quiet, |
| 120 | + } as never); |
| 121 | + analytics = registered.analytics as AnalyticsService; |
| 122 | + }); |
| 123 | + |
| 124 | + afterAll(async () => { |
| 125 | + try { await engine?.destroy(); } catch { /* noop */ } |
| 126 | + }); |
| 127 | + |
| 128 | + /** The refusal `p` rejects with, as the keys a caller reads; a resolution fails the case. */ |
| 129 | + const refusalOf = async (face: string, p: Promise<unknown>) => { |
| 130 | + const err = (await p.then( |
| 131 | + () => { throw new Error(`${face}: expected a refusal, but it resolved`); }, |
| 132 | + (e: unknown) => e, |
| 133 | + )) as Error & Record<string, unknown>; |
| 134 | + return { |
| 135 | + message: err.message, code: err.code, status: err.status, httpStatus: err.httpStatus, |
| 136 | + object: err.object, param: err.param, path: err.path, field: err.field, fields: err.fields, |
| 137 | + }; |
| 138 | + }; |
| 139 | + |
| 140 | + /** The query's refusal and the dry run's, for one selection. */ |
| 141 | + const bothRefusals = async (query: Query) => ({ |
| 142 | + asQuery: await refusalOf('query', analytics.query({ ...query } as never)), |
| 143 | + asSql: await refusalOf('sql', analytics.generateSql({ ...query } as never)), |
| 144 | + }); |
| 145 | + |
| 146 | + it.each<[string, Query, [field: string, type: string, granularity: string, path: string]]>([ |
| 147 | + ['text', onObject({ timeDimensions: [td('region', 'month')] }), ['region', 'text', 'month', 'groupBy.0.dateGranularity']], |
| 148 | + ['select', onObject({ timeDimensions: [td('stage', 'month')] }), ['stage', 'select', 'month', 'groupBy.0.dateGranularity']], |
| 149 | + ['number', onObject({ timeDimensions: [td('amount', 'year')] }), ['amount', 'number', 'year', 'groupBy.0.dateGranularity']], |
| 150 | + ['boolean', onObject({ timeDimensions: [td('flag', 'month')] }), ['flag', 'boolean', 'month', 'groupBy.0.dateGranularity']], |
| 151 | + ['time', onObject({ timeDimensions: [td('opened_time', 'day')] }), ['opened_time', 'time', 'day', 'groupBy.0.dateGranularity']], |
| 152 | + ])('refuses a bucket over a %s column with the query\'s refusal, field for field', async (_label, query, expected) => { |
| 153 | + const { asQuery, asSql } = await bothRefusals(query); |
| 154 | + expect(asQuery).toEqual(refusalFor(...expected)); |
| 155 | + expect(asSql, 'the dry run vs the query').toEqual(asQuery); |
| 156 | + }); |
| 157 | + |
| 158 | + it.each<[string, Query, string]>([ |
| 159 | + ["beside a cross-object 'account.name' (its FK column first)", onObject({ dimensions: ['account.name'], timeDimensions: [td('region', 'month')] }), 'groupBy.1.dateGranularity'], |
| 160 | + ['after a raw date column and a datetime bucket', onObject({ dimensions: ['closed_on'], timeDimensions: [td('closed_at', 'month'), td('region', 'month')] }), 'groupBy.2.dateGranularity'], |
| 161 | + ["by a cube dimension's one declared granularity, asked raw", onCube({ dimensions: ['region_month'] }), 'groupBy.0.dateGranularity'], |
| 162 | + ['at a non-UTC zone, where the dry run said the query is served (501)', onObject({ timeDimensions: [td('region', 'month')], timezone: 'America/New_York' }), 'groupBy.0.dateGranularity'], |
| 163 | + ])('refuses a text bucket %s with the query\'s refusal, field for field', async (_label, query, path) => { |
| 164 | + const { asQuery, asSql } = await bothRefusals(query); |
| 165 | + expect(asQuery).toEqual(refusalFor('region', 'text', 'month', path)); |
| 166 | + expect(asSql, 'the dry run vs the query').toEqual(asQuery); |
| 167 | + }); |
| 168 | + |
| 169 | + it.each<[string, Query, string]>([ |
| 170 | + ['an unrecognised dateRange on the bucket itself', onObject({ timeDimensions: [td('region', 'month', { dateRange: 'not a range' })] }), 'ANALYTICS_DATE_RANGE_UNRECOGNIZED'], |
| 171 | + ['a one-entry dateRange on another entry', onObject({ timeDimensions: [td('region', 'month'), td('closed_at', 'year', { dateRange: ['2026-01-01'] })] }), 'ANALYTICS_DATE_RANGE_UNRECOGNIZED'], |
| 172 | + ['the column asked twice', onObject({ timeDimensions: [td('region', 'month'), td('region', 'year')] }), 'INVALID_QUERY'], |
| 173 | + ])('answers %s before a text bucket, as the query does', async (_label, query, code) => { |
| 174 | + const { asQuery, asSql } = await bothRefusals(query); |
| 175 | + expect(asQuery).toMatchObject({ code, status: 400 }); |
| 176 | + expect(asSql, 'the dry run vs the query').toEqual(asQuery); |
| 177 | + }); |
| 178 | + |
| 179 | + it.each<[string, string]>([ |
| 180 | + ['date', 'closed_on'], |
| 181 | + ['datetime', 'closed_at'], |
| 182 | + ])('still renders a %s bucket byte for byte, the statement the query echoes', async (_label, column) => { |
| 183 | + const query = onObject({ timeDimensions: [td(column, 'month')] }); |
| 184 | + const sql = `SELECT strftime('%Y-%m', \`${column}\`) AS "${column}", SUM(amount) AS "amount_sum" FROM "${DEAL}" ` |
| 185 | + + `GROUP BY strftime('%Y-%m', \`${column}\`)`; |
| 186 | + expect(await analytics.generateSql({ ...query } as never)).toEqual({ sql, params: [] }); |
| 187 | + expect((await analytics.query({ ...query } as never)).sql).toBe(sql); |
| 188 | + }); |
| 189 | +}); |
0 commit comments