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,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 {