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

@ -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;
}