2 files changed
+131
No files matched your search
@@ -124,6 +124,62 @@ describe("SQL Server datepart completion", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("SQL Server local variable completion", () => {
|
||||
const completionItems = (sql: string, cursor = sql.length) =>
|
||||
buildSqlCompletionItems(sql, cursor, {
|
||||
tables: [],
|
||||
columnsByTable: new Map(),
|
||||
databaseType: "sqlserver",
|
||||
dialect: "sqlserver",
|
||||
});
|
||||
|
||||
it("suggests variables declared earlier in the current batch", () => {
|
||||
const sql = `CREATE OR ALTER PROCEDURE dbo.find_customer AS
|
||||
BEGIN
|
||||
DECLARE @customer_id INT = 1,
|
||||
@customer_name NVARCHAR(100);
|
||||
SELECT @customer_`;
|
||||
|
||||
expect(completionItems(sql)).toEqual(expect.arrayContaining([expect.objectContaining({ label: "@customer_id", type: "variable" }), expect.objectContaining({ label: "@customer_name", type: "variable" })]));
|
||||
});
|
||||
|
||||
it("ignores later declarations and declarations inside comments or strings", () => {
|
||||
const sql = `DECLARE @visible INT;
|
||||
-- DECLARE @commented INT;
|
||||
SELECT 'DECLARE @string_value INT';
|
||||
SELECT @|
|
||||
DECLARE @later INT;`;
|
||||
const cursor = sql.indexOf("|");
|
||||
const variables = completionItems(sql.replace("|", ""), cursor)
|
||||
.filter((item) => item.type === "variable")
|
||||
.map((item) => item.label);
|
||||
|
||||
expect(variables).toContain("@visible");
|
||||
expect(variables).not.toContain("@commented");
|
||||
expect(variables).not.toContain("@string_value");
|
||||
expect(variables).not.toContain("@later");
|
||||
});
|
||||
|
||||
it("does not leak variables across GO batch boundaries", () => {
|
||||
const sql = `DECLARE @old_batch INT;
|
||||
GO
|
||||
DECLARE @current_batch INT;
|
||||
SELECT @`;
|
||||
const variables = completionItems(sql)
|
||||
.filter((item) => item.type === "variable")
|
||||
.map((item) => item.label);
|
||||
|
||||
expect(variables).toContain("@current_batch");
|
||||
expect(variables).not.toContain("@old_batch");
|
||||
});
|
||||
|
||||
it("preserves SQL Server system variable completion", () => {
|
||||
const sql = "DECLARE @row_id INT; SELECT @@row";
|
||||
|
||||
expect(completionItems(sql)).toEqual(expect.arrayContaining([expect.objectContaining({ label: "@@ROWCOUNT", type: "keyword" })]));
|
||||
});
|
||||
});
|
||||
|
||||
describe("MySQL DESCRIBE table completion", () => {
|
||||
it.each(["DESC", "DESCRIBE"])("treats %s as a table-name context", (keyword) => {
|
||||
const sql = `${keyword} ord`;
|
||||
|
||||
@@ -1474,6 +1474,7 @@ export interface SqlCompletionContext {
|
||||
prefix: string;
|
||||
replacementRange?: { start: number; end: number };
|
||||
preferredValueKeywords?: string[];
|
||||
localVariables?: string[];
|
||||
qualifier?: string;
|
||||
qualifierParts?: string[];
|
||||
suggestTables: boolean;
|
||||
@@ -1702,6 +1703,7 @@ class SqlCompletionProvider {
|
||||
|
||||
const preferReferencedColumns = hasMatchingReferencedColumnPrefix(context, this.input.columnsByTable);
|
||||
this.items.push(...customSnippetItems);
|
||||
this.items.push(...buildSqlServerLocalVariableItems(context));
|
||||
if (!pendingJoinKeyword && !context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions) {
|
||||
if (!preferReferencedColumns) {
|
||||
this.items.push(...buildSnippetItems(context.prefix, snippets.filter(shouldFormatBuiltinSnippet), this.input.keywordCase, this.databaseType));
|
||||
@@ -2569,6 +2571,7 @@ export function getSqlCompletionContext(sql: string, cursor: number, options: Sq
|
||||
const selectListWildcardAfterCursor = isStandaloneSelectWildcard(rawStatement, cursor - statementSpan.start, selectListColumnContext, statementKind, resolveSqlDialectId(options));
|
||||
const dataTypeContext = isCreateTableColumnTypeContext(beforeToken, options.databaseType);
|
||||
const preferredValueKeywords = sqlServerDatepartCompletionValues(beforeCursor, options.databaseType);
|
||||
const localVariables = prefix.startsWith("@") ? collectSqlServerLocalVariables(sql, cursor, options) : undefined;
|
||||
const preferredKeywords = qualifier ? [] : preferredKeywordsForCompletion(beforeCursor, beforeToken, selectListColumnContext, exclusiveTableSuggestions, updateInfo, deleteInfo, options.databaseType);
|
||||
const contextKind = detectCompletionContextKind({
|
||||
qualifier,
|
||||
@@ -2588,6 +2591,7 @@ export function getSqlCompletionContext(sql: string, cursor: number, options: Sq
|
||||
return {
|
||||
prefix,
|
||||
preferredValueKeywords,
|
||||
localVariables,
|
||||
qualifier: insertInfo ? undefined : qualifier,
|
||||
qualifierParts: insertInfo ? undefined : qualifierParts,
|
||||
suggestTables: insertInfo ? false : afterTableTrigger,
|
||||
@@ -2625,6 +2629,66 @@ export function getSqlCompletionContext(sql: string, cursor: number, options: Sq
|
||||
};
|
||||
}
|
||||
|
||||
const SQLSERVER_DECLARATION_BOUNDARY_KEYWORDS = new Set(["alter", "begin", "create", "declare", "delete", "drop", "end", "exec", "execute", "go", "if", "insert", "merge", "print", "raiserror", "return", "select", "set", "throw", "update", "while", "with"]);
|
||||
|
||||
function collectSqlServerLocalVariables(sql: string, cursor: number, options: SqlSemanticBuildOptions): string[] | undefined {
|
||||
if (resolveSqlDialectId(options) !== "sqlserver") return undefined;
|
||||
const beforeCursor = sql.slice(0, Math.max(0, Math.min(cursor, sql.length)));
|
||||
const allTokens = tokenizeSqlSemantic(beforeCursor, "sqlserver");
|
||||
let batchStart = 0;
|
||||
for (const token of allTokens) {
|
||||
if (token.kind !== "word" || token.normalized !== "go") continue;
|
||||
const lineStart = beforeCursor.lastIndexOf("\n", token.span.start - 1) + 1;
|
||||
const lineEndIndex = beforeCursor.indexOf("\n", token.span.end);
|
||||
const lineEnd = lineEndIndex < 0 ? beforeCursor.length : lineEndIndex;
|
||||
if (/^\s*go(?:\s+\d+)?\s*$/i.test(beforeCursor.slice(lineStart, lineEnd))) {
|
||||
batchStart = lineEndIndex < 0 ? lineEnd : lineEnd + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const batchSql = beforeCursor.slice(batchStart);
|
||||
const tokens = tokenizeSqlSemantic(batchSql, "sqlserver").filter((token) => token.kind !== "comment" && token.kind !== "string");
|
||||
const variables: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (let index = 0; index < tokens.length; index += 1) {
|
||||
const declare = tokens[index];
|
||||
if (declare?.kind !== "word" || declare.normalized !== "declare") continue;
|
||||
const declarationDepth = declare.depth;
|
||||
let expectVariable = true;
|
||||
|
||||
for (let declarationIndex = index + 1; declarationIndex < tokens.length; declarationIndex += 1) {
|
||||
const token = tokens[declarationIndex]!;
|
||||
if (token.depth < declarationDepth || (token.depth === declarationDepth && token.text === ";")) break;
|
||||
if (token.depth === declarationDepth && token.kind === "word" && SQLSERVER_DECLARATION_BOUNDARY_KEYWORDS.has(token.normalized) && sqlTokenStartsLine(batchSql, token.span.start)) {
|
||||
break;
|
||||
}
|
||||
if (expectVariable) {
|
||||
if (token.kind === "word" && /^@[A-Za-z_@$#][\w@$#]*$/u.test(token.text) && !token.text.startsWith("@@")) {
|
||||
const next = tokens[declarationIndex + 1];
|
||||
if (next && next.text !== "," && next.text !== ";") {
|
||||
const key = token.text.toLowerCase();
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
variables.push(token.text);
|
||||
}
|
||||
}
|
||||
expectVariable = false;
|
||||
}
|
||||
} else if (token.depth === declarationDepth && token.text === ",") {
|
||||
expectVariable = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return variables;
|
||||
}
|
||||
|
||||
function sqlTokenStartsLine(sql: string, position: number): boolean {
|
||||
const lineStart = sql.lastIndexOf("\n", Math.max(0, position - 1)) + 1;
|
||||
return sql.slice(lineStart, position).trim().length === 0;
|
||||
}
|
||||
|
||||
function sqlServerDatepartCompletionValues(beforeCursor: string, databaseType?: DatabaseType): string[] | undefined {
|
||||
if (databaseType !== "sqlserver") return undefined;
|
||||
const call = findActiveFunctionCall(beforeCursor);
|
||||
@@ -4282,6 +4346,17 @@ function buildPreferredKeywordItems(prefix: string, keywords: string[], keywordC
|
||||
}));
|
||||
}
|
||||
|
||||
function buildSqlServerLocalVariableItems(context: SqlCompletionContext): SqlCompletionItem[] {
|
||||
return (context.localVariables ?? [])
|
||||
.filter((variable) => matchesPrefix(variable, context.prefix))
|
||||
.map((variable) => ({
|
||||
label: variable,
|
||||
type: "variable" as const,
|
||||
detail: "local variable",
|
||||
boost: computeBoost(variable, context.prefix) + 4_000,
|
||||
}));
|
||||
}
|
||||
|
||||
function selectStarExpansionColumns(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>): SqlCompletionColumn[] {
|
||||
const references = referencedTablesForSelectAllColumns(context);
|
||||
if (context.qualifier || references.length > 1) {
|
||||
|
||||
Reference in new issue
Block a user