|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#21267] An analytics `order` key must name a member the query selects — a |
| 5 | + * `dimensions` entry, a `measures` entry, or a `timeDimensions` entry with a |
| 6 | + * `granularity` — or the analytics door refuses the query `INVALID_FIELD` / |
| 7 | + * 400, on the native-SQL and the ObjectQL face alike, before either strategy |
| 8 | + * runs (`order-key-door.ts`). |
| 9 | + * |
| 10 | + * ## The shape this closes |
| 11 | + * |
| 12 | + * Measured through `POST /api/v1/analytics/query` on the real dispatcher route |
| 13 | + * at `3196ef1a1`, SQLite and PostgreSQL 16.14. The cube over `deal` declares no |
| 14 | + * join; `owner` is a lookup whose target also declares `note` and `amount`: |
| 15 | + * |
| 16 | + * | query | native SQLite | native PostgreSQL | ObjectQL face | |
| 17 | + * |:--|:--|:--|:--| |
| 18 | + * | `dimensions: ['owner.email']`, `order: { note }` | 500 | 500 (42702) | 200 | |
| 19 | + * | `dimensions: ['note']`, `order: { amount }` | 200, arbitrary order | 500 (42803) | 200 | |
| 20 | + * | `dimensions: ['note']`, `order: { 'owner.email' }` | 500 | 500 (42703) | 200 | |
| 21 | + * |
| 22 | + * Every refusal pin below also asserts nothing ran: no raw statement and no |
| 23 | + * engine aggregate, on either face. |
| 24 | + * |
| 25 | + * ## The dialect axis of THIS file |
| 26 | + * |
| 27 | + * The SQLite cell always runs. The PostgreSQL cell runs where |
| 28 | + * `OS_TEST_POSTGRES_URL` is set and is a named skip otherwise; no CI step |
| 29 | + * provisions that variable for this package, so the live cell is red-capable |
| 30 | + * and un-run in CI, and the PR that landed this file carries its local |
| 31 | + * PostgreSQL 16 run. The live cell owns its tables, dropped before and after. |
| 32 | + */ |
| 33 | + |
| 34 | +import { describe, it, expect, beforeAll, afterAll } 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 { AnalyticsService } from '../analytics-service.js'; |
| 39 | +import { AnalyticsServicePlugin } from '../plugin.js'; |
| 40 | + |
| 41 | +const PERSON = 'os21267_person'; |
| 42 | +const DEAL = 'os21267_deal'; |
| 43 | + |
| 44 | +/** The lookup's target declares `note` and `amount` too, so an unqualified ORDER BY over a join is ambiguous. */ |
| 45 | +const PERSON_OBJECT = { |
| 46 | + name: PERSON, |
| 47 | + label: 'Order key person', |
| 48 | + fields: { |
| 49 | + email: { name: 'email', type: 'text' as const }, |
| 50 | + note: { name: 'note', type: 'text' as const }, |
| 51 | + amount: { name: 'amount', type: 'number' as const }, |
| 52 | + }, |
| 53 | +}; |
| 54 | + |
| 55 | +const DEAL_OBJECT = { |
| 56 | + name: DEAL, |
| 57 | + label: 'Order key deal', |
| 58 | + fields: { |
| 59 | + note: { name: 'note', type: 'text' as const }, |
| 60 | + amount: { name: 'amount', type: 'number' as const }, |
| 61 | + closed_on: { name: 'closed_on', type: 'date' as const }, |
| 62 | + owner: { name: 'owner', type: 'lookup' as const, reference: PERSON }, |
| 63 | + }, |
| 64 | +}; |
| 65 | + |
| 66 | +const PEOPLE = [ |
| 67 | + { id: 'p1', email: 'a@x', note: 'pn1', amount: 100 }, |
| 68 | + { id: 'p2', email: 'b@x', note: 'pn2', amount: 200 }, |
| 69 | +] as const; |
| 70 | +// Groups by `note`: x (2 rows, amount 15), y (1, 7), z (1, 1). Neither the |
| 71 | +// note order nor the amount order matches insertion order reversed. |
| 72 | +const DEALS = [ |
| 73 | + { id: 'd1', note: 'x', amount: 10, closed_on: '2026-03-01', owner: 'p1' }, |
| 74 | + { id: 'd2', note: 'x', amount: 5, closed_on: '2026-03-02', owner: 'p1' }, |
| 75 | + { id: 'd3', note: 'y', amount: 7, closed_on: '2026-04-03', owner: 'p2' }, |
| 76 | + { id: 'd4', note: 'z', amount: 1, closed_on: '2026-05-01', owner: 'p2' }, |
| 77 | +] as const; |
| 78 | + |
| 79 | +/** The card's cube: it declares NO join, so `owner` is joined through the lookup's declared `reference`. */ |
| 80 | +const CUBE = 'os21267_cube'; |
| 81 | +const CUBES = [ |
| 82 | + { |
| 83 | + name: CUBE, |
| 84 | + title: 'Order key cube', |
| 85 | + sql: DEAL, |
| 86 | + public: true, |
| 87 | + measures: { |
| 88 | + count: { type: 'count', sql: '*', label: 'Rows' }, |
| 89 | + amount_sum: { type: 'sum', sql: 'amount', label: 'Amount' }, |
| 90 | + }, |
| 91 | + dimensions: { |
| 92 | + note: { type: 'string', sql: 'note', label: 'Note' }, |
| 93 | + closed_on: { type: 'time', sql: 'closed_on', label: 'Closed on' }, |
| 94 | + }, |
| 95 | + }, |
| 96 | +] as unknown as Cube[]; |
| 97 | + |
| 98 | +/** The card's three rows: each orders by a key the query does not select. */ |
| 99 | +const CARD_ROWS = [ |
| 100 | + { |
| 101 | + label: 'an unselected base column beside a relationship path (ambiguous on the native face)', |
| 102 | + query: { cube: CUBE, measures: ['count'], dimensions: ['owner.email'], order: { note: 'asc' } }, |
| 103 | + key: 'note', |
| 104 | + selected: ['owner.email', 'count'], |
| 105 | + }, |
| 106 | + { |
| 107 | + label: 'an unselected base column with no join (an arbitrary row on SQLite, 42803 on PostgreSQL)', |
| 108 | + query: { cube: CUBE, measures: ['count'], dimensions: ['note'], order: { amount: 'asc' } }, |
| 109 | + key: 'amount', |
| 110 | + selected: ['note', 'count'], |
| 111 | + }, |
| 112 | + { |
| 113 | + label: 'an unselected relationship path', |
| 114 | + query: { cube: CUBE, measures: ['count'], dimensions: ['note'], order: { 'owner.email': 'asc' } }, |
| 115 | + key: 'owner.email', |
| 116 | + selected: ['note', 'count'], |
| 117 | + }, |
| 118 | +] as const; |
| 119 | + |
| 120 | +interface Cell { |
| 121 | + id: 'sqlite' | 'pg'; |
| 122 | + label: string; |
| 123 | + env: string | null; |
| 124 | + config: () => Record<string, unknown> | null; |
| 125 | +} |
| 126 | + |
| 127 | +const CELLS: readonly Cell[] = [ |
| 128 | + { id: 'sqlite', label: 'sqlite', env: null, config: () => ({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) }, |
| 129 | + { |
| 130 | + id: 'pg', |
| 131 | + label: 'live postgres', |
| 132 | + env: 'OS_TEST_POSTGRES_URL', |
| 133 | + config: () => (process.env.OS_TEST_POSTGRES_URL ? { client: 'pg', connection: process.env.OS_TEST_POSTGRES_URL } : null), |
| 134 | + }, |
| 135 | +]; |
| 136 | + |
| 137 | +const FACES = ['native', 'objectql'] as const; |
| 138 | +type Face = (typeof FACES)[number]; |
| 139 | + |
| 140 | +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; |
| 141 | + |
| 142 | +type Row = Record<string, unknown>; |
| 143 | +type Refusal = Error & { code?: string; status?: number; field?: string; param?: string }; |
| 144 | + |
| 145 | +/** Rows as tuples of the named columns, in the order they arrived; a measure reads as a number on every dialect. */ |
| 146 | +const tuples = (rows: unknown, columns: readonly string[]) => |
| 147 | + (rows as Row[]).map((row) => columns.map((c) => (typeof row[c] === 'number' || /^-?\d+(\.\d+)?$/.test(String(row[c])) ? Number(row[c]) : row[c]))); |
| 148 | +const sorted = (list: unknown[][]) => [...list].sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))); |
| 149 | + |
| 150 | +for (const cell of CELLS) { |
| 151 | + const config = cell.config(); |
| 152 | + describe.skipIf(!config)( |
| 153 | + `[#21267] an analytics order key must name a member the query selects (${cell.label})${config ? '' : ` (skipped: set ${cell.env} to run this cell)`}`, |
| 154 | + () => { |
| 155 | + let driver: any; |
| 156 | + let engine: ObjectQL; |
| 157 | + /** Raw-SQL statements and engine aggregates, on any object. */ |
| 158 | + const reads = { rawSql: 0, aggregate: 0 }; |
| 159 | + /** `native`: the plugin's own capabilities. `objectql`: narrowed to the engine-aggregate path. */ |
| 160 | + const services: Partial<Record<Face, AnalyticsService>> = {}; |
| 161 | + |
| 162 | + const dropTables = async () => { |
| 163 | + if (cell.id !== 'pg') return; |
| 164 | + for (const table of [DEAL, PERSON]) await driver?.execute(`drop table if exists ${table}`).catch(() => {}); |
| 165 | + }; |
| 166 | + |
| 167 | + /** One call on one face: its result or its error, and the reads it caused. */ |
| 168 | + const call = async (face: Face, door: 'query' | 'generateSql', query: Record<string, unknown>) => { |
| 169 | + const before = { ...reads }; |
| 170 | + const outcome = await (services[face]![door] as (q: any) => Promise<any>).call(services[face], query as any).then( |
| 171 | + (res) => ({ res, err: undefined as Refusal | undefined }), |
| 172 | + (err) => ({ res: undefined, err: err as Refusal }), |
| 173 | + ); |
| 174 | + return { ...outcome, rawSql: reads.rawSql - before.rawSql, aggregate: reads.aggregate - before.aggregate }; |
| 175 | + }; |
| 176 | + |
| 177 | + /** Both doors on both faces refuse `query` with the order-key envelope, and nothing ran. */ |
| 178 | + const refusedEverywhere = async (query: Record<string, unknown>, key: string, selected: readonly string[]) => { |
| 179 | + for (const face of FACES) { |
| 180 | + for (const door of ['query', 'generateSql'] as const) { |
| 181 | + const { res, err, rawSql, aggregate } = await call(face, door, query); |
| 182 | + const where = `${face} ${door}`; |
| 183 | + expect(res, `${where}: answered instead of refusing`).toBeUndefined(); |
| 184 | + expect(err?.code, `${where}: ${err?.message}`).toBe('INVALID_FIELD'); |
| 185 | + expect(err?.status, where).toBe(400); |
| 186 | + expect(err?.param, where).toBe('order'); |
| 187 | + expect(err?.field, where).toBe(key); |
| 188 | + // The refusal names the offending key and every member the query does select. |
| 189 | + for (const name of [key, ...selected]) expect(err?.message, where).toContain(`${name}`); |
| 190 | + expect(rawSql, `${where}: no raw statement ran`).toBe(0); |
| 191 | + expect(aggregate, `${where}: no engine aggregate ran`).toBe(0); |
| 192 | + } |
| 193 | + } |
| 194 | + }; |
| 195 | + |
| 196 | + beforeAll(async () => { |
| 197 | + driver = new SqlDriver(config as any); |
| 198 | + await dropTables(); |
| 199 | + engine = new ObjectQL({ logger: quiet } as any); |
| 200 | + engine.registerDriver(driver, true); |
| 201 | + await engine.init(); |
| 202 | + for (const object of [PERSON_OBJECT, DEAL_OBJECT]) engine.registry.registerObject(object as any); |
| 203 | + await engine.syncSchemas(); |
| 204 | + for (const row of PEOPLE) await engine.insert(PERSON, { ...row } as any); |
| 205 | + for (const row of DEALS) await engine.insert(DEAL, { ...row } as any); |
| 206 | + |
| 207 | + const realExecute = (engine as any).execute.bind(engine); |
| 208 | + (engine as any).execute = (sql: unknown, opts?: unknown) => { |
| 209 | + reads.rawSql += 1; |
| 210 | + return realExecute(sql, opts); |
| 211 | + }; |
| 212 | + const realAggregate = engine.aggregate.bind(engine); |
| 213 | + (engine as any).aggregate = (...args: unknown[]) => { |
| 214 | + reads.aggregate += 1; |
| 215 | + return (realAggregate as any)(...args); |
| 216 | + }; |
| 217 | + |
| 218 | + for (const [face, caps] of [ |
| 219 | + ['native', undefined], |
| 220 | + ['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })], |
| 221 | + ] as const) { |
| 222 | + const registered: Record<string, unknown> = {}; |
| 223 | + await new AnalyticsServicePlugin({ cubes: CUBES, ...(caps ? { queryCapabilities: caps } : {}) } as any).init({ |
| 224 | + getService: (name: string) => (name === 'data' ? engine : registered[name]), |
| 225 | + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 226 | + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 227 | + hook: () => {}, |
| 228 | + logger: quiet, |
| 229 | + } as never); |
| 230 | + services[face] = registered.analytics as AnalyticsService; |
| 231 | + } |
| 232 | + }); |
| 233 | + |
| 234 | + afterAll(async () => { |
| 235 | + await dropTables(); |
| 236 | + try { await engine?.destroy(); } catch { /* noop */ } |
| 237 | + }); |
| 238 | + |
| 239 | + for (const row of CARD_ROWS) { |
| 240 | + it(`the card's row is refused 400 INVALID_FIELD on both faces and both doors: ${row.label}`, async () => { |
| 241 | + await refusedEverywhere(row.query, row.key, row.selected); |
| 242 | + }); |
| 243 | + } |
| 244 | + |
| 245 | + it('a time-dimension entry that only windows the rows is not a column, so ordering by it is refused', async () => { |
| 246 | + await refusedEverywhere( |
| 247 | + { |
| 248 | + cube: CUBE, |
| 249 | + measures: ['count'], |
| 250 | + dimensions: ['note'], |
| 251 | + timeDimensions: [{ dimension: 'closed_on', dateRange: ['2026-03-01', '2026-05-31'] }], |
| 252 | + order: { closed_on: 'asc' }, |
| 253 | + }, |
| 254 | + 'closed_on', |
| 255 | + ['note', 'count'], |
| 256 | + ); |
| 257 | + }); |
| 258 | + |
| 259 | + it('a key matches by its exact spelling: a qualified spelling of a measure selected bare names no column', async () => { |
| 260 | + await refusedEverywhere( |
| 261 | + { cube: CUBE, measures: ['amount_sum'], dimensions: ['note'], order: { [`${CUBE}.amount_sum`]: 'desc' } }, |
| 262 | + `${CUBE}.amount_sum`, |
| 263 | + ['note', 'amount_sum'], |
| 264 | + ); |
| 265 | + }); |
| 266 | + |
| 267 | + it('CONTROL ordering by a selected dimension is served unchanged on both faces', async () => { |
| 268 | + const query = { cube: CUBE, measures: ['count'], dimensions: ['note'], order: { note: 'desc' } }; |
| 269 | + for (const face of FACES) { |
| 270 | + const { res, err } = await call(face, 'query', query); |
| 271 | + expect(err, `${face}: ${err?.message}`).toBeUndefined(); |
| 272 | + const got = tuples(res.rows, ['note', 'count']); |
| 273 | + // The native face runs the ORDER BY; the ObjectQL face serves the same groups. |
| 274 | + if (face === 'native') expect(got).toEqual([['z', 1], ['y', 1], ['x', 2]]); |
| 275 | + else expect(sorted(got)).toEqual([['x', 2], ['y', 1], ['z', 1]]); |
| 276 | + const { res: dry, err: dryErr } = await call(face, 'generateSql', query); |
| 277 | + expect(dryErr, `${face} dry run: ${dryErr?.message}`).toBeUndefined(); |
| 278 | + expect(dry.sql, face).toContain('ORDER BY "note" DESC'); |
| 279 | + } |
| 280 | + }); |
| 281 | + |
| 282 | + it('CONTROL ordering by a selected measure is served unchanged on both faces', async () => { |
| 283 | + const query = { cube: CUBE, measures: ['amount_sum'], dimensions: ['note'], order: { amount_sum: 'desc' } }; |
| 284 | + for (const face of FACES) { |
| 285 | + const { res, err } = await call(face, 'query', query); |
| 286 | + expect(err, `${face}: ${err?.message}`).toBeUndefined(); |
| 287 | + const got = tuples(res.rows, ['note', 'amount_sum']); |
| 288 | + if (face === 'native') expect(got).toEqual([['x', 15], ['y', 7], ['z', 1]]); |
| 289 | + else expect(sorted(got)).toEqual([['x', 15], ['y', 7], ['z', 1]]); |
| 290 | + const { res: dry, err: dryErr } = await call(face, 'generateSql', query); |
| 291 | + expect(dryErr, `${face} dry run: ${dryErr?.message}`).toBeUndefined(); |
| 292 | + expect(dry.sql, face).toContain('ORDER BY "amount_sum" DESC'); |
| 293 | + } |
| 294 | + }); |
| 295 | + |
| 296 | + it('CONTROL a bucketed time dimension is a column the answer carries, so ordering by it is served', async () => { |
| 297 | + const query = { |
| 298 | + cube: CUBE, |
| 299 | + measures: ['count'], |
| 300 | + timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }], |
| 301 | + order: { closed_on: 'asc' }, |
| 302 | + }; |
| 303 | + for (const face of FACES) { |
| 304 | + const { res, err } = await call(face, 'query', query); |
| 305 | + expect(err, `${face}: ${err?.message}`).toBeUndefined(); |
| 306 | + // Three month buckets (March, April, May), whichever face served them. |
| 307 | + expect((res.rows as Row[]).length, face).toBe(3); |
| 308 | + expect(sorted(tuples(res.rows, ['count'])), face).toEqual([[1], [1], [2]]); |
| 309 | + } |
| 310 | + }); |
| 311 | + }, |
| 312 | + ); |
| 313 | +} |
0 commit comments