All files / core QueryBuilder.ts

87.5% Statements 105/120
68.42% Branches 26/38
87.71% Functions 50/57
89.38% Lines 101/113

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 37411x                                     11x 133x 133x 133x 133x           133x         36x         19x       2x                 1x 1x 1x       1x 1x 1x                     2x 2x 2x       1x 1x 1x         9x 9x 9x       5x 5x 5x       4x 4x 4x                                                   4x 4x       2x       2x                       8x 8x 8x 8x 8x   8x                         1x 1x   1x                       56x       1x       56x       3x       37x       10x       36x       36x         80x 80x 80x 80x 80x 80x 80x 80x         8x 7x 4x 2x 1x 1x 1x 1x               11x           57x 57x 57x         11x       1x       1x                 18x       4x       1x       1x       1x         3x       1x         1x       1x       4x       1x       1x       1x         1x       1x         2x         1x 1x       53x             53x 53x       2x               2x 2x             11x 53x  
import "reflect-metadata";
import { 
  IQueryBuilder, 
  IQueryConditionBuilder, 
  QueryCondition, 
  QueryOperator, 
  QueryResult, 
  QuerySort, 
  QueryInclude, 
  AsyncConditionFunction,
  PropertyMetadata,
  RelationshipMetadata,
  CompiledQuery
} from "./types";
 
/**
 * Core QueryBuilder class - implements progressive disclosure interface
 * for both humans and AI agents
 */
export class QueryBuilder<T> implements IQueryBuilder<T> {
  protected conditions: QueryCondition[] = [];
  protected asyncConditions: AsyncConditionFunction<T>[] = [];
  protected sorts: QuerySort[] = [];
  protected includes: QueryInclude[] = [];
  protected limitCount?: number;
  protected offsetCount?: number;
  private entityClass: new (...args: any[]) => T;
 
  constructor(entityClass: new (...args: any[]) => T) {
    this.entityClass = entityClass;
  }
 
  // Basic conditions
  where(property: keyof T): IQueryConditionBuilder<T> {
    return new QueryConditionBuilder(this.clone(), property as string);
  }
 
  // Logical operators
  and(property: keyof T): IQueryConditionBuilder<T> {
    return new QueryConditionBuilder(this.clone(), property as string, 'and');
  }
 
  or(property: keyof T): IQueryConditionBuilder<T> {
    return new QueryConditionBuilder(this.clone(), property as string, 'or');
  }
 
  not(property: keyof T): IQueryConditionBuilder<T> {
    return new QueryConditionBuilder(this.clone(), property as string, 'not');
  }
 
  // Async conditions for AI agents
  whereAsync(condition: AsyncConditionFunction<T>): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.asyncConditions.push(condition);
    return cloned;
  }
 
  andAsync(condition: AsyncConditionFunction<T>): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.asyncConditions.push(condition);
    return cloned;
  }
 
  orAsync(condition: AsyncConditionFunction<T>): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.asyncConditions.push(condition);
    return cloned;
  }
 
  // Relationships
  include(relationship: string): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.includes.push({ relationship });
    return cloned;
  }
 
  includeNested(relationship: string, nested: QueryInclude[]): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.includes.push({ relationship, nested });
    return cloned;
  }
 
  // Sorting & Pagination
  orderBy(property: keyof T, direction: 'asc' | 'desc' = 'asc'): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.sorts.push({ property: property as string, direction });
    return cloned;
  }
 
  limit(count: number): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.limitCount = count;
    return cloned;
  }
 
  offset(count: number): IQueryBuilder<T> {
    const cloned = this.clone();
    cloned.offsetCount = count;
    return cloned;
  }
 
  // Execution methods (to be implemented with adapters)
  async execute(): Promise<QueryResult<T>> {
    // This will be implemented with database adapters
    throw new Error("Execute method requires database adapter implementation");
  }
 
  async first(): Promise<T | null> {
    const result = await this.limit(1).execute();
    return result.data.length > 0 ? result.data[0] : null;
  }
 
  async count(): Promise<number> {
    const result = await this.execute();
    return result.total;
  }
 
  async exists(): Promise<boolean> {
    const result = await this.limit(1).execute();
    return result.data.length > 0;
  }
 
  // AI Agent Discovery Methods - THE MAGIC! 🎯
  getAvailableProperties(): (keyof T)[] {
    const properties = Reflect.getMetadata("entity:properties", this.entityClass) || [];
    return properties as (keyof T)[];
  }
 
  getAvailableRelationships(): string[] {
    return Reflect.getMetadata("entity:relationships", this.entityClass) || [];
  }
 
  getAvailableOperators(): QueryOperator[] {
    return [
      'equals', 'eq', 'not_equals', 'ne', 'not',
      'greater_than', 'gt', 'greater_than_or_equal', 'gte',
      'less_than', 'lt', 'less_than_or_equal', 'lte',
      'in', 'not_in', 'like', 'ilike',
      'contains', 'starts_with', 'ends_with',
      'is_null', 'is_not_null', 'between', 'not_between',
      'regex', 'not_regex'
    ];
  }
 
  describeProperty(property: keyof T): PropertyMetadata {
    const propertyName = property as string;
    const options = Reflect.getMetadata("property:options", this.entityClass.prototype, propertyName) || {};
    const validationRules = Reflect.getMetadata("validation:rules", this.entityClass.prototype, propertyName) || [];
    const isId = Reflect.getMetadata("property:id", this.entityClass.prototype, propertyName) || false;
    const isIndexed = Reflect.getMetadata("index:options", this.entityClass.prototype, propertyName) !== undefined;
 
    return {
      name: propertyName,
      type: options.type || 'unknown',
      required: options.required || isId,
      unique: options.unique || isId,
      indexed: isIndexed,
      description: options.description,
      validationRules,
      examples: this.generateExamples(propertyName, options.type)
    };
  }
 
  describeRelationship(relationship: string): RelationshipMetadata {
    const relationshipType = Reflect.getMetadata("relationship:type", this.entityClass.prototype, relationship);
    const relationshipOptions = Reflect.getMetadata("relationship:options", this.entityClass.prototype, relationship) || {};
 
    return {
      name: relationship,
      type: relationshipType || 'unknown',
      target: relationshipOptions.target?.name || 'unknown',
      inverse: relationshipOptions.inverse,
      required: relationshipOptions.required || false,
      description: relationshipOptions.description
    };
  }
 
  // Internal helper methods
  addCondition(condition: QueryCondition): void {
    this.conditions.push(condition);
  }
 
  addAsyncCondition(condition: AsyncConditionFunction<T>): void {
    this.asyncConditions.push(condition);
  }
 
  getConditions(): QueryCondition[] {
    return [...this.conditions];
  }
 
  getAsyncConditions(): AsyncConditionFunction<T>[] {
    return [...this.asyncConditions];
  }
 
  getSorts(): QuerySort[] {
    return [...this.sorts];
  }
 
  getIncludes(): QueryInclude[] {
    return [...this.includes];
  }
 
  getLimit(): number | undefined {
    return this.limitCount;
  }
 
  getOffset(): number | undefined {
    return this.offsetCount;
  }
 
  // Clone method for immutability
  private clone(): QueryBuilder<T> {
    const cloned = new QueryBuilder(this.entityClass);
    cloned.conditions = [...this.conditions];
    cloned.asyncConditions = [...this.asyncConditions];
    cloned.sorts = [...this.sorts];
    cloned.includes = [...this.includes];
    cloned.limitCount = this.limitCount;
    cloned.offsetCount = this.offsetCount;
    return cloned;
  }
 
  private generateExamples(propertyName: string, type: string): any[] {
    // Generate contextual examples based on property name and type
    if (propertyName.includes('email')) return ['user@example.com', 'admin@company.org'];
    if (propertyName.includes('age')) return [25, 30, 45];
    if (propertyName.includes('name')) return ['John Doe', 'Jane Smith'];
    if (propertyName.includes('status')) return ['active', 'inactive', 'pending'];
    Iif (type === 'number') return [1, 100, 500];
    Iif (type === 'string') return ['example', 'test', 'sample'];
    Iif (type === 'boolean') return [true, false];
    return [];
  }
}
 
