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
35d5de815b
commit
a67d9c1644
5 changed files with 232 additions and 40 deletions
|
|
@ -7,7 +7,7 @@ A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized fo
|
|||
- **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
|
||||
- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string, returns `INT32` `listing_id` values, and projects `ts` and `known_at` as lossless UTC epoch microseconds (`bigint`)
|
||||
- **InfluxDB Line Protocol**: Batch ingestion writer
|
||||
- **Health Monitoring**: Connection health monitoring and metrics
|
||||
|
||||
|
|
@ -78,7 +78,7 @@ const bars = await readBars1m(
|
|||
);
|
||||
```
|
||||
|
||||
> **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.
|
||||
> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` with `ts` and `known_at` projected via `CAST(... AS LONG)` as UTC epoch microseconds (`bigint`, preserving all 6 fractional digits independent of host timezone) without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing.
|
||||
|
||||
### M2 Intraday Contract DDL (Offline)
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ import type {
|
|||
const INT32_MIN = -2147483648;
|
||||
const INT32_MAX = 2147483647;
|
||||
const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/;
|
||||
const ISO_UTC_OR_OFFSET_RE =
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|([+-])(\d{2}):(\d{2}))$/;
|
||||
const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']);
|
||||
|
||||
function formatInt32ListingId(listingId: number): string {
|
||||
|
|
@ -53,29 +55,67 @@ function toUtcIsoString(value: Date | string, label: string): string {
|
|||
}
|
||||
return value.toISOString();
|
||||
}
|
||||
if (typeof value === 'string' && value.trim().length > 0) {
|
||||
const parsed = new Date(value);
|
||||
if (!Number.isNaN(parsed.getTime())) {
|
||||
return parsed.toISOString();
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim();
|
||||
const match = ISO_UTC_OR_OFFSET_RE.exec(trimmed);
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
`Invalid ${label} timestamp: expected ISO-8601 string with explicit UTC or offset timezone, received "${value}"`
|
||||
);
|
||||
}
|
||||
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
const hour = Number(match[4]);
|
||||
const minute = Number(match[5]);
|
||||
const second = Number(match[6]);
|
||||
const frac = match[7];
|
||||
const tz = match[8];
|
||||
|
||||
const baseUtcMs = Date.UTC(year, month - 1, day, hour, minute, second);
|
||||
const check = new Date(baseUtcMs);
|
||||
if (
|
||||
check.getUTCFullYear() !== year ||
|
||||
check.getUTCMonth() !== month - 1 ||
|
||||
check.getUTCDate() !== day ||
|
||||
check.getUTCHours() !== hour ||
|
||||
check.getUTCMinutes() !== minute ||
|
||||
check.getUTCSeconds() !== second
|
||||
) {
|
||||
throw new Error(`Invalid ${label} timestamp calendar date/time: "${value}"`);
|
||||
}
|
||||
|
||||
if (tz === 'Z') {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const sign = match[9] === '+' ? 1 : -1;
|
||||
const offsetHours = Number(match[10]);
|
||||
const offsetMinutes = Number(match[11]);
|
||||
if (offsetHours > 23 || offsetMinutes > 59) {
|
||||
throw new Error(`Invalid ${label} timestamp timezone offset: "${value}"`);
|
||||
}
|
||||
|
||||
const adjustedUtcMs = baseUtcMs - sign * (offsetHours * 60 + offsetMinutes) * 60_000;
|
||||
const utcDate = new Date(adjustedUtcMs);
|
||||
const isoSeconds = utcDate.toISOString().slice(0, 19);
|
||||
return frac ? `${isoSeconds}.${frac}Z` : `${isoSeconds}Z`;
|
||||
}
|
||||
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());
|
||||
function parseUtcEpochMicros(raw: unknown, field: string): bigint {
|
||||
if (typeof raw === 'bigint') {
|
||||
return raw;
|
||||
}
|
||||
if (typeof raw === 'string' || typeof raw === 'number') {
|
||||
const parsed = new Date(raw);
|
||||
if (!Number.isNaN(parsed.getTime())) {
|
||||
return parsed;
|
||||
}
|
||||
if (typeof raw === 'string' && CANONICAL_INT_RE.test(raw)) {
|
||||
return BigInt(raw);
|
||||
}
|
||||
throw new Error(`Invalid bars_1m ${field} timestamp: "${String(raw)}"`);
|
||||
if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
|
||||
return BigInt(raw);
|
||||
}
|
||||
throw new Error(`Invalid bars_1m ${field} UTC epoch microseconds: "${String(raw)}"`);
|
||||
}
|
||||
|
||||
function parseRequiredFiniteNumber(raw: unknown, field: string): number {
|
||||
|
|
@ -128,7 +168,7 @@ export async function readBars1m(
|
|||
const toIso = toUtcIsoString(to, 'to');
|
||||
|
||||
const sql =
|
||||
'SELECT listing_id, open, high, low, close, volume, vwap, session, source, known_at, ts ' +
|
||||
'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' +
|
||||
'FROM bars_1m ' +
|
||||
'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' +
|
||||
'ORDER BY ts ASC';
|
||||
|
|
@ -145,8 +185,8 @@ export async function readBars1m(
|
|||
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'),
|
||||
known_at: parseUtcEpochMicros(row.known_at_us, 'known_at'),
|
||||
ts: parseUtcEpochMicros(row.ts_us, 'ts'),
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
@ -511,9 +551,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 = $1`, [
|
||||
tableName,
|
||||
]);
|
||||
const result = await this.query('SELECT * FROM table_columns($1)', [tableName]);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -92,6 +92,7 @@ export function rebaseWhereCondition(
|
|||
if (ch === "'") {
|
||||
out += ch;
|
||||
i += 1;
|
||||
let closed = false;
|
||||
while (i < condition.length) {
|
||||
const cur = condition.charAt(i);
|
||||
out += cur;
|
||||
|
|
@ -101,10 +102,14 @@ export function rebaseWhereCondition(
|
|||
out += "'";
|
||||
i += 1;
|
||||
} else {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!closed) {
|
||||
throw new Error('Unterminated string literal in WHERE condition');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -112,6 +117,7 @@ export function rebaseWhereCondition(
|
|||
if (ch === '"') {
|
||||
out += ch;
|
||||
i += 1;
|
||||
let closed = false;
|
||||
while (i < condition.length) {
|
||||
const cur = condition.charAt(i);
|
||||
out += cur;
|
||||
|
|
@ -121,25 +127,34 @@ export function rebaseWhereCondition(
|
|||
out += '"';
|
||||
i += 1;
|
||||
} else {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!closed) {
|
||||
throw new Error('Unterminated quoted identifier in WHERE condition');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Line comment (-- ... \n)
|
||||
// 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;
|
||||
}
|
||||
|
||||
|
|
@ -147,15 +162,20 @@ export function rebaseWhereCondition(
|
|||
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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -93,7 +93,9 @@ export interface LatestByOptions {
|
|||
|
||||
/**
|
||||
* 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.
|
||||
* - `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary.
|
||||
* - `known_at` and `ts` are lossless UTC epoch microseconds (`bigint`) projected via `CAST(... AS LONG)`
|
||||
* to preserve all 6 fractional digits and avoid PGWire local-timezone `Date` coercion.
|
||||
*/
|
||||
export interface Bar1mRow {
|
||||
listing_id: number;
|
||||
|
|
@ -105,8 +107,8 @@ export interface Bar1mRow {
|
|||
vwap: number | null;
|
||||
session: string | null;
|
||||
source: string | null;
|
||||
known_at: Date;
|
||||
ts: Date;
|
||||
known_at: bigint;
|
||||
ts: bigint;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -277,6 +277,57 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
// Builder is reset again after successful execute()
|
||||
expect(() => builder.build()).toThrow('FROM clause is required');
|
||||
});
|
||||
|
||||
it('terminates trailing line comments with a newline before subsequent predicates, LATEST ON, and SAMPLE BY', async () => {
|
||||
const fake = new FakeQuestDBClient();
|
||||
const client = createClientWithFakeQuery(fake);
|
||||
|
||||
const builderResult = QuestDBQueryBuilder.create(fake)
|
||||
.select('listing_id', 'ts', 'close')
|
||||
.from('bars_1m')
|
||||
.where('session = $1 -- regular session', ['RTH'])
|
||||
.where('close > $1 -- minimum price', [100])
|
||||
.latestOn('ts', 'listing_id')
|
||||
.buildParameterized();
|
||||
|
||||
expect(builderResult.sql).toBe(
|
||||
'SELECT listing_id, ts, close FROM bars_1m ' +
|
||||
'WHERE session = $1 -- regular session\n ' +
|
||||
'AND close > $2 -- minimum price\n ' +
|
||||
'LATEST ON ts PARTITION BY listing_id'
|
||||
);
|
||||
expect(builderResult.params).toEqual(['RTH', 100]);
|
||||
|
||||
await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', {
|
||||
where: 'session = $1 -- regular session',
|
||||
params: ['RTH'],
|
||||
});
|
||||
await client.sampleBy(
|
||||
'bars_1m',
|
||||
['ts', 'close'],
|
||||
'1h',
|
||||
'ts',
|
||||
'session = $1 -- regular session',
|
||||
['RTH']
|
||||
);
|
||||
|
||||
expect(fake.calls).toEqual([
|
||||
{
|
||||
sql:
|
||||
'SELECT listing_id, ts, close FROM bars_1m ' +
|
||||
'WHERE session = $1 -- regular session\n ' +
|
||||
'LATEST ON ts PARTITION BY listing_id',
|
||||
params: ['RTH'],
|
||||
},
|
||||
{
|
||||
sql:
|
||||
'SELECT ts, close FROM bars_1m ' +
|
||||
'WHERE session = $1 -- regular session\n ' +
|
||||
'SAMPLE BY 1h ALIGN TO CALENDAR',
|
||||
params: ['RTH'],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('identifier and interval validation', () => {
|
||||
|
|
@ -337,6 +388,22 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
params: [hostileTable],
|
||||
});
|
||||
});
|
||||
|
||||
it('binds table name in QuestDBClient.getTableInfo() via table_columns($1)', async () => {
|
||||
const fake = new FakeQuestDBClient();
|
||||
const client = createClientWithFakeQuery(fake);
|
||||
fake.setRows([{ column: 'ts', type: 'TIMESTAMP' }]);
|
||||
|
||||
const rows = await client.getTableInfo('bars_1m');
|
||||
|
||||
expect(rows).toEqual([{ column: 'ts', type: 'TIMESTAMP' }]);
|
||||
expect(fake.calls).toEqual([
|
||||
{
|
||||
sql: 'SELECT * FROM table_columns($1)',
|
||||
params: ['bars_1m'],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('M2 intraday contract DDL', () => {
|
||||
|
|
@ -395,8 +462,12 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
});
|
||||
|
||||
describe('readBars1m storage reader', () => {
|
||||
it('sends one parameterized [from, to) query and converts decimal-string listing_id to INT32', async () => {
|
||||
it('sends one parameterized [from, to) query with UTC epoch-microsecond projection and converts listing_id to INT32', async () => {
|
||||
const fake = new FakeQuestDBClient();
|
||||
// 2024-01-02T14:30:00.000000Z = 1704205800000000 us
|
||||
// 2024-01-02T14:31:00.000700Z = 1704205860000700 us (6 fractional digits preserved)
|
||||
// 2024-01-02T14:31:00.000000Z = 1704205860000000 us
|
||||
// 2024-01-02T14:32:00.123456Z = 1704205920123456 us
|
||||
const fixtureRows = [
|
||||
{
|
||||
listing_id: '1042',
|
||||
|
|
@ -408,8 +479,8 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
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'),
|
||||
known_at_us: '1704205860000700',
|
||||
ts_us: '1704205800000000',
|
||||
},
|
||||
{
|
||||
listing_id: '1042',
|
||||
|
|
@ -421,8 +492,8 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
vwap: null,
|
||||
session: 'RTH',
|
||||
source: 'ib_live',
|
||||
known_at: '2024-01-02T14:32:00.000Z',
|
||||
ts: '2024-01-02T14:31:00.000Z',
|
||||
known_at_us: 1704205920123456n,
|
||||
ts_us: 1704205860000000,
|
||||
},
|
||||
];
|
||||
fake.setRows(fixtureRows);
|
||||
|
|
@ -436,7 +507,7 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
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 ' +
|
||||
'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' +
|
||||
'FROM bars_1m ' +
|
||||
'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' +
|
||||
'ORDER BY ts ASC',
|
||||
|
|
@ -455,8 +526,8 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
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'),
|
||||
known_at: 1704205860000700n,
|
||||
ts: 1704205800000000n,
|
||||
},
|
||||
{
|
||||
listing_id: 1042,
|
||||
|
|
@ -468,11 +539,72 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
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'),
|
||||
known_at: 1704205920123456n,
|
||||
ts: 1704205860000000n,
|
||||
},
|
||||
]);
|
||||
expect(typeof firstRead[0]!.listing_id).toBe('number');
|
||||
// Verify sub-millisecond ordering is preserved (14:31:00.000700Z > 14:31:00.000000Z)
|
||||
expect(firstRead[0]!.known_at > 1704205860000000n).toBe(true);
|
||||
});
|
||||
|
||||
it('preserves 6-digit microsecond bounds and produces identical results under non-UTC TZ', async () => {
|
||||
const fake = new FakeQuestDBClient();
|
||||
fake.setRows([
|
||||
{
|
||||
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_us: '1704205860000700',
|
||||
ts_us: '1704205800000000',
|
||||
},
|
||||
]);
|
||||
|
||||
const previousTz = process.env.TZ;
|
||||
try {
|
||||
process.env.TZ = 'UTC';
|
||||
const utcRows = await readBars1m(
|
||||
fake,
|
||||
1042,
|
||||
'2024-01-02T14:30:00.000000Z',
|
||||
'2024-01-02T14:31:00.000700Z'
|
||||
);
|
||||
|
||||
process.env.TZ = 'America/Toronto';
|
||||
const torontoRows = await readBars1m(
|
||||
fake,
|
||||
1042,
|
||||
'2024-01-02T14:30:00.000000Z',
|
||||
'2024-01-02T14:31:00.000700Z'
|
||||
);
|
||||
|
||||
expect(torontoRows).toEqual(utcRows);
|
||||
expect(torontoRows[0]!.known_at).toBe(1704205860000700n);
|
||||
expect(torontoRows[0]!.ts).toBe(1704205800000000n);
|
||||
expect(fake.calls[0]?.params).toEqual([
|
||||
'1042',
|
||||
'2024-01-02T14:30:00.000000Z',
|
||||
'2024-01-02T14:31:00.000700Z',
|
||||
]);
|
||||
expect(fake.calls[1]?.params).toEqual(fake.calls[0]?.params);
|
||||
} finally {
|
||||
if (previousTz === undefined) {
|
||||
delete process.env.TZ;
|
||||
} else {
|
||||
process.env.TZ = previousTz;
|
||||
}
|
||||
}
|
||||
|
||||
// Reject timezone-naive string bounds that would depend on host local timezone
|
||||
await expect(
|
||||
readBars1m(fake, 1042, '2024-01-02T14:30:00', '2024-01-02T14:35:00Z')
|
||||
).rejects.toThrow(/timezone/i);
|
||||
});
|
||||
|
||||
it('returns empty array when no bars exist in range', async () => {
|
||||
|
|
@ -515,8 +647,8 @@ describe('QuestDB 10.2.0 query layer', () => {
|
|||
vwap: 1.5,
|
||||
session: 'RTH',
|
||||
source: 'eod_unadj',
|
||||
known_at: from,
|
||||
ts: from,
|
||||
known_at_us: '1704205800000000',
|
||||
ts_us: '1704205800000000',
|
||||
},
|
||||
]);
|
||||
await expect(readBars1m(fake, 42, from, to)).rejects.toThrow(/listing_id SYMBOL/i);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue