@simonecoelhosfo/optimizely-mcp-server
Version:
Optimizely MCP Server for AI assistants with integrated CLI tools
221 lines • 6.8 kB
TypeScript
/**
* Advanced SQL Query Parser - Phase 3.2 Task 3.2.2
*
* This parser enhances the basic SQL parsing capabilities in QueryAnalysisEngine
* with advanced features needed for complex analytics queries:
*
* 1. Subquery parsing and nested field extraction
* 2. CTE (Common Table Expression) support
* 3. Window function analysis
* 4. Complex JOIN pattern detection
* 5. Advanced aggregation function analysis
* 6. Dynamic field reference resolution
*
* The parser is designed to handle the complex SQL queries that the Dynamic
* Analytics Query Engine will generate when flattening nested JSON structures.
*/
import { ParsedQuery } from './QueryAnalysisEngine.js';
import { EntityType } from './types.js';
/**
* Enhanced parsed query with advanced SQL features
*/
export interface AdvancedParsedQuery extends ParsedQuery {
/** Common Table Expressions found in the query */
ctes: CTEDefinition[];
/** Window functions used in the query */
windowFunctions: WindowFunction[];
/** Aggregate functions and their contexts */
aggregates: AggregateFunction[];
/** Dynamic field references that need runtime resolution */
dynamicReferences: DynamicFieldReference[];
/** Query complexity metrics */
complexityMetrics: QueryComplexityMetrics;
/** Optimization opportunities detected */
optimizationOpportunities: OptimizationOpportunity[];
}
/**
* Common Table Expression definition
*/
export interface CTEDefinition {
/** Name of the CTE */
name: string;
/** Column names defined by the CTE */
columns?: string[];
/** The CTE query definition */
query: string;
/** Fields referenced within the CTE */
referencedFields: string[];
/** Whether the CTE is recursive */
isRecursive: boolean;
}
/**
* Window function analysis
*/
export interface WindowFunction {
/** Function name (ROW_NUMBER, RANK, etc.) */
functionName: string;
/** Partition BY clause fields */
partitionBy: string[];
/** ORDER BY clause fields */
orderBy: string[];
/** Window frame specification */
frameSpec?: WindowFrame;
/** Context where the window function appears */
context: 'SELECT' | 'WHERE' | 'HAVING' | 'ORDER_BY';
}
/**
* Window frame specification
*/
export interface WindowFrame {
/** Frame type (ROWS, RANGE, GROUPS) */
type: 'ROWS' | 'RANGE' | 'GROUPS';
/** Frame start boundary */
start: FrameBoundary;
/** Frame end boundary */
end?: FrameBoundary;
}
/**
* Frame boundary specification
*/
export interface FrameBoundary {
/** Boundary type */
type: 'UNBOUNDED_PRECEDING' | 'CURRENT_ROW' | 'UNBOUNDED_FOLLOWING' | 'PRECEDING' | 'FOLLOWING';
/** Offset value for PRECEDING/FOLLOWING */
offset?: number;
}
/**
* Aggregate function analysis
*/
export interface AggregateFunction {
/** Function name (SUM, COUNT, AVG, etc.) */
functionName: string;
/** Arguments to the function */
arguments: string[];
/** DISTINCT modifier */
distinct: boolean;
/** Filter clause (WHERE within aggregate) */
filter?: string;
/** Fields referenced in the aggregate */
referencedFields: string[];
}
/**
* Dynamic field reference that needs runtime resolution
*/
export interface DynamicFieldReference {
/** Original field expression */
expression: string;
/** Type of dynamic reference */
type: 'JSON_EXTRACT' | 'ARRAY_ELEMENT' | 'COMPUTED_FIELD' | 'CONDITIONAL_FIELD';
/** Base entity being referenced */
baseEntity: string;
/** Path components for resolution */
pathComponents: string[];
/** Conditions for conditional fields */
conditions?: ConditionalField[];
}
/**
* Conditional field specification
*/
export interface ConditionalField {
/** Condition expression */
condition: string;
/** Field to use when condition is true */
trueField: string;
/** Field to use when condition is false */
falseField?: string;
}
/**
* Query complexity metrics
*/
export interface QueryComplexityMetrics {
/** Total number of tables/entities referenced */
tableCount: number;
/** Number of JOIN operations */
joinCount: number;
/** Maximum nesting depth of subqueries */
maxSubqueryDepth: number;
/** Number of aggregate functions */
aggregateCount: number;
/** Number of window functions */
windowFunctionCount: number;
/** Number of dynamic field references */
dynamicFieldCount: number;
/** Estimated cartesian product size */
estimatedCartesianSize: number;
/** Overall complexity score (0-100) */
complexityScore: number;
}
/**
* Optimization opportunity detected by parser
*/
export interface OptimizationOpportunity {
/** Type of optimization */
type: 'INDEX_RECOMMENDATION' | 'QUERY_REWRITE' | 'CACHING_OPPORTUNITY' | 'PARTITION_PRUNING';
/** Severity/impact level */
impact: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
/** Description of the opportunity */
description: string;
/** Suggested implementation */
suggestion: string;
/** Estimated performance improvement */
estimatedImprovement: string;
/** Fields or tables affected */
affectedElements: string[];
}
/**
* Advanced SQL parser with sophisticated analysis capabilities
*/
export declare class AdvancedSQLParser {
private readonly version;
constructor();
/**
* Parse a SQL query with advanced analysis
*/
parseQuery(query: string, primaryEntity: EntityType): AdvancedParsedQuery;
/**
* Perform basic SQL parsing (similar to QueryAnalysisEngine)
*/
private performBasicParsing;
/**
* Extract Common Table Expressions from query
*/
private extractCTEs;
/**
* Extract window functions from query
*/
private extractWindowFunctions;
/**
* Parse window frame specification
*/
private parseWindowFrame;
/**
* Parse individual frame boundary
*/
private parseFrameBoundary;
/**
* Extract aggregate functions from query
*/
private extractAggregates;
/**
* Extract dynamic field references that need runtime resolution
*/
private extractDynamicReferences;
/**
* Calculate comprehensive query complexity metrics
*/
private calculateComplexityMetrics;
/**
* Identify optimization opportunities
*/
private identifyOptimizationOpportunities;
private extractBasicFieldReferences;
private extractFilterFields;
private extractProjectionFields;
private extractGroupByFields;
private extractOrderByFields;
private extractJoins;
private extractSubqueries;
private extractFieldsFromExpression;
private calculateSubqueryDepth;
}
//# sourceMappingURL=AdvancedSQLParser.d.ts.map