import { describe, expect, it } from 'bun:test'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import type { QueryResultRow } from 'pg'; import { formatCreateTableSQL, getM2IntradayDDL, QuestDBClient, QuestDBQueryBuilder, QuestDBSchemaManager, readBars1m, type QueryResult, type QuestDBQueryable, } from '../src'; interface RecordedQuery { sql: string; params: unknown[] | undefined; } class FakeQuestDBClient implements QuestDBQueryable { public readonly calls: RecordedQuery[] = []; private nextRows: unknown[] = []; private nextError: Error | null = null; public setRows(rows: unknown[]): void { this.nextRows = rows; } public failNext(error: Error): void { this.nextError = error; } public async query( sql: string, params?: unknown[] ): Promise> { this.calls.push({ sql, params }); if (this.nextError) { const err = this.nextError; this.nextError = null; throw err; } return { rows: this.nextRows as T[], rowCount: this.nextRows.length, executionTime: 1, }; } } function createClientWithFakeQuery(fake: FakeQuestDBClient): QuestDBClient { const client = new QuestDBClient( { host: 'questdb.test.local', httpPort: 9000, pgPort: 8812, influxPort: 9009, database: 'qdb', }, { info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, } ); // Route PGWire query execution to the recording fake without opening a network socket. (client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake); return client; } function normalizeSql(sql: string): string { return sql .replace(/--[^\n]*/g, '') .replace(/;/g, '') .replace(/\s+/g, ' ') .replace(/\(\s+/g, '(') .replace(/\s+\)/g, ')') .replace(/\s+,/g, ',') .trim(); } describe('QuestDB 10.2.0 query layer', () => { describe('LATEST ON clause generation', () => { it('emits LATEST ON after WHERE with explicit timestamp and partition key', async () => { const fake = new FakeQuestDBClient(); const builder = QuestDBQueryBuilder.create(fake) .select('listing_id', 'ts', 'close') .from('bars_1m') .where('listing_id = $1', ['1042']) .latestOn('ts', 'listing_id'); const built = builder.buildParameterized(); expect(built.sql).toBe( 'SELECT listing_id, ts, close FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id' ); expect(built.params).toEqual(['1042']); expect(builder.build()).toBe(built.sql); expect(builder.toSQL()).toBe(built.sql); await builder.execute(); expect(fake.calls).toHaveLength(1); expect(fake.calls[0]).toEqual({ sql: built.sql, params: ['1042'], }); }); it('preserves multi-key PARTITION BY ordering', () => { const fake = new FakeQuestDBClient(); const sql = QuestDBQueryBuilder.create(fake) .select('listing_id', 'session', 'ts', 'close') .from('bars_1m') .latestOn('ts', 'listing_id', 'session') .build(); expect(sql).toBe( 'SELECT listing_id, session, ts, close FROM bars_1m LATEST ON ts PARTITION BY listing_id, session' ); }); it('resolves table-appropriate default timestamps for latestBy()', () => { const fake = new FakeQuestDBClient(); expect(QuestDBQueryBuilder.create(fake).from('bars_1m').latestBy('listing_id').build()).toBe( 'SELECT * FROM bars_1m LATEST ON ts PARTITION BY listing_id' ); expect(QuestDBQueryBuilder.create(fake).from('fx_1m').latestBy('pair').build()).toBe( 'SELECT * FROM fx_1m LATEST ON ts PARTITION BY pair' ); expect( QuestDBQueryBuilder.create(fake).from('bar_revisions').latestBy('listing_id').build() ).toBe('SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id'); expect(QuestDBQueryBuilder.create(fake).from('ohlcv_data').latestBy('symbol').build()).toBe( 'SELECT * FROM ohlcv_data LATEST ON timestamp PARTITION BY symbol' ); }); it('routes QuestDBClient.latestBy() through the builder with timestamp override and bound filters', async () => { const fake = new FakeQuestDBClient(); const client = createClientWithFakeQuery(fake); await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { where: 'session = $1', params: ['RTH'], }); await client.latestBy('bar_revisions', '*', ['listing_id', 'timeframe']); await client.latestBy('bars_1m', 'close', 'listing_id', { timestampColumn: 'known_at', }); expect(fake.calls).toEqual([ { sql: 'SELECT listing_id, ts, close FROM bars_1m WHERE session = $1 LATEST ON ts PARTITION BY listing_id', params: ['RTH'], }, { sql: 'SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id, timeframe', params: [], }, { sql: 'SELECT close FROM bars_1m LATEST ON known_at PARTITION BY listing_id', params: [], }, ]); }); }); describe('parameterized predicates and placeholder renumbering', () => { it('binds all filter values and keeps hostile input out of SQL', () => { const fake = new FakeQuestDBClient(); const hostile = "x' OR '1'='1"; const start = new Date('2024-01-02T14:30:00.000Z'); const end = new Date('2024-01-02T15:30:00.000Z'); const { sql, params } = QuestDBQueryBuilder.create(fake) .select('symbol', 'exchange', 'timestamp', 'close') .from('ohlcv_data') .whereSymbol(hostile) .whereSymbolIn(['AAPL', 'MSFT']) .whereExchange('NASDAQ') .whereTimeRange(start, end) .whereLastHours(6) .whereLastDays(2) .limit(25) .buildParameterized(); expect(sql).toBe( 'SELECT symbol, exchange, timestamp, close FROM ohlcv_data ' + "WHERE symbol = $1 AND symbol IN ($2, $3) AND exchange = $4 AND timestamp >= $5 AND timestamp <= $6 AND timestamp > dateadd('h', $7, now()) AND timestamp > dateadd('d', $8, now()) " + 'LIMIT $9' ); expect(sql).not.toContain(hostile); expect(sql).not.toContain('AAPL'); expect(sql).not.toContain('NASDAQ'); expect(params).toEqual([ hostile, 'AAPL', 'MSFT', 'NASDAQ', '2024-01-02T14:30:00.000Z', '2024-01-02T15:30:00.000Z', -6, -2, 25, ]); }); it('renumbers raw where() fragments consecutively across repeated, multi-digit, quoted, and commented placeholders', () => { const fake = new FakeQuestDBClient(); const tenParams = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10']; const tenPred = 'c1=$1 AND c2=$2 AND c3=$3 AND c4=$4 AND c5=$5 AND c6=$6 AND c7=$7 AND c8=$8 AND c9=$9 AND c10=$10'; const { sql, params } = QuestDBQueryBuilder.create(fake) .from('ohlcv_data') .limit(10) .whereSymbol('SPY') .where( "note = '$1' AND \"col_$2\" = $1 AND close >= $1 -- ignore $3\n/* ignore $4 */ AND volume > $2", [100.5, 5000] ) .where(tenPred, tenParams) .buildParameterized(); expect(sql).toBe( 'SELECT * FROM ohlcv_data WHERE symbol = $1 ' + 'AND note = \'$1\' AND "col_$2" = $2 AND close >= $2 -- ignore $3\n/* ignore $4 */ AND volume > $3 ' + 'AND c1=$4 AND c2=$5 AND c3=$6 AND c4=$7 AND c5=$8 AND c6=$9 AND c7=$10 AND c8=$11 AND c9=$12 AND c10=$13 ' + 'LIMIT $14' ); expect(params).toHaveLength(14); expect(params).toEqual(['SPY', 100.5, 5000, ...tenParams, 10]); }); it('rejects empty IN lists and malformed/mismatched where() placeholders before querying', () => { const fake = new FakeQuestDBClient(); expect(() => QuestDBQueryBuilder.create(fake).whereSymbolIn([])).toThrow( /at least one symbol/i ); expect(() => QuestDBQueryBuilder.create(fake).where('close > $0', [1])).toThrow(/1-based/i); expect(() => QuestDBQueryBuilder.create(fake).where('close > $2', [1])).toThrow( /out of range/i ); expect(() => QuestDBQueryBuilder.create(fake).where('close > $1', [1, 2])).toThrow( /Unused parameter/i ); expect(() => QuestDBQueryBuilder.create(fake).where('close > 10', [1])).toThrow( /Unused parameter/i ); expect(() => QuestDBQueryBuilder.create(fake).where(' ')).toThrow(/non-empty/i); expect(fake.calls).toHaveLength(0); }); it('resets builder cleanly for reuse after execution and after rejection', async () => { const fake = new FakeQuestDBClient(); const builder = QuestDBQueryBuilder.create(fake); fake.failNext(new Error('simulated wire failure')); await expect(builder.from('ohlcv_data').whereSymbol('AAPL').execute()).rejects.toThrow( 'simulated wire failure' ); // Builder must be reset after failed execute() const nextBuilt = builder.select('close').from('bars_1m').where('listing_id = $1', ['7']).buildParameterized(); expect(nextBuilt).toEqual({ sql: 'SELECT close FROM bars_1m WHERE listing_id = $1', params: ['7'], }); await builder.execute(); expect(fake.calls).toHaveLength(2); expect(fake.calls[1]).toEqual(nextBuilt); // Builder is reset again after successful execute() expect(() => builder.build()).toThrow('FROM clause is required'); }); }); describe('identifier and interval validation', () => { it('rejects hostile table, column, alias, latestOn, sort, and sampleBy inputs before querying', async () => { const fake = new FakeQuestDBClient(); const client = createClientWithFakeQuery(fake); expect(() => QuestDBQueryBuilder.create(fake).from('bars_1m; DROP TABLE x')).toThrow( /Invalid table name/i ); expect(() => QuestDBQueryBuilder.create(fake).select('close; --')).toThrow( /Invalid SELECT column/i ); expect(() => QuestDBQueryBuilder.create(fake).selectAgg({ 'bad alias': 'avg(close)' }) ).toThrow(/Invalid aggregation alias/i); expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts; --', 'listing_id')).toThrow( /Invalid LATEST ON timestamp column/i ); expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts', 'listing_id; DROP')).toThrow( /Invalid LATEST ON partition column/i ); expect(() => QuestDBQueryBuilder.create(fake).orderBy('ts', 'UP' as 'ASC')).toThrow( /Invalid ORDER BY direction/i ); expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1h; DROP TABLE x')).toThrow( /Invalid SAMPLE BY interval/i ); expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1x')).toThrow( /Invalid SAMPLE BY interval/i ); await expect( client.sampleBy('bars_1m', ['ts', 'close'], 'bad_interval') ).rejects.toThrow(/Invalid SAMPLE BY interval/i); await expect( client.latestBy('bars_1m; DROP TABLE x', '*', 'listing_id') ).rejects.toThrow(/Invalid table name/i); await expect( client.asofJoin('bars_1m', 'fx_1m; DROP', 'bars_1m.ts = fx_1m.ts') ).rejects.toThrow(/Invalid right table name/i); expect(fake.calls).toHaveLength(0); }); it('binds table name in QuestDBSchemaManager.tableExists() via tables()', async () => { const fake = new FakeQuestDBClient(); fake.setRows([{ count: 1 }]); const manager = new QuestDBSchemaManager(fake); const hostileTable = "bars_1m' OR '1'='1"; const exists = await manager.tableExists(hostileTable); expect(exists).toBe(true); expect(fake.calls).toHaveLength(1); expect(fake.calls[0]).toEqual({ sql: 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1', params: [hostileTable], }); }); }); describe('M2 intraday contract DDL', () => { it('matches design/DATA-CONTRACTS.md ยง3.B exactly after whitespace and comment normalization', () => { const contractPath = resolve(import.meta.dir, '../../../../design/DATA-CONTRACTS.md'); const contractDoc = readFileSync(contractPath, 'utf8'); const sectionMatch = contractDoc.match( /### B\. QuestDB `10\.2\.0`[\s\S]*?```sql\n([\s\S]*?)```/ ); expect(sectionMatch).not.toBeNull(); const contractStatements = sectionMatch![1]! .split(';') .map(normalizeSql) .filter(Boolean); expect(contractStatements).toHaveLength(3); const generated = getM2IntradayDDL(); expect(normalizeSql(generated.bars_1m)).toBe(contractStatements[0]!); expect(normalizeSql(generated.fx_1m)).toBe(contractStatements[1]!); expect(normalizeSql(generated.bar_revisions)).toBe(contractStatements[2]!); expect(generated.bars_1m).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); expect(generated.bars_1m).toContain('session SYMBOL CAPACITY 8 CACHE'); expect(generated.bars_1m).toContain('source SYMBOL CAPACITY 8 CACHE'); expect(generated.bars_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); expect(generated.bars_1m).toContain('DEDUP UPSERT KEYS(ts, listing_id)'); expect(generated.fx_1m).toContain('pair SYMBOL CAPACITY 32 CACHE'); expect(generated.fx_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); expect(generated.fx_1m).toContain('DEDUP UPSERT KEYS(ts, pair)'); expect(generated.bar_revisions).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); expect(generated.bar_revisions).toContain('TIMESTAMP(revised_at) PARTITION BY MONTH WAL'); expect(generated.bar_revisions).not.toContain('DEDUP'); }); it('keeps M2 intraday tables opt-in outside legacy startup initialization', () => { const fake = new FakeQuestDBClient(); const manager = new QuestDBSchemaManager(fake); const startupNames = manager.getSchemaNames(); expect(startupNames).not.toContain('bars_1m'); expect(startupNames).not.toContain('fx_1m'); expect(startupNames).not.toContain('bar_revisions'); // Shared formatter also validates dedup keys exist on the table expect(() => formatCreateTableSQL({ tableName: 'bad_table', columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }], dedupUpsertKeys: ['ts', 'missing_col'], }) ).toThrow(/does not exist/i); }); }); describe('readBars1m storage reader', () => { it('sends one parameterized [from, to) query and converts decimal-string listing_id to INT32', async () => { const fake = new FakeQuestDBClient(); const fixtureRows = [ { listing_id: '1042', open: 185.1, high: 185.5, low: 184.9, close: 185.4, volume: 12500, vwap: 185.28, session: 'RTH', source: 'eod_unadj', known_at: new Date('2024-01-02T14:31:00.000Z'), ts: new Date('2024-01-02T14:30:00.000Z'), }, { listing_id: '1042', open: 185.4, high: 185.6, low: 185.3, close: 185.55, volume: 0, vwap: null, session: 'RTH', source: 'ib_live', known_at: '2024-01-02T14:32:00.000Z', ts: '2024-01-02T14:31:00.000Z', }, ]; fake.setRows(fixtureRows); const from = new Date('2024-01-02T14:30:00.000Z'); const to = new Date('2024-01-02T14:32:00.000Z'); const firstRead = await readBars1m(fake, 1042, from, to); const secondRead = await readBars1m(fake, 1042, from, to); expect(fake.calls).toHaveLength(2); expect(fake.calls[0]).toEqual({ sql: 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, known_at, ts ' + 'FROM bars_1m ' + 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + 'ORDER BY ts ASC', params: ['1042', '2024-01-02T14:30:00.000Z', '2024-01-02T14:32:00.000Z'], }); expect(firstRead).toEqual(secondRead); expect(firstRead).toEqual([ { listing_id: 1042, open: 185.1, high: 185.5, low: 184.9, close: 185.4, volume: 12500, vwap: 185.28, session: 'RTH', source: 'eod_unadj', known_at: new Date('2024-01-02T14:31:00.000Z'), ts: new Date('2024-01-02T14:30:00.000Z'), }, { listing_id: 1042, open: 185.4, high: 185.6, low: 185.3, close: 185.55, volume: 0, vwap: null, session: 'RTH', source: 'ib_live', known_at: new Date('2024-01-02T14:32:00.000Z'), ts: new Date('2024-01-02T14:31:00.000Z'), }, ]); expect(typeof firstRead[0]!.listing_id).toBe('number'); }); it('returns empty array when no bars exist in range', async () => { const fake = new FakeQuestDBClient(); fake.setRows([]); const rows = await readBars1m( fake, 0, '2024-01-02T14:30:00.000Z', '2024-01-02T14:35:00.000Z' ); expect(rows).toEqual([]); expect(fake.calls[0]?.params).toEqual([ '0', '2024-01-02T14:30:00.000Z', '2024-01-02T14:35:00.000Z', ]); }); it('rejects invalid input listingIds and malformed returned SYMBOL listing_id values', async () => { const fake = new FakeQuestDBClient(); const from = new Date('2024-01-02T14:30:00.000Z'); const to = new Date('2024-01-02T14:35:00.000Z'); await expect(readBars1m(fake, 1.5, from, to)).rejects.toThrow(/INT32/i); await expect(readBars1m(fake, 2147483648, from, to)).rejects.toThrow(/INT32/i); expect(fake.calls).toHaveLength(0); for (const badSymbol of ['abc', '007', '12.5', '2147483648', null]) { fake.setRows([ { listing_id: badSymbol, open: 1, high: 2, low: 1, close: 2, volume: 10, vwap: 1.5, session: 'RTH', source: 'eod_unadj', known_at: from, ts: from, }, ]); await expect(readBars1m(fake, 42, from, to)).rejects.toThrow(/listing_id SYMBOL/i); } }); }); });