/** * Base Adapter - Abstract interface for database adapters * * All database-specific adapters (PostgreSQL, MySQL, MongoDB, DynamoDB, MariaDB, Cassandra) * must extend this base class and implement all abstract methods. */ import { DatabaseType } from '../types/enums'; import { IAdapterConnectionOptions, IAdapterConnectionResult } from '../types/connection.interface'; import { IQueryResult, IRawQueryOptions, IRawQueryResult, IBuiltQuery } from '../types/query.interface'; import { IInsertOptions, IInsertResult, IUpdateOptions, IUpdateResult, IDeleteOptions, IDeleteResult, IUpsertOptions, IUpsertResult } from '../types/write.interface'; import { ITransactionContext, ISavepoint } from '../types/transaction.interface'; import { ICountOptions, ISumOptions, IAvgOptions, IMinMaxOptions, IAggregateResult, IGroupByResult, IBuiltAggregation } from '../types/aggregation.interface'; import { ITableDefinition, IAlterTableOperation, ITableSchema, ITableInfo, IIndexDefinition, IIndexInfo, IIndexStatistics, ICreateTableOptions } from '../types/schema.interface'; import { IsolationLevel } from '../types/enums'; /** * Abstract base class for all database adapters * * Each database type (PostgreSQL, MySQL, MongoDB, DynamoDB, MariaDB, Cassandra) * must implement all abstract methods to provide consistent behavior across * the ORM layer. */ export declare abstract class BaseAdapter { /** Database type this adapter handles */ protected abstract readonly databaseType: DatabaseType; /** Native client instance (database-specific) */ protected client: any; /** Connection state */ protected connected: boolean; /** Connection URL */ protected connectionUrl: string; /** Connection options (stored for reconnection) */ protected connectionOptions: IAdapterConnectionOptions | null; /** Maximum retry attempts for auto-reconnection */ protected maxRetries: number; /** Flag to indicate if a reconnection is in progress */ private reconnecting; /** * Execute an operation with automatic retry on connection errors. * This handles transient connection timeouts and disconnects silently. * @param operation The async operation to execute * @param retries Maximum number of retries (default: 2) * @returns The result of the operation */ protected executeWithRetry(operation: () => Promise, retries?: number): Promise; /** * Check if an error is a connection-related error that might benefit from reconnection * @param error The error to check * @returns True if the error is connection-related */ protected isConnectionError(error: any): boolean; /** * Attempt to reconnect to the database. * Subclasses should override this to implement database-specific reconnection. */ protected attemptReconnect(): Promise; /** * Get the database type this adapter handles */ getDatabaseType(): DatabaseType; /** * Check if adapter is currently connected */ isConnected(): boolean; /** * Get the native client instance */ getClient(): any; /** * Connect to the database * @param options Connection options including URL * @returns Connection result with version and other info */ abstract connect(options: IAdapterConnectionOptions): Promise; /** * Test connection without establishing persistent connection * @param options Connection options * @returns Connection test result */ abstract testConnection(options: IAdapterConnectionOptions): Promise; /** * Disconnect from the database */ abstract disconnect(): Promise; /** * Execute a built query * @param query Built query from QueryBuilder * @returns Query result with data and count */ abstract query(query: IBuiltQuery): Promise>; /** * Execute a raw query/command * @param options Raw query options * @returns Raw query result */ abstract raw(options: IRawQueryOptions): Promise>; /** * Insert one or more records * @param options Insert options * @returns Insert result with IDs and count */ abstract insert(options: IInsertOptions): Promise>; /** * Update records matching conditions * @param options Update options with where clause * @returns Update result with affected count */ abstract update(options: IUpdateOptions): Promise>; /** * Delete records matching conditions * @param options Delete options with where clause * @returns Delete result with affected count */ abstract delete(options: IDeleteOptions): Promise; /** * Insert or update based on conflict keys * @param options Upsert options * @returns Upsert result with operation type */ abstract upsert(options: IUpsertOptions): Promise>; /** * Count records matching conditions * @param options Count options * @returns Number of matching records */ abstract count(options: ICountOptions): Promise; /** * Sum values of a column * @param options Sum options * @returns Sum of column values */ abstract sum(options: ISumOptions): Promise; /** * Calculate average of a column * @param options Average options * @returns Average of column values */ abstract avg(options: IAvgOptions): Promise; /** * Get minimum value of a column * @param options Min options * @returns Minimum value */ abstract min(options: IMinMaxOptions): Promise; /** * Get maximum value of a column * @param options Max options * @returns Maximum value */ abstract max(options: IMinMaxOptions): Promise; /** * Execute multiple aggregations * @param builtAggregation Built aggregation from AggregationBuilder * @returns Aggregation results */ abstract aggregate(builtAggregation: IBuiltAggregation): Promise; /** * Group records and aggregate * @param builtGroupBy Built group by from AggregationBuilder * @returns Grouped results */ abstract groupBy(builtGroupBy: IBuiltAggregation): Promise[]>; /** * Begin a new transaction * @param isolationLevel Transaction isolation level * @param readOnly Whether transaction is read-only * @param timeout Transaction timeout in milliseconds * @returns Transaction context */ abstract beginTransaction(isolationLevel?: IsolationLevel, readOnly?: boolean, timeout?: number): Promise; /** * Commit a transaction * @param context Transaction context to commit */ abstract commitTransaction(context: ITransactionContext): Promise; /** * Rollback a transaction * @param context Transaction context to rollback */ abstract rollbackTransaction(context: ITransactionContext): Promise; /** * Create a savepoint within a transaction * @param context Transaction context * @param name Savepoint name * @returns Savepoint instance */ abstract createSavepoint(context: ITransactionContext, name: string): Promise; /** * Release a savepoint * @param context Transaction context * @param savepoint Savepoint to release */ abstract releaseSavepoint(context: ITransactionContext, savepoint: ISavepoint): Promise; /** * Rollback to a savepoint * @param context Transaction context * @param savepoint Savepoint to rollback to */ abstract rollbackToSavepoint(context: ITransactionContext, savepoint: ISavepoint): Promise; /** * Check if the database supports savepoints * @returns Whether savepoints are supported */ abstract supportsSavepoints(): boolean; /** * Create a new table * @param definition Table definition * @param options Create options */ abstract createTable(definition: ITableDefinition, options?: ICreateTableOptions): Promise; /** * Alter an existing table * @param tableName Table to alter * @param operations Alterations to perform */ abstract alterTable(tableName: string, operations: IAlterTableOperation[]): Promise; /** * Drop a table * @param tableName Table to drop * @param ifExists Only drop if exists * @param cascade Cascade to dependent objects */ abstract dropTable(tableName: string, ifExists?: boolean, cascade?: boolean): Promise; /** * List all tables in the database * @returns Array of table names */ abstract listTables(): Promise; /** * List all tables with basic information including row counts * @returns Array of table information */ abstract listTablesWithInfo(): Promise; /** * Check if a table exists * @param tableName Table name to check * @returns Whether table exists */ abstract tableExists(tableName: string): Promise; /** * Get schema information for a table * @param tableName Table to inspect * @returns Table schema information */ abstract getTableSchema(tableName: string): Promise; /** * Create an index * @param index Index definition * @param ifNotExists Only create if not exists * @param concurrent Create concurrently (PostgreSQL) */ abstract createIndex(index: IIndexDefinition, ifNotExists?: boolean, concurrent?: boolean): Promise; /** * Drop an index * @param tableName Table containing the index * @param indexName Index name to drop * @param ifExists Only drop if exists * @param concurrent Drop concurrently (PostgreSQL) * @param cascade Cascade to dependent objects */ abstract dropIndex(tableName: string, indexName: string, ifExists?: boolean, concurrent?: boolean, cascade?: boolean): Promise; /** * List all indexes on a table * @param tableName Table to list indexes for * @param includeSystem Include system indexes * @returns Array of index information */ abstract listIndexes(tableName: string, includeSystem?: boolean): Promise; /** * Get statistics for indexes * @param tableName Table name * @param indexName Optional specific index * @returns Array of index statistics */ abstract getIndexStatistics(tableName: string, indexName?: string): Promise; /** * Escape an identifier (table name, column name) for SQL * @param identifier Identifier to escape * @returns Escaped identifier */ abstract escapeIdentifier(identifier: string): string; /** * Escape a value for use in SQL * @param value Value to escape * @returns Escaped value */ abstract escapeValue(value: any): string; /** * Get the parameter placeholder for prepared statements * @param index Parameter index (1-based for PostgreSQL, 0-based for MySQL) * @returns Parameter placeholder string */ abstract getParameterPlaceholder(index: number): string; /** * Get the database-specific column type string * @param columnType Abstract column type * @param options Type options (minLength, maxLength, precision, scale, etc.) * @returns Database-specific type string */ abstract getColumnTypeString(columnType: string, options?: { minLength?: number; maxLength?: number; precision?: number; scale?: number; enumValues?: string[]; arrayType?: string; }): string; /** * Check if the database supports a specific feature * @param feature Feature name * @returns Whether the feature is supported */ supportsFeature(feature: DatabaseFeature): boolean; /** * Get list of supported features for this database * @returns Array of supported feature names */ abstract getSupportedFeatures(): DatabaseFeature[]; /** * Parse error from native database error * Maps database-specific error codes to DatabaseErrorType * @param error Native error * @returns Parsed error information */ abstract parseError(error: any): { type: string; message: string; code?: string; details?: Record; }; } /** * Database features that may or may not be supported by each adapter */ export declare enum DatabaseFeature { /** Transaction support */ TRANSACTIONS = "TRANSACTIONS", /** Savepoint support within transactions */ SAVEPOINTS = "SAVEPOINTS", /** JSONB data type (PostgreSQL) */ JSONB = "JSONB", /** JSON data type */ JSON = "JSON", /** Array data type */ ARRAYS = "ARRAYS", /** UUID data type */ UUID = "UUID", /** Full-text search */ FULLTEXT_SEARCH = "FULLTEXT_SEARCH", /** GIN index type */ GIN_INDEX = "GIN_INDEX", /** GIST index type */ GIST_INDEX = "GIST_INDEX", /** Hash index type */ HASH_INDEX = "HASH_INDEX", /** Partial/conditional indexes */ PARTIAL_INDEX = "PARTIAL_INDEX", /** Covering indexes (INCLUDE clause) */ COVERING_INDEX = "COVERING_INDEX", /** Concurrent index creation */ CONCURRENT_INDEX = "CONCURRENT_INDEX", /** Common Table Expressions (WITH clause) */ CTE = "CTE", /** Window functions */ WINDOW_FUNCTIONS = "WINDOW_FUNCTIONS", /** RETURNING clause for insert/update/delete */ RETURNING = "RETURNING", /** UPSERT / ON CONFLICT */ UPSERT = "UPSERT", /** Foreign keys */ FOREIGN_KEYS = "FOREIGN_KEYS", /** Check constraints */ CHECK_CONSTRAINTS = "CHECK_CONSTRAINTS", /** Stored procedures */ STORED_PROCEDURES = "STORED_PROCEDURES", /** Views */ VIEWS = "VIEWS", /** Materialized views */ MATERIALIZED_VIEWS = "MATERIALIZED_VIEWS", /** Triggers */ TRIGGERS = "TRIGGERS", /** Schema/namespace support */ SCHEMAS = "SCHEMAS", /** Table inheritance */ TABLE_INHERITANCE = "TABLE_INHERITANCE", /** Read replicas */ READ_REPLICAS = "READ_REPLICAS", /** Streaming replication */ STREAMING_REPLICATION = "STREAMING_REPLICATION", /** Point in time recovery */ PITR = "PITR", /** LIKE/ILIKE pattern matching */ LIKE = "LIKE", /** Case-insensitive LIKE */ ILIKE = "ILIKE", /** Regular expression matching */ REGEX = "REGEX", /** BETWEEN operator */ BETWEEN = "BETWEEN", /** Array contains operator */ ARRAY_CONTAINS = "ARRAY_CONTAINS", /** LIMIT/OFFSET pagination */ LIMIT_OFFSET = "LIMIT_OFFSET", /** Cursor-based pagination */ CURSOR_PAGINATION = "CURSOR_PAGINATION", /** Aggregation framework (MongoDB) */ AGGREGATION_PIPELINE = "AGGREGATION_PIPELINE", /** Secondary indexes */ SECONDARY_INDEXES = "SECONDARY_INDEXES", /** Global secondary indexes (DynamoDB) */ GLOBAL_SECONDARY_INDEXES = "GLOBAL_SECONDARY_INDEXES", /** Local secondary indexes (DynamoDB) */ LOCAL_SECONDARY_INDEXES = "LOCAL_SECONDARY_INDEXES", /** TTL (Time to Live) for records */ TTL = "TTL", /** Change streams / CDC */ CHANGE_STREAMS = "CHANGE_STREAMS", /** Batch operations */ BATCH_OPERATIONS = "BATCH_OPERATIONS", /** Atomic counters */ ATOMIC_COUNTERS = "ATOMIC_COUNTERS", /** Deferrable transactions (PostgreSQL) */ DEFERRABLE_TRANSACTIONS = "DEFERRABLE_TRANSACTIONS" }