All files / server/explain sqlite-parser.ts

100% Statements 52/52
100% Branches 32/32
100% Functions 3/3
100% Lines 52/52

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                                                                  57x     57x 57x 21x             36x     36x 15x                 21x     21x 3x               18x 18x 2x             16x 5x 2x   3x 1x   2x 1x   1x       11x 4x       7x 3x       4x 2x       2x                             39x 39x 39x     39x   39x 57x     57x 21x       57x 15x     57x               57x     57x 46x   11x 11x 10x 8x   10x     1x         39x                   39x   57x     39x              
/**
 * SQLite EXPLAIN QUERY PLAN output parser
 * Parses SQLite EXPLAIN QUERY PLAN output and normalizes to common structure
 */
 
import type { ExplainOperation, ExplainResult, ExplainSummary } from '../types/executor'
 
/**
 * SQLite EXPLAIN QUERY PLAN row structure
 */
interface SQLiteExplainRow {
  id: number
  parent: number
  notused: number
  detail: string
}
 
/**
 * Parse SQLite EXPLAIN QUERY PLAN detail string
 *
 * Examples:
 * "SCAN employees"
 * "SEARCH employees USING INDEX idx_org_id (organisation_id=?)"
 * "SEARCH departments USING INTEGER PRIMARY KEY (rowid=?)"
 * "USE TEMP B-TREE FOR ORDER BY"
 * "COMPOUND QUERY"
 */
function parseSQLiteDetail(detail: string): {
  type: string
  table?: string
  index?: string
  filter?: string
} {
  const detailLower = detail.toLowerCase()
 
  // SCAN = sequential scan
  const scanMatch = detail.match(/^SCAN\s+(\S+)/i)
  if (scanMatch) {
    return {
      type: 'Seq Scan',
      table: scanMatch[1],
    }
  }
 
  // SEARCH USING INDEX = index scan
  const indexMatch = detail.match(
    /^SEARCH\s+(\S+)\s+USING\s+(?:COVERING\s+)?INDEX\s+(\S+)(?:\s+\((.+)\))?/i
  )
  if (indexMatch) {
    return {
      type: 'Index Scan',
      table: indexMatch[1],
      index: indexMatch[2],
      filter: indexMatch[3],
    }
  }
 
  // SEARCH USING INTEGER PRIMARY KEY = primary key lookup
  const pkMatch = detail.match(
    /^SEARCH\s+(\S+)\s+USING\s+INTEGER\s+PRIMARY\s+KEY\s+\((.+)\)/i
  )
  if (pkMatch) {
    return {
      type: 'Primary Key Lookup',
      table: pkMatch[1],
      filter: pkMatch[2],
    }
  }
 
  // SEARCH without index = partial scan
  const searchMatch = detail.match(/^SEARCH\s+(\S+)/i)
  if (searchMatch) {
    return {
      type: 'Search',
      table: searchMatch[1],
    }
  }
 
  // USE TEMP B-TREE = sorting/grouping
  if (detailLower.includes('temp b-tree')) {
    if (detailLower.includes('order by')) {
      return { type: 'Sort' }
    }
    if (detailLower.includes('group by')) {
      return { type: 'Group' }
    }
    if (detailLower.includes('distinct')) {
      return { type: 'Distinct' }
    }
    return { type: 'Temp B-Tree' }
  }
 
  // COMPOUND QUERY = UNION/INTERSECT/EXCEPT
  if (detailLower.includes('compound')) {
    return { type: 'Compound Query' }
  }
 
  // SUBQUERY = subquery
  if (detailLower.includes('subquery')) {
    return { type: 'Subquery' }
  }
 
  // CO-ROUTINE = CTE or view materialization
  if (detailLower.includes('co-routine')) {
    return { type: 'Coroutine' }
  }
 
  // Default: use the detail as type
  return { type: detail }
}
 
/**
 * Parse SQLite EXPLAIN QUERY PLAN output
 *
 * SQLite EXPLAIN QUERY PLAN returns rows with columns:
 * id, parent, notused, detail
 *
 * The 'detail' column contains human-readable operation descriptions
 */
export function parseSQLiteExplain(
  rows: SQLiteExplainRow[],
  sqlQuery: { sql: string; params?: unknown[] }
): ExplainResult {
  const operations: ExplainOperation[] = []
  const usedIndexes: string[] = []
  let hasSequentialScans = false
 
  // Build a map of id -> operation for parent lookup
  const opMap = new Map<number, ExplainOperation>()
 
  for (const row of rows) {
    const parsed = parseSQLiteDetail(row.detail)
 
    // Track sequential scans
    if (parsed.type === 'Seq Scan') {
      hasSequentialScans = true
    }
 
    // Track used indexes
    if (parsed.index) {
      usedIndexes.push(parsed.index)
    }
 
    const operation: ExplainOperation = {
      type: parsed.type,
      table: parsed.table,
      index: parsed.index,
      filter: parsed.filter,
      details: row.detail, // Keep original detail for reference
    }
 
    opMap.set(row.id, operation)
 
    // Find parent and add as child, or add to root
    if (row.parent === 0) {
      operations.push(operation)
    } else {
      const parent = opMap.get(row.parent)
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(operation)
      } else {
        // Parent not found, add to root
        operations.push(operation)
      }
    }
  }
 
  const summary: ExplainSummary = {
    database: 'sqlite',
    planningTime: undefined, // SQLite doesn't report timing
    executionTime: undefined,
    totalCost: undefined, // SQLite doesn't report costs
    hasSequentialScans,
    usedIndexes: [...new Set(usedIndexes)],
  }
 
  // Format raw output
  const rawLines = [
    'id\tparent\tdetail',
    ...rows.map((r) => `${r.id}\t${r.parent}\t${r.detail}`),
  ]
 
  return {
    operations,
    summary,
    raw: rawLines.join('\n'),
    sql: sqlQuery,
  }
}