|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [latest per group] `find()` compiles the window directive the engine hands |
| 5 | + * it (objectql `latest-per.ts`) into its own statement: one more predicate, |
| 6 | + * `id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY … |
| 7 | + * ORDER BY …, id) rn FROM t WHERE <tenant wall> AND <where>) w WHERE rn = 1)`. |
| 8 | + * |
| 9 | + * Pinned here: one row per group, the order's first row, ties broken by id in |
| 10 | + * the last key's direction, a NULL order value ranked last; the window chosen |
| 11 | + * among the rows the read's `where` admits (a group whose newest row the |
| 12 | + * `where` hides answers its newest admitted row) and inside the tenant wall |
| 13 | + * (another tenant's newer row never wins a group); the read's own ORDER BY, |
| 14 | + * limit, offset and projection applied to the groups; no helper column on the |
| 15 | + * rows; and a malformed directive refused before anything compiles. |
| 16 | + * |
| 17 | + * Every live cell runs where the suite provisions it (`OS_TEST_POSTGRES_URL`, |
| 18 | + * `OS_TEST_MYSQL_URL`); SQLite always runs. |
| 19 | + */ |
| 20 | + |
| 21 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 22 | +import type { DriverQuery } from '@objectstack/spec/contracts'; |
| 23 | +import { SqlDriver } from './sql-driver.js'; |
| 24 | +import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; |
| 25 | +import { LATEST_PER_DIRECTIVE, type LatestPerDirective } from './sql-driver-latest-per.js'; |
| 26 | + |
| 27 | +const TABLE = 'os_latest_per_deal'; |
| 28 | + |
| 29 | +/** |
| 30 | + * Deals by account and owner. Account `a1`: d3 is newest; `a2`: d5 and d6 tie |
| 31 | + * on the date (d6 wins on id, descending); `a3`: d8 has no date and ranks last |
| 32 | + * whatever the direction; `ab` is another tenant's account, and `a1` carries |
| 33 | + * one more deal, newer than all, in another tenant (xb). |
| 34 | + */ |
| 35 | +const DEALS = [ |
| 36 | + { id: 'd1', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-01-10', amount: 10, organization_id: 'org_a' }, |
| 37 | + { id: 'd2', account: 'a1', owner: 'u2', stage: 'lost', close_date: '2026-02-10', amount: 20, organization_id: 'org_a' }, |
| 38 | + { id: 'd3', account: 'a1', owner: 'u1', stage: 'hidden', close_date: '2026-03-10', amount: 30, organization_id: 'org_a' }, |
| 39 | + { id: 'd4', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-01-05', amount: 40, organization_id: 'org_a' }, |
| 40 | + { id: 'd5', account: 'a2', owner: 'u1', stage: 'won', close_date: '2026-04-01', amount: 50, organization_id: 'org_a' }, |
| 41 | + { id: 'd6', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-04-01', amount: 60, organization_id: 'org_a' }, |
| 42 | + { id: 'd7', account: 'a3', owner: 'u1', stage: 'won', close_date: '2026-01-01', amount: 70, organization_id: 'org_a' }, |
| 43 | + { id: 'd8', account: 'a3', owner: 'u1', stage: 'won', close_date: null, amount: 80, organization_id: 'org_a' }, |
| 44 | + { id: 'xb', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-12-31', amount: 90, organization_id: 'org_b' }, |
| 45 | + { id: 'yb', account: 'ab', owner: 'u9', stage: 'won', close_date: '2026-06-01', amount: 99, organization_id: 'org_b' }, |
| 46 | +]; |
| 47 | + |
| 48 | +const latestBy = (by: string[], orderBy: LatestPerDirective['orderBy']): LatestPerDirective => ({ by, orderBy }); |
| 49 | +const NEWEST_PER_ACCOUNT = latestBy(['account'], [{ field: 'close_date', order: 'desc' }]); |
| 50 | + |
| 51 | +const query = (directive: unknown, over: Partial<DriverQuery> = {}): DriverQuery => ({ |
| 52 | + orderBy: [{ field: 'account', order: 'asc' }], |
| 53 | + ...over, |
| 54 | + [LATEST_PER_DIRECTIVE]: directive, |
| 55 | +} as unknown as DriverQuery); |
| 56 | + |
| 57 | +const ids = (rows: Array<Record<string, unknown>>) => rows.map((r) => String(r.id)); |
| 58 | + |
| 59 | +function declareCell(cell: DialectCell): void { |
| 60 | + describe(`[latest per group] driver-sql — find answers one row per group (${cell.label})`, () => { |
| 61 | + let driver: SqlDriver; |
| 62 | + const OLD_POSTURE = process.env.OS_TENANCY_POSTURE; |
| 63 | + |
| 64 | + beforeAll(async () => { |
| 65 | + process.env.OS_TENANCY_POSTURE = 'isolated'; |
| 66 | + driver = new SqlDriver(cell.config()); |
| 67 | + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); |
| 68 | + await driver.initObjects([ |
| 69 | + { |
| 70 | + name: TABLE, |
| 71 | + fields: { |
| 72 | + account: { type: 'text' }, owner: { type: 'text' }, stage: { type: 'text' }, |
| 73 | + close_date: { type: 'date' }, amount: { type: 'number' }, organization_id: { type: 'text' }, |
| 74 | + }, |
| 75 | + }, |
| 76 | + ] as never); |
| 77 | + for (const row of DEALS) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true }); |
| 78 | + }); |
| 79 | + |
| 80 | + afterAll(async () => { |
| 81 | + await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {}); |
| 82 | + await driver?.disconnect?.(); |
| 83 | + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; |
| 84 | + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; |
| 85 | + }); |
| 86 | + |
| 87 | + it('one row per group: the newest; a tie goes to the larger id; a NULL date ranks last', async () => { |
| 88 | + const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' }); |
| 89 | + expect(ids(rows)).toEqual(['d3', 'd6', 'd7']); |
| 90 | + }); |
| 91 | + |
| 92 | + it('ascending: the earliest per group, a tie to the smaller id, NULL still last', async () => { |
| 93 | + const rows = await driver.find(TABLE, query(latestBy(['account'], [{ field: 'close_date', order: 'asc' }])), { tenantId: 'org_a' }); |
| 94 | + expect(ids(rows)).toEqual(['d1', 'd4', 'd7']); |
| 95 | + }); |
| 96 | + |
| 97 | + it('a group whose newest row the where hides answers its newest ADMITTED row, never nothing', async () => { |
| 98 | + const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, { where: { stage: { $ne: 'hidden' } } }), { tenantId: 'org_a' }); |
| 99 | + expect(ids(rows)).toEqual(['d2', 'd6', 'd7']); |
| 100 | + }); |
| 101 | + |
| 102 | + it('inside the tenant wall: another tenant\'s newer row never wins, its groups never appear', async () => { |
| 103 | + const a = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' }); |
| 104 | + expect(ids(a)).not.toContain('xb'); |
| 105 | + expect(ids(a)).not.toContain('yb'); |
| 106 | + const b = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_b' }); |
| 107 | + expect(ids(b)).toEqual(['xb', 'yb']); |
| 108 | + }); |
| 109 | + |
| 110 | + it('several partition fields: one row per (account, owner)', async () => { |
| 111 | + const rows = await driver.find(TABLE, query(latestBy(['account', 'owner'], [{ field: 'close_date', order: 'desc' }]), { |
| 112 | + orderBy: [{ field: 'id', order: 'asc' }], |
| 113 | + }), { tenantId: 'org_a' }); |
| 114 | + expect(ids(rows)).toEqual(['d2', 'd3', 'd5', 'd6', 'd7']); |
| 115 | + }); |
| 116 | + |
| 117 | + it('the read\'s own ORDER BY, limit, offset and projection apply to the groups; no helper column', async () => { |
| 118 | + const page = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, { |
| 119 | + orderBy: [{ field: 'amount', order: 'desc' }], |
| 120 | + limit: 2, |
| 121 | + offset: 1, |
| 122 | + fields: ['id', 'amount'], |
| 123 | + }), { tenantId: 'org_a' }); |
| 124 | + // Groups by amount desc: d7 (70), d6 (60), d3 (30) → offset 1, limit 2. |
| 125 | + expect(ids(page)).toEqual(['d6', 'd3']); |
| 126 | + for (const row of page) expect(Object.keys(row).sort()).toEqual(['amount', 'id']); |
| 127 | + const full = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' }); |
| 128 | + for (const row of full) expect(Object.keys(row).some((k) => k.startsWith('__os_latest_per'))).toBe(false); |
| 129 | + }); |
| 130 | + |
| 131 | + it('control: the same read without the directive answers every row', async () => { |
| 132 | + const rows = await driver.find(TABLE, { orderBy: [{ field: 'id', order: 'asc' }] } as DriverQuery, { tenantId: 'org_a' }); |
| 133 | + expect(ids(rows)).toEqual(['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8']); |
| 134 | + }); |
| 135 | + |
| 136 | + it('a malformed directive is refused before anything compiles', async () => { |
| 137 | + const err = await driver.find(TABLE, query({ by: [], orderBy: [] }), { tenantId: 'org_a' }) |
| 138 | + .then(() => null, (e: Error) => e); |
| 139 | + expect(err?.message).toMatch(/latest-per directive is malformed/); |
| 140 | + }); |
| 141 | + }); |
| 142 | +} |
| 143 | + |
| 144 | +for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'find latest per group', declareCell); |
0 commit comments