/**
 * QueryConditionBuilder - handles the fluent condition building
 * This is where the progressive disclosure magic happens! ✨
 */
export class QueryConditionBuilder<T> implements IQueryConditionBuilder<T> {
  private queryBuilder: QueryBuilder<T>;
  private property: string;
  private logicalOperator?: 'and' | 'or' | 'not';
 
  constructor(queryBuilder: QueryBuilder<T>, property: string, logicalOperator?: 'and' | 'or' | 'not') {
    this.queryBuilder = queryBuilder;
    this.property = property;
    this.logicalOperator = logicalOperator;
  }
 
  // Comparison operators
  equals(value: any): IQueryBuilder<T> {
    return this.addCondition('equals', value);
  }
 
  eq(value: any): IQueryBuilder<T> {
    return this.addCondition('eq', value);
  }
 
  not(value: any): IQueryBuilder<T> {
    return this.addCondition('not', value);
  }
 
  ne(value: any): IQueryBuilder<T> {
    return this.addCondition('ne', value);
  }
 
  // Numeric operators
  gt(value: number): IQueryBuilder<T> {
    return this.addCondition('gt', value);
  }
 
  gte(value: number): IQueryBuilder<T> {
    return this.addCondition('gte', value);
  }
 
  lt(value: number): IQueryBuilder<T> {
    return this.addCondition('lt', value);
  }
 
  lte(value: number): IQueryBuilder<T> {
    return this.addCondition('lte', value);
  }
 
  between(min: number, max: number): IQueryBuilder<T> {
    return this.addCondition('between', { min, max });
  }
 
  // Array operators
  in(values: any[]): IQueryBuilder<T> {
    return this.addCondition('in', values);
  }
 
  notIn(values: any[]): IQueryBuilder<T> {
    return this.addCondition('not_in', values);
  }
 
  // String operators
  like(pattern: string): IQueryBuilder<T> {
    return this.addCondition('like', pattern);
  }
 
  ilike(pattern: string): IQueryBuilder<T> {
    return this.addCondition('ilike', pattern);
  }
 
  contains(value: string): IQueryBuilder<T> {
    return this.addCondition('contains', value);
  }
 
  startsWith(value: string): IQueryBuilder<T> {
    return this.addCondition('starts_with', value);
  }
 
  endsWith(value: string): IQueryBuilder<T> {
    return this.addCondition('ends_with', value);
  }
 
  regex(pattern: RegExp): IQueryBuilder<T> {
    return this.addCondition('regex', pattern);
  }
 
  // Null operators
  isNull(): IQueryBuilder<T> {
    return this.addCondition('is_null', null);
  }
 
  isNotNull(): IQueryBuilder<T> {
    return this.addCondition('is_not_null', null);
  }
 
  // Async operators for AI agents
  equalsAsync(valueProvider: () => Promise<any>): IQueryBuilder<T> {
    return this.addAsyncCondition('equals', valueProvider);
  }
 
  matchesAsync(condition: AsyncConditionFunction<T>): IQueryBuilder<T> {
    // Use the public method to add async condition
    this.queryBuilder.addAsyncCondition(condition);
    return this.queryBuilder;
  }
 
  private addCondition(operator: QueryOperator, value: any): IQueryBuilder<T> {
    const condition: QueryCondition = {
      property: this.property,
      operator,
      value
    };
 
    // QueryBuilder should already be cloned when passed to constructor
    this.queryBuilder.addCondition(condition);
    return this.queryBuilder;
  }
 
  private addAsyncCondition(operator: QueryOperator, valueProvider: () => Promise<any>): IQueryBuilder<T> {
    const condition: QueryCondition = {
      property: this.property,
      operator,
      value: valueProvider,
      async: true
    };
 
    // QueryBuilder should already be cloned when passed to constructor
    this.queryBuilder.addCondition(condition);
    return this.queryBuilder;
  }
}
 
/**
 * Factory function to create a QueryBuilder for a specific entity
 */
export function createQueryBuilder<T>(entityClass: new (...args: any[]) => T): IQueryBuilder<T> {
  return new QueryBuilder(entityClass);
}