stock-bot/libs/data/questdb/test/questdb-query-layer-edges.test.ts
2026-12-01 06:39:23 -05:00

305 lines
11 KiB
TypeScript

import { describe, expect, it } from 'bun:test';
import type { QueryResultRow } from 'pg';
import {
formatCreateTableSQL,
QuestDBClient,
QuestDBQueryBuilder,
QuestDBSchemaManager,
readBars1m,
type QueryResult,
type QuestDBQueryable,
} from '../src';
interface RecordedQuery {
sql: string;
params: unknown[] | undefined;
}
class RecordingClient implements QuestDBQueryable {
public readonly calls: RecordedQuery[] = [];
public async query<T = QueryResultRow>(
sql: string,
params?: unknown[]
): Promise<QueryResult<T>> {
this.calls.push({ sql, params });
return { rows: [] as T[], rowCount: 0, executionTime: 0 };
}
}
function clientRoutedTo(fake: RecordingClient): QuestDBClient {
const client = new QuestDBClient(
{ host: 'questdb.test.local', httpPort: 9000, pgPort: 8812, influxPort: 9009, database: 'qdb' },
{ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }
);
(client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake);
return client;
}
describe('QuestDB query layer edge cases (QA)', () => {
describe('predefined builders', () => {
it('latestOHLCV binds symbols and exchange and emits LATEST ON timestamp after WHERE', () => {
const fake = new RecordingClient();
const hostile = "AAPL' OR '1'='1";
const { sql, params } = QuestDBQueryBuilder.latestOHLCV(
fake,
[hostile, 'MSFT'],
'NASDAQ'
).buildParameterized();
expect(sql).toBe(
'SELECT symbol, timestamp, open, high, low, close, volume FROM ohlcv_data ' +
'WHERE symbol IN ($1, $2) AND exchange = $3 ' +
'LATEST ON timestamp PARTITION BY symbol ORDER BY timestamp DESC'
);
expect(params).toEqual([hostile, 'MSFT', 'NASDAQ']);
expect(sql).not.toContain(hostile);
});
it('ohlcvTimeSeries and tradeExecutions bind values in placeholder order', () => {
const fake = new RecordingClient();
const series = QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '5m', 12).buildParameterized();
expect(series.sql).toBe(
'SELECT first(open) as first_open, max(high) as max_high, min(low) as min_low, ' +
'last(close) as last_close, sum(volume) as sum_volume FROM ohlcv_data ' +
"WHERE symbol = $1 AND timestamp > dateadd('h', $2, now()) SAMPLE BY 5m ORDER BY timestamp DESC"
);
expect(series.params).toEqual(['AAPL', -12]);
const trades = QuestDBQueryBuilder.tradeExecutions(fake, 'AAPL', 3).buildParameterized();
expect(trades.sql).toBe(
'SELECT symbol, timestamp, side, quantity, price, execution_time FROM trade_executions ' +
"WHERE timestamp > dateadd('h', $1, now()) AND symbol = $2 ORDER BY timestamp DESC"
);
expect(trades.params).toEqual([-3, 'AAPL']);
});
it('ohlcvTimeSeries rejects a hostile SAMPLE BY interval at build time', () => {
const fake = new RecordingClient();
expect(() => QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '1h; DROP TABLE x')).toThrow(
/Invalid SAMPLE BY interval/
);
expect(fake.calls).toHaveLength(0);
});
});
describe('builder input validation', () => {
it('binds LIMIT 0 instead of silently dropping it and rejects negative or fractional limits', () => {
const fake = new RecordingClient();
expect(QuestDBQueryBuilder.create(fake).from('t').limit(0).buildParameterized()).toEqual({
sql: 'SELECT * FROM t LIMIT $1',
params: [0],
});
expect(() => QuestDBQueryBuilder.create(fake).limit(-1)).toThrow(/LIMIT/);
expect(() => QuestDBQueryBuilder.create(fake).limit(1.5)).toThrow(/LIMIT/);
});
it('rejects non-positive relative windows and invalid dates', () => {
const fake = new RecordingClient();
expect(() => QuestDBQueryBuilder.create(fake).whereLastHours(0)).toThrow(/hours/);
expect(() => QuestDBQueryBuilder.create(fake).whereLastDays(-2)).toThrow(/days/);
expect(() =>
QuestDBQueryBuilder.create(fake).whereTimeRange(new Date('nope'), new Date())
).toThrow(/startTime/);
});
it('rejects unterminated quotes and block comments in raw where() before mutating state', () => {
const fake = new RecordingClient();
const builder = QuestDBQueryBuilder.create(fake).from('bars_1m');
expect(() => builder.where("session = 'RTH", [])).toThrow(/Unterminated string/);
expect(() => builder.where('"session = $1', ['RTH'])).toThrow(/Unterminated quoted/);
expect(() => builder.where('session = $1 /* open', ['RTH'])).toThrow(/Unterminated block/);
// Rejected fragments must not leak into the next build.
expect(builder.where('session = $1', ['RTH']).buildParameterized()).toEqual({
sql: 'SELECT * FROM bars_1m WHERE session = $1',
params: ['RTH'],
});
});
it('keeps doubled quotes inside literals and still rebases the following placeholder', () => {
const fake = new RecordingClient();
const { sql, params } = QuestDBQueryBuilder.create(fake)
.from('bars_1m')
.whereSymbol('X')
.where("note = 'it''s $1' AND close > $1", [10])
.buildParameterized();
expect(sql).toBe("SELECT * FROM bars_1m WHERE symbol = $1 AND note = 'it''s $1' AND close > $2");
expect(params).toEqual(['X', 10]);
});
});
describe('QuestDBClient helpers', () => {
it('reject params without a where fragment before sending a query', async () => {
const fake = new RecordingClient();
const client = clientRoutedTo(fake);
await expect(
client.sampleBy('bars_1m', ['ts', 'close'], '1h', 'ts', undefined, ['RTH'])
).rejects.toThrow(/without a where/);
await expect(
client.asofJoin('bars_1m', 'fx_1m', 'bars_1m.ts = fx_1m.ts', undefined, undefined, [1])
).rejects.toThrow(/without a where/);
await expect(
client.latestBy('bars_1m', '*', 'listing_id', { params: ['RTH'] })
).rejects.toThrow(/without a where/);
await expect(client.sampleBy('bars_1m', ['ts'], '1h', 'ts; --')).rejects.toThrow(
/Invalid timestamp column/
);
await expect(
client.createTable('bars_1m', 'ts TIMESTAMP', 'DAY; DROP TABLE x', 'ts')
).rejects.toThrow(/PARTITION BY/);
await expect(client.optimizeTable('bars_1m; DROP TABLE x')).rejects.toThrow(
/Invalid table name/
);
expect(fake.calls).toHaveLength(0);
});
it('asofJoin binds where params and keeps SQL on validated identifiers', async () => {
const fake = new RecordingClient();
const client = clientRoutedTo(fake);
await client.asofJoin(
'bars_1m',
'fx_1m',
'bars_1m.ts = fx_1m.ts',
['close'],
'listing_id = $1 AND pair = $2',
['1042', 'USDCAD']
);
expect(fake.calls).toEqual([
{
sql:
'SELECT close FROM bars_1m ASOF JOIN fx_1m ON bars_1m.ts = fx_1m.ts ' +
'WHERE listing_id = $1 AND pair = $2',
params: ['1042', 'USDCAD'],
},
]);
});
});
describe('schema DDL', () => {
it('leaves legacy startup DDL unchanged (no CAPACITY, CACHE, WAL or DEDUP)', async () => {
const fake = new RecordingClient();
await new QuestDBSchemaManager(fake).createAllTables();
const ddl = fake.calls.map(call => call.sql);
expect(ddl).toHaveLength(6);
expect(ddl[0]).toBe(
'CREATE TABLE IF NOT EXISTS ohlcv_data (symbol SYMBOL, exchange SYMBOL, timestamp TIMESTAMP, ' +
'open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume LONG, data_source SYMBOL) ' +
'TIMESTAMP(timestamp) PARTITION BY DAY'
);
for (const statement of ddl) {
expect(statement).not.toMatch(/CAPACITY|CACHE|WAL|DEDUP|bars_1m|fx_1m|bar_revisions/);
}
});
it('formatCreateTableSQL rejects hostile identifiers, bad capacities and multiple designated timestamps', () => {
expect(() =>
formatCreateTableSQL({
tableName: 'bars_1m; DROP TABLE x',
columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }],
})
).toThrow(/Invalid table name/);
expect(() =>
formatCreateTableSQL({
tableName: 't',
columns: [{ name: 'ts TIMESTAMP); --', type: 'TIMESTAMP' }],
})
).toThrow(/Invalid column name/);
expect(() =>
formatCreateTableSQL({
tableName: 't',
columns: [{ name: 's', type: 'SYMBOL', capacity: 0 }],
})
).toThrow(/capacity/);
expect(() =>
formatCreateTableSQL({
tableName: 't',
columns: [
{ name: 'a', type: 'TIMESTAMP', designated: true },
{ name: 'b', type: 'TIMESTAMP', designated: true },
],
})
).toThrow(/Only one designated/);
});
});
describe('readBars1m bound normalisation', () => {
it('converts offset bounds to UTC with fractional digits intact, across a day boundary', async () => {
const fake = new RecordingClient();
await readBars1m(fake, -0, '2024-01-01T23:30:00.5-05:00', '2024-01-02T09:30:00.000123+05:30');
expect(fake.calls).toHaveLength(1);
expect(fake.calls[0]?.params).toEqual([
'0',
'2024-01-02T04:30:00.5Z',
'2024-01-02T04:00:00.000123Z',
]);
});
it('binds negative INT32 listing ids and parses negative SYMBOL values back', async () => {
const fake = new RecordingClient();
(fake as unknown as { query: QuestDBQueryable['query'] }).query = async <T,>(
sql: string,
params?: unknown[]
) => {
fake.calls.push({ sql, params });
return {
rows: [
{
listing_id: '-2147483648',
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
vwap: null,
session: null,
source: null,
known_at_us: '1704205800000000',
ts_us: '1704205800000000',
},
] as T[],
rowCount: 1,
executionTime: 0,
};
};
const rows = await readBars1m(
fake,
-2147483648,
'2024-01-02T14:30:00Z',
'2024-01-02T14:31:00Z'
);
expect(fake.calls[0]?.params?.[0]).toBe('-2147483648');
expect(rows[0]?.listing_id).toBe(-2147483648);
expect(rows[0]?.vwap).toBeNull();
});
it('rejects impossible calendar dates, out-of-range offsets and NaN dates before querying', async () => {
const fake = new RecordingClient();
const to = '2024-03-01T00:00:00Z';
await expect(readBars1m(fake, 1, '2024-02-30T00:00:00Z', to)).rejects.toThrow(/calendar/);
await expect(readBars1m(fake, 1, '2024-02-01T00:00:00+24:00', to)).rejects.toThrow(
/offset/
);
await expect(readBars1m(fake, 1, new Date('nope'), to)).rejects.toThrow(/NaN/);
await expect(readBars1m(fake, 1, '2024-02-01T00:00:00.1234567Z', to)).rejects.toThrow(
/timezone/
);
expect(fake.calls).toHaveLength(0);
});
});
});