UNPKG

@ordojs/core

Version:

Core compiler and runtime for OrdoJS framework

505 lines 11.8 kB
/** * @fileoverview OrdoJS Database Manager - Comprehensive database integration */ /** * Database configuration */ export interface DatabaseConfig { /** Database type */ type: 'postgresql' | 'mysql' | 'sqlite' | 'mongodb' | 'redis'; /** Connection string or configuration */ connectionString?: string; /** Host */ host?: string; /** Port */ port?: number; /** Database name */ database?: string; /** Username */ username?: string; /** Password */ password?: string; /** Connection pool size */ poolSize: number; /** Connection timeout in milliseconds */ connectionTimeout: number; /** Query timeout in milliseconds */ queryTimeout: number; /** Whether to enable SSL */ enableSSL: boolean; /** Whether to enable connection pooling */ enablePooling: boolean; /** Whether to enable query logging */ enableQueryLogging: boolean; /** Whether to enable migrations */ enableMigrations: boolean; /** Migration directory */ migrationDir: string; /** Whether to enable caching */ enableCaching: boolean; /** Cache TTL in seconds */ cacheTTL: number; /** Whether to enable real-time features */ enableRealtime: boolean; /** WebSocket configuration */ websocketConfig?: WebSocketConfig; } /** * WebSocket configuration for real-time features */ export interface WebSocketConfig { /** WebSocket server URL */ url: string; /** Authentication token */ authToken?: string; /** Reconnection settings */ reconnectInterval: number; /** Max reconnection attempts */ maxReconnectAttempts: number; } /** * Database connection status */ export interface ConnectionStatus { /** Whether connected */ connected: boolean; /** Connection error if any */ error?: string; /** Connection pool status */ poolStatus: PoolStatus; /** Last connection time */ lastConnected?: Date; /** Connection duration */ connectionDuration?: number; } /** * Connection pool status */ export interface PoolStatus { /** Total connections */ total: number; /** Active connections */ active: number; /** Idle connections */ idle: number; /** Waiting connections */ waiting: number; } /** * Query result */ export interface QueryResult<T = any> { /** Query success */ success: boolean; /** Result data */ data?: T; /** Error message */ error?: string; /** Affected rows */ affectedRows?: number; /** Insert ID */ insertId?: number; /** Query execution time */ executionTime?: number; /** Query metadata */ metadata?: QueryMetadata; } /** * Query metadata */ export interface QueryMetadata { /** Query type */ type: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'CREATE' | 'DROP' | 'ALTER'; /** Table name */ table?: string; /** Column count */ columnCount?: number; /** Row count */ rowCount?: number; /** Index usage */ indexUsage?: string[]; } /** * Migration result */ export interface MigrationResult { /** Migration success */ success: boolean; /** Migration name */ name: string; /** Applied migrations */ applied: string[]; /** Rolled back migrations */ rolledBack: string[]; /** Error message */ error?: string; /** Execution time */ executionTime?: number; } /** * Cache result */ export interface CacheResult<T = any> { /** Cache hit */ hit: boolean; /** Cached data */ data?: T; /** Cache key */ key: string; /** TTL remaining */ ttl?: number; /** Error message */ error?: string; } /** * Real-time subscription */ export interface RealtimeSubscription { /** Subscription ID */ id: string; /** Channel name */ channel: string; /** Event type */ event: string; /** Callback function */ callback: (data: any) => void; /** Active status */ active: boolean; /** Created time */ createdAt: Date; } /** * Model definition */ export interface ModelDefinition { /** Model name */ name: string; /** Table name */ table: string; /** Fields */ fields: FieldDefinition[]; /** Indexes */ indexes: IndexDefinition[]; /** Relationships */ relationships: RelationshipDefinition[]; /** Validation rules */ validation: ValidationRule[]; /** Hooks */ hooks: HookDefinition[]; } /** * Field definition */ export interface FieldDefinition { /** Field name */ name: string; /** Field type */ type: 'string' | 'number' | 'boolean' | 'date' | 'json' | 'text' | 'binary'; /** Field constraints */ constraints: FieldConstraint[]; /** Default value */ defaultValue?: any; /** Whether field is required */ required: boolean; /** Whether field is unique */ unique: boolean; /** Field length */ length?: number; /** Field precision */ precision?: number; /** Field scale */ scale?: number; } /** * Field constraint */ export interface FieldConstraint { /** Constraint type */ type: 'PRIMARY_KEY' | 'FOREIGN_KEY' | 'NOT_NULL' | 'UNIQUE' | 'CHECK' | 'DEFAULT'; /** Constraint value */ value?: any; /** Referenced table */ referencedTable?: string; /** Referenced column */ referencedColumn?: string; } /** * Index definition */ export interface IndexDefinition { /** Index name */ name: string; /** Index type */ type: 'PRIMARY' | 'UNIQUE' | 'INDEX' | 'FULLTEXT'; /** Index columns */ columns: string[]; /** Index options */ options?: Record<string, any>; } /** * Relationship definition */ export interface RelationshipDefinition { /** Relationship name */ name: string; /** Relationship type */ type: 'ONE_TO_ONE' | 'ONE_TO_MANY' | 'MANY_TO_ONE' | 'MANY_TO_MANY'; /** Related model */ relatedModel: string; /** Foreign key */ foreignKey: string; /** Local key */ localKey: string; /** Cascade options */ cascade?: 'CASCADE' | 'SET_NULL' | 'RESTRICT'; } /** * Validation rule */ export interface ValidationRule { /** Rule name */ name: string; /** Rule type */ type: 'REQUIRED' | 'MIN_LENGTH' | 'MAX_LENGTH' | 'PATTERN' | 'RANGE' | 'CUSTOM'; /** Rule value */ value?: any; /** Error message */ message: string; } /** * Hook definition */ export interface HookDefinition { /** Hook name */ name: string; /** Hook type */ type: 'BEFORE_CREATE' | 'AFTER_CREATE' | 'BEFORE_UPDATE' | 'AFTER_UPDATE' | 'BEFORE_DELETE' | 'AFTER_DELETE'; /** Hook function */ handler: (data: any) => Promise<void>; } /** * Comprehensive database manager for OrdoJS applications */ export declare class DatabaseManager { private config; private connection; private pool; private models; private cache; private subscriptions; private websocket; private queryLog; private migrations; constructor(config?: Partial<DatabaseConfig>); /** * Connect to database */ connect(): Promise<ConnectionStatus>; /** * Disconnect from database */ disconnect(): Promise<void>; /** * Execute query */ query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>; /** * Execute transaction */ transaction<T = any>(callback: (transaction: DatabaseManager) => Promise<T>): Promise<QueryResult<T>>; /** * Define model */ defineModel(definition: ModelDefinition): void; /** * Create model instance */ createModel<T = any>(modelName: string): Model<T>; /** * Run migrations */ runMigrations(): Promise<MigrationResult>; /** * Rollback migrations */ rollbackMigrations(count?: number): Promise<MigrationResult>; /** * Cache data */ cacheSet<T = any>(key: string, data: T, ttl?: number): Promise<void>; /** * Get cached data */ cacheGet<T = any>(key: string): Promise<CacheResult<T>>; /** * Delete cached data */ cacheDelete(key: string): Promise<void>; /** * Clear all cached data */ cacheClear(): Promise<void>; /** * Subscribe to real-time updates */ subscribe(channel: string, event: string, callback: (data: any) => void): Promise<string>; /** * Unsubscribe from real-time updates */ unsubscribe(subscriptionId: string): Promise<void>; /** * Publish real-time update */ publish(channel: string, event: string, data: any): Promise<void>; /** * Get connection status */ getConnectionStatus(): ConnectionStatus; /** * Get query log */ getQueryLog(): Array<{ query: string; params: any[]; executionTime: number; timestamp: Date; }>; /** * Clear query log */ clearQueryLog(): void; /** * Get all models */ getModels(): ModelDefinition[]; /** * Get all subscriptions */ getSubscriptions(): RealtimeSubscription[]; /** * Create connection pool */ private createConnectionPool; /** * Create single connection */ private createSingleConnection; /** * Execute query */ private executeQuery; /** * Begin transaction */ private beginTransaction; /** * Commit transaction */ private commitTransaction; /** * Get pool status */ private getPoolStatus; /** * Log query */ private logQuery; /** * Extract query metadata */ private extractQueryMetadata; /** * Initialize migrations */ private initializeMigrations; /** * Create migrations table */ private createMigrationsTable; /** * Get applied migrations */ private getAppliedMigrations; /** * Execute migration */ private executeMigration; /** * Record migration */ private recordMigration; /** * Remove migration */ private removeMigration; /** * Initialize real-time features */ private initializeRealtime; /** * Handle real-time message */ private handleRealtimeMessage; } /** * Model class for ORM functionality */ export declare class Model<T = any> { private db; private definition; constructor(db: DatabaseManager, definition: ModelDefinition); /** * Find all records */ findAll(options?: QueryOptions): Promise<QueryResult<T[]>>; /** * Find record by ID */ findById(id: any, options?: QueryOptions): Promise<QueryResult<T>>; /** * Find one record */ findOne(options?: QueryOptions): Promise<QueryResult<T>>; /** * Create record */ create(data: Partial<T>): Promise<QueryResult<T>>; /** * Update record */ update(id: any, data: Partial<T>): Promise<QueryResult<T>>; /** * Delete record */ delete(id: any): Promise<QueryResult>; /** * Count records */ count(options?: QueryOptions): Promise<QueryResult<number>>; /** * Build SELECT query */ private buildSelectQuery; /** * Build COUNT query */ private buildCountQuery; } /** * Query options */ export interface QueryOptions { /** Select fields */ select?: string; /** Where conditions */ where?: Record<string, any>; /** Order by clause */ orderBy?: string; /** Limit */ limit?: number; /** Offset */ offset?: number; /** Query parameters */ params?: any[]; } //# sourceMappingURL=database-manager.d.ts.map