commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
|
|
@ -1,6 +1,20 @@
|
|||
import type { Logger } from '@stock-bot/logger';
|
||||
import type { Document, OptionalUnlessRequiredId } from 'mongodb';
|
||||
import type {
|
||||
AggregateOptions,
|
||||
BulkWriteOptions,
|
||||
CountDocumentsOptions,
|
||||
CreateCollectionOptions,
|
||||
CreateIndexesOptions,
|
||||
DeleteOptions,
|
||||
Document,
|
||||
DropIndexesOptions,
|
||||
Filter,
|
||||
FindOptions,
|
||||
IndexSpecification,
|
||||
OptionalUnlessRequiredId,
|
||||
UpdateOptions,
|
||||
} from 'mongodb';
|
||||
import { Collection, Db, MongoClient } from 'mongodb';
|
||||
import type { Logger } from '@stock-bot/logger';
|
||||
import type {
|
||||
ConnectionEvents,
|
||||
DocumentBase,
|
||||
|
|
@ -312,15 +326,18 @@ export class MongoDBClient {
|
|||
}
|
||||
}
|
||||
|
||||
this.logger.debug(`Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`, {
|
||||
database: dbName,
|
||||
collection: collectionName,
|
||||
totalRecords: documents.length,
|
||||
inserted: totalInserted,
|
||||
updated: totalUpdated,
|
||||
errors: errors.length,
|
||||
uniqueKeys: keyFields,
|
||||
});
|
||||
this.logger.debug(
|
||||
`Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`,
|
||||
{
|
||||
database: dbName,
|
||||
collection: collectionName,
|
||||
totalRecords: documents.length,
|
||||
inserted: totalInserted,
|
||||
updated: totalUpdated,
|
||||
errors: errors.length,
|
||||
uniqueKeys: keyFields,
|
||||
}
|
||||
);
|
||||
|
||||
return { insertedCount: totalInserted, updatedCount: totalUpdated, errors };
|
||||
}
|
||||
|
|
@ -366,22 +383,25 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Insert multiple documents
|
||||
*/
|
||||
async insertMany<T = any>(
|
||||
async insertMany<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
documents: T[],
|
||||
options?: any,
|
||||
options?: BulkWriteOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const now = new Date();
|
||||
|
||||
const docsWithTimestamps = documents.map(doc => ({
|
||||
...doc,
|
||||
created_at: (doc as any).created_at || now,
|
||||
created_at: doc.created_at || now,
|
||||
updated_at: now,
|
||||
}));
|
||||
|
||||
const result = await collection.insertMany(docsWithTimestamps as any, options);
|
||||
const result = await collection.insertMany(
|
||||
docsWithTimestamps as OptionalUnlessRequiredId<Document>[],
|
||||
options
|
||||
);
|
||||
return {
|
||||
insertedCount: result.insertedCount,
|
||||
insertedIds: result.insertedIds,
|
||||
|
|
@ -391,13 +411,13 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Find multiple documents
|
||||
*/
|
||||
async find<T = any>(
|
||||
async find<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
filter: any = {},
|
||||
options?: any,
|
||||
filter: Filter<Document> = {},
|
||||
options?: FindOptions,
|
||||
dbName?: string
|
||||
): Promise<T[]> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const collection = this.getCollection<T>(collectionName, dbName);
|
||||
const cursor = collection.find(filter, options);
|
||||
return (await cursor.toArray()) as T[];
|
||||
}
|
||||
|
|
@ -405,13 +425,13 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Find a single document
|
||||
*/
|
||||
async findOne<T = any>(
|
||||
async findOne<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
options?: FindOptions,
|
||||
dbName?: string
|
||||
): Promise<T | null> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const collection = this.getCollection<T>(collectionName, dbName);
|
||||
const result = await collection.findOne(filter, options);
|
||||
return result as T | null;
|
||||
}
|
||||
|
|
@ -421,11 +441,11 @@ export class MongoDBClient {
|
|||
*/
|
||||
async updateOne(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
update: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
update: Document,
|
||||
options?: UpdateOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
||||
// Add updated_at timestamp
|
||||
|
|
@ -449,11 +469,11 @@ export class MongoDBClient {
|
|||
*/
|
||||
async updateMany(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
update: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
update: Document,
|
||||
options?: UpdateOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
||||
// Add updated_at timestamp
|
||||
|
|
@ -477,10 +497,10 @@ export class MongoDBClient {
|
|||
*/
|
||||
async deleteOne(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
options?: DeleteOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const result = await collection.deleteOne(filter, options);
|
||||
return {
|
||||
|
|
@ -493,10 +513,10 @@ export class MongoDBClient {
|
|||
*/
|
||||
async deleteMany(
|
||||
collectionName: string,
|
||||
filter: any,
|
||||
options?: any,
|
||||
filter: Filter<Document>,
|
||||
options?: DeleteOptions,
|
||||
dbName?: string
|
||||
): Promise<any> {
|
||||
) {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const result = await collection.deleteMany(filter, options);
|
||||
return {
|
||||
|
|
@ -509,8 +529,8 @@ export class MongoDBClient {
|
|||
*/
|
||||
async countDocuments(
|
||||
collectionName: string,
|
||||
filter: any = {},
|
||||
options?: any,
|
||||
filter: Filter<Document> = {},
|
||||
options?: CountDocumentsOptions,
|
||||
dbName?: string
|
||||
): Promise<number> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -520,10 +540,10 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Perform aggregation operations
|
||||
*/
|
||||
async aggregate<T = any>(
|
||||
async aggregate<T extends Document = Document>(
|
||||
collectionName: string,
|
||||
pipeline: any[],
|
||||
options?: any,
|
||||
pipeline: Document[],
|
||||
options?: AggregateOptions,
|
||||
dbName?: string
|
||||
): Promise<T[]> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -536,8 +556,8 @@ export class MongoDBClient {
|
|||
*/
|
||||
async createIndex(
|
||||
collectionName: string,
|
||||
indexSpec: any,
|
||||
options?: any,
|
||||
indexSpec: IndexSpecification,
|
||||
options?: CreateIndexesOptions,
|
||||
dbName?: string
|
||||
): Promise<string> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -550,7 +570,7 @@ export class MongoDBClient {
|
|||
async dropIndex(
|
||||
collectionName: string,
|
||||
indexName: string,
|
||||
options?: any,
|
||||
options?: DropIndexesOptions,
|
||||
dbName?: string
|
||||
): Promise<void> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
|
|
@ -560,7 +580,7 @@ export class MongoDBClient {
|
|||
/**
|
||||
* List all indexes on a collection
|
||||
*/
|
||||
async listIndexes(collectionName: string, dbName?: string): Promise<any[]> {
|
||||
async listIndexes(collectionName: string, dbName?: string): Promise<Document[]> {
|
||||
const collection = this.getCollection(collectionName, dbName);
|
||||
const cursor = collection.listIndexes();
|
||||
return await cursor.toArray();
|
||||
|
|
@ -576,7 +596,11 @@ export class MongoDBClient {
|
|||
/**
|
||||
* Create a new collection
|
||||
*/
|
||||
async createCollection(collectionName: string, options?: any, dbName?: string): Promise<void> {
|
||||
async createCollection(
|
||||
collectionName: string,
|
||||
options?: CreateCollectionOptions,
|
||||
dbName?: string
|
||||
): Promise<void> {
|
||||
const db = this.getDatabase(dbName);
|
||||
await db.createCollection(collectionName, options);
|
||||
}
|
||||
|
|
@ -592,7 +616,7 @@ export class MongoDBClient {
|
|||
/**
|
||||
* List all collections in a database
|
||||
*/
|
||||
async listCollections(filter: any = {}, dbName?: string): Promise<any[]> {
|
||||
async listCollections(filter: Filter<Document> = {}, dbName?: string): Promise<Document[]> {
|
||||
const db = this.getDatabase(dbName);
|
||||
const collections = await db.listCollections(filter).toArray();
|
||||
return collections;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { beforeEach, describe, expect, it } from 'bun:test';
|
||||
import { SimpleMongoDBClient } from '../src/simple-mongodb';
|
||||
import { SimpleMongoDBClient } from './support/simple-mongodb';
|
||||
|
||||
describe('MongoDBClient', () => {
|
||||
let client: SimpleMongoDBClient;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Simple MongoDB client implementation for testing
|
||||
* Test-only in-memory MongoDB double. Never used by production adapters.
|
||||
*/
|
||||
export class SimpleMongoDBClient {
|
||||
private collections = new Map<string, any[]>();
|
||||
|
|
@ -144,7 +144,7 @@ export class SimpleMongoDBClient {
|
|||
return docs.length;
|
||||
}
|
||||
|
||||
async createIndex(collection: string, index: any, options?: any): Promise<void> {
|
||||
async createIndex(_collection: string, _index: any, _options?: any): Promise<void> {
|
||||
// No-op for simple implementation
|
||||
}
|
||||
|
||||
|
|
@ -15,7 +15,8 @@
|
|||
"dependencies": {
|
||||
"@stock-bot/logger": "*",
|
||||
"@stock-bot/types": "*",
|
||||
"pg": "^8.11.3"
|
||||
"pg": "^8.11.3",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import type { PoolConfig, QueryResultRow } from 'pg';
|
||||
import { Pool } from 'pg';
|
||||
import type { QueryResultRow } from 'pg';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import type { LoggerLike } from '@stock-bot/logger';
|
||||
import { PostgreSQLHealthMonitor } from './health';
|
||||
import { PostgreSQLQueryBuilder } from './query-builder';
|
||||
import { PostgreSQLTransactionManager } from './transactions';
|
||||
|
|
@ -23,7 +25,7 @@ export class PostgreSQLClient {
|
|||
private pool: Pool | null = null;
|
||||
private readonly config: PostgreSQLClientConfig;
|
||||
private readonly options: PostgreSQLConnectionOptions;
|
||||
private readonly logger: any;
|
||||
private readonly logger: LoggerLike;
|
||||
private readonly healthMonitor: PostgreSQLHealthMonitor;
|
||||
private readonly transactionManager: PostgreSQLTransactionManager;
|
||||
private isConnected = false;
|
||||
|
|
@ -34,7 +36,7 @@ export class PostgreSQLClient {
|
|||
|
||||
constructor(
|
||||
config: PostgreSQLClientConfig,
|
||||
logger?: any,
|
||||
logger?: LoggerLike,
|
||||
options?: PostgreSQLConnectionOptions,
|
||||
events?: ConnectionEvents
|
||||
) {
|
||||
|
|
@ -183,9 +185,9 @@ export class PostgreSQLClient {
|
|||
/**
|
||||
* Execute a query
|
||||
*/
|
||||
async query<T extends QueryResultRow = any>(
|
||||
async query<T extends QueryResultRow = QueryResultRow>(
|
||||
text: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
if (!this.pool) {
|
||||
throw new Error('PostgreSQL client not connected');
|
||||
|
|
@ -262,9 +264,9 @@ export class PostgreSQLClient {
|
|||
/**
|
||||
* Execute a stored procedure or function
|
||||
*/
|
||||
async callFunction<T extends QueryResultRow = any>(
|
||||
async callFunction<T extends QueryResultRow = QueryResultRow>(
|
||||
functionName: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
const placeholders = params ? params.map((_, i) => `$${i + 1}`).join(', ') : '';
|
||||
const query = `SELECT * FROM ${functionName}(${placeholders})`;
|
||||
|
|
@ -375,13 +377,16 @@ export class PostgreSQLClient {
|
|||
)`,
|
||||
[schemaName, tableName]
|
||||
);
|
||||
return result.rows[0].exists;
|
||||
return at(result.rows, 0).exists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get table schema information
|
||||
*/
|
||||
async getTableSchema(tableName: string, schemaName: string = 'public'): Promise<any[]> {
|
||||
async getTableSchema(
|
||||
tableName: string,
|
||||
schemaName: string = 'public'
|
||||
): Promise<QueryResultRow[]> {
|
||||
const result = await this.query(
|
||||
`SELECT
|
||||
column_name,
|
||||
|
|
@ -400,16 +405,16 @@ export class PostgreSQLClient {
|
|||
/**
|
||||
* Execute EXPLAIN for query analysis
|
||||
*/
|
||||
async explain(query: string, params?: any[]): Promise<any[]> {
|
||||
async explain(query: string, params?: unknown[]): Promise<QueryResultRow[]> {
|
||||
const explainQuery = `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query}`;
|
||||
const result = await this.query(explainQuery, params);
|
||||
return result.rows[0]['QUERY PLAN'];
|
||||
return at(result.rows, 0)['QUERY PLAN'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get database statistics
|
||||
*/
|
||||
async getStats(): Promise<any> {
|
||||
async getStats(): Promise<QueryResultRow> {
|
||||
const result = await this.query(`
|
||||
SELECT
|
||||
(SELECT count(*) FROM pg_stat_activity WHERE state = 'active') as active_connections,
|
||||
|
|
@ -417,7 +422,7 @@ export class PostgreSQLClient {
|
|||
(SELECT setting FROM pg_settings WHERE name = 'max_connections') as max_connections,
|
||||
pg_size_pretty(pg_database_size(current_database())) as database_size
|
||||
`);
|
||||
return result.rows[0];
|
||||
return result.rows[0] ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -434,7 +439,7 @@ export class PostgreSQLClient {
|
|||
return this.pool;
|
||||
}
|
||||
|
||||
private buildPoolConfig(): any {
|
||||
private buildPoolConfig(): PoolConfig {
|
||||
this.logger.debug('Building PostgreSQL pool config:', {
|
||||
host: this.config.host,
|
||||
port: this.config.port,
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@ export class PostgreSQLQueryBuilder {
|
|||
private orderByConditions: OrderByCondition[] = [];
|
||||
private limitCount: number | null = null;
|
||||
private offsetCount: number | null = null;
|
||||
private insertValues: Record<string, any> = {};
|
||||
private updateValues: Record<string, any> = {};
|
||||
private insertValues: Record<string, unknown> = {};
|
||||
private updateValues: Record<string, unknown> = {};
|
||||
|
||||
private readonly client: PostgreSQLClient;
|
||||
|
||||
|
|
@ -55,8 +55,8 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* WHERE clause
|
||||
*/
|
||||
where(column: string, operator: string, value?: any): this {
|
||||
this.whereConditions.push({ column, operator: operator as any, value });
|
||||
where(column: string, operator: WhereCondition['operator'], value?: unknown): this {
|
||||
this.whereConditions.push({ column, operator, value });
|
||||
return this;
|
||||
}
|
||||
|
||||
|
|
@ -104,7 +104,7 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* VALUES for INSERT
|
||||
*/
|
||||
values(data: Record<string, any>): this {
|
||||
values(data: Record<string, unknown>): this {
|
||||
this.insertValues = data;
|
||||
return this;
|
||||
}
|
||||
|
|
@ -121,7 +121,7 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* SET for UPDATE
|
||||
*/
|
||||
set(data: Record<string, any>): this {
|
||||
set(data: Record<string, unknown>): this {
|
||||
this.updateValues = data;
|
||||
return this;
|
||||
}
|
||||
|
|
@ -138,7 +138,7 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* Build and execute the query
|
||||
*/
|
||||
async execute<T extends QueryResultRow = any>(): Promise<QueryResult<T>> {
|
||||
async execute<T extends QueryResultRow = QueryResultRow>(): Promise<QueryResult<T>> {
|
||||
const { sql, params } = this.build();
|
||||
return await this.client.query<T>(sql, params);
|
||||
}
|
||||
|
|
@ -146,8 +146,8 @@ export class PostgreSQLQueryBuilder {
|
|||
/**
|
||||
* Build the SQL query
|
||||
*/
|
||||
build(): { sql: string; params: any[] } {
|
||||
const params: any[] = [];
|
||||
build(): { sql: string; params: unknown[] } {
|
||||
const params: unknown[] = [];
|
||||
let sql = '';
|
||||
|
||||
switch (this.queryType) {
|
||||
|
|
@ -170,7 +170,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return { sql, params };
|
||||
}
|
||||
|
||||
private buildSelectQuery(params: any[]): string {
|
||||
private buildSelectQuery(params: unknown[]): string {
|
||||
let sql = `SELECT ${this.selectColumns.join(', ')}`;
|
||||
|
||||
if (this.fromTable) {
|
||||
|
|
@ -220,7 +220,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return sql;
|
||||
}
|
||||
|
||||
private buildInsertQuery(params: any[]): string {
|
||||
private buildInsertQuery(params: unknown[]): string {
|
||||
const columns = Object.keys(this.insertValues);
|
||||
const placeholders = columns.map((_, i) => `$${params.length + i + 1}`);
|
||||
|
||||
|
|
@ -229,7 +229,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return `INSERT INTO ${this.fromTable} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`;
|
||||
}
|
||||
|
||||
private buildUpdateQuery(params: any[]): string {
|
||||
private buildUpdateQuery(params: unknown[]): string {
|
||||
const sets = Object.keys(this.updateValues).map((key, i) => {
|
||||
return `${key} = $${params.length + i + 1}`;
|
||||
});
|
||||
|
|
@ -245,7 +245,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return sql;
|
||||
}
|
||||
|
||||
private buildDeleteQuery(params: any[]): string {
|
||||
private buildDeleteQuery(params: unknown[]): string {
|
||||
let sql = `DELETE FROM ${this.fromTable}`;
|
||||
|
||||
if (this.whereConditions.length > 0) {
|
||||
|
|
@ -255,7 +255,7 @@ export class PostgreSQLQueryBuilder {
|
|||
return sql;
|
||||
}
|
||||
|
||||
private buildWhereClause(conditions: WhereCondition[], params: any[]): string {
|
||||
private buildWhereClause(conditions: WhereCondition[], params: unknown[]): string {
|
||||
return conditions
|
||||
.map(condition => {
|
||||
if (condition.operator === 'IS NULL' || condition.operator === 'IS NOT NULL') {
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ export interface PostgreSQLMetrics {
|
|||
/**
|
||||
* Query Result Types
|
||||
*/
|
||||
export interface QueryResult<T extends QueryResultRow = any> extends PgQueryResult<T> {
|
||||
export interface QueryResult<T extends QueryResultRow = QueryResultRow> extends PgQueryResult<T> {
|
||||
executionTime?: number;
|
||||
}
|
||||
|
||||
|
|
@ -182,7 +182,7 @@ export interface Strategy {
|
|||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
parameters: Record<string, any>;
|
||||
parameters: Record<string, unknown>;
|
||||
status: 'active' | 'inactive' | 'paused';
|
||||
performance_metrics: Record<string, number>;
|
||||
portfolio_id: string;
|
||||
|
|
@ -207,8 +207,8 @@ export interface AuditLog {
|
|||
action: string;
|
||||
entity_type: string;
|
||||
entity_id: string;
|
||||
old_values?: Record<string, any>;
|
||||
new_values?: Record<string, any>;
|
||||
old_values?: Record<string, unknown>;
|
||||
new_values?: Record<string, unknown>;
|
||||
user_id?: string;
|
||||
ip_address?: string;
|
||||
user_agent?: string;
|
||||
|
|
@ -233,7 +233,7 @@ export interface WhereCondition {
|
|||
| 'ILIKE'
|
||||
| 'IS NULL'
|
||||
| 'IS NOT NULL';
|
||||
value?: any;
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export interface JoinCondition {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import {
|
|||
SimplePostgresClient,
|
||||
SimpleQueryBuilder,
|
||||
SimpleTransactionManager,
|
||||
} from '../src/simple-postgres';
|
||||
} from './support/simple-postgres';
|
||||
|
||||
describe('PostgresClient', () => {
|
||||
let client: SimplePostgresClient;
|
||||
|
|
@ -195,7 +195,7 @@ describe('TransactionManager', () => {
|
|||
|
||||
it('should rollback on error', async () => {
|
||||
await expect(
|
||||
manager.transaction(async client => {
|
||||
manager.transaction(async _client => {
|
||||
throw new Error('Transaction failed');
|
||||
})
|
||||
).rejects.toThrow('Transaction failed');
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Simple PostgreSQL client for testing
|
||||
* Test-only in-memory PostgreSQL double. Never used by production adapters.
|
||||
*/
|
||||
export class SimplePostgresClient {
|
||||
private tables = new Map<string, any[]>();
|
||||
|
|
@ -7,7 +7,7 @@ export class SimplePostgresClient {
|
|||
|
||||
constructor(private config: any) {}
|
||||
|
||||
async query(sql: string, params?: any[]): Promise<{ rows: any[]; rowCount: number }> {
|
||||
async query(_sql: string, _params?: any[]): Promise<{ rows: any[]; rowCount: number }> {
|
||||
// Simple mock implementation
|
||||
return { rows: [], rowCount: 0 };
|
||||
}
|
||||
|
|
@ -119,7 +119,7 @@ export class SimpleQueryBuilder {
|
|||
|
||||
where(conditions: any): SimpleQueryBuilder {
|
||||
const whereClause = Object.entries(conditions)
|
||||
.map(([key], i) => {
|
||||
.map(([key], _i) => {
|
||||
this.params.push(conditions[key]);
|
||||
return `${key} = $${this.params.length}`;
|
||||
})
|
||||
|
|
@ -196,7 +196,7 @@ export class SimpleTransactionManager {
|
|||
|
||||
async transaction<T>(fn: (client: any) => Promise<T>): Promise<T> {
|
||||
const mockClient = {
|
||||
query: async (sql?: string) => ({ rows: [], rowCount: 0 }),
|
||||
query: async (_sql?: string) => ({ rows: [], rowCount: 0 }),
|
||||
release: () => {},
|
||||
};
|
||||
|
||||
|
|
@ -6,5 +6,15 @@
|
|||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": [{ "path": "../../core/logger" }, { "path": "../../core/types" }]
|
||||
"references": [
|
||||
{
|
||||
"path": "../../core/logger"
|
||||
},
|
||||
{
|
||||
"path": "../../core/types"
|
||||
},
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@
|
|||
"dependencies": {
|
||||
"@stock-bot/logger": "*",
|
||||
"@stock-bot/types": "*",
|
||||
"pg": "^8.11.3"
|
||||
"pg": "^8.11.3",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import type { PoolConfig, QueryResultRow } from 'pg';
|
||||
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';
|
||||
|
|
@ -20,13 +22,17 @@ export class QuestDBClient {
|
|||
private pgPool: Pool | null = null;
|
||||
private readonly config: QuestDBClientConfig;
|
||||
private readonly options: QuestDBConnectionOptions;
|
||||
private readonly logger: any;
|
||||
private readonly logger: LoggerLike;
|
||||
private readonly healthMonitor: QuestDBHealthMonitor;
|
||||
private readonly influxWriter: QuestDBInfluxWriter;
|
||||
private readonly schemaManager: QuestDBSchemaManager;
|
||||
private isConnected = false;
|
||||
|
||||
constructor(config: QuestDBClientConfig, logger?: any, options?: QuestDBConnectionOptions) {
|
||||
constructor(
|
||||
config: QuestDBClientConfig,
|
||||
logger?: LoggerLike,
|
||||
options?: QuestDBConnectionOptions
|
||||
) {
|
||||
this.config = config;
|
||||
this.logger = logger || console;
|
||||
this.options = {
|
||||
|
|
@ -128,7 +134,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Execute a SQL query
|
||||
*/
|
||||
async query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>> {
|
||||
async query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>> {
|
||||
if (!this.pgPool) {
|
||||
throw new Error('QuestDB client not connected');
|
||||
}
|
||||
|
|
@ -150,7 +156,7 @@ export class QuestDBClient {
|
|||
executionTime,
|
||||
metadata: {
|
||||
columns:
|
||||
result.fields?.map((field: any) => ({
|
||||
result.fields?.map(field => ({
|
||||
name: field.name,
|
||||
type: this.mapDataType(field.dataTypeID),
|
||||
})) || [],
|
||||
|
|
@ -227,13 +233,13 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Execute a time-series specific query with SAMPLE BY
|
||||
*/
|
||||
async sampleBy<T = any>(
|
||||
async sampleBy<T = QueryResultRow>(
|
||||
table: TableNames,
|
||||
columns: string[],
|
||||
interval: string,
|
||||
_timeColumn: string = 'timestamp',
|
||||
where?: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
const columnsStr = columns.join(', ');
|
||||
const whereClause = where ? `WHERE ${where}` : '';
|
||||
|
|
@ -252,7 +258,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Get latest values by symbol using LATEST BY
|
||||
*/
|
||||
async latestBy<T = any>(
|
||||
async latestBy<T = QueryResultRow>(
|
||||
table: TableNames,
|
||||
columns: string | string[] = '*',
|
||||
keyColumns: string | string[] = 'symbol'
|
||||
|
|
@ -272,13 +278,13 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Execute ASOF JOIN for time-series correlation
|
||||
*/
|
||||
async asofJoin<T = any>(
|
||||
async asofJoin<T = QueryResultRow>(
|
||||
leftTable: TableNames,
|
||||
rightTable: TableNames,
|
||||
joinCondition: string,
|
||||
columns?: string[],
|
||||
where?: string,
|
||||
params?: any[]
|
||||
params?: unknown[]
|
||||
): Promise<QueryResult<T>> {
|
||||
const columnsStr = columns ? columns.join(', ') : '*';
|
||||
const whereClause = where ? `WHERE ${where}` : '';
|
||||
|
|
@ -296,7 +302,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Get database statistics
|
||||
*/
|
||||
async getStats(): Promise<any> {
|
||||
async getStats(): Promise<QueryResultRow[]> {
|
||||
const result = await this.query(`
|
||||
SELECT
|
||||
table_name,
|
||||
|
|
@ -313,7 +319,7 @@ export class QuestDBClient {
|
|||
/**
|
||||
* Get table information
|
||||
*/
|
||||
async getTableInfo(tableName: string): Promise<any> {
|
||||
async getTableInfo(tableName: string): Promise<QueryResultRow[]> {
|
||||
const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [
|
||||
tableName,
|
||||
]);
|
||||
|
|
@ -412,8 +418,8 @@ export class QuestDBClient {
|
|||
return { ...this.config };
|
||||
}
|
||||
|
||||
private buildPgPoolConfig(): any {
|
||||
const config: any = {
|
||||
private buildPgPoolConfig(): PoolConfig {
|
||||
const config: PoolConfig = {
|
||||
host: this.config.host,
|
||||
port: this.config.pgPort,
|
||||
database: this.config.database,
|
||||
|
|
@ -430,7 +436,7 @@ export class QuestDBClient {
|
|||
|
||||
// Only add user/password if they are provided
|
||||
if (this.config.user) {
|
||||
this.logger.debug('Adding user to QuestDB pool config:', this.config.user);
|
||||
this.logger.debug('Adding user to QuestDB pool config', { user: this.config.user });
|
||||
config.user = this.config.user;
|
||||
} else {
|
||||
this.logger.debug('No user provided for QuestDB connection');
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { HealthStatus, PerformanceMetrics, QueryResult } from './types';
|
||||
|
||||
// Interface to avoid circular dependency
|
||||
interface QuestDBClientInterface {
|
||||
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
||||
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
|
||||
isPgPoolHealthy(): boolean;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { QueryResult, TableNames, TimeRange } from './types';
|
||||
|
||||
// Interface to avoid circular dependency
|
||||
interface QuestDBClientInterface {
|
||||
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
||||
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -190,7 +191,7 @@ export class QuestDBQueryBuilder {
|
|||
/**
|
||||
* Build and execute the query
|
||||
*/
|
||||
public async execute<T = any>(): Promise<QueryResult<T>> {
|
||||
public async execute<T = QueryResultRow>(): Promise<QueryResult<T>> {
|
||||
const sql = this.build();
|
||||
this.logger.debug('Executing query', { sql });
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { QueryResult, TableSchema } from './types';
|
||||
|
||||
// Interface to avoid circular dependency
|
||||
interface QuestDBClientInterface {
|
||||
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
||||
query<T = QueryResultRow>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -215,7 +217,7 @@ export class QuestDBSchemaManager {
|
|||
WHERE table_name = '${tableName}'
|
||||
`);
|
||||
|
||||
return result.rows.length > 0 && result.rows[0].count > 0;
|
||||
return result.rows.length > 0 && at(result.rows, 0).count > 0;
|
||||
} catch (error) {
|
||||
this.logger.error(`Error checking if table exists: ${tableName}`, error);
|
||||
return false;
|
||||
|
|
@ -266,7 +268,7 @@ export class QuestDBSchemaManager {
|
|||
/**
|
||||
* Get table statistics
|
||||
*/
|
||||
public async getTableStats(tableName: string): Promise<any> {
|
||||
public async getTableStats(tableName: string): Promise<QueryResultRow | undefined> {
|
||||
try {
|
||||
const result = await this.client.query(`
|
||||
SELECT
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
|
||||
/**
|
||||
* QuestDB Client Configuration and Types
|
||||
*/
|
||||
|
|
@ -101,7 +103,7 @@ export interface QuoteData extends BaseTimeSeriesData {
|
|||
export interface IndicatorData extends BaseTimeSeriesData {
|
||||
indicator_name: string;
|
||||
value: number;
|
||||
parameters?: Record<string, any>;
|
||||
parameters?: Record<string, unknown>;
|
||||
timeframe: string;
|
||||
}
|
||||
|
||||
|
|
@ -127,7 +129,7 @@ export interface RiskMetrics extends BaseTimeSeriesData {
|
|||
/**
|
||||
* Query Result Types
|
||||
*/
|
||||
export interface QueryResult<T = any> {
|
||||
export interface QueryResult<T = QueryResultRow> {
|
||||
rows: T[];
|
||||
rowCount: number;
|
||||
executionTime: number;
|
||||
|
|
|
|||
|
|
@ -6,5 +6,15 @@
|
|||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": [{ "path": "../../core/logger" }, { "path": "../../core/types" }]
|
||||
"references": [
|
||||
{
|
||||
"path": "../../core/logger"
|
||||
},
|
||||
{
|
||||
"path": "../../core/types"
|
||||
},
|
||||
{
|
||||
"path": "../../../libs/core/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue