All files / core QueryCompiler.ts

71.08% Statements 177/249
41.6% Branches 57/137
86.11% Functions 31/36
71.25% Lines 171/240

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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635              11x 11x 11x           1x             1x                     18x     18x 18x 1x       17x     17x   7x 6x   5x 5x   2x 2x   2x 2x   1x       15x   15x             18x 18x 18x 18x   18x 24x                     15x         15x               17x     17x     17x   17x             17x 17x     17x 23x 23x 22x   23x       17x 22x 21x     1x 1x       17x                     1x             7x 7x 7x 7x 7x   7x 7x 7x     7x 7x 2x       7x 7x 7x 11x 11x 11x     6x       6x 1x 1x       6x 1x   6x 1x     6x             7x     11x 7x 2x       7x       7x             7x   6x 2x     2x 2x 2x   2x 2x                     5x 5x 5x 5x   5x 5x     5x 5x   5x   4x   1x         5x 2x 2x 3x       2x 1x         5x 1x   5x 1x     5x                   5x     5x 6x 6x   6x                     6x       5x             1x 1x 2x   1x             2x 2x 2x 2x   2x 2x 2x     2x 2x 3x 3x 3x     2x     2x     2x 1x 1x       2x     2x 1x     2x             2x 2x 2x 2x     2x     2x 2x 2x   2x         2x                   11x   11x     2x             7x                                     1x                           1x               6x   6x     2x             4x                                                                           3x   3x     1x             2x                                                                     2x     2x     1x   1x                             11x                                                                                                    
import { QueryBuilder } from "./QueryBuilder";
import { QueryCondition, QueryOperator, CompiledQuery, IQueryBuilder } from "./types";
 
/**
 * QueryCompiler - translates fluent queries into database-specific queries
 * This is the bridge between our universal API and specific database dialects
 */
export class QueryCompiler {
  private static queryCache = new Map<string, CompiledQuery>();
  private static cacheSize = 1000;
  
  /**
   * Clear the query cache
   */
  static clearCache(): void {
    this.queryCache.clear();
  }
  
  /**
   * Get cache statistics
   */
  static getCacheStats(): { size: number; hitRate: number } {
    return {
      size: this.queryCache.size,
      hitRate: 0 // TODO: Implement hit rate tracking
    };
  }
  
  /**
   * Compile a QueryBuilder into database-specific queries
   */
  static compile<T>(queryBuilder: IQueryBuilder<T>, targetDatabase: 'postgresql' | 'mongodb' | 'neo4j' | 'redis'): CompiledQuery {
    // Generate cache key based on query structure
    const cacheKey = this.generateCacheKey(queryBuilder, targetDatabase);
    
    // Check cache first
    const cached = this.queryCache.get(cacheKey);
    if (cached) {
      return cached;
    }
    
    // Optimize query before compilation
    const optimizedQuery = this.optimizeQuery(queryBuilder);
    
    let compiled: CompiledQuery;
    switch (targetDatabase) {
      case 'postgresql':
        compiled = this.compileToSQL(optimizedQuery);
        break;
      case 'mongodb':
        compiled = this.compileToMongoDB(optimizedQuery);
        break;
      case 'neo4j':
        compiled = this.compileToNeo4j(optimizedQuery);
        break;
      case 'redis':
        compiled = this.compileToRedis(optimizedQuery);
        break;
      default:
        throw new Error(`Unsupported database: ${targetDatabase}`);
    }
    
    // Cache the result
    this.cacheCompiledQuery(cacheKey, compiled);
    
    return compiled;
  }
  
  /**
   * Generate a cache key for a query
   */
  private static generateCacheKey<T>(queryBuilder: IQueryBuilder<T>, targetDatabase: string): string {
    const conditions = queryBuilder.getConditions();
    const sorts = queryBuilder.getSorts();
    const limit = queryBuilder.getLimit();
    const offset = queryBuilder.getOffset();
    
    return `${targetDatabase}:${JSON.stringify({
      conditions: conditions.map(c => ({ property: c.property, operator: c.operator })),
      sorts,
      limit,
      offset
    })}`;
  }
  
