All files / src/database utils.js

0% Statements 0/374
0% Branches 0/1
0% Functions 0/1
0% Lines 0/374

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Database Utilities for Coherent.js
 * 
 * @fileoverview Utility functions for database operations, model registration, and migrations.
 */
 
import { DatabaseManager } from './connection-manager.js';
// Migration utilities are handled by the createMigration factory function
 
/**
 * Model registry for managing model classes
 */
const modelRegistry = new Map();
 
/**
 * Create database connection with configuration
 * 
 * @param {Object} config - Database configuration
 * @returns {Promise<DatabaseManager>} Database manager instance
 * 
 * @example
 * const db = await createConnection({
 *   type: 'postgresql',
 *   host: 'localhost',
 *   database: 'myapp',
 *   username: 'user',
 *   password: 'pass'
 * });
 */
export async function createConnection(config) {
  const db = new DatabaseManager(config);
  await db.connect();
  return db;
}
 
/**
 
  // Add custom methods if provided
  if (definition.methods) {
    Object.entries(definition.methods).forEach(([methodName, method]) => {
      DynamicModel.prototype[methodName] = method;
    });
  }
 
  // Add custom static methods if provided
  if (definition.staticMethods) {
    Object.entries(definition.staticMethods).forEach(([methodName, method]) => {
      DynamicModel[methodName] = method;
    });
  }
 
  // Register the model
  registerModel(name, DynamicModel);
 
  return DynamicModel;
}
 
/**
 * Register a model class
 * 
 * @param {string} name - Model name
 * @param {Function} ModelClass - Model class
 * 
 * @example
 * registerModel('User', UserModel);
 */
export function registerModel(name, ModelClass) {
  modelRegistry.set(name, ModelClass);
  
  // Make model globally available for relationships
  if (typeof global !== 'undefined') {
    global[name] = ModelClass;
  }
}
 
/**
 * Get registered model by name
 * 
 * @param {string} name - Model name
 * @returns {Function|null} Model class or null if not found
 * 
 * @example
 * const User = getModel('User');
 */
export function getModel(name) {
  return modelRegistry.get(name) || null;
}
 
/**
 * Get all registered models
 * 
 * @returns {Map<string, Function>} Map of model names to classes
 */
export function getAllModels() {
  return new Map(modelRegistry);
}
 
/**
 * Run database migrations
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Object} [config={}] - Migration configuration
 * @returns {Promise<Array<string>>} Applied migration names
 * 
 * @example
 * const applied = await runMigrations(db, {
 *   directory: './migrations'
 * });
 */
export async function runMigrations(db, config = {}) {
  const { createMigration } = await import('./migration.js');
  const migration = createMigration(db, config);
  return await migration.run();
}
 
/**
 * Rollback database migrations
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {number} [steps=1] - Number of batches to rollback
 * @param {Object} [config={}] - Migration configuration
 * @returns {Promise<Array<string>>} Rolled back migration names
 * 
 * @example
 * const rolledBack = await rollbackMigrations(db, 2);
 */
export async function rollbackMigrations(db, steps = 1, config = {}) {
  const { createMigration } = await import('./migration.js');
  const migration = createMigration(db, config);
  return await migration.rollback(steps);
}
 
/**
 * Create a new migration file
 * 
 * @param {string} name - Migration name
 * @param {Object} [config={}] - Migration configuration
 * @returns {Promise<string>} Created file path
 * 
 * @example
 * const filePath = await createMigration('create_users_table');
 */
export async function createMigrationFile(name, config = {}) {
  const { createMigration } = await import('./migration.js');
  const migration = createMigration(null, config);
  return await migration.create(name);
}
 
/**
 * Seed database with initial data
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Function|Array<Function>} seeders - Seeder functions
 * @returns {Promise<void>}
 * 
 * @example
 * await seedDatabase(db, [
 *   async (db) => {
 *     await User.create({ name: 'Admin', email: 'admin@example.com' });
 *   }
 * ]);
 */
export async function seedDatabase(db, seeders) {
  const seederArray = Array.isArray(seeders) ? seeders : [seeders];
  
  for (const seeder of seederArray) {
    if (typeof seeder === 'function') {
      await seeder(db);
    }
  }
}
 
/**
 * Validate database configuration
 * 
 * @param {Object} config - Database configuration
 * @returns {Object} Validation result
 * 
 * @example
 * const validation = validateConfig(config);
 * if (!validation.valid) {
 *   console.error('Config errors:', validation.errors);
 * }
 */
