T-135: M2.3b — libs/data/questdb query layer for QuestDB 10.2.0: LATEST ON + parameterized PGWire queries + contract DDL for bars_1m / fx_1m / bar_revisions (pure, no live QuestDB)

This commit is contained in:
Studio 2026-12-01 06:12:25 -05:00
parent c6bd028dcc
commit 35d5de815b
8 changed files with 1523 additions and 305 deletions

View file

@ -1,102 +1,115 @@
# QuestDB Client Library
A comprehensive QuestDB client library for the Stock Bot trading platform, optimized for time-series data, market analytics, and high-performance queries.
## Features
- **Time-Series Optimized**: Built specifically for time-series data patterns
- **Dual Protocol Support**: HTTP REST API and PostgreSQL wire protocol
- **InfluxDB Line Protocol**: High-performance data ingestion
- **SQL Analytics**: Full SQL support for complex analytics
- **Schema Management**: Automatic table creation and partitioning
- **Performance Monitoring**: Query performance tracking and optimization
- **Health Monitoring**: Connection health monitoring and metrics
## Usage
```typescript
import { QuestDBClient } from '@stock-bot/questdb';
// Initialize client
const questClient = new QuestDBClient();
await questClient.connect();
// Insert market data using InfluxDB Line Protocol
await questClient.insert('ohlcv', {
symbol: 'AAPL',
open: 150.00,
high: 152.00,
low: 149.50,
close: 151.50,
volume: 1000000,
timestamp: new Date()
});
// Query with SQL
const prices = await questClient.query(`
SELECT symbol, close, timestamp
FROM ohlcv
WHERE symbol = 'AAPL'
AND timestamp > dateadd('d', -1, now())
ORDER BY timestamp DESC
`);
// Time-series aggregations
const dailyStats = await questClient.aggregate('ohlcv')
.select(['symbol', 'avg(close) as avg_price'])
.where('symbol = ?', ['AAPL'])
.groupBy('symbol')
.sampleBy('1d', 'timestamp')
.execute();
```
## Data Types
The client provides typed access to the following time-series data:
- **ohlcv**: OHLCV candlestick data
- **trades**: Individual trade executions
- **quotes**: Bid/ask quote data
- **indicators**: Technical indicator values
- **performance**: Portfolio performance metrics
- **risk_metrics**: Risk calculation results
## Configuration
Configure using environment variables:
```env
QUESTDB_HOST=localhost
QUESTDB_HTTP_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_INFLUX_PORT=9009
```
## Time-Series Features
QuestDB excels at:
- **High-frequency data**: Millions of data points per second
- **Time-based partitioning**: Automatic partitioning by time
- **ASOF JOINs**: Time-series specific joins
- **SAMPLE BY**: Time-based aggregations
- **LATEST BY**: Get latest values by key
## Performance
The client includes performance optimizations:
- Connection pooling for HTTP and PostgreSQL protocols
- Batch insertions for high throughput
- Compressed data transfer
- Query result caching
- Automatic schema optimization
## Health Monitoring
Built-in health monitoring:
```typescript
const health = await questClient.getHealth();
console.log(health.status); // 'healthy' | 'degraded' | 'unhealthy'
```
# QuestDB Client Library
A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized for time-series data, parameterized PGWire queries, and intraday bar storage.
## Features
- **Time-Series Optimized**: Built for QuestDB 10.2.0 (`LATEST ON`, `SAMPLE BY`, `ASOF JOIN`)
- **Parameterized PGWire Queries**: All value filters bind `$1..$n` placeholders; structured identifiers and intervals are strictly validated
- **Contract DDL**: Offline DDL generator for M2 intraday tables (`bars_1m`, `fx_1m`, `bar_revisions`) with `SYMBOL CAPACITY ... [NO]CACHE`, `PARTITION BY MONTH WAL`, and `DEDUP UPSERT KEYS`
- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string and returns `INT32` `listing_id` values with `known_at` preserved
- **InfluxDB Line Protocol**: Batch ingestion writer
- **Health Monitoring**: Connection health monitoring and metrics
## Usage
### Parameterized Queries & `LATEST ON`
```typescript
import { QuestDBClient, QuestDBQueryBuilder } from '@stock-bot/questdb';
const questClient = new QuestDBClient({
host: 'localhost',
httpPort: 9000,
pgPort: 8812,
influxPort: 9009,
database: 'qdb',
});
await questClient.connect();
// Parameterized PGWire query via query builder
const { sql, params } = QuestDBQueryBuilder.create(questClient)
.select('listing_id', 'ts', 'close', 'volume')
.from('bars_1m')
.where('listing_id = $1', ['1042'])
.latestOn('ts', 'listing_id')
.buildParameterized();
// sql:
// SELECT listing_id, ts, close, volume FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id
// params: ['1042']
// Execute directly (forwards both SQL and bound params)
const latestBars = await questClient.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', {
where: 'session = $1',
params: ['RTH'],
});
// Override the designated timestamp column explicitly
const latestRevisions = await questClient.latestBy(
'bar_revisions',
['listing_id', 'revised_at', 'new_close'],
'listing_id',
{ timestampColumn: 'revised_at' }
);
// Time-series aggregations with bound filters
const hourlyStats = await questClient
.aggregate('ohlcv_data')
.selectAgg({ avg_close: 'avg(close)' })
.whereSymbol('AAPL')
.whereLastHours(24)
.groupBy('symbol')
.sampleBy('1h')
.execute();
```
### Reading `bars_1m` Ranges
```typescript
import { readBars1m } from '@stock-bot/questdb';
// Queries `[from, to)` ordered by `ts ASC`, binding listingId as decimal string SYMBOL
// and converting returned `listing_id` back to signed INT32.
const bars = await readBars1m(
questClient,
1042,
new Date('2024-01-02T14:30:00.000Z'),
new Date('2024-01-02T21:00:00.000Z')
);
```
> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` and preserves `known_at` on each row without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing.
### M2 Intraday Contract DDL (Offline)
```typescript
import { getM2IntradayDDL } from '@stock-bot/questdb';
const ddl = getM2IntradayDDL();
// ddl.bars_1m -> CREATE TABLE IF NOT EXISTS bars_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, listing_id)
// ddl.fx_1m -> CREATE TABLE IF NOT EXISTS fx_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, pair)
// ddl.bar_revisions -> CREATE TABLE IF NOT EXISTS bar_revisions (...) TIMESTAMP(revised_at) PARTITION BY MONTH WAL
```
M2 intraday tables are opt-in and are not auto-created during `QuestDBClient.connect()`.
## Configuration
Configure using environment variables:
```env
QUESTDB_HOST=localhost
QUESTDB_HTTP_PORT=9000
QUESTDB_PG_PORT=8812
QUESTDB_INFLUX_PORT=9009
```
## Time-Series Features
QuestDB 10.2.0 supports:
- **High-frequency data**: Millions of data points per second
- **Time-based partitioning**: Monthly WAL partitions for intraday tables
- **ASOF JOINs**: Time-series specific joins
- **SAMPLE BY**: Time-based aggregations
- **LATEST ON**: Get latest values per partition key (`LATEST ON <ts> PARTITION BY <keys>`)

View file

@ -3,15 +3,153 @@ import { Pool } from 'pg';
import type { LoggerLike } from '@stock-bot/logger';
import { QuestDBHealthMonitor } from './health';
import { QuestDBInfluxWriter } from './influx-writer';
import { QuestDBQueryBuilder } from './query-builder';
import {
assertIdentifier,
assertSampleInterval,
assertSelectColumn,
QuestDBQueryBuilder,
rebaseWhereCondition,
} from './query-builder';
import { QuestDBSchemaManager } from './schema';
import type {
Bar1mRow,
LatestByOptions,
QueryResult,
QuestDBClientConfig,
QuestDBConnectionOptions,
QuestDBQueryable,
TableNames,
} from './types';
const INT32_MIN = -2147483648;
const INT32_MAX = 2147483647;
const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/;
const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']);
function formatInt32ListingId(listingId: number): string {
if (!Number.isInteger(listingId) || listingId < INT32_MIN || listingId > INT32_MAX) {
throw new RangeError(
`Invalid listingId: expected signed INT32 integer, received ${String(listingId)}`
);
}
return String(listingId === 0 ? 0 : listingId);
}
function parseInt32ListingSymbol(raw: unknown): number {
if (typeof raw !== 'string' || !CANONICAL_INT_RE.test(raw)) {
throw new Error(`Malformed bars_1m listing_id SYMBOL value: "${String(raw)}"`);
}
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < INT32_MIN || parsed > INT32_MAX) {
throw new RangeError(`Out-of-range bars_1m listing_id SYMBOL value: "${raw}"`);
}
return parsed;
}
function toUtcIsoString(value: Date | string, label: string): string {
if (value instanceof Date) {
if (Number.isNaN(value.getTime())) {
throw new Error(`Invalid ${label} timestamp: Date is NaN`);
}
return value.toISOString();
}
if (typeof value === 'string' && value.trim().length > 0) {
const parsed = new Date(value);
if (!Number.isNaN(parsed.getTime())) {
return parsed.toISOString();
}
}
throw new Error(`Invalid ${label} timestamp: "${String(value)}"`);
}
function parseBarTimestamp(raw: unknown, field: string): Date {
if (raw instanceof Date) {
if (Number.isNaN(raw.getTime())) {
throw new Error(`Invalid bars_1m ${field} timestamp: Date is NaN`);
}
return new Date(raw.getTime());
}
if (typeof raw === 'string' || typeof raw === 'number') {
const parsed = new Date(raw);
if (!Number.isNaN(parsed.getTime())) {
return parsed;
}
}
throw new Error(`Invalid bars_1m ${field} timestamp: "${String(raw)}"`);
}
function parseRequiredFiniteNumber(raw: unknown, field: string): number {
const value =
typeof raw === 'number'
? raw
: typeof raw === 'string' && raw.trim().length > 0
? Number(raw)
: Number.NaN;
if (!Number.isFinite(value)) {
throw new Error(`Invalid bars_1m ${field} value: "${String(raw)}"`);
}
return value;
}
function parseNullableFiniteNumber(raw: unknown, field: string): number | null {
if (raw === null || raw === undefined) {
return null;
}
return parseRequiredFiniteNumber(raw, field);
}
function parseNullableString(raw: unknown, field: string): string | null {
if (raw === null || raw === undefined) {
return null;
}
if (typeof raw === 'string') {
return raw;
}
throw new Error(`Invalid bars_1m ${field} value: expected string or null`);
}
/**
* Read 1-minute bars for a single listing over `[from, to)` ordered by `ts ASC` from `bars_1m`.
*
* Binds `listingId` as its canonical decimal string (`SYMBOL`) and converts returned `listing_id`
* values back to signed `INT32` numbers at the boundary (`design/DATA-CONTRACTS.md` §3.B).
*
* Storage-layer read: preserves `known_at` on each row without applying replay cutoffs.
* Research callers (`MarketDataStore`) remain responsible for as-of availability and Vault fencing.
*/
export async function readBars1m(
client: QuestDBQueryable,
listingId: number,
from: Date | string,
to: Date | string
): Promise<Bar1mRow[]> {
const listingIdParam = formatInt32ListingId(listingId);
const fromIso = toUtcIsoString(from, 'from');
const toIso = toUtcIsoString(to, 'to');
const 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';
const result = await client.query<Record<string, unknown>>(sql, [listingIdParam, fromIso, toIso]);
return result.rows.map(row => ({
listing_id: parseInt32ListingSymbol(row.listing_id),
open: parseRequiredFiniteNumber(row.open, 'open'),
high: parseRequiredFiniteNumber(row.high, 'high'),
low: parseRequiredFiniteNumber(row.low, 'low'),
close: parseRequiredFiniteNumber(row.close, 'close'),
volume: parseRequiredFiniteNumber(row.volume, 'volume'),
vwap: parseNullableFiniteNumber(row.vwap, 'vwap'),
session: parseNullableString(row.session, 'session'),
source: parseNullableString(row.source, 'source'),
known_at: parseBarTimestamp(row.known_at, 'known_at'),
ts: parseBarTimestamp(row.ts, 'ts'),
}));
}
/**
* QuestDB Client for Stock Bot
*
@ -231,72 +369,125 @@ export class QuestDBClient {
}
/**
* Execute a time-series specific query with SAMPLE BY
* Execute a time-series specific query with SAMPLE BY.
* `where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `params`.
*/
async sampleBy<T = QueryResultRow>(
table: TableNames,
table: TableNames | string,
columns: string[],
interval: string,
_timeColumn: string = 'timestamp',
timeColumn: string = 'timestamp',
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const columnsStr = columns.join(', ');
const whereClause = where ? `WHERE ${where}` : '';
const validTable = assertIdentifier(table, 'table name');
if (columns.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
const validColumns = columns.map(col => assertSelectColumn(col));
const validInterval = assertSampleInterval(interval);
assertIdentifier(timeColumn, 'timestamp column');
const sql = `
SELECT ${columnsStr}
FROM ${table}
${whereClause}
SAMPLE BY ${interval}
ALIGN TO CALENDAR
`;
let whereClause = '';
const boundParams = params ? [...params] : [];
if (where !== undefined) {
const validatedWhere = rebaseWhereCondition(where, boundParams, 0);
whereClause = `WHERE ${validatedWhere}`;
} else if (boundParams.length > 0) {
throw new Error('params provided to sampleBy without a where clause');
}
return await this.query<T>(sql, params);
const sql = [
`SELECT ${validColumns.join(', ')}`,
`FROM ${validTable}`,
whereClause,
`SAMPLE BY ${validInterval}`,
'ALIGN TO CALENDAR',
]
.filter(Boolean)
.join(' ');
return await this.query<T>(sql, boundParams.length > 0 ? boundParams : undefined);
}
/**
* Get latest values by symbol using LATEST BY
* Get latest rows per partition key using QuestDB 10.2.0 `LATEST ON`.
* Defaults to `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` otherwise.
* `options.where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `options.params`.
*/
async latestBy<T = QueryResultRow>(
table: TableNames,
table: TableNames | string,
columns: string | string[] = '*',
keyColumns: string | string[] = 'symbol'
keyColumns: string | string[] = 'symbol',
options?: LatestByOptions
): Promise<QueryResult<T>> {
const columnsStr = Array.isArray(columns) ? columns.join(', ') : columns;
const keyColumnsStr = Array.isArray(keyColumns) ? keyColumns.join(', ') : keyColumns;
const cols = Array.isArray(columns) ? columns : [columns];
if (cols.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
const keys = Array.isArray(keyColumns) ? keyColumns : [keyColumns];
const sql = `
SELECT ${columnsStr}
FROM ${table}
LATEST BY ${keyColumnsStr}
`;
const builder = this.queryBuilder().select(...cols).from(table);
return await this.query<T>(sql);
if (options?.where !== undefined) {
builder.where(options.where, options.params);
} else if (options?.params && options.params.length > 0) {
throw new Error('params provided to latestBy without a where clause');
}
if (options?.timestampColumn !== undefined) {
builder.latestOn(options.timestampColumn, ...keys);
} else {
builder.latestBy(...keys);
}
return await builder.execute<T>();
}
/**
* Execute ASOF JOIN for time-series correlation
* Execute ASOF JOIN for time-series correlation.
* `joinCondition` and `where` are treated as trusted SQL fragments.
*/
async asofJoin<T = QueryResultRow>(
leftTable: TableNames,
rightTable: TableNames,
leftTable: TableNames | string,
rightTable: TableNames | string,
joinCondition: string,
columns?: string[],
where?: string,
params?: unknown[]
): Promise<QueryResult<T>> {
const columnsStr = columns ? columns.join(', ') : '*';
const whereClause = where ? `WHERE ${where}` : '';
const validLeft = assertIdentifier(leftTable, 'left table name');
const validRight = assertIdentifier(rightTable, 'right table name');
if (typeof joinCondition !== 'string' || joinCondition.trim().length === 0) {
throw new Error('ASOF JOIN condition must be a non-empty SQL fragment');
}
let columnsStr = '*';
if (columns !== undefined) {
if (columns.length === 0) {
throw new Error('SELECT columns cannot be empty');
}
columnsStr = columns.map(col => assertSelectColumn(col)).join(', ');
}
const sql = `
SELECT ${columnsStr}
FROM ${leftTable}
ASOF JOIN ${rightTable} ON ${joinCondition}
${whereClause}
`;
let whereClause = '';
const boundParams = params ? [...params] : [];
if (where !== undefined) {
const validatedWhere = rebaseWhereCondition(where, boundParams, 0);
whereClause = `WHERE ${validatedWhere}`;
} else if (boundParams.length > 0) {
throw new Error('params provided to asofJoin without a where clause');
}
return await this.query<T>(sql, params);
const sql = [
`SELECT ${columnsStr}`,
`FROM ${validLeft}`,
`ASOF JOIN ${validRight} ON ${joinCondition}`,
whereClause,
]
.filter(Boolean)
.join(' ');
return await this.query<T>(sql, boundParams.length > 0 ? boundParams : undefined);
}
/**
@ -320,7 +511,7 @@ export class QuestDBClient {
* Get table information
*/
async getTableInfo(tableName: string): Promise<QueryResultRow[]> {
const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [
const result = await this.query(`SELECT * FROM table_columns WHERE table_name = $1`, [
tableName,
]);
return result.rows;
@ -374,8 +565,9 @@ export class QuestDBClient {
* Optimize table by rebuilding partitions
*/
async optimizeTable(tableName: string): Promise<void> {
await this.query(`VACUUM TABLE ${tableName}`);
this.logger.debug(`Optimized table: ${tableName}`);
const validTable = assertIdentifier(tableName, 'table name');
await this.query(`VACUUM TABLE ${validTable}`);
this.logger.debug(`Optimized table: ${validTable}`);
}
/**
@ -387,14 +579,19 @@ export class QuestDBClient {
partitionBy: string = 'DAY',
timestampColumn: string = 'timestamp'
): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
const validTimestamp = assertIdentifier(timestampColumn, 'timestamp column');
if (!ALLOWED_PARTITIONS.has(partitionBy)) {
throw new Error(`Invalid PARTITION BY value: "${String(partitionBy)}"`);
}
const sql = `
CREATE TABLE IF NOT EXISTS ${tableName} (
CREATE TABLE IF NOT EXISTS ${validTable} (
${columns}
) TIMESTAMP(${timestampColumn}) PARTITION BY ${partitionBy}
) TIMESTAMP(${validTimestamp}) PARTITION BY ${partitionBy}
`;
await this.query(sql);
this.logger.info(`Created table: ${tableName}`);
this.logger.info(`Created table: ${validTable}`);
}
/**

View file

@ -5,27 +5,39 @@
* InfluxDB Line Protocol, SQL queries, and PostgreSQL wire protocol.
*/
export { QuestDBClient } from './client';
export { QuestDBClient, readBars1m } from './client';
export { QuestDBHealthMonitor } from './health';
export { QuestDBQueryBuilder } from './query-builder';
export { QuestDBInfluxWriter } from './influx-writer';
export { QuestDBSchemaManager } from './schema';
export {
formatCreateTableSQL,
getM2IntradayDDL,
M2_INTRADAY_SCHEMAS,
QuestDBSchemaManager,
type M2IntradayTableName,
} from './schema';
// Types
export type {
Bar1mRow,
ColumnSchema,
InsertResult,
LatestByOptions,
OHLCVData,
ParameterizedQuery,
PerformanceData,
QueryResult,
QuestDBClientConfig,
QuestDBConnectionOptions,
QuestDBHealthStatus,
QuestDBMetrics,
TableNames,
OHLCVData,
TradeData,
QuestDBQueryable,
QuoteData,
IndicatorData,
PerformanceData,
RiskMetrics,
QueryResult,
InsertResult,
TableNames,
TableSchema,
TradeData,
IndicatorData,
} from './types';
// Note: Factory functions removed - instantiate directly with new QuestDBClient()

View file

@ -1,32 +1,252 @@
import type { QueryResultRow } from 'pg';
import { getLogger } from '@stock-bot/logger';
import type { QueryResult, TableNames, TimeRange } from './types';
import type {
ParameterizedQuery,
QueryResult,
QuestDBQueryable,
TableNames,
TimeRange,
} from './types';
// Interface to avoid circular dependency
interface QuestDBClientInterface {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
const SAMPLE_INTERVAL_RE = /^\d+[UTsmhdwMy]$/;
/**
* Validate a SQL identifier (table, column, alias, or timestamp column).
*/
export function assertIdentifier(value: string, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_RE.test(value)) {
throw new Error(`Invalid ${label}: "${String(value)}"`);
}
return value;
}
/**
* Validate a projection column (literal `*` or strict SQL identifier).
*/
export function assertSelectColumn(value: string): string {
if (value === '*') {
return value;
}
return assertIdentifier(value, 'SELECT column');
}
/**
* Validate a QuestDB SAMPLE BY interval (e.g. `1m`, `5m`, `1h`, `1d`).
*/
export function assertSampleInterval(value: string): string {
if (typeof value !== 'string' || !SAMPLE_INTERVAL_RE.test(value)) {
throw new Error(`Invalid SAMPLE BY interval: "${String(value)}"`);
}
return value;
}
/**
* Validate a SQL sort direction.
*/
export function assertSortDirection(value: string): 'ASC' | 'DESC' {
if (value !== 'ASC' && value !== 'DESC') {
throw new Error(`Invalid ORDER BY direction: "${String(value)}"`);
}
return value;
}
/**
* Resolve the default designated timestamp column for a QuestDB table.
*/
export function defaultTimestampColumnForTable(table: string): string {
switch (table) {
case 'bars_1m':
case 'fx_1m':
return 'ts';
case 'bar_revisions':
return 'revised_at';
default:
return 'timestamp';
}
}
/**
* Offset fragment-local `$1..$k` placeholders in a trusted SQL WHERE fragment by `offset`.
* Preserves repeated references and ignores `$n` inside single/double quotes and SQL comments.
* Rejects `$0`, out-of-range placeholders, and unused parameters.
*/
export function rebaseWhereCondition(
condition: string,
params: readonly unknown[] = [],
offset: number = 0
): string {
if (typeof condition !== 'string' || condition.trim().length === 0) {
throw new Error('WHERE condition must be a non-empty SQL string');
}
const usedIndices = new Set<number>();
let out = '';
let i = 0;
while (i < condition.length) {
const ch = condition.charAt(i);
const next = condition.charAt(i + 1);
// Single-quoted string literal ('...' with '' escape)
if (ch === "'") {
out += ch;
i += 1;
while (i < condition.length) {
const cur = condition.charAt(i);
out += cur;
i += 1;
if (cur === "'") {
if (condition.charAt(i) === "'") {
out += "'";
i += 1;
} else {
break;
}
}
}
continue;
}
// Double-quoted identifier ("..." with "" escape)
if (ch === '"') {
out += ch;
i += 1;
while (i < condition.length) {
const cur = condition.charAt(i);
out += cur;
i += 1;
if (cur === '"') {
if (condition.charAt(i) === '"') {
out += '"';
i += 1;
} else {
break;
}
}
}
continue;
}
// Line comment (-- ... \n)
if (ch === '-' && next === '-') {
out += '--';
i += 2;
while (i < condition.length) {
const cur = condition.charAt(i);
out += cur;
i += 1;
if (cur === '\n') {
break;
}
}
continue;
}
// Block comment (/* ... */)
if (ch === '/' && next === '*') {
out += '/*';
i += 2;
while (i < condition.length) {
if (condition.charAt(i) === '*' && condition.charAt(i + 1) === '/') {
out += '*/';
i += 2;
break;
}
out += condition.charAt(i);
i += 1;
}
continue;
}
// Parameter placeholder ($1, $2, ..., $10, ...)
if (ch === '$' && next >= '0' && next <= '9') {
const prev = i > 0 ? condition.charAt(i - 1) : '';
const isPartOfIdentifier = /[A-Za-z0-9_]/.test(prev);
if (!isPartOfIdentifier) {
let j = i + 1;
while (j < condition.length) {
const digit = condition.charAt(j);
if (digit < '0' || digit > '9') {
break;
}
j += 1;
}
const digits = condition.slice(i + 1, j);
const index = Number(digits);
if (!Number.isSafeInteger(index) || index < 1) {
throw new Error(`Invalid parameter placeholder $${digits}: placeholders are 1-based`);
}
if (index > params.length) {
throw new Error(
`Parameter placeholder $${index} is out of range for ${params.length} provided parameter(s)`
);
}
usedIndices.add(index);
out += `$${offset + index}`;
i = j;
continue;
}
}
out += ch;
i += 1;
}
for (let idx = 1; idx <= params.length; idx += 1) {
if (!usedIndices.has(idx)) {
throw new Error(`Unused parameter at index ${idx} in WHERE condition`);
}
}
return out;
}
interface WherePredicate {
sql: string;
params: unknown[];
}
interface LatestOnClause {
timestampColumn?: string;
partitionBy: string[];
}
function assertValidDate(value: Date, label: string): Date {
if (!(value instanceof Date) || Number.isNaN(value.getTime())) {
throw new Error(`Invalid ${label}: expected a valid Date`);
}
return value;
}
function assertPositiveInteger(value: number, label: string): number {
if (!Number.isInteger(value) || value <= 0) {
throw new Error(`Invalid ${label}: expected a positive integer, received ${String(value)}`);
}
return value;
}
/**
* QuestDB Query Builder
*
* Provides a fluent interface for building optimized time-series queries
* with support for QuestDB-specific functions and optimizations.
* Provides a fluent interface for building parameterized PGWire time-series queries
* with support for QuestDB 10.2.0 SQL clauses (`LATEST ON`, `SAMPLE BY`).
*/
export class QuestDBQueryBuilder {
private readonly logger: ReturnType<typeof getLogger>;
private query!: {
select: string[];
from: string;
where: string[];
where: WherePredicate[];
groupBy: string[];
orderBy: string[];
limit?: number;
sampleBy?: string;
latestBy?: string[];
latestOn?: LatestOnClause;
timeRange?: TimeRange;
};
constructor(private readonly client: QuestDBClientInterface) {
constructor(private readonly client: QuestDBQueryable) {
this.logger = getLogger('questdb-query-builder');
this.reset();
}
@ -41,193 +261,263 @@ export class QuestDBQueryBuilder {
where: [],
groupBy: [],
orderBy: [],
limit: undefined,
sampleBy: undefined,
latestBy: undefined,
latestOn: undefined,
timeRange: undefined,
};
return this;
}
/**
* Start a new query
*/
public static create(client: QuestDBClientInterface): QuestDBQueryBuilder {
public static create(client: QuestDBQueryable): QuestDBQueryBuilder {
return new QuestDBQueryBuilder(client);
}
/**
* Select columns
* Select columns (`*` or validated SQL identifiers)
*/
public select(...columns: string[]): QuestDBQueryBuilder {
this.query.select.push(...columns);
const validated = columns.map(col => assertSelectColumn(col));
this.query.select.push(...validated);
return this;
}
/**
* Select with aggregation functions
* Select with aggregation functions.
* Aliases are validated as SQL identifiers; aggregation expressions are treated as trusted SQL fragments.
*/
public selectAgg(aggregations: Record<string, string>): QuestDBQueryBuilder {
Object.entries(aggregations).forEach(([alias, expression]) => {
this.query.select.push(`${expression} as ${alias}`);
const validatedEntries = Object.entries(aggregations).map(([alias, expression]) => {
const validAlias = assertIdentifier(alias, 'aggregation alias');
if (typeof expression !== 'string' || expression.trim().length === 0) {
throw new Error(`Invalid aggregation expression for alias "${validAlias}"`);
}
return `${expression} as ${validAlias}`;
});
this.query.select.push(...validatedEntries);
return this;
}
/**
* From table (validated SQL identifier)
*/
public from(table: TableNames | string): QuestDBQueryBuilder {
this.query.from = assertIdentifier(table, 'table name');
return this;
}
/**
* Raw WHERE predicate (trusted SQL fragment escape hatch).
* Supports fragment-local `$1..$n` placeholders, which are renumbered automatically during build.
*/
public where(condition: string, params?: unknown[]): QuestDBQueryBuilder {
const boundParams = params ? [...params] : [];
// Validate fragment syntax and parameter indices eagerly before mutating builder state.
rebaseWhereCondition(condition, boundParams, 0);
this.query.where.push({ sql: condition, params: boundParams });
return this;
}
/**
* Where symbol equals (bound parameter)
*/
public whereSymbol(symbol: string): QuestDBQueryBuilder {
this.query.where.push({ sql: 'symbol = $1', params: [symbol] });
return this;
}
/**
* Where symbols in list (one bound parameter per element; rejects empty lists)
*/
public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder {
if (symbols.length === 0) {
throw new Error('whereSymbolIn requires at least one symbol');
}
const placeholders = symbols.map((_, index) => `$${index + 1}`).join(', ');
this.query.where.push({
sql: `symbol IN (${placeholders})`,
params: [...symbols],
});
return this;
}
/**
* From table
*/
public from(table: TableNames | string): QuestDBQueryBuilder {
this.query.from = table;
return this;
}
/**
* Where condition
*/
public where(condition: string): QuestDBQueryBuilder {
this.query.where.push(condition);
return this;
}
/**
* Where symbol equals
*/
public whereSymbol(symbol: string): QuestDBQueryBuilder {
this.query.where.push(`symbol = '${symbol}'`);
return this;
}
/**
* Where symbols in list
*/
public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder {
const symbolList = symbols.map(s => `'${s}'`).join(', ');
this.query.where.push(`symbol IN (${symbolList})`);
return this;
}
/**
* Where exchange equals
* Where exchange equals (bound parameter)
*/
public whereExchange(exchange: string): QuestDBQueryBuilder {
this.query.where.push(`exchange = '${exchange}'`);
this.query.where.push({ sql: 'exchange = $1', params: [exchange] });
return this;
}
/**
* Time range filter
* Time range filter with inclusive bounds (bound UTC ISO-8601 parameters)
*/
public whereTimeRange(startTime: Date, endTime: Date): QuestDBQueryBuilder {
this.query.timeRange = { startTime, endTime };
this.query.where.push(
`timestamp >= '${startTime.toISOString()}' AND timestamp <= '${endTime.toISOString()}'`
);
const validStart = assertValidDate(startTime, 'startTime');
const validEnd = assertValidDate(endTime, 'endTime');
this.query.timeRange = { startTime: validStart, endTime: validEnd };
this.query.where.push({
sql: 'timestamp >= $1 AND timestamp <= $2',
params: [validStart.toISOString(), validEnd.toISOString()],
});
return this;
}
/**
* Last N hours
* Last N hours (bound negative hour offset)
*/
public whereLastHours(hours: number): QuestDBQueryBuilder {
this.query.where.push(`timestamp > dateadd('h', -${hours}, now())`);
const validHours = assertPositiveInteger(hours, 'hours');
this.query.where.push({
sql: "timestamp > dateadd('h', $1, now())",
params: [-validHours],
});
return this;
}
/**
* Last N days
* Last N days (bound negative day offset)
*/
public whereLastDays(days: number): QuestDBQueryBuilder {
this.query.where.push(`timestamp > dateadd('d', -${days}, now())`);
const validDays = assertPositiveInteger(days, 'days');
this.query.where.push({
sql: "timestamp > dateadd('d', $1, now())",
params: [-validDays],
});
return this;
}
/**
* Group by columns
* Group by columns (validated SQL identifiers)
*/
public groupBy(...columns: string[]): QuestDBQueryBuilder {
this.query.groupBy.push(...columns);
const validated = columns.map(col => assertIdentifier(col, 'GROUP BY column'));
this.query.groupBy.push(...validated);
return this;
}
/**
* Order by column
* Order by column (validated identifier and direction)
*/
public orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): QuestDBQueryBuilder {
this.query.orderBy.push(`${column} ${direction}`);
const validColumn = assertIdentifier(column, 'ORDER BY column');
const validDirection = assertSortDirection(direction);
this.query.orderBy.push(`${validColumn} ${validDirection}`);
return this;
}
/**
* Order by timestamp descending (most recent first)
*/
public orderByTimeDesc(): QuestDBQueryBuilder {
this.query.orderBy.push('timestamp DESC');
public orderByTimeDesc(timestampColumn: string = 'timestamp'): QuestDBQueryBuilder {
const validColumn = assertIdentifier(timestampColumn, 'ORDER BY column');
this.query.orderBy.push(`${validColumn} DESC`);
return this;
}
/**
* Limit results
* Limit results (bound non-negative integer parameter)
*/
public limit(count: number): QuestDBQueryBuilder {
if (!Number.isInteger(count) || count < 0) {
throw new Error(`Invalid LIMIT count: expected a non-negative integer, received ${String(count)}`);
}
this.query.limit = count;
return this;
}
/**
* Sample by time interval (QuestDB specific)
* Sample by time interval (QuestDB specific, validated interval)
*/
public sampleBy(interval: string): QuestDBQueryBuilder {
this.query.sampleBy = interval;
this.query.sampleBy = assertSampleInterval(interval);
return this;
}
/**
* Latest by columns (QuestDB specific)
* QuestDB 10.2.0 `LATEST ON <timestamp> PARTITION BY <keys>` with explicit timestamp column.
*/
public latestBy(...columns: string[]): QuestDBQueryBuilder {
this.query.latestBy = columns;
public latestOn(timestampColumn: string, ...partitionByColumns: string[]): QuestDBQueryBuilder {
const validTs = assertIdentifier(timestampColumn, 'LATEST ON timestamp column');
if (partitionByColumns.length === 0) {
throw new Error('latestOn requires at least one partition column');
}
const validKeys = partitionByColumns.map(col =>
assertIdentifier(col, 'LATEST ON partition column')
);
this.query.latestOn = {
timestampColumn: validTs,
partitionBy: validKeys,
};
return this;
}
/**
* Build and execute the query
* Convenience wrapper emitting `LATEST ON <table default timestamp> PARTITION BY <keys>`.
* Uses `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` for legacy tables.
*/
public latestBy(...partitionByColumns: string[]): QuestDBQueryBuilder {
if (partitionByColumns.length === 0) {
throw new Error('latestBy requires at least one partition column');
}
const validKeys = partitionByColumns.map(col =>
assertIdentifier(col, 'LATEST ON partition column')
);
this.query.latestOn = {
timestampColumn: undefined,
partitionBy: validKeys,
};
return this;
}
/**
* Build and execute the parameterized query
*/
public async execute<T = QueryResultRow>(): Promise<QueryResult<T>> {
const sql = this.build();
this.logger.debug('Executing query', { sql });
let built: ParameterizedQuery | undefined;
try {
const result = await this.client.query<T>(sql);
this.reset(); // Reset for next query
return result;
built = this.buildParameterized();
this.logger.debug('Executing query', { sql: built.sql, paramCount: built.params.length });
return await this.client.query<T>(built.sql, built.params);
} catch (error) {
this.logger.error('Query execution failed', { sql, error });
this.reset(); // Reset even on error
this.logger.error('Query execution failed', { sql: built?.sql, error });
throw error;
} finally {
this.reset();
}
}
/**
* Build the SQL query string
* Build the parameterized SQL query and ordered parameter list (`$1..$n`).
*/
public build(): string {
public buildParameterized(): ParameterizedQuery {
if (!this.query.from) {
throw new Error('FROM clause is required');
}
if (this.query.select.length === 0) {
this.query.select.push('*');
}
const selectColumns = this.query.select.length > 0 ? this.query.select : ['*'];
const params: unknown[] = [];
let sql = `SELECT ${this.query.select.join(', ')} FROM ${this.query.from}`;
let sql = `SELECT ${selectColumns.join(', ')} FROM ${this.query.from}`;
// Add WHERE clause
// Add WHERE clause with consecutively renumbered $1..$n placeholders
if (this.query.where.length > 0) {
sql += ` WHERE ${this.query.where.join(' AND ')}`;
const renderedPredicates = this.query.where.map(predicate => {
const rebased = rebaseWhereCondition(predicate.sql, predicate.params, params.length);
params.push(...predicate.params);
return rebased;
});
sql += ` WHERE ${renderedPredicates.join(' AND ')}`;
}
// Add LATEST BY (QuestDB specific - must come before GROUP BY)
if (this.query.latestBy && this.query.latestBy.length > 0) {
sql += ` LATEST BY ${this.query.latestBy.join(', ')}`;
// Add LATEST ON (QuestDB 10.2.0 - placed after WHERE, before SAMPLE BY / GROUP BY)
if (this.query.latestOn && this.query.latestOn.partitionBy.length > 0) {
const tsColumn =
this.query.latestOn.timestampColumn ?? defaultTimestampColumnForTable(this.query.from);
sql += ` LATEST ON ${tsColumn} PARTITION BY ${this.query.latestOn.partitionBy.join(', ')}`;
}
// Add SAMPLE BY (QuestDB specific)
@ -245,27 +535,36 @@ export class QuestDBQueryBuilder {
sql += ` ORDER BY ${this.query.orderBy.join(', ')}`;
}
// Add LIMIT
if (this.query.limit) {
sql += ` LIMIT ${this.query.limit}`;
// Add LIMIT (bound parameter)
if (this.query.limit !== undefined) {
params.push(this.query.limit);
sql += ` LIMIT $${params.length}`;
}
return sql;
return { sql, params };
}
/**
* Get the built query without executing
* Build the SQL query string (placeholder view of `buildParameterized().sql`)
*/
public build(): string {
return this.buildParameterized().sql;
}
/**
* Get the built query string without executing
*/
public toSQL(): string {
return this.build();
}
// Predefined query methods for common use cases
/**
* Get latest OHLCV data for symbols
*/
public static latestOHLCV(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbols: string[],
exchange?: string
): QuestDBQueryBuilder {
@ -282,11 +581,12 @@ export class QuestDBQueryBuilder {
return builder;
}
/**
* Get OHLCV data with time sampling
*/
public static ohlcvTimeSeries(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbol: string,
interval: string,
hours: number = 24
@ -305,11 +605,12 @@ export class QuestDBQueryBuilder {
.sampleBy(interval)
.orderByTimeDesc();
}
/**
* Get market analytics data
*/
public static marketAnalytics(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbols: string[],
hours: number = 1
): QuestDBQueryBuilder {
@ -329,11 +630,12 @@ export class QuestDBQueryBuilder {
.orderBy('symbol')
.orderByTimeDesc();
}
/**
* Get performance metrics for a time range
*/
public static performanceMetrics(
client: QuestDBClientInterface,
client: QuestDBQueryable,
startTime: Date,
endTime: Date
): QuestDBQueryBuilder {
@ -348,11 +650,12 @@ export class QuestDBQueryBuilder {
.whereTimeRange(startTime, endTime)
.sampleBy('1m');
}
/**
* Get trade execution data
*/
public static tradeExecutions(
client: QuestDBClientInterface,
client: QuestDBQueryable,
symbol?: string,
hours: number = 24
): QuestDBQueryBuilder {

View file

@ -1,11 +1,147 @@
import type { QueryResultRow } from 'pg';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { QueryResult, TableSchema } from './types';
import { assertIdentifier } from './query-builder';
import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types';
// Interface to avoid circular dependency
interface QuestDBClientInterface {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions';
/**
* Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B).
* Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`).
*/
export const M2_INTRADAY_SCHEMAS: Readonly<Record<M2IntradayTableName, TableSchema>> = {
bars_1m: {
tableName: 'bars_1m',
columns: [
{ name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false },
{ name: 'open', type: 'DOUBLE' },
{ name: 'high', type: 'DOUBLE' },
{ name: 'low', type: 'DOUBLE' },
{ name: 'close', type: 'DOUBLE' },
{ name: 'volume', type: 'DOUBLE' },
{ name: 'vwap', type: 'DOUBLE' },
{ name: 'session', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'source', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'known_at', type: 'TIMESTAMP' },
{ name: 'ts', type: 'TIMESTAMP', designated: true },
],
partitionBy: 'MONTH',
wal: true,
dedupUpsertKeys: ['ts', 'listing_id'],
},
fx_1m: {
tableName: 'fx_1m',
columns: [
{ name: 'pair', type: 'SYMBOL', capacity: 32, cache: true },
{ name: 'open', type: 'DOUBLE' },
{ name: 'high', type: 'DOUBLE' },
{ name: 'low', type: 'DOUBLE' },
{ name: 'close', type: 'DOUBLE' },
{ name: 'source', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'ts', type: 'TIMESTAMP', designated: true },
],
partitionBy: 'MONTH',
wal: true,
dedupUpsertKeys: ['ts', 'pair'],
},
bar_revisions: {
tableName: 'bar_revisions',
columns: [
{ name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false },
{ name: 'timeframe', type: 'SYMBOL', capacity: 8, cache: true },
{ name: 'bar_ts', type: 'TIMESTAMP' },
{ name: 'prev_close', type: 'DOUBLE' },
{ name: 'new_close', type: 'DOUBLE' },
{ name: 'prev_volume', type: 'DOUBLE' },
{ name: 'new_volume', type: 'DOUBLE' },
{ name: 'revised_at', type: 'TIMESTAMP', designated: true },
],
partitionBy: 'MONTH',
wal: true,
},
};
function formatColumnDDL(col: ColumnSchema): string {
const name = assertIdentifier(col.name, 'column name');
let def = `${name} ${col.type}`;
if (col.type === 'SYMBOL') {
if (col.capacity !== undefined) {
if (!Number.isInteger(col.capacity) || col.capacity <= 0) {
throw new Error(
`Invalid SYMBOL capacity for column "${name}": expected positive integer, received ${String(col.capacity)}`
);
}
def += ` CAPACITY ${col.capacity}`;
}
if (col.cache === true) {
def += ' CACHE';
} else if (col.cache === false) {
def += ' NOCACHE';
}
}
return def;
}
/**
* Pure QuestDB CREATE TABLE DDL formatter shared by legacy schemas and M2 contract tables.
*/
export function formatCreateTableSQL(schema: TableSchema): string {
const tableName = assertIdentifier(schema.tableName, 'table name');
if (!schema.columns || schema.columns.length === 0) {
throw new Error('At least one column is required');
}
const columnNames = new Set(schema.columns.map(col => assertIdentifier(col.name, 'column name')));
// QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint.
// nullable remains descriptive metadata; the designated timestamp is declared below.
const columns = schema.columns.map(formatColumnDDL).join(', ');
let sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns})`;
const timestampColumns = schema.columns.filter(col => col.designated);
if (timestampColumns.length > 1) {
throw new Error('Only one designated timestamp column is allowed');
}
const timestampColumn = timestampColumns[0];
if (timestampColumn) {
sql += ` TIMESTAMP(${assertIdentifier(timestampColumn.name, 'designated timestamp column')})`;
}
if (schema.partitionBy) {
sql += ` PARTITION BY ${schema.partitionBy}`;
}
if (schema.wal) {
sql += ' WAL';
}
if (schema.dedupUpsertKeys && schema.dedupUpsertKeys.length > 0) {
const keys = schema.dedupUpsertKeys.map(key => {
const validKey = assertIdentifier(key, 'DEDUP UPSERT key');
if (!columnNames.has(validKey)) {
throw new Error(`DEDUP UPSERT key "${validKey}" does not exist on table "${tableName}"`);
}
return validKey;
});
sql += ` DEDUP UPSERT KEYS(${keys.join(', ')})`;
}
return sql;
}
/**
* Return the QuestDB 10.2.0 DDL statements for `bars_1m`, `fx_1m`, and `bar_revisions`.
* Pure offline helper; requires no database connection.
*/
export function getM2IntradayDDL(): Record<M2IntradayTableName, string> {
return {
bars_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bars_1m),
fx_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.fx_1m),
bar_revisions: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bar_revisions),
};
}
/**
@ -17,7 +153,7 @@ interface QuestDBClientInterface {
export class QuestDBSchemaManager {
private readonly logger: ReturnType<typeof getLogger>;
private readonly schemas: Map<string, TableSchema> = new Map();
constructor(private readonly client: QuestDBClientInterface) {
constructor(private readonly client: QuestDBQueryable) {
this.logger = getLogger('questdb-schema-manager');
this.initializeSchemas();
}
@ -195,13 +331,14 @@ export class QuestDBSchemaManager {
* Drop a table
*/
public async dropTable(tableName: string): Promise<void> {
const sql = `DROP TABLE IF EXISTS ${tableName}`;
const validTable = assertIdentifier(tableName, 'table name');
const sql = `DROP TABLE IF EXISTS ${validTable}`;
try {
await this.client.query(sql);
this.logger.warn(`Table ${tableName} dropped`);
this.logger.warn(`Table ${validTable} dropped`);
} catch (error) {
this.logger.error(`Failed to drop table ${tableName}`, error);
this.logger.error(`Failed to drop table ${validTable}`, error);
throw error;
}
}
@ -211,13 +348,12 @@ export class QuestDBSchemaManager {
*/
public async tableExists(tableName: string): Promise<boolean> {
try {
const result = await this.client.query(`
SELECT COUNT(*) as count
FROM information_schema.tables
WHERE table_name = '${tableName}'
`);
const result = await this.client.query<{ count: number | string }>(
'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1',
[tableName]
);
return result.rows.length > 0 && at(result.rows, 0).count > 0;
return result.rows.length > 0 && Number(at(result.rows, 0).count) > 0;
} catch (error) {
this.logger.error(`Error checking if table exists: ${tableName}`, error);
return false;
@ -269,18 +405,19 @@ export class QuestDBSchemaManager {
* Get table statistics
*/
public async getTableStats(tableName: string): Promise<QueryResultRow | undefined> {
const validTable = assertIdentifier(tableName, 'table name');
try {
const result = await this.client.query(`
SELECT
COUNT(*) as row_count,
MIN(timestamp) as min_timestamp,
MAX(timestamp) as max_timestamp
FROM ${tableName}
FROM ${validTable}
`);
return result.rows[0] || {};
} catch (error) {
this.logger.error(`Failed to get table stats for ${tableName}`, error);
this.logger.error(`Failed to get table stats for ${validTable}`, error);
throw error;
}
}
@ -289,11 +426,12 @@ export class QuestDBSchemaManager {
* Truncate table (remove all data but keep structure)
*/
public async truncateTable(tableName: string): Promise<void> {
const validTable = assertIdentifier(tableName, 'table name');
try {
await this.client.query(`TRUNCATE TABLE ${tableName}`);
this.logger.warn(`Table ${tableName} truncated`);
await this.client.query(`TRUNCATE TABLE ${validTable}`);
this.logger.warn(`Table ${validTable} truncated`);
} catch (error) {
this.logger.error(`Failed to truncate table ${tableName}`, error);
this.logger.error(`Failed to truncate table ${validTable}`, error);
throw error;
}
}
@ -311,27 +449,7 @@ export class QuestDBSchemaManager {
* Build CREATE TABLE SQL statement
*/
private buildCreateTableSQL(schema: TableSchema): string {
// QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint.
// nullable remains descriptive metadata; the designated timestamp is declared
// below. See https://questdb.com/docs/query/sql/create-table/.
const columns = schema.columns
.map(col => `${col.name} ${col.type}`)
.join(', ');
let sql = `CREATE TABLE IF NOT EXISTS ${schema.tableName} (${columns})`;
// Add designated timestamp
const timestampColumn = schema.columns.find(col => col.designated);
if (timestampColumn) {
sql += ` TIMESTAMP(${timestampColumn.name})`;
}
// Add partition by
if (schema.partitionBy) {
sql += ` PARTITION BY ${schema.partitionBy}`;
}
return sql;
return formatCreateTableSQL(schema);
}
/**

View file

@ -62,7 +62,52 @@ export type TableNames =
| 'risk_metrics'
| 'market_events'
| 'strategy_signals'
| 'portfolio_snapshots';
| 'portfolio_snapshots'
| 'bars_1m'
| 'fx_1m'
| 'bar_revisions';
/**
* Shared minimal query executor interface for QuestDB helpers.
*/
export interface QuestDBQueryable {
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
}
/**
* Parameterized PGWire SQL query and ordered bound parameters ($1..$n).
*/
export interface ParameterizedQuery {
sql: string;
params: unknown[];
}
/**
* Options for QuestDBClient.latestBy().
*/
export interface LatestByOptions {
timestampColumn?: string;
where?: string;
params?: unknown[];
}
/**
* Typed 1-minute bar row returned from QuestDB `bars_1m`.
* `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary.
*/
export interface Bar1mRow {
listing_id: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
vwap: number | null;
session: string | null;
source: string | null;
known_at: Date;
ts: Date;
}
/**
* Time-Series Data Types
@ -214,12 +259,14 @@ export interface TableSchema {
tableName: string;
columns: ColumnSchema[];
partitionBy?: 'NONE' | 'HOUR' | 'DAY' | 'MONTH' | 'YEAR';
wal?: boolean;
dedupUpsertKeys?: string[];
orderBy?: string[];
indices?: IndexDefinition[];
dedup?: boolean;
}
interface ColumnSchema {
export interface ColumnSchema {
name: string;
type:
| 'SYMBOL'
@ -235,6 +282,7 @@ interface ColumnSchema {
nullable?: boolean;
designated?: boolean; // For designated timestamp column
capacity?: number; // For SYMBOL type
cache?: boolean; // For SYMBOL type: true -> CACHE, false -> NOCACHE
indexed?: boolean;
}

View file

@ -0,0 +1,526 @@
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<T = QueryResultRow>(
sql: string,
params?: unknown[]
): Promise<QueryResult<T>> {
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);
}
});
});
});

View file

@ -252,19 +252,20 @@ describe('QuestDB', () => {
const builder = new QuestDBQueryBuilder(mockClient);
const query = builder
const { sql, params } = builder
.select('symbol', 'close', 'volume')
.from('ohlcv_data')
.whereSymbol('AAPL')
.orderBy('timestamp', 'DESC')
.limit(100)
.build();
.buildParameterized();
expect(query).toContain('SELECT symbol, close, volume');
expect(query).toContain('FROM ohlcv_data');
expect(query).toContain("symbol = 'AAPL'");
expect(query).toContain('ORDER BY timestamp DESC');
expect(query).toContain('LIMIT 100');
expect(sql).toContain('SELECT symbol, close, volume');
expect(sql).toContain('FROM ohlcv_data');
expect(sql).toContain('symbol = $1');
expect(sql).toContain('ORDER BY timestamp DESC');
expect(sql).toContain('LIMIT $2');
expect(params).toEqual(['AAPL', 100]);
});
it('should build query with time range', () => {