UNPKG

@bhagat-surya-dev/dashchat-database-manager

Version:

AI-powered database schema analysis and management library

380 lines (274 loc) 10.5 kB
# @bhagat-surya-dev/dashchat-database-manager AI-powered database schema analysis and management library with support for multiple database types. ## Installation ```bash npm install @bhagat-surya-dev/dashchat-database-manager ``` ### Peer Dependencies Install the database driver for your specific database: ```bash # For PostgreSQL npm install pg @types/pg # For MySQL/MariaDB npm install mysql2 # For SQLite npm install sqlite3 # For MongoDB npm install mongodb ``` ## Quick Start ```typescript import DatabaseManager from '@bhagat-surya-dev/dashchat-database-manager'; // Initialize the manager const dbManager = new DatabaseManager({ cerebrasApiKey: 'your-cerebras-api-key', databaseUrl: 'postgresql://user:pass@localhost:5432/mydb' // Optional }); // Test connection const isConnected = await dbManager.testConnection(); console.log('Connected:', isConnected); // Get schema information const schema = await dbManager.getSchemaInfo(); console.log('Tables:', schema.tables.length); // AI-powered schema analysis const analyzedSchema = await dbManager.analyzeAndCacheSchema( 'postgresql://user:pass@localhost:5432/mydb', 'my-database-id' ); ``` ## Constructor Options ### `DbManagerOptions` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `cerebrasApiKey` | `string` | Yes | Your Cerebras Cloud API key for AI analysis | | `databaseUrl` | `string` | No | Default database connection string (can be provided later to methods) | ### Example ```typescript const dbManager = new DatabaseManager({ cerebrasApiKey: process.env.CEREBRAS_API_KEY!, databaseUrl: process.env.DATABASE_URL // Optional default }); ``` ## Methods ### `testConnection(databaseUrl?: string): Promise<boolean>` Tests database connectivity. **Parameters:** - `databaseUrl` (optional): Database connection string. Uses constructor URL if not provided. **Returns:** Promise resolving to `true` if connection successful. ```typescript // Using constructor URL const isConnected = await dbManager.testConnection(); // Using specific URL const isConnected = await dbManager.testConnection('postgresql://user:pass@host:5432/db'); ``` ### `getSchemaInfo(databaseUrl?: string): Promise<FormattedSchema>` Extracts database schema information. **Parameters:** - `databaseUrl` (optional): Database connection string. Uses constructor URL if not provided. **Returns:** Promise resolving to formatted schema object. ```typescript const schema = await dbManager.getSchemaInfo(); console.log(`Found ${schema.tables.length} tables`); schema.tables.forEach(table => { console.log(`Table: ${table.name}`); console.log(`Columns: ${table.columns.map(c => c.name).join(', ')}`); }); ``` ### `analyzeAndCacheSchema(databaseUrl: string, databaseId: string, forceAnalysis?: boolean): Promise<AnalyzedSchema | null>` Performs AI-powered schema analysis with detailed descriptions. **Parameters:** - `databaseUrl` (required): Database connection string - `databaseId` (required): Unique identifier for the database - `forceAnalysis` (optional): Force new analysis, skip cache (default: false) **Returns:** Promise resolving to analyzed schema with AI-generated descriptions. ```typescript const analyzed = await dbManager.analyzeAndCacheSchema( 'postgresql://user:pass@localhost:5432/mydb', 'production-db', false // Use cache if available ); if (analyzed) { // Display overall schema summary (automatically generated) console.log('Overall Summary:', analyzed.overallSummary); analyzed.tables.forEach(table => { console.log(`Table: ${table.table_name}`); console.log(`Description: ${table.description}`); table.columns.forEach(column => { console.log(` ${column.column_name}: ${column.description}`); }); }); } ``` ### `getOverallSchemaSummary(analyzedSchema: AnalyzedSchema): Promise<string>` Generates a concise, high-level summary of the entire database schema using AI. **Parameters:** - `analyzedSchema` (required): The analyzed schema object from `analyzeAndCacheSchema()` **Returns:** Promise resolving to a one-paragraph summary describing the database's overall purpose, table count, and core tables. ```typescript // First, get the analyzed schema const analyzed = await dbManager.analyzeAndCacheSchema( 'postgresql://user:pass@localhost:5432/ecommerce', 'ecommerce-db' ); // Generate a standalone summary (if you need it separately) const summary = await dbManager.getOverallSchemaSummary(analyzed); console.log('Database Summary:', summary); // Note: The summary is also automatically included in the analyzed schema // as analyzed.overallSummary when you call analyzeAndCacheSchema() ``` ### `validateConnectionString(connectionString: string)` Validates connection string format and determines database type. **Parameters:** - `connectionString` (required): Connection string to validate **Returns:** Validation result object. ```typescript const validation = dbManager.validateConnectionString('postgresql://user:pass@host:5432/db'); console.log('Valid:', validation.isValid); console.log('Type:', validation.type); console.log('Errors:', validation.errors); ``` ### `getSupportedDatabaseTypes(): string[]` Returns array of supported database types. ```typescript const supported = dbManager.getSupportedDatabaseTypes(); console.log('Supported:', supported); // ['postgres', 'postgresql', 'mysql', 'mariadb', 'mongodb', 'sqlite'] ``` ### `getDatabaseUrlType(databaseUrl?: string): string | null` Automatically detects and returns the database type from a connection URL. **Parameters:** - `databaseUrl` (optional): Database connection string. Uses constructor URL if not provided. **Returns:** Database type string (`'postgres'`, `'mysql'`, `'mongodb'`, `'sqlite'`, etc.) or `null` if unsupported. ```typescript // Using constructor URL const dbManager = new DatabaseManager({ cerebrasApiKey: 'your-key', databaseUrl: 'postgresql://user:pass@localhost:5432/mydb' }); const type = dbManager.getDatabaseUrlType(); console.log('Database type:', type); // 'postgres' // Using specific URL const mysqlType = dbManager.getDatabaseUrlType('mysql://user:pass@localhost:3306/mydb'); console.log('Database type:', mysqlType); // 'mysql' const mongoType = dbManager.getDatabaseUrlType('mongodb://localhost:27017/mydb'); console.log('Database type:', mongoType); // 'mongodb' const sqliteType = dbManager.getDatabaseUrlType('./database.db'); console.log('Database type:', sqliteType); // 'sqlite' ``` ## Connection Strings ### PostgreSQL ``` postgresql://username:password@hostname:port/database postgres://username:password@hostname:port/database ``` ### MySQL/MariaDB ``` mysql://username:password@hostname:port/database mariadb://username:password@hostname:port/database ``` ### SQLite ``` sqlite:///path/to/database.db ./database.db /absolute/path/to/database.db ``` ### MongoDB ``` mongodb://username:password@hostname:port/database mongodb+srv://username:password@cluster.mongodb.net/database ``` ## Environment Variables Create a `.env` file in your project root: ```env CEREBRAS_API_KEY=your_cerebras_api_key_here DATABASE_URL=postgresql://user:pass@localhost:5432/mydb ``` ## Error Handling The library provides enhanced error messages for common issues: ```typescript try { await dbManager.testConnection('invalid://connection/string'); } catch (error) { console.error('Connection failed:', error.message); // Enhanced error messages like: // - "Database host not found. Please verify the hostname..." // - "Authentication failed. Please verify your username and password." // - "Connection refused. Please check if the database server is running..." } ``` ## TypeScript Support Full TypeScript support with exported interfaces: ```typescript import DatabaseManager, { DbManagerOptions } from '@bhagat-surya-dev/dashchat-database-manager'; interface AnalyzedSchema { tables: AnalyzedTable[]; overallSummary?: string; // AI-generated database summary } interface AnalyzedTable { table_name: string; description: string; columns: AnalyzedColumn[]; } interface AnalyzedColumn { column_name: string; description: string; data_type: string; nullable: boolean; } ``` ## Schema Summary Feature The library now automatically generates an overall database summary when performing AI analysis: ### Automatic Summary Generation When you call `analyzeAndCacheSchema()`, the system automatically: 1. **Analyzes each table and column** with detailed AI-generated descriptions 2. **Generates an overall summary** describing the database's purpose and key tables 3. **Includes the summary** in the returned schema object as `overallSummary` ### Example Usage ```typescript const analyzed = await dbManager.analyzeAndCacheSchema( 'mongodb://admin:password123@localhost:27017/ecommerce_startup', 'ecommerce-startup-db' ); // The summary is automatically available console.log('📋 Database Summary:'); console.log(analyzed.overallSummary); // Output: "This database supports a comprehensive e-commerce platform with 8 tables..." // Save analysis and summary to files import * as fs from 'fs/promises'; // Save full analysis await fs.writeFile('schema_analysis.json', JSON.stringify(analyzed, null, 2)); // Save summary report const summaryReport = `Database Schema Summary Report Generated: ${new Date().toISOString()} Total Tables: ${analyzed.tables.length} SUMMARY: ${analyzed.overallSummary} TABLES: ${analyzed.tables.map(table => `- ${table.table_name}: ${table.description}` ).join('\n')}`; await fs.writeFile('schema_summary.txt', summaryReport); ``` ### Summary Content The AI-generated summary includes: - **Database purpose** (e.g., "e-commerce platform", "CRM system") - **Total number of tables** - **Core/important tables identified** - **Overall architecture description** ## Features - ✅ Multi-database support (PostgreSQL, MySQL, SQLite, MongoDB) - ✅ AI-powered schema analysis with Cerebras - ✅ **Automatic schema summary generation** - ✅ Comprehensive error handling - ✅ Connection validation - ✅ TypeScript support - ✅ Performance monitoring - ✅ Detailed logging - ✅ Schema optimization for AI accuracy ## Requirements - Node.js >= 16.0.0 - Valid Cerebras API key for AI analysis - Appropriate database driver for your database type ## License MIT ## Support For issues and feature requests, please visit the [GitHub repository](https://github.com/Bhagat028/dashchat-datamanger/tree/npm-manager).