SQL Alias-Based Code Completion
This document describes the intelligent SQL code completion feature that provides context-aware autocompletion with alias support in the Monaco Editor.
Features
Section titled “Features”1. Alias-Based Column Completion
Section titled “1. Alias-Based Column Completion”When you define a table alias in your SQL query, typing the alias followed by a dot (.) will suggest columns from the referenced table.
Supported Patterns:
| Pattern | Example | Result |
|---|---|---|
FROM table AS alias |
FROM employee AS e WHERE e. |
employee columns |
FROM table alias |
FROM employee e WHERE e. |
employee columns |
JOIN table AS alias |
JOIN department AS d ON d. |
department columns |
JOIN table alias |
LEFT JOIN salary s ON s. |
salary columns |
schema.table alias |
FROM employees.employee e WHERE e. |
employee columns |
| Multiple aliases | FROM a AS x JOIN b AS y |
Both x. and y. work |
| CTE references | WITH cte AS (...) SELECT cte. |
CTE columns |
| Direct table | employee. |
employee columns |
2. Context-Aware Completions
Section titled “2. Context-Aware Completions”The completion system intelligently shows suggestions based on SQL context:
Columns are shown only after:
SELECTkeywordWHEREclauseAND,ORoperatorsON(in JOIN conditions)SET(in UPDATE statements)HAVINGclauseORDER BY,GROUP BYclauses- Comma (
,) in column lists
Columns are NOT shown when:
- Typing keywords like
FROM,JOIN,WHERE - After
SELECT *(expecting keyword, not column)
3. Prioritized Suggestions
Section titled “3. Prioritized Suggestions”Suggestions are sorted by relevance:
| Priority | Type | Description |
|---|---|---|
| 1st | Keywords | SQL keywords (SELECT, FROM, WHERE, etc.) |
| 2nd | Functions | SQL functions (COUNT, SUM, AVG, etc.) |
| 3rd | Tables | Database tables |
| 4th | Snippets | Query templates |
| 5th | Columns | Table columns (context-dependent) |
Architecture
Section titled “Architecture”Module Structure
Section titled “Module Structure”src/lib/sql/├── alias-extractor.ts # Core alias extraction logic├── types.ts # TypeScript interfaces└── index.ts # Module exports
src/lib/editor/└── sql-completions.ts # Monaco completion provider (consumes the alias extractor)Key Components
Section titled “Key Components”1. Alias Extractor (src/lib/sql/alias-extractor.ts)
Section titled “1. Alias Extractor (src/lib/sql/alias-extractor.ts)”Lightweight regex-based SQL parser that extracts table aliases without external dependencies.
Functions:
extractAliases(sql: string)- Extract all table aliases from a SQL queryresolveAlias(identifier: string, aliases: Map)- Resolve an alias to its table name
How it works:
- Preprocesses SQL to remove comments and string literals
- Extracts FROM clause aliases
- Extracts JOIN clause aliases
- Extracts CTE (WITH clause) aliases
- Returns a Map of alias → table name
2. Completion Provider (src/lib/editor/sql-completions.ts)
Section titled “2. Completion Provider (src/lib/editor/sql-completions.ts)”Monaco Editor completion provider that integrates with the alias extractor. It is implemented as
registerSQLCompletionProvider(monaco, schemaCompletionCache), which calls
registerCompletionItemProvider('sql', …) with trigger characters . and space. It is registered
from src/components/QueryEditor.tsx in a useEffect that returns the disposable for cleanup.
Dot-triggered completion flow:
User types: "e." ↓1. Try direct table lookup: columnMap.get("e") ↓ (not found)2. Extract aliases from query text ↓3. Resolve "e" → "employee" ↓4. Find columns: columnMap.get("employee") ↓5. Return column suggestionsEdge Cases Handled
Section titled “Edge Cases Handled”- SQL Keywords as Aliases: Filters out
ON,WHERE,AND, etc. - Comments: Removes
--and/* */before parsing - String Literals: Replaces with placeholder to avoid false matches
- Case Insensitivity: Alias lookup is case-insensitive
- Schema Prefixes: Handles
schema.tableformat (e.g.,employees.employee)
Performance Considerations
Section titled “Performance Considerations”- No external SQL parser: Keeps bundle size small
- Regex-based parsing: Fast execution (<10ms for typical queries)
- Lazy evaluation: Alias extraction only runs on dot-trigger
- Cursor-limited parsing: Only parses text from start to cursor position
- Early exit: Skips parsing if no FROM/JOIN/WITH keywords found
Examples
Section titled “Examples”Basic Alias Usage
Section titled “Basic Alias Usage”SELECT e.first_name, e.last_nameFROM employee eWHERE e.hire_date > '2020-01-01'Typing e. after defining FROM employee e will suggest all employee columns.
Multiple Table Aliases
Section titled “Multiple Table Aliases”SELECT e.first_name, d.dept_name, s.amountFROM employee eJOIN department_employee de ON de.employee_id = e.idJOIN department d ON d.id = de.department_idJOIN salary s ON s.employee_id = e.idEach alias (e, de, d, s) resolves to its respective table.
CTE Support
Section titled “CTE Support”WITH active_employees AS ( SELECT * FROM employee WHERE status = 'active')SELECT ae.first_nameFROM active_employees aeWHERE ae.department_id = 1The ae alias resolves to the CTE active_employees.
Integration
Section titled “Integration”The alias completion is automatically available in the SQL editor. No configuration required.
import { extractAliases, resolveAlias } from '@/lib/sql';
// Extract aliases from a queryconst { aliases } = extractAliases('SELECT * FROM employee e WHERE e.id = 1');
// Resolve an aliasconst tableName = resolveAlias('e', aliases); // Returns 'employee'Type Definitions
Section titled “Type Definitions”interface TableAlias { alias: string; // e.g., 'e' tableName: string; // e.g., 'employee' schema?: string; // e.g., 'employees' source: 'from' | 'join' | 'cte';}
interface AliasExtractionResult { aliases: Map<string, TableAlias>; hasTableReferences: boolean;}Related Files
Section titled “Related Files”| File | Description |
|---|---|
src/lib/sql/alias-extractor.ts |
Core alias parsing logic (extractAliases, resolveAlias) |
src/lib/sql/types.ts |
Type definitions (TableAlias, AliasExtractionResult) |
src/lib/sql/index.ts |
Module exports |
src/lib/editor/sql-completions.ts |
Monaco completion provider (dot/space-triggered; consumes the alias extractor) |
src/components/QueryEditor.tsx |
Hosts the Monaco editor and registers the provider |