export function validateConfig(config) {
  const errors = [];
  
  if (!config || typeof config !== 'object') {
    errors.push('Configuration must be an object');
    return { valid: false, errors };
  }
 
  if (!config.type) {
    errors.push('Database type is required');
  } else {
    const supportedTypes = ['postgresql', 'mysql', 'sqlite', 'mongodb'];
    if (!supportedTypes.includes(config.type)) {
      errors.push(`Unsupported database type: ${config.type}`);
    }
  }
 
  if (!config.database) {
    errors.push('Database name is required');
  }
 
  if (config.type !== 'sqlite') {
    if (!config.host) {
      errors.push('Host is required for non-SQLite databases');
    }
  }
 
  if (config.pool) {
    if (config.pool.min && config.pool.max && config.pool.min > config.pool.max) {
      errors.push('Pool min size cannot be greater than max size');
    }
  }
 
  return {
    valid: errors.length === 0,
    errors
  };
}
 
/**
 * Create database backup
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Object} [options={}] - Backup options
 * @returns {Promise<string>} Backup file path or data
 * 
 * @example
 * const backupPath = await createBackup(db, {
 *   format: 'sql',
 *   outputPath: './backups'
 * });
 */
export async function createBackup(db, options = {}) {
  const backupConfig = {
    format: 'sql',
    outputPath: './backups',
    timestamp: true,
    ...options
  };
 
  const timestamp = backupConfig.timestamp ? new Date().toISOString().replace(/[:.]/g, '-') : '';
  const fileName = `backup${timestamp ? `_${  timestamp}` : ''}.${backupConfig.format}`;
  const filePath = `${backupConfig.outputPath}/${fileName}`;
 
  // This would be adapter-specific implementation
  // For now, return a placeholder
  console.log(`Backup would be created at: ${filePath}`);
  return filePath;
}
 
/**
 * Restore database from backup
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {string} backupPath - Path to backup file
 * @param {Object} [options={}] - Restore options
 * @returns {Promise<void>}
 * 
 * @example
 * await restoreBackup(db, './backups/backup_2023-12-01.sql');
 */
export async function restoreBackup(db, backupPath) {
  // This would be adapter-specific implementation
  console.log(`Restore would be performed from: ${backupPath}`);
}
 
/**
 * Generate database schema documentation
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Object} [options={}] - Documentation options
 * @returns {Promise<Object>} Schema documentation
 * 
 * @example
 * const docs = await generateSchemaDocs(db, {
 *   includeIndexes: true,
 *   includeRelationships: true
 * });
 */
export async function generateSchemaDocs(db) {
  const schema = {
    database: db.config.database,
    type: db.config.type,
    tables: [],
    models: []
  };
 
  // Add registered models to documentation
  for (const [name, ModelClass] of modelRegistry) {
    schema.models.push({
      name,
      tableName: ModelClass.tableName,
      primaryKey: ModelClass.primaryKey,
      fillable: ModelClass.fillable,
      relationships: ModelClass.relationships,
      validationRules: ModelClass.validationRules
    });
  }
 
  return schema;
}
 
/**
 * Database health check utility
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @returns {Promise<Object>} Health check result
 * 
 * @example
 * const health = await checkDatabaseHealth(db);
 * console.log(`Database is ${health.status}`);
 */
export async function checkDatabaseHealth(db) {
  const startTime = Date.now();
  
  try {
    await db.query('SELECT 1');
    
    const responseTime = Date.now() - startTime;
    const stats = db.getStats();
    
    return {
      status: 'healthy',
      responseTime,
      connected: db.isConnected,
      stats
    };
    
  } catch (error) {
    return {
      status: 'unhealthy',
      error: error.message,
      connected: db.isConnected,
      responseTime: Date.now() - startTime
    };
  }
}
 
/**
 * Batch operation utility
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Array} operations - Array of operations to execute
 * @param {Object} [options={}] - Batch options
 * @returns {Promise<Array>} Results array
 * 
 * @example
 * const results = await batchOperations(db, [
 *   { sql: 'INSERT INTO users (name) VALUES (?)', params: ['John'] },
 *   { sql: 'INSERT INTO users (name) VALUES (?)', params: ['Jane'] }
 * ]);
 */
export async function batchOperations(db, operations, options = {}) {
  const config = {
    useTransaction: true,
    continueOnError: false,
    ...options
  };
 
  const results = [];
  
  if (config.useTransaction) {
    const tx = await db.transaction();
    
    try {
      for (const operation of operations) {
        try {
          const result = await tx.query(operation.sql, operation.params);
          results.push({ success: true, result });
        } catch (error) {
          results.push({ success: false, error: error.message });
          
          if (!config.continueOnError) {
            throw error;
          }
        }
      }
      
      await tx.commit();
      
    } catch (error) {
      await tx.rollback();
      throw error;
    }
    
  } else {
    for (const operation of operations) {
      try {
        const result = await db.query(operation.sql, operation.params);
        results.push({ success: true, result });
      } catch (error) {
        results.push({ success: false, error: error.message });
        
        if (!config.continueOnError) {
          throw error;
        }
      }
    }
  }
  
  return results;
}