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:
parent
c6bd028dcc
commit
35d5de815b
8 changed files with 1523 additions and 305 deletions
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue