commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
|
|
@ -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') {
|
||||
|
|
|
|||
|
|
@ -1,215 +0,0 @@
|
|||
/**
|
||||
* Simple PostgreSQL client for testing
|
||||
*/
|
||||
export class SimplePostgresClient {
|
||||
private tables = new Map<string, any[]>();
|
||||
private connected = false;
|
||||
|
||||
constructor(private config: any) {}
|
||||
|
||||
async query(sql: string, params?: any[]): Promise<{ rows: any[]; rowCount: number }> {
|
||||
// Simple mock implementation
|
||||
return { rows: [], rowCount: 0 };
|
||||
}
|
||||
|
||||
async findOne(table: string, where: any): Promise<any | null> {
|
||||
const rows = this.tables.get(table) || [];
|
||||
for (const row of rows) {
|
||||
let match = true;
|
||||
for (const [key, value] of Object.entries(where)) {
|
||||
if (row[key] !== value) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
return row;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async find(table: string, where: any): Promise<any[]> {
|
||||
const rows = this.tables.get(table) || [];
|
||||
if (Object.keys(where).length === 0) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
return rows.filter(row => {
|
||||
for (const [key, value] of Object.entries(where)) {
|
||||
if (row[key] !== value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
async insert(table: string, data: any): Promise<any> {
|
||||
const rows = this.tables.get(table) || [];
|
||||
const newRow = { ...data, id: rows.length + 1 };
|
||||
rows.push(newRow);
|
||||
this.tables.set(table, rows);
|
||||
return newRow;
|
||||
}
|
||||
|
||||
async update(table: string, where: any, data: any): Promise<number> {
|
||||
const rows = this.tables.get(table) || [];
|
||||
let updated = 0;
|
||||
|
||||
for (const row of rows) {
|
||||
let match = true;
|
||||
for (const [key, value] of Object.entries(where)) {
|
||||
if (row[key] !== value) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
Object.assign(row, data);
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
async delete(table: string, where: any): Promise<number> {
|
||||
const rows = this.tables.get(table) || [];
|
||||
const remaining = rows.filter(row => {
|
||||
for (const [key, value] of Object.entries(where)) {
|
||||
if (row[key] !== value) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
const deleted = rows.length - remaining.length;
|
||||
this.tables.set(table, remaining);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
async healthCheck(): Promise<{ status: string; isConnected: boolean; error?: string }> {
|
||||
return {
|
||||
status: 'healthy',
|
||||
isConnected: true,
|
||||
};
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.connected = false;
|
||||
}
|
||||
}
|
||||
|
||||
export class SimpleQueryBuilder {
|
||||
private parts: string[] = [];
|
||||
private params: any[] = [];
|
||||
|
||||
select(columns: string[] | string = '*'): SimpleQueryBuilder {
|
||||
const cols = Array.isArray(columns) ? columns.join(', ') : columns;
|
||||
this.parts.push(`SELECT ${cols}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
from(table: string): SimpleQueryBuilder {
|
||||
this.parts.push(`FROM ${table}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
where(conditions: any): SimpleQueryBuilder {
|
||||
const whereClause = Object.entries(conditions)
|
||||
.map(([key], i) => {
|
||||
this.params.push(conditions[key]);
|
||||
return `${key} = $${this.params.length}`;
|
||||
})
|
||||
.join(' AND ');
|
||||
|
||||
this.parts.push(`WHERE ${whereClause}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
orderBy(column: string, direction = 'ASC'): SimpleQueryBuilder {
|
||||
this.parts.push(`ORDER BY ${column} ${direction}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
limit(count: number): SimpleQueryBuilder {
|
||||
this.parts.push(`LIMIT ${count}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
insert(table: string, data: any): SimpleQueryBuilder {
|
||||
const columns = Object.keys(data);
|
||||
const values = Object.values(data);
|
||||
this.params.push(...values);
|
||||
|
||||
const placeholders = columns.map((_, i) => `$${i + 1}`);
|
||||
this.parts.push(
|
||||
`INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`
|
||||
);
|
||||
return this;
|
||||
}
|
||||
|
||||
update(table: string): SimpleQueryBuilder {
|
||||
this.parts.push(`UPDATE ${table}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
set(data: any): SimpleQueryBuilder {
|
||||
const setClause = Object.entries(data)
|
||||
.map(([key, value]) => {
|
||||
this.params.push(value);
|
||||
return `${key} = $${this.params.length}`;
|
||||
})
|
||||
.join(', ');
|
||||
|
||||
this.parts.push(`SET ${setClause}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
delete(table: string): SimpleQueryBuilder {
|
||||
this.parts.push(`DELETE FROM ${table}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
returning(columns: string): SimpleQueryBuilder {
|
||||
this.parts.push(`RETURNING ${columns}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
join(table: string, condition: string): SimpleQueryBuilder {
|
||||
this.parts.push(`JOIN ${table} ON ${condition}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
build(): { text: string; values: any[] } {
|
||||
return {
|
||||
text: this.parts.join(' '),
|
||||
values: this.params,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class SimpleTransactionManager {
|
||||
constructor(private pool: any) {}
|
||||
|
||||
async transaction<T>(fn: (client: any) => Promise<T>): Promise<T> {
|
||||
const mockClient = {
|
||||
query: async (sql?: string) => ({ rows: [], rowCount: 0 }),
|
||||
release: () => {},
|
||||
};
|
||||
|
||||
await mockClient.query('BEGIN');
|
||||
try {
|
||||
const result = await fn(mockClient);
|
||||
await mockClient.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await mockClient.query('ROLLBACK');
|
||||
throw error;
|
||||
} finally {
|
||||
mockClient.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue