-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstructure-analyzer.ts
More file actions
328 lines (280 loc) · 9.12 KB
/
Copy pathstructure-analyzer.ts
File metadata and controls
328 lines (280 loc) · 9.12 KB
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
import type { EditorState } from "@codemirror/state";
import type { SqlParser } from "./types.js";
/**
* Represents a SQL statement with position information
*/
export interface SqlStatement {
/** Start position of the statement in the document */
from: number;
/** End position of the statement in the document */
to: number;
/** First line number of the statement (1-based) */
lineFrom: number;
/** Last line number of the statement (1-based) */
lineTo: number;
/** The actual SQL content */
content: string;
/** Type of SQL statement */
type: "select" | "insert" | "update" | "delete" | "create" | "drop" | "alter" | "use" | "other";
/** Whether this statement is syntactically valid */
isValid: boolean;
}
/**
* Analyzes SQL documents to extract statement boundaries and information
* for use with gutter markers and other SQL-aware features.
*/
export class SqlStructureAnalyzer {
private parser: SqlParser;
private cache = new Map<string, SqlStatement[]>();
constructor(parser: SqlParser) {
this.parser = parser;
}
/**
* Analyzes the document and extracts all SQL statements
*/
async analyzeDocument(state: EditorState): Promise<SqlStatement[]> {
const content = state.doc.toString();
const cacheKey = this.generateCacheKey(content);
const existingValue = this.cache.get(cacheKey);
if (existingValue) {
return existingValue;
}
const statements = await this.extractStatements(content, state);
this.cache.set(cacheKey, statements);
// Keep cache size reasonable
if (this.cache.size > 10) {
const firstKey = this.cache.keys().next().value;
if (firstKey !== undefined) {
this.cache.delete(firstKey);
}
}
return statements;
}
/**
* Gets the SQL statement at a specific cursor position
*/
async getStatementAtPosition(state: EditorState, position: number): Promise<SqlStatement | null> {
const statements = await this.analyzeDocument(state);
return statements.find((stmt) => position >= stmt.from && position <= stmt.to) || null;
}
/**
* Gets all SQL statements that intersect with a selection range
*/
async getStatementsInRange(
state: EditorState,
from: number,
to: number,
): Promise<SqlStatement[]> {
const statements = await this.analyzeDocument(state);
return statements.filter(
(stmt) => stmt.from <= to && stmt.to >= from, // Statements that overlap with the range
);
}
private async extractStatements(content: string, state: EditorState): Promise<SqlStatement[]> {
const statements: SqlStatement[] = [];
// Split content by semicolons to find potential statement boundaries
const parts = this.splitByStatementSeparators(content);
let currentPosition = 0;
for (const part of parts) {
const trimmedPart = part.trim();
if (trimmedPart.length === 0) {
currentPosition += part.length;
continue;
}
const from = currentPosition + part.indexOf(trimmedPart);
const to = from + trimmedPart.length;
const fromLine = state.doc.lineAt(from);
const toLine = state.doc.lineAt(to);
// Strip comments from the statement content
const strippedContent = this.stripComments(trimmedPart);
// Skip if the statement is empty after stripping comments
if (strippedContent.trim().length === 0 || strippedContent.trim() === ";") {
currentPosition += part.length;
continue;
}
// Parse the statement to determine validity and type (use stripped content)
const parseResult = await this.parser.parse(strippedContent, { state });
const type = this.determineStatementType(strippedContent);
// Remove trailing semicolon from content for cleaner display
const cleanContent = strippedContent.endsWith(";")
? strippedContent.slice(0, -1).trim()
: strippedContent.trim();
statements.push({
from,
to,
lineFrom: fromLine.number,
lineTo: toLine.number,
content: cleanContent,
type,
isValid: parseResult.success,
});
currentPosition += part.length;
}
return statements;
}
private splitByStatementSeparators(content: string): string[] {
// More sophisticated splitting that handles semicolons in strings and comments
const parts: string[] = [];
let current = "";
let inString = false;
let stringChar = "";
let inSingleLineComment = false;
let inMultiLineComment = false;
let i = 0;
while (i < content.length) {
const char = content[i];
const nextChar = content[i + 1];
// Handle single-line comments (-- comment)
if (!inString && !inMultiLineComment && char === "-" && nextChar === "-") {
inSingleLineComment = true;
current += char + nextChar;
i += 2;
continue;
}
// Handle multi-line comments (/* comment */)
if (!inString && !inSingleLineComment && char === "/" && nextChar === "*") {
inMultiLineComment = true;
current += char + nextChar;
i += 2;
continue;
}
// End multi-line comment
if (inMultiLineComment && char === "*" && nextChar === "/") {
inMultiLineComment = false;
current += char + nextChar;
i += 2;
continue;
}
// End single-line comment on newline
if (inSingleLineComment && (char === "\n" || char === "\r")) {
inSingleLineComment = false;
current += char;
i++;
continue;
}
// Include characters inside comments (for proper position tracking)
if (inSingleLineComment || inMultiLineComment) {
current += char;
i++;
continue;
}
// Handle string literals
if (!inString && (char === "'" || char === '"' || char === "`")) {
inString = true;
stringChar = char;
current += char;
} else if (inString && char === stringChar) {
// Check for escaped quotes
if (nextChar === stringChar) {
current += char + nextChar;
i += 2;
continue;
}
inString = false;
stringChar = "";
current += char;
} else if (!inString && char === ";") {
current += char;
parts.push(current);
current = "";
} else {
current += char;
}
i++;
}
if (current.trim()) {
parts.push(current);
}
return parts;
}
private determineStatementType(sql: string): SqlStatement["type"] {
const trimmed = sql.trim().toLowerCase();
if (trimmed.startsWith("select")) return "select";
if (trimmed.startsWith("insert")) return "insert";
if (trimmed.startsWith("update")) return "update";
if (trimmed.startsWith("delete")) return "delete";
if (trimmed.startsWith("create")) return "create";
if (trimmed.startsWith("drop")) return "drop";
if (trimmed.startsWith("alter")) return "alter";
if (trimmed.startsWith("use")) return "use";
return "other";
}
private stripComments(sql: string): string {
let result = "";
let inString = false;
let stringChar = "";
let inSingleLineComment = false;
let inMultiLineComment = false;
let i = 0;
while (i < sql.length) {
const char = sql[i];
const nextChar = sql[i + 1];
// Handle single-line comments (-- comment)
if (!inString && !inMultiLineComment && char === "-" && nextChar === "-") {
inSingleLineComment = true;
i += 2;
continue;
}
// Handle multi-line comments (/* comment */)
if (!inString && !inSingleLineComment && char === "/" && nextChar === "*") {
inMultiLineComment = true;
i += 2;
continue;
}
// End multi-line comment
if (inMultiLineComment && char === "*" && nextChar === "/") {
inMultiLineComment = false;
i += 2;
continue;
}
// End single-line comment on newline
if (inSingleLineComment && (char === "\n" || char === "\r")) {
inSingleLineComment = false;
result += char;
i++;
continue;
}
// Skip characters inside comments
if (inSingleLineComment || inMultiLineComment) {
i++;
continue;
}
// Handle string literals
if (!inString && (char === "'" || char === '"' || char === "`")) {
inString = true;
stringChar = char;
result += char;
} else if (inString && char === stringChar) {
// Check for escaped quotes
if (nextChar === stringChar) {
result += char + nextChar;
i += 2;
continue;
}
inString = false;
stringChar = "";
result += char;
} else {
result += char;
}
i++;
}
return result;
}
private generateCacheKey(content: string): string {
// Simple hash function for caching
let hash = 0;
for (let i = 0; i < content.length; i++) {
const char = content.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32-bit integer
}
return hash.toString();
}
/**
* Clears the internal cache
*/
clearCache(): void {
this.cache.clear();
}
}