@dbcube/core
Version:
347 lines (334 loc) • 11.2 kB
text/typescript
import * as sqlite3 from 'sqlite3';
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);
setArguments(): any[];
setConfig(name: string): {
[x: string]: any;
} | null;
getConfig(): any;
run(binary: string, args: []): 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 {
static get(): BinaryType;
}
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[];
}
/**
* Main class to handle SQLite database connections and queries.
* Implements the Singleton pattern to ensure a single instance of the connection.
*/
declare class SQLite {
private db;
private database?;
constructor(config: DatabaseConfig$1);
ifExist(): Boolean;
connect(): Promise<sqlite3.Database>;
disconnect(): Promise<void>;
/**
* Executes a SQL query on the currently set database.
*
* @param {string} sqlQuery - The SQL query to execute.
* @returns {Promise<QueryResult>} - Returns a JSON object with the status, message, and data (if any).
*
* @example
* const result = await db.query('SELECT * FROM users;');
* console.log(result);
* // { status: 'success', message: 'Query executed successfully', data: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] }
*
* @example
* const result = await db.query('INVALID SQL QUERY;');
* console.log(result);
* // { status: 'error', message: 'SQL syntax error', data: null }
*/
query(sqlQuery: string): Promise<QueryResult>;
/**
* Executes a SQL query with parameters on the currently set database.
*
* @param {string} sqlQuery - The SQL query to execute with placeholders (?).
* @param {any[]} params - Array of parameters to bind to the query placeholders.
* @returns {Promise<QueryResult>} - Returns a JSON object with the status, message, and data (if any).
*
* @example
* const result = await db.queryWithParameters('INSERT INTO users (name, email) VALUES (?, ?)', ['John', 'john@example.com']);
* console.log(result);
* // { status: 'success', message: 'Query executed successfully', data: { changes: 1, lastID: 3 } }
*/
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, TableProcessor, TriggerProcessor };