  /**
   * Cache a compiled query with LRU eviction
   */
  private static cacheCompiledQuery(key: string, compiled: CompiledQuery): void {
    Iif (this.queryCache.size >= this.cacheSize) {
      // Remove oldest entry (simple LRU)
      const firstKey = this.queryCache.keys().next().value;
      this.queryCache.delete(firstKey);
    }
    this.queryCache.set(key, compiled);
  }
  
  /**
   * Optimize query conditions before compilation
   */
  private static optimizeQuery<T>(queryBuilder: IQueryBuilder<T>): IQueryBuilder<T> {
    // Create a copy to avoid mutating the original
    const optimized = Object.create(queryBuilder);
    
    // Merge redundant conditions
    const conditions = this.mergeConditions(queryBuilder.getConditions());
    
    // Override getConditions to return optimized conditions
    optimized.getConditions = () => conditions;
    
    return optimized;
  }
  
  /**
   * Merge redundant conditions (e.g., multiple equals on same property)
   */
  private static mergeConditions(conditions: QueryCondition[]): QueryCondition[] {
    const merged: QueryCondition[] = [];
    const propertyMap = new Map<string, QueryCondition[]>();
    
    // Group by property
    for (const condition of conditions) {
      const key = condition.property;
      if (!propertyMap.has(key)) {
        propertyMap.set(key, []);
      }
      propertyMap.get(key)!.push(condition);
    }
    
    // Merge conditions for each property
    for (const [property, propConditions] of propertyMap) {
      if (propConditions.length === 1) {
        merged.push(propConditions[0]);
      } else {
        // Try to merge multiple conditions
        const mergedCondition = this.mergePropertyConditions(propConditions);
        merged.push(...mergedCondition);
      }
    }
    
    return merged;
  }
  
  /**
   * Merge conditions for a single property
   */
  private static mergePropertyConditions(conditions: QueryCondition[]): QueryCondition[] {
    // For now, just return as-is. Future optimization:
    // - Merge multiple 'equals' into 'in'
    // - Combine range conditions (gt + lt = between)
    // - Remove contradictory conditions
    return conditions;
  }
 
  /**
   * Compile to PostgreSQL with optimizations
   */
  private static compileToSQL<T>(queryBuilder: IQueryBuilder<T>): CompiledQuery {
    const conditions = queryBuilder.getConditions();
    const sorts = queryBuilder.getSorts();
    const includes = queryBuilder.getIncludes();
    const limit = queryBuilder.getLimit();
    const offset = queryBuilder.getOffset();
 
    let sql = 'SELECT * FROM entities';
    const parameters: Record<string, any> = {};
    let paramCount = 1;
    
    // Add query hints for optimization
    const hints = this.generateSQLHints(conditions, sorts, limit);
    if (hints.length > 0) {
      sql += ` /*+ ${hints.join(' ')} */`;
    }
 
    // WHERE clause with optimized condition ordering
    if (conditions.length > 0) {
      const optimizedConditions = this.optimizeSQLConditions(conditions);
      const whereClause = optimizedConditions.map(condition => {
        const paramName = `param${paramCount++}`;
        parameters[paramName] = condition.value;
        return this.compileConditionToSQL(condition, paramName);
      }).join(' AND ');
      
      sql += ` WHERE ${whereClause}`;
    }
 
    // ORDER BY clause
    if (sorts.length > 0) {
      const orderClause = sorts.map(sort => `${sort.property} ${sort.direction.toUpperCase()}`).join(', ');
      sql += ` ORDER BY ${orderClause}`;
    }
 
    // LIMIT and OFFSET
    if (limit !== undefined) {
      sql += ` LIMIT ${limit}`;
    }
    if (offset !== undefined) {
      sql += ` OFFSET ${offset}`;
    }
 
    return { sql, parameters };
  }
  
  /**
   * Generate SQL performance hints
   */
  private static generateSQLHints(conditions: QueryCondition[], sorts: any[], limit?: number): string[] {
    const hints: string[] = [];
    
    // Use index hints for equality conditions
    const equalityConditions = conditions.filter(c => c.operator === 'equals' || c.operator === 'eq');
    if (equalityConditions.length > 0) {
      hints.push(`USE_INDEX(entities_${equalityConditions[0].property}_idx)`);
    }
    
    // Sort optimization hint
    Iif (sorts.length > 0 && limit && limit <= 1000) {
      hints.push('USE_INDEX_FOR_ORDER_BY');
    }
    
    return hints;
  }
  
