UNPKG

@dbcube/core

Version:
382 lines (367 loc) 11.6 kB
import { EventEmitter } from 'events'; interface ResponseEngine { status: number; message: String; data: any; } declare class Engine { private name; private config; private arguments; private binary; private timeout; constructor(name: string, timeout?: number); initializeBinary(): Promise<void>; setArguments(): any[]; setConfig(name: string): { [x: string]: any; } | null; getConfig(): any; run(binary: string, args: []): Promise<ResponseEngine>; } declare class QueryEngine { private name; private config; private arguments; private binary; private timeout; private connectionId; private tcpPort; constructor(name: string, timeout?: number); private generatePort; private findAvailablePort; private isPortAvailable; initializeBinary(): Promise<void>; setArguments(): any[]; setConfig(name: string): { [x: string]: any; } | null; getConfig(): any; run(binary: string, args: string[]): Promise<ResponseEngine>; private executeWithTcpServer; private waitForServerReady; private isServerResponding; private sleep; private getCachedDML; private startTcpServer; private sendTcpRequest; private sendTcpRequestFast; private sendOnExistingConnection; private createPersistentConnection; private createProcess; disconnect(): Promise<ResponseEngine>; } interface SystemInfo { platform: string; arch: string; release: string; type: string; endianness: string; cpus: number; } declare class Arquitecture { private systemInfo; constructor(); /** * Detecta información completa del sistema */ private detectSystemInfo; /** * Obtiene la plataforma normalizada */ getPlatform(): string; /** * Obtiene la arquitectura normalizada */ getArchitecture(): string; /** * Genera el nombre del binario basado en la arquitectura */ getBinaryName(baseName: string): string; /** * Obtiene información completa del sistema */ getSystemInfo(): SystemInfo; /** * Obtiene el triple de destino (target triple) para Rust */ getRustTargetTriple(): string; /** * Muestra información detallada del sistema */ printSystemInfo(): void; } interface BinaryType { query_engine: string; schema_engine: string; } declare class Binary { private static isDownloading; private static downloadPromise; static ensureBinariesExist(): Promise<void>; private static downloadBinaries; private static getBinDir; static get(): Promise<BinaryType>; } interface SqliteResult { status: 'success' | 'error'; message: string; data: any | null; } interface RunResult { changes: number; lastID: number; } declare class SqliteExecutor { private binaryPath; private dbPath; constructor(dbPath: string); private getBinaryPath; private executeBinary; connect(): Promise<boolean>; exists(): Promise<boolean>; query(sql: string, params?: any[]): Promise<SqliteResult>; queryMultiple(sql: string): Promise<SqliteResult>; prepare(sql: string): { all: (...params: any[]) => Promise<any[]>; run: (...params: any[]) => Promise<RunResult>; }; prepareSync(sql: string): { all: (...params: any[]) => any; run: (...params: any[]) => any; }; } interface DatabaseConfig$1 { name?: string; HOST?: string; USER?: string; PASSWORD?: string; DATABASE?: string; PORT?: number; } interface QueryResult { status: 'success' | 'error'; message: string; data: any | null; } interface ParametrizedQueryResult { query: string; parameters: any[]; } declare class SQLite { private executor; private database?; constructor(config: DatabaseConfig$1); ifExist(): Promise<Boolean>; connect(): Promise<SqliteExecutor>; disconnect(): Promise<void>; query(sqlQuery: string): Promise<QueryResult>; queryWithParameters(sqlQuery: string, params?: any[]): Promise<QueryResult>; convertToParameterizedQuery(sql: string): ParametrizedQueryResult; } declare const DbConfig: SQLite; /** * Tipo para la configuración de una base de datos */ type DatabaseConfig = Record<string, any>; /** * Tipo para la configuración general del ORM */ interface ConfigData { [key: string]: any; databases?: Record<string, DatabaseConfig>; } /** * Clase para manejar la configuración del ORM */ declare class Config { private data; private databases; /** * Establece la configuración * @param configData - Datos de configuración */ set(configData: ConfigData): void; /** * Obtiene un valor de configuración * @param key - Clave de configuración * @returns Valor de configuración */ get<T = any>(key: string): T; /** * Obtiene la configuración de una base de datos específica * @param dbName - Nombre de la base de datos * @returns Configuración de la base de datos o null */ getDatabase(dbName: string): DatabaseConfig | null; /** * Obtiene todas las bases de datos configuradas * @returns Todas las configuraciones de bases de datos */ getAllDatabases(): Record<string, DatabaseConfig>; } interface InterceptOptions { interceptLog?: boolean; interceptError?: boolean; interceptWarn?: boolean; keepOriginal?: boolean; useBuffer?: boolean; } interface ReadOptions { lines?: number | null; fromEnd?: boolean; asArray?: boolean; } interface WatchOptions { persistent?: boolean; interval?: number; fromEnd?: boolean; } interface WatchController { id: string; stop: () => void; isWatching: () => boolean; } interface InterceptController { restore: () => void; commit: () => Promise<boolean>; discard: () => number; hasBuffer: () => boolean; getBufferSize: () => number; } interface DeleteResult { filePath: string; deleted: boolean; error: string | null; } type LogLevel = 'INFO' | 'ERROR' | 'WARN' | 'DEBUG'; declare class FileLogger extends EventEmitter { private static watchers; private static buffers; /** * Escribe un log en el archivo especificado * @param filePath - Ruta del archivo de log * @param message - Mensaje a escribir * @param level - Nivel del log (INFO, ERROR, WARN, DEBUG) * @param append - Si debe agregar al final del archivo (default: true) */ static write(filePath: string, message: string, level?: LogLevel, append?: boolean): Promise<boolean>; /** * Inicia un buffer temporal para un archivo de log * @param filePath - Ruta del archivo de log */ static startBuffer(filePath: string): void; /** * Confirma y escribe todos los logs del buffer al archivo * @param filePath - Ruta del archivo de log */ static commitBuffer(filePath: string): Promise<boolean>; /** * Descarta todos los logs del buffer sin escribirlos * @param filePath - Ruta del archivo de log */ static discardBuffer(filePath: string): number; /** * Verifica si existe un buffer activo para un archivo * @param filePath - Ruta del archivo de log */ static hasBuffer(filePath: string): boolean; /** * Obtiene el número de logs en el buffer * @param filePath - Ruta del archivo de log */ static getBufferSize(filePath: string): number; /** * Intercepta console.log y console.error para escribir a archivo * @param filePath - Ruta del archivo de log * @param options - Opciones de interceptación */ static interceptConsole(filePath: string, options?: InterceptOptions): InterceptController; /** * Lee el contenido completo del archivo de log * @param filePath - Ruta del archivo de log * @param options - Opciones de lectura * @returns Contenido del archivo */ static read(filePath: string, options?: ReadOptions): Promise<string | string[]>; /** * Observa un archivo de log en tiempo real * @param filePath - Ruta del archivo de log * @param callback - Función callback para nuevas líneas * @param options - Opciones del watcher * @returns Objeto con métodos para controlar el watcher */ static watch(filePath: string, callback: (line: string, filePath: string) => void, options?: WatchOptions): WatchController; /** * Detiene todos los watchers activos */ static stopAllWatchers(): void; /** * Métodos de conveniencia para diferentes niveles de log */ static info(filePath: string, message: string): Promise<boolean>; static error(filePath: string, message: string): Promise<boolean>; static warn(filePath: string, message: string): Promise<boolean>; static debug(filePath: string, message: string): Promise<boolean>; /** * Limpia logs antiguos * @param filePath - Ruta del archivo de log * @param maxLines - Máximo número de líneas a mantener */ static cleanup(filePath: string, maxLines?: number): Promise<number>; /** * Elimina un archivo de log * @param filePath - Ruta del archivo de log a eliminar */ static deleteLogFile(filePath: string): Promise<boolean>; /** * Elimina múltiples archivos de log * @param filePaths - Array de rutas de archivos de log a eliminar */ static deleteLogFiles(filePaths: string[]): Promise<DeleteResult[]>; } interface DataObject { [key: string]: any; } interface ComputedFieldConfig { id: number; table_ref: string; column: string; type: 'string' | 'number' | 'boolean' | 'date' | 'object'; instruction: string; database_ref: string; created_at: string; updated_at: string; } type DatabaseType = 'mysql' | 'sqlite' | 'postgres' | 'mongodb'; declare class ComputedFieldProcessor { static getComputedFields(name: string): Promise<any[]>; /** * Processes computed field instruction and returns the computed value * @param instruction - The @compute instruction * @param rowData - The row data containing column values * @returns The computed value or null if there's an error */ static processInstruction(instruction: string, rowData: Record<string, any>): any; /** * Extracts column dependencies from a computed field instruction * @param instruction - The @compute instruction * @returns Array of column names that this computed field depends on */ static extractDependencies(instruction: string): string[]; /** * Adds computed fields to an array of data objects based on configuration array * @param data - Array of data objects * @param computedConfigs - Array of computed field configurations * @returns Array with the new computed fields added */ static computedFields<T extends DataObject>(data: T[], computedConfigs: ComputedFieldConfig[]): T[]; } declare class TableProcessor { static generateAlterQueries(nowQuery: string, dbType: DatabaseType, tableName: string, database_ref: string): Promise<string[]>; static saveQuery(table_ref: string, database_ref: string, struct: string): Promise<void>; } declare class TriggerProcessor { static getTriggers(name: string): Promise<any[]>; } export { Arquitecture, Binary, ComputedFieldProcessor, Config, DbConfig, Engine, FileLogger, type InterceptController, QueryEngine, TableProcessor, TriggerProcessor };