import type { QueryResultRow } from 'pg'; import { getLogger } from '@stock-bot/logger'; import type { ParameterizedQuery, QueryResult, QuestDBQueryable, TableNames, TimeRange, } from './types'; 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(); 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; let closed = false; while (i < condition.length) { const cur = condition.charAt(i); out += cur; i += 1; if (cur === "'") { if (condition.charAt(i) === "'") { out += "'"; i += 1; } else { closed = true; break; } } } if (!closed) { throw new Error('Unterminated string literal in WHERE condition'); } continue; } // Double-quoted identifier ("..." with "" escape) if (ch === '"') { out += ch; i += 1; let closed = false; while (i < condition.length) { const cur = condition.charAt(i); out += cur; i += 1; if (cur === '"') { if (condition.charAt(i) === '"') { out += '"'; i += 1; } else { closed = true; break; } } } if (!closed) { throw new Error('Unterminated quoted identifier in WHERE condition'); } continue; } // Line comment (-- ... \n); terminate at EOF so subsequent clauses are never swallowed if (ch === '-' && next === '-') { out += '--'; i += 2; let sawNewline = false; while (i < condition.length) { const cur = condition.charAt(i); out += cur; i += 1; if (cur === '\n') { sawNewline = true; break; } } if (!sawNewline) { out += '\n'; } continue; } // Block comment (/* ... */) if (ch === '/' && next === '*') { out += '/*'; i += 2; let closed = false; while (i < condition.length) { if (condition.charAt(i) === '*' && condition.charAt(i + 1) === '/') { out += '*/'; i += 2; closed = true; break; } out += condition.charAt(i); i += 1; } if (!closed) { throw new Error('Unterminated block comment in WHERE condition'); } 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 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; private query!: { select: string[]; from: string; where: WherePredicate[]; groupBy: string[]; orderBy: string[]; limit?: number; sampleBy?: string; latestOn?: LatestOnClause; timeRange?: TimeRange; }; constructor(private readonly client: QuestDBQueryable) { this.logger = getLogger('questdb-query-builder'); this.reset(); } /** * Reset the query builder */ private reset(): QuestDBQueryBuilder { this.query = { select: [], from: '', where: [], groupBy: [], orderBy: [], limit: undefined, sampleBy: undefined, latestOn: undefined, timeRange: undefined, }; return this; } /** * Start a new query */ public static create(client: QuestDBQueryable): QuestDBQueryBuilder { return new QuestDBQueryBuilder(client); } /** * Select columns (`*` or validated SQL identifiers) */ public select(...columns: string[]): QuestDBQueryBuilder { const validated = columns.map(col => assertSelectColumn(col)); this.query.select.push(...validated); return this; } /** * Select with aggregation functions. * Aliases are validated as SQL identifiers; aggregation expressions are treated as trusted SQL fragments. */ public selectAgg(aggregations: Record): QuestDBQueryBuilder { 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; } /** * Where exchange equals (bound parameter) */ public whereExchange(exchange: string): QuestDBQueryBuilder { this.query.where.push({ sql: 'exchange = $1', params: [exchange] }); return this; } /** * Time range filter with inclusive bounds (bound UTC ISO-8601 parameters) */ public whereTimeRange(startTime: Date, endTime: Date): QuestDBQueryBuilder { 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 (bound negative hour offset) */ public whereLastHours(hours: number): QuestDBQueryBuilder { const validHours = assertPositiveInteger(hours, 'hours'); this.query.where.push({ sql: "timestamp > dateadd('h', $1, now())", params: [-validHours], }); return this; } /** * Last N days (bound negative day offset) */ public whereLastDays(days: number): QuestDBQueryBuilder { const validDays = assertPositiveInteger(days, 'days'); this.query.where.push({ sql: "timestamp > dateadd('d', $1, now())", params: [-validDays], }); return this; } /** * Group by columns (validated SQL identifiers) */ public groupBy(...columns: string[]): QuestDBQueryBuilder { const validated = columns.map(col => assertIdentifier(col, 'GROUP BY column')); this.query.groupBy.push(...validated); return this; } /** * Order by column (validated identifier and direction) */ public orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): QuestDBQueryBuilder { 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(timestampColumn: string = 'timestamp'): QuestDBQueryBuilder { const validColumn = assertIdentifier(timestampColumn, 'ORDER BY column'); this.query.orderBy.push(`${validColumn} DESC`); return this; } /** * 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, validated interval) */ public sampleBy(interval: string): QuestDBQueryBuilder { this.query.sampleBy = assertSampleInterval(interval); return this; } /** * QuestDB 10.2.0 `LATEST ON PARTITION BY ` with explicit timestamp column. */ 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; } /** * Convenience wrapper emitting `LATEST ON PARTITION BY `. * 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(): Promise> { let built: ParameterizedQuery | undefined; try { built = this.buildParameterized(); this.logger.debug('Executing query', { sql: built.sql, paramCount: built.params.length }); return await this.client.query(built.sql, built.params); } catch (error) { this.logger.error('Query execution failed', { sql: built?.sql, error }); throw error; } finally { this.reset(); } } /** * Build the parameterized SQL query and ordered parameter list (`$1..$n`). */ public buildParameterized(): ParameterizedQuery { if (!this.query.from) { throw new Error('FROM clause is required'); } const selectColumns = this.query.select.length > 0 ? this.query.select : ['*']; const params: unknown[] = []; let sql = `SELECT ${selectColumns.join(', ')} FROM ${this.query.from}`; // Add WHERE clause with consecutively renumbered $1..$n placeholders if (this.query.where.length > 0) { 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 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) if (this.query.sampleBy) { sql += ` SAMPLE BY ${this.query.sampleBy}`; } // Add GROUP BY if (this.query.groupBy.length > 0) { sql += ` GROUP BY ${this.query.groupBy.join(', ')}`; } // Add ORDER BY if (this.query.orderBy.length > 0) { sql += ` ORDER BY ${this.query.orderBy.join(', ')}`; } // Add LIMIT (bound parameter) if (this.query.limit !== undefined) { params.push(this.query.limit); sql += ` LIMIT $${params.length}`; } return { sql, params }; } /** * 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: QuestDBQueryable, symbols: string[], exchange?: string ): QuestDBQueryBuilder { const builder = QuestDBQueryBuilder.create(client) .select('symbol', 'timestamp', 'open', 'high', 'low', 'close', 'volume') .from('ohlcv_data') .whereSymbolIn(symbols) .latestBy('symbol') .orderByTimeDesc(); if (exchange) { builder.whereExchange(exchange); } return builder; } /** * Get OHLCV data with time sampling */ public static ohlcvTimeSeries( client: QuestDBQueryable, symbol: string, interval: string, hours: number = 24 ): QuestDBQueryBuilder { return QuestDBQueryBuilder.create(client) .selectAgg({ first_open: 'first(open)', max_high: 'max(high)', min_low: 'min(low)', last_close: 'last(close)', sum_volume: 'sum(volume)', }) .from('ohlcv_data') .whereSymbol(symbol) .whereLastHours(hours) .sampleBy(interval) .orderByTimeDesc(); } /** * Get market analytics data */ public static marketAnalytics( client: QuestDBQueryable, symbols: string[], hours: number = 1 ): QuestDBQueryBuilder { return QuestDBQueryBuilder.create(client) .select( 'symbol', 'timestamp', 'rsi', 'macd', 'bollinger_upper', 'bollinger_lower', 'volume_sma' ) .from('market_analytics') .whereSymbolIn(symbols) .whereLastHours(hours) .orderBy('symbol') .orderByTimeDesc(); } /** * Get performance metrics for a time range */ public static performanceMetrics( client: QuestDBQueryable, startTime: Date, endTime: Date ): QuestDBQueryBuilder { return QuestDBQueryBuilder.create(client) .selectAgg({ total_trades: 'count(*)', avg_response_time: 'avg(response_time)', max_response_time: 'max(response_time)', error_rate: 'sum(case when success = false then 1 else 0 end) * 100.0 / count(*)', }) .from('performance_metrics') .whereTimeRange(startTime, endTime) .sampleBy('1m'); } /** * Get trade execution data */ public static tradeExecutions( client: QuestDBQueryable, symbol?: string, hours: number = 24 ): QuestDBQueryBuilder { const builder = QuestDBQueryBuilder.create(client) .select('symbol', 'timestamp', 'side', 'quantity', 'price', 'execution_time') .from('trade_executions') .whereLastHours(hours) .orderByTimeDesc(); if (symbol) { builder.whereSymbol(symbol); } return builder; } }