  /**
   * Optimize SQL condition ordering (most selective first)
   */
  private static optimizeSQLConditions(conditions: QueryCondition[]): QueryCondition[] {
    return conditions.sort((a, b) => {
      // Equality conditions first (most selective)
      if (a.operator === 'equals' && b.operator !== 'equals') return -1;
      Iif (b.operator === 'equals' && a.operator !== 'equals') return 1;
      
      // Range conditions next
      const rangeOps = ['gt', 'gte', 'lt', 'lte', 'between'];
      const aIsRange = rangeOps.includes(a.operator);
      const bIsRange = rangeOps.includes(b.operator);
      
      Iif (aIsRange && !bIsRange) return -1;
      if (bIsRange && !aIsRange) return 1;
      
      // Keep original order for same types
      return 0;
    });
  }
 
  /**
   * Compile to MongoDB with optimizations
   */
  private static compileToMongoDB<T>(queryBuilder: IQueryBuilder<T>): CompiledQuery {
    const conditions = queryBuilder.getConditions();
    const sorts = queryBuilder.getSorts();
    const limit = queryBuilder.getLimit();
    const offset = queryBuilder.getOffset();
 
    const mongoQuery: any = {};
    const mongoOptions: any = {};
 
    // Build MongoDB query object with optimizations
    if (conditions.length > 0) {
      const optimizedConditions = this.optimizeMongoConditions(conditions);
      
      if (optimizedConditions.length === 1) {
        // Single condition - no need for $and
        Object.assign(mongoQuery, optimizedConditions[0]);
      } else {
        mongoQuery.$and = optimizedConditions;
      }
    }
 
    // Sort with index hints
    if (sorts.length > 0) {
      mongoOptions.sort = {};
      sorts.forEach(sort => {
        mongoOptions.sort[sort.property] = sort.direction === 'asc' ? 1 : -1;
      });
      
      // Add hint for compound indexes
      if (sorts.length > 1) {
        mongoOptions.hint = this.generateMongoIndexHint(sorts);
      }
    }
 
    // Limit and Skip
    if (limit !== undefined) {
      mongoOptions.limit = limit;
    }
    if (offset !== undefined) {
      mongoOptions.skip = offset;
    }
 
    return {
      mongodb: { query: mongoQuery, options: mongoOptions },
      parameters: {}
    };
  }
  
  /**
   * Optimize MongoDB conditions
   */
  private static optimizeMongoConditions(conditions: QueryCondition[]): any[] {
    const conditionMap = new Map<string, any>();
    
    // Group conditions by property to merge them
    for (const condition of conditions) {
      const compiled = this.compileConditionToMongoDB(condition);
      const property = condition.property;
      
      Iif (conditionMap.has(property)) {
        // Merge multiple conditions on same property
        const existing = conditionMap.get(property);
        if (typeof existing[property] === 'object' && compiled[property] && typeof compiled[property] === 'object') {
          // Merge MongoDB operators
          Object.assign(existing[property], compiled[property]);
        } else {
          // Create array for multiple values
          conditionMap.set(property, { $and: [existing, compiled] });
        }
      } else {
        conditionMap.set(property, compiled);
      }
    }
    
    return Array.from(conditionMap.values());
  }
  
  /**
   * Generate MongoDB index hint
   */
  private static generateMongoIndexHint(sorts: any[]): any {
    const indexHint: any = {};
    sorts.forEach(sort => {
      indexHint[sort.property] = sort.direction === 'asc' ? 1 : -1;
    });
    return indexHint;
  }
 
  /**
   * Compile to Neo4j Cypher
   */
  private static compileToNeo4j<T>(queryBuilder: IQueryBuilder<T>): CompiledQuery {
    const conditions = queryBuilder.getConditions();
    const sorts = queryBuilder.getSorts();
    const limit = queryBuilder.getLimit();
    const offset = queryBuilder.getOffset();
 
    let cypher = 'MATCH (n:Entity)';
    const parameters: Record<string, any> = {};
    let paramCount = 1;
 
    // WHERE clause
    if (conditions.length > 0) {
      const whereClause = conditions.map(condition => {
        const paramName = `param${paramCount++}`;
        parameters[paramName] = condition.value;
        return this.compileConditionToNeo4j(condition, paramName);
      }).join(' AND ');
      
      cypher += ` WHERE ${whereClause}`;
    }
 
    cypher += ' RETURN n';
 
    // ORDER BY clause
    if (sorts.length > 0) {
      const orderClause = sorts.map(sort => `n.${sort.property} ${sort.direction.toUpperCase()}`).join(', ');
      cypher += ` ORDER BY ${orderClause}`;
    }
 
    // SKIP and LIMIT
    Iif (offset !== undefined) {
      cypher += ` SKIP ${offset}`;
    }
    if (limit !== undefined) {
      cypher += ` LIMIT ${limit}`;
    }
 
    return { neo4j: cypher, parameters };
  }
 
