import { EventEmitter } from 'events'; /** * Type definitions for ZeroDB CRUD operations * * Provides comprehensive type safety for database operations including * CRUD operations, query building, transactions, and connection management. */ /** * ZeroDB connection configuration */ interface ZeroDBConfig { /** ZeroDB project ID */ projectId: string; /** API key for authentication */ apiKey: string; /** Base URL for ZeroDB API (optional, defaults to production URL) */ baseUrl?: string; /** Connection pool configuration */ pool?: PoolConfig; /** Retry configuration for failed requests */ retry?: RetryConfig; /** Request timeout in milliseconds */ timeout?: number; /** Enable debug logging */ debug?: boolean; } /** * Connection pool configuration */ interface PoolConfig { /** Minimum number of connections to maintain */ min?: number; /** Maximum number of connections */ max?: number; /** Idle timeout in milliseconds */ idleTimeout?: number; /** Connection acquisition timeout in milliseconds */ acquireTimeout?: number; /** Enable connection validation */ validate?: boolean; } /** * Retry configuration */ interface RetryConfig { /** Maximum number of retry attempts */ maxRetries?: number; /** Initial retry delay in milliseconds */ initialDelay?: number; /** Maximum retry delay in milliseconds */ maxDelay?: number; /** Backoff multiplier */ backoffMultiplier?: number; /** Retry on these error codes */ retryableErrors?: string[]; } /** * Query filter operators */ type FilterOperator = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'nin' | 'like' | 'ilike' | 'is' | 'contains' | 'overlap'; /** * Query filter condition */ interface FilterCondition { field: string; operator: FilterOperator; value: any; } /** * Complex filter with logical operators */ interface Filter { and?: Filter[]; or?: Filter[]; not?: Filter; condition?: FilterCondition; } /** * Sort direction */ type SortDirection = 'asc' | 'desc'; /** * Sort specification */ interface SortSpec { field: string; direction: SortDirection; } /** * Pagination options */ interface PaginationOptions { /** Number of records to return */ limit?: number; /** Number of records to skip */ offset?: number; /** Cursor for cursor-based pagination */ cursor?: string; } /** * Query options */ interface QueryOptions extends PaginationOptions { /** Fields to select (if not specified, returns all) */ select?: string[]; /** Filter conditions */ filter?: Filter; /** Sort specifications */ sort?: SortSpec[]; /** Include total count in response */ count?: boolean; /** Join other tables */ joins?: JoinSpec[]; } /** * Join specification */ interface JoinSpec { /** Table to join */ table: string; /** Join type */ type?: 'inner' | 'left' | 'right' | 'full'; /** Join condition */ on: { left: string; right: string; }; /** Alias for joined table */ alias?: string; } /** * Aggregation function */ type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max'; /** * Aggregation specification */ interface AggregateSpec { function: AggregateFunction; field?: string; alias?: string; } /** * Group by options */ interface GroupByOptions { /** Fields to group by */ fields: string[]; /** Aggregations to compute */ aggregates: AggregateSpec[]; /** Filter on groups (HAVING clause) */ having?: Filter; } /** * Insert options */ interface InsertOptions { /** Return inserted records */ returning?: boolean; /** On conflict action */ onConflict?: { /** Conflict target fields */ target: string[]; /** Action: 'ignore' or 'update' */ action: 'ignore' | 'update'; /** Fields to update on conflict (if action is 'update') */ updateFields?: string[]; }; } /** * Update options */ interface UpdateOptions { /** Return updated records */ returning?: boolean; /** Filter for records to update */ filter?: Filter; } /** * Delete options */ interface DeleteOptions { /** Return deleted records */ returning?: boolean; /** Filter for records to delete */ filter?: Filter; } /** * Transaction options */ interface TransactionOptions { /** Transaction isolation level */ isolationLevel?: 'read_uncommitted' | 'read_committed' | 'repeatable_read' | 'serializable'; /** Read-only transaction */ readOnly?: boolean; /** Transaction timeout in milliseconds */ timeout?: number; } /** * Batch operation type */ type BatchOperationType = 'insert' | 'update' | 'delete'; /** * Batch operation */ interface BatchOperation { type: BatchOperationType; table: string; data?: Record | Record[]; filter?: Filter; options?: InsertOptions | UpdateOptions | DeleteOptions; } /** * Query result */ interface QueryResult { /** Result rows */ rows: T[]; /** Total count (if requested) */ count?: number; /** Next cursor for pagination */ nextCursor?: string; /** Execution metadata */ metadata?: { executionTime: number; rowsScanned: number; }; } /** * CRUD result */ interface CRUDResult { /** Success status */ success: boolean; /** Number of rows affected */ rowsAffected: number; /** Returned rows (if requested) */ rows?: T[]; /** Error message (if failed) */ error?: string; } /** * Transaction result */ interface TransactionResult { /** Success status */ success: boolean; /** Number of operations executed */ operationsExecuted: number; /** Total rows affected */ totalRowsAffected: number; /** Error message (if failed) */ error?: string; } /** * Connection health status */ interface HealthStatus { /** Connection status */ connected: boolean; /** Response time in milliseconds */ responseTime?: number; /** Error message (if unhealthy) */ error?: string; /** Pool statistics */ pool?: PoolStats; } /** * Connection pool statistics */ interface PoolStats { /** Total connections */ total: number; /** Active connections */ active: number; /** Idle connections */ idle: number; /** Waiting requests */ waiting: number; } /** * Query builder interface */ interface IQueryBuilder { /** Select specific fields */ select(...fields: string[]): IQueryBuilder; /** Add WHERE condition */ where(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** Add AND condition */ and(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** Add OR condition */ or(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** Add NOT condition */ not(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** Add ORDER BY */ orderBy(field: string, direction?: SortDirection): IQueryBuilder; /** Add LIMIT */ limit(limit: number): IQueryBuilder; /** Add OFFSET */ offset(offset: number): IQueryBuilder; /** Add JOIN */ join(table: string, on: { left: string; right: string; }, type?: 'inner' | 'left' | 'right' | 'full'): IQueryBuilder; /** Add GROUP BY */ groupBy(...fields: string[]): IQueryBuilder; /** Add HAVING */ having(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** Execute query */ execute(): Promise>; /** Get first result */ first(): Promise; /** Get all results */ all(): Promise; /** Count results */ count(): Promise; } /** * Table schema definition */ interface TableSchema { /** Table name */ name: string; /** Columns */ columns: ColumnDefinition[]; /** Primary key */ primaryKey?: string[]; /** Indexes */ indexes?: IndexDefinition[]; /** Unique constraints */ uniqueConstraints?: string[][]; } /** * Column definition */ interface ColumnDefinition { /** Column name */ name: string; /** Data type */ type: 'string' | 'number' | 'boolean' | 'date' | 'json' | 'array'; /** Nullable */ nullable?: boolean; /** Default value */ default?: any; /** Auto-increment */ autoIncrement?: boolean; } /** * Index definition */ interface IndexDefinition { /** Index name */ name: string; /** Columns */ columns: string[]; /** Unique index */ unique?: boolean; /** Index type */ type?: 'btree' | 'hash' | 'gin' | 'gist'; } /** * Migration definition */ interface Migration { /** Migration version */ version: string; /** Migration description */ description: string; /** Up migration function */ up: (client: any) => Promise; /** Down migration function */ down: (client: any) => Promise; } /** * ZeroDB client events */ interface ZeroDBEvents { /** Connection established */ connect: () => void; /** Connection closed */ disconnect: () => void; /** Error occurred */ error: (error: Error) => void; /** Query executed */ query: (query: string, duration: number) => void; /** Transaction started */ transactionStart: (id: string) => void; /** Transaction committed */ transactionCommit: (id: string) => void; /** Transaction rolled back */ transactionRollback: (id: string) => void; } /** * ZeroDB client interface */ interface IZeroDBClient { /** Insert records */ insert(table: string, data: Record | Record[], options?: InsertOptions): Promise>; /** Select records */ select(table: string, options?: QueryOptions): Promise>; /** Update records */ update(table: string, data: Record, options?: UpdateOptions): Promise>; /** Delete records */ delete(table: string, options?: DeleteOptions): Promise>; /** Upsert records */ upsert(table: string, data: Record | Record[], options?: InsertOptions): Promise>; /** Execute batch operations */ batch(operations: BatchOperation[]): Promise; /** Create query builder */ query(table: string): IQueryBuilder; /** Execute transaction */ transaction(callback: (client: IZeroDBClient) => Promise, options?: TransactionOptions): Promise; /** Check connection health */ healthCheck(): Promise; /** Close connection */ close(): Promise; } /** * ZeroDB CRUD Client * * Comprehensive client for performing CRUD operations on ZeroDB with support for: * - Full CRUD operations (Create, Read, Update, Delete) * - Query builder with fluent API * - Transaction support * - Connection pooling * - Automatic retries * - Health checks */ /** * ZeroDB Client implementation */ declare class ZeroDBClient extends EventEmitter implements IZeroDBClient { private config; private pool; private closed; private transactionId; constructor(config: ZeroDBConfig); /** * Execute API request with retry logic */ private executeRequest; /** * Mock API call (to be replaced with actual HTTP requests) */ private mockApiCall; /** * Retry with exponential backoff */ private retryWithBackoff; /** * Check if error is retryable */ private isRetryableError; /** * Insert records */ insert(table: string, data: Record | Record[], options?: InsertOptions): Promise>; /** * Select records */ select(table: string, options?: QueryOptions): Promise>; /** * Update records */ update(table: string, data: Record, options?: UpdateOptions): Promise>; /** * Delete records */ delete(table: string, options?: DeleteOptions): Promise>; /** * Upsert records (insert or update on conflict) */ upsert(table: string, data: Record | Record[], options?: InsertOptions): Promise>; /** * Execute batch operations */ batch(operations: BatchOperation[]): Promise; /** * Create query builder */ query(table: string): IQueryBuilder; /** * Execute transaction */ transaction(callback: (client: IZeroDBClient) => Promise, _options?: TransactionOptions): Promise; /** * Generate unique transaction ID */ private generateTransactionId; /** * Check connection health */ healthCheck(): Promise; /** * Close connection */ close(): Promise; /** * Get pool statistics */ getPoolStats(): PoolStats; /** * Check if client is closed */ isClosed(): boolean; /** * Get configuration (excluding sensitive data) */ getConfig(): Partial; } /** * Create a new ZeroDB client */ declare function createZeroDBClient(config: ZeroDBConfig): ZeroDBClient; /** * Fluent Query Builder for ZeroDB * * Provides a fluent API for building complex database queries with * type safety and method chaining. */ declare class QueryBuilder implements IQueryBuilder { private tableName; private options; private filters; private orFilters; private notFilters; private executor; constructor(table: string, executor: (table: string, options: QueryOptions) => Promise>); /** * Select specific fields */ select(...fields: string[]): IQueryBuilder; /** * Add WHERE condition */ where(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** * Add AND condition */ and(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** * Add OR condition */ or(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** * Add NOT condition */ not(field: string, operator: FilterOperator, value: any): IQueryBuilder; /** * Add ORDER BY */ orderBy(field: string, direction?: SortDirection): IQueryBuilder; /** * Add LIMIT */ limit(limit: number): IQueryBuilder; /** * Add OFFSET */ offset(offset: number): IQueryBuilder; /** * Add JOIN */ join(table: string, on: { left: string; right: string; }, type?: 'inner' | 'left' | 'right' | 'full'): IQueryBuilder; /** * Add GROUP BY */ groupBy(..._fields: string[]): IQueryBuilder; /** * Add HAVING */ having(_field: string, _operator: FilterOperator, _value: any): IQueryBuilder; /** * Build the final filter */ private buildFilter; /** * Execute query */ execute(): Promise>; /** * Get first result */ first(): Promise; /** * Get all results */ all(): Promise; /** * Count results */ count(): Promise; /** * Clone the query builder */ clone(): QueryBuilder; /** * Reset the query builder */ reset(): IQueryBuilder; /** * Paginate results */ paginate(page: number, pageSize: number): IQueryBuilder; /** * Get query options (for debugging) */ getOptions(): QueryOptions; } export { type AggregateFunction, type AggregateSpec, type BatchOperation, type BatchOperationType, type CRUDResult, type ColumnDefinition, type DeleteOptions, type Filter, type FilterCondition, type FilterOperator, type GroupByOptions, type HealthStatus, type IQueryBuilder, type IZeroDBClient, type IndexDefinition, type InsertOptions, type JoinSpec, type Migration, type PaginationOptions, type PoolConfig, type PoolStats, QueryBuilder, type QueryOptions, type QueryResult, type RetryConfig, type SortDirection, type SortSpec, type TableSchema, type TransactionOptions, type TransactionResult, type UpdateOptions, ZeroDBClient, type ZeroDBConfig, type ZeroDBEvents, createZeroDBClient };