#!/usr/bin/env bun /** * Opt-in CLI to initialize M2 QuestDB 10.2.0 intraday tables (`bars_1m`, * `fx_1m`, `bar_revisions`) via PGWire using `applyM2IntradayDDL()`. * * Connection env vars (checked in order): * - `QUESTDB_URL` or `RESEARCH_MCP_QUESTDB_URL` * - `QUESTDB_HOST` / `RESEARCH_MCP_QUESTDB_HOST` (default `localhost`) * - `QUESTDB_PG_PORT` / `RESEARCH_MCP_QUESTDB_PG_PORT` (default `8812`) * - `QUESTDB_DATABASE` / `RESEARCH_MCP_QUESTDB_DATABASE` (default `qdb`) * - `QUESTDB_USER` / `RESEARCH_MCP_QUESTDB_USER` * - `QUESTDB_PASSWORD` / `RESEARCH_MCP_QUESTDB_PASSWORD` * - `QUESTDB_SSL` / `RESEARCH_MCP_QUESTDB_SSL` (`true` | `false`) */ import { applyM2IntradayDDL, openQuestDbPgExecutor, type QuestDbPgExecutorConfig, } from '@stock-bot/questdb'; function readEnv(primary: string, fallback: string): string | undefined { const value = process.env[primary] ?? process.env[fallback]; if (value === undefined) { return undefined; } const trimmed = value.trim(); return trimmed.length > 0 ? trimmed : undefined; } function resolveConfig(): QuestDbPgExecutorConfig { const url = readEnv('QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL'); const sslRaw = readEnv('QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL'); const ssl = sslRaw === undefined ? undefined : sslRaw.toLowerCase() === 'true' || sslRaw === '1' ? true : sslRaw.toLowerCase() === 'false' || sslRaw === '0' ? false : undefined; if (url !== undefined) { return { url, ...(ssl !== undefined ? { ssl } : {}), }; } const host = readEnv('QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost'; const portRaw = readEnv('QUESTDB_PG_PORT', 'RESEARCH_MCP_QUESTDB_PG_PORT'); const port = portRaw !== undefined ? Number(portRaw) : 8812; if (!Number.isInteger(port) || port < 1 || port > 65535) { throw new Error(`Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.`); } const database = readEnv('QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb'; const user = readEnv('QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER'); const password = readEnv('QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD'); return { host, port, database, ...(user !== undefined ? { user } : {}), ...(password !== undefined ? { password } : {}), ...(ssl !== undefined ? { ssl } : {}), }; } async function main(): Promise { const config = resolveConfig(); const handle = await openQuestDbPgExecutor(config); try { const result = await applyM2IntradayDDL(handle.executor); process.stdout.write( `Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n` ); } finally { await handle.close(); } } main().catch((err: unknown) => { const message = err instanceof Error ? err.message : String(err); process.stderr.write(`questdb-init-m2 failed: ${message}\n`); process.exit(1); });