  /**
   * Compile to Redis commands
   */
  private static compileToRedis<T>(queryBuilder: IQueryBuilder<T>): CompiledQuery {
    const conditions = queryBuilder.getConditions();
    const sorts = queryBuilder.getSorts();
    const limit = queryBuilder.getLimit();
    const offset = queryBuilder.getOffset();
 
    // Redis is more limited - we'll use basic key patterns and scanning
    const commands: string[] = [];
    
    // Basic pattern matching
    if (conditions.length > 0) {
      const patterns = conditions.map(condition => {
        return this.compileConditionToRedis(condition);
      });
      commands.push(`SCAN 0 MATCH ${patterns.join('*')}`);
    } else E{
      commands.push('SCAN 0 MATCH *');
    }
 
    return {
      redis: commands,
      parameters: {}
    };
  }
 
  /**
   * Helper methods for SQL compilation
   */
  private static compileConditionToSQL(condition: QueryCondition, paramName: string): string {
    const { property, operator } = condition;
    
    switch (operator) {
      case 'equals':
      case 'eq':
        return `${property} = $${paramName}`;
      case 'not_equals':
      case 'ne':
      case 'not':
        return `${property} != $${paramName}`;
      case 'greater_than':
      case 'gt':
        return `${property} > $${paramName}`;
      case 'greater_than_or_equal':
      case 'gte':
        return `${property} >= $${paramName}`;
      case 'less_than':
      case 'lt':
        return `${property} < $${paramName}`;
      case 'less_than_or_equal':
      case 'lte':
        return `${property} <= $${paramName}`;
      case 'in':
        return `${property} = ANY($${paramName})`;
      case 'not_in':
        return `${property} != ALL($${paramName})`;
      case 'like':
        return `${property} LIKE $${paramName}`;
      case 'ilike':
        return `${property} ILIKE $${paramName}`;
      case 'contains':
        return `${property} LIKE '%' || $${paramName} || '%'`;
      case 'starts_with':
        return `${property} LIKE $${paramName} || '%'`;
      case 'ends_with':
        return `${property} LIKE '%' || $${paramName}`;
      case 'is_null':
        return `${property} IS NULL`;
      case 'is_not_null':
        return `${property} IS NOT NULL`;
      case 'between':
        return `${property} BETWEEN $${paramName}.min AND $${paramName}.max`;
      case 'regex':
        return `${property} ~ $${paramName}`;
      default:
        throw new Error(`Unsupported SQL operator: ${operator}`);
    }
  }
 
  /**
   * Helper methods for MongoDB compilation
   */
  private static compileConditionToMongoDB(condition: QueryCondition): any {
    const { property, operator, value } = condition;
    
    switch (operator) {
      case 'equals':
      case 'eq':
        return { [property]: value };
      case 'not_equals':
      case 'ne':
      case 'not':
        return { [property]: { $ne: value } };
      case 'greater_than':
      case 'gt':
        return { [property]: { $gt: value } };
      case 'greater_than_or_equal':
      case 'gte':
        return { [property]: { $gte: value } };
      case 'less_than':
      case 'lt':
        return { [property]: { $lt: value } };
      case 'less_than_or_equal':
      case 'lte':
        return { [property]: { $lte: value } };
      case 'in':
        return { [property]: { $in: value } };
      case 'not_in':
        return { [property]: { $nin: value } };
      case 'like':
      case 'contains':
        return { [property]: { $regex: new RegExp(value, 'i') } };
      case 'starts_with':
        return { [property]: { $regex: new RegExp(`^${value}`, 'i') } };
      case 'ends_with':
        return { [property]: { $regex: new RegExp(`${value}$`, 'i') } };
      case 'is_null':
        return { [property]: null };
      case 'is_not_null':
        return { [property]: { $ne: null } };
      case 'between':
        return { [property]: { $gte: value.min, $lte: value.max } };
      case 'regex':
        return { [property]: { $regex: value } };
      default:
        throw new Error(`Unsupported MongoDB operator: ${operator}`);
    }
  }
 
  /**
   * Helper methods for Neo4j compilation
   */
  private static compileConditionToNeo4j(condition: QueryCondition, paramName: string): string {
    const { property, operator } = condition;
    
    switch (operator) {
      case 'equals':
      case 'eq':
        return `n.${property} = $${paramName}`;
      case 'not_equals':
      case 'ne':
      case 'not':
        return `n.${property} <> $${paramName}`;
      case 'greater_than':
      case 'gt':
        return `n.${property} > $${paramName}`;
      case 'greater_than_or_equal':
      case 'gte':
        return `n.${property} >= $${paramName}`;
      case 'less_than':
      case 'lt':
        return `n.${property} < $${paramName}`;
      case 'less_than_or_equal':
      case 'lte':
        return `n.${property} <= $${paramName}`;
      case 'in':
        return `n.${property} IN $${paramName}`;
      case 'not_in':
        return `NOT n.${property} IN $${paramName}`;
      case 'contains':
        return `n.${property} CONTAINS $${paramName}`;
      case 'starts_with':
        return `n.${property} STARTS WITH $${paramName}`;
      case 'ends_with':
        return `n.${property} ENDS WITH $${paramName}`;
      case 'is_null':
        return `n.${property} IS NULL`;
      case 'is_not_null':
        return `n.${property} IS NOT NULL`;
      case 'regex':
        return `n.${property} =~ $${paramName}`;
      default:
        throw new Error(`Unsupported Neo4j operator: ${operator}`);
    }
  }
 
  /**
   * Helper methods for Redis compilation
   */
  private static compileConditionToRedis(condition: QueryCondition): string {
    const { property, operator, value } = condition;
    
    // Redis has limited querying capabilities - we'll use basic pattern matching
    switch (operator) {
      case 'equals':
      case 'eq':
        return `${property}:${value}`;
      case 'contains':
        return `${property}:*${value}*`;
      case 'starts_with':
        return `${property}:${value}*`;
      case 'ends_with':
        return `${property}:*${value}`;
      default:
        // For complex queries, we'll need to fetch all and filter in memory
        return `${property}:*`;
    }
  }
}
 
/**
 * Query execution engine that uses the compiler
 */
export class QueryExecutor {
  static async execute<T>(
    queryBuilder: IQueryBuilder<T>, 
    adapter: QueryDatabaseAdapter, 
    entityClass: new (...args: any[]) => T
  ): Promise<any> {
    const compiled = QueryCompiler.compile(queryBuilder, adapter.type);
    
    // Execute async conditions first
    const asyncConditions = queryBuilder.getAsyncConditions();
    const asyncResults = await Promise.all(
      asyncConditions.map(condition => this.executeAsyncCondition(condition, adapter))
    );
    
    // Execute the main query
    const result = await adapter.execute(compiled, entityClass);
    
    // Filter results by async conditions
    Iif (asyncResults.length > 0) {
      const filteredData = [];
      for (const item of result.data) {
        const asyncChecks = await Promise.all(
          asyncResults.map(condition => condition(item))
        );
        Iif (asyncChecks.every(check => check)) {
          filteredData.push(item);
        }
      }
      result.data = filteredData;
    }
    
    return result;
  }
 
  private static async executeAsyncCondition<T>(
    condition: (entity: T) => Promise<boolean>,
    adapter: QueryDatabaseAdapter
  ): Promise<(entity: T) => Promise<boolean>> {
    // This is a simplified implementation
    // In practice, you'd want to optimize this by pushing conditions to the database where possible
    return condition;
  }
}
 
/**
 * Query execution database adapter interface
 */
export interface QueryDatabaseAdapter {
  type: 'postgresql' | 'mongodb' | 'neo4j' | 'redis';
  execute<T>(compiled: CompiledQuery, entityClass: new (...args: any[]) => T): Promise<any>;
}