Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README-zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,18 @@ console.log(sqlSlices)
[ 'CATALOG', 'FUNCTION', 'TEMPORARY', 'VIEW', 'DATABASE', 'TABLE' ]
*/
```

可以通过可选的 `keywordFilter` 移除不需要的关键字候选项。返回 `true` 保留关键字,返回 `false` 移除关键字。

```typescript
const sql = 'SELECT * FROM tb ';
const pos = { lineNumber: 1, column: sql.length + 1 };
const excludedKeywords = new Set(['WHERE', 'ORDER BY']);
const keywords = flink.getSuggestionAtCaretPosition(sql, pos, {
keywordFilter: (keyword) => !excludedKeywords.has(keyword),
})?.keywords;
```

+ **获取语法相关自动补全信息**
```typescript
import { FlinkSQL } from 'dt-sql-parser';
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,18 @@ Call the `getAllEntities` method on the SQL instance, pass the SQL content and t
[ 'CATALOG', 'FUNCTION', 'TEMPORARY', 'VIEW', 'DATABASE', 'TABLE' ]
*/
```

Use the optional `keywordFilter` to remove unwanted keyword candidates. Return `true` to keep a keyword and `false` to remove it.

```typescript
const sql = 'SELECT * FROM tb ';
const pos = { lineNumber: 1, column: sql.length + 1 };
const excludedKeywords = new Set(['WHERE', 'ORDER BY']);
const keywords = flink.getSuggestionAtCaretPosition(sql, pos, {
keywordFilter: (keyword) => !excludedKeywords.has(keyword),
})?.keywords;
```

+ **Obtaining information related to grammar completion**
```javascript
import { FlinkSQL } from 'dt-sql-parser';
Expand Down
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ export { EntityContextType } from './parser/common/types';

export { StmtContextType } from './parser/common/entityCollector';

export type { CaretPosition, Suggestions, SyntaxSuggestion } from './parser/common/types';
export type {
CaretPosition,
SuggestionOptions,
Suggestions,
SyntaxSuggestion,
} from './parser/common/types';

export type { WordRange, TextSlice } from './parser/common/textAndWord';

Expand Down
105 changes: 97 additions & 8 deletions src/parser/common/basicSQL.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
CaretPosition,
LOCALE_TYPE,
SemanticCollectOptions,
SuggestionOptions,
Suggestions,
SyntaxSuggestion,
} from './types';
Expand All @@ -48,6 +49,7 @@ export abstract class BasicSQL<
protected _parseTree: PRC | null;
protected _parsedInput: string;
protected _parseErrors: ParseError[] = [];
private _statementStartTokenTypes: Set<number> | null = null;
/** members for cache end */

private _errorListener: ErrorListener = (error) => {
Expand Down Expand Up @@ -555,15 +557,98 @@ export abstract class BasicSQL<
};
}

/**
* Get the minimum statement tree for collecting completion candidates
* Each supported grammar exposes one top-level statement per direct program child
* Keep the lookup shallow to avoid selecting nested statements or subqueries
*/
private getSuggestionParseTree(
parseTree: ParserRuleContext,
caretTokenIndex: number
): ParserRuleContext {
const children = parseTree.children;
if (!children?.length) return parseTree;

for (let index = children.length - 1; index >= 0; index--) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

你这里是只向下看一层,它假设 program 的直接子节点就是语句。一旦文法把语句包了一层中间规则(如 program → batch → statement,或 list 规则),收窄会静默回退到整棵树,修复悄悄失效且无报错,确认下这个链路在这种情况下是否有问题?是否需要加一条断言/测试守护该假设?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已经加了守护测试:suggestion.test.ts 的用例遍历全部方言,断言 SELECT * FROM t; SELECT * FROM u 解析出的 program 直接子节点恰好是两个 statement。

所有方言 grammar 都是 program: (statement SEMI?)* 扁平结构,直接子节点即语句;只向下看一层是刻意的,避免误选嵌套语句/子查询(见 getSuggestionParseTree 上方注释)。

若未来引入中间规则,这条测试会立即失败暴露,不会静默回退。

const child = children[index];
if (!(child instanceof ParserRuleContext)) continue;

const startTokenIndex = child.start?.tokenIndex;
const stopTokenIndex = child.stop?.tokenIndex;
if (
startTokenIndex === undefined ||
stopTokenIndex === undefined ||
startTokenIndex > caretTokenIndex
)
continue;

// Use the current statement tree when the caret is inside it
if (stopTokenIndex >= caretTokenIndex) return child;

// Keep using the current statement until it ends with a semicolon
return child.stop?.text === SQL_SPLIT_SYMBOL_TEXT ? parseTree : child;
}

return parseTree;
}

/**
* Collect candidates for the current statement and remove new-statement-only keywords
*/
private collectSuggestionCandidates(
parser: Parser,
parseTree: ParserRuleContext,
caretTokenIndex: number
): CandidatesCollection {
const core = new CodeCompletionCore(parser);
core.preferredRules = this.preferredRules;
const candidates = core.collectCandidates(caretTokenIndex, parseTree);
const suggestionParseTree = this.getSuggestionParseTree(parseTree, caretTokenIndex);

if (suggestionParseTree === parseTree) return candidates;

// Keep the program candidates for outer rule paths and use statement candidates for isolation
const statementCore = new CodeCompletionCore(parser);
statementCore.preferredRules = this.preferredRules;
const statementCandidates = statementCore.collectCandidates(
caretTokenIndex,
suggestionParseTree
);

if (this._statementStartTokenTypes === null) {
const statementStartCore = new CodeCompletionCore(parser);
statementStartCore.preferredRules = this.preferredRules;
const statementStartCandidates = statementStartCore.collectCandidates(0, parseTree);
this._statementStartTokenTypes = new Set(statementStartCandidates.tokens.keys());
}

const tokens = new Map(candidates.tokens);
for (const tokenType of this._statementStartTokenTypes) {
if (!statementCandidates.tokens.has(tokenType)) {
tokens.delete(tokenType);
} else if (tokens.has(tokenType)) {
// Use the current statement follow-list to preserve valid combined keywords
tokens.set(tokenType, statementCandidates.tokens.get(tokenType)!);
}
}

return {
rules: candidates.rules,
tokens,
};
}

/**
* Get suggestions of syntax and token at caretPosition
* @param input source string
* @param caretPosition caret position, such as cursor position
* @param options suggestion options
* @returns suggestion
*/
public getSuggestionAtCaretPosition(
input: string,
caretPosition: CaretPosition
caretPosition: CaretPosition,
options?: SuggestionOptions
): Suggestions | null {
this.parseWithCache(input);
if (!this._parseTree) return null;
Expand Down Expand Up @@ -614,12 +699,11 @@ export abstract class BasicSQL<
parseTree = sqlParserIns.program();
}

const core = new CodeCompletionCore(sqlParserIns);
core.preferredRules = this.preferredRules;
// core.showRuleStack = true;
// core.showResult = true;

const candidates = core.collectCandidates(caretTokenIndex, parseTree);
const candidates = this.collectSuggestionCandidates(
sqlParserIns,
parseTree,
caretTokenIndex
);
Comment on lines +702 to +706

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

collectSuggestionCandidates 在最坏情况下会跑 3 次 collectCandidates(整棵树 + 语句树 + 仅在首次缓存的语句起始 token 集)。常见未切片场景是 2 次。对大 SQL 输入这是可感知的额外开销。建议补充一个针对大输入的 benchmark,确认回归在可接受范围。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

三次 collectCandidates 是「两层隔离」保证正确性的刻意设计——Issue 436 之前的单次 C3 正是把下一条语句的 SELECT/CREATE/INSERT 混进当前补全的根源。三步各司其职:

  1. program —— 保留外层 rule path、syntax 候选与上下文;
  2. statement 子树 —— 过滤下一条语句的起始关键字,保留 LOCK IN SHARE MODE 等组合关键字;
  3. token 0(仅首次,缓存在 _statementStartTokenTypes —— 得到语句起始关键字集合,只删 SELECT/CREATE/INSERT 这类起始词。

调用次数:首次最多 3 次,后续 2 次,分号后或无需隔离 1 次。

不能砍掉 statement 那次,否则退化回 Issue 436 之前的错误(复核确认会丢 MySQL LOCK IN SHARE MODE、Impala WITH SERDEPROPERTIES,嵌套查询也会重新混入顶层起始关键字)。

性能 A/B 对比(热启动 50 次取中位数):

场景 修复前 修复后
SELECT ... WHERE ... (无分号末尾) 0.78 ms / 93 关键词 1.75 ms / 28 关键词
60 行 SELECT 的 FROM 之后 3.6 ms 5.8 ms

额外成本就是一次等量 statement C3,毫秒级,误报的 SELECT/INSERT/CREATE 全部消失(93→28),可接受。

benchmark 方面:benchmark:release 冷启动的 clearATNCache() 存在预先存在的内存泄漏(每次 +30MB 无法 GC,累积 OOM),与本次改动无关,故改用手工测量;OOM 我会另开 issue 跟进。

结论:接受首次 3 次、后续 2 次的实现。

const originalSuggestions = this.processCandidates(candidates, allTokens, caretTokenIndex);

const syntaxSuggestions: SyntaxSuggestion<WordRange>[] = originalSuggestions.syntax.map(
Expand All @@ -633,9 +717,14 @@ export abstract class BasicSQL<
};
}
);
const keywordFilter = options?.keywordFilter;
const keywords = keywordFilter
? originalSuggestions.keywords.filter((keyword) => keywordFilter(keyword))
: originalSuggestions.keywords;

return {
syntax: syntaxSuggestions,
keywords: originalSuggestions.keywords,
keywords,
};
}

Expand Down
10 changes: 10 additions & 0 deletions src/parser/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ export interface Suggestions<T = WordRange> {
readonly keywords: string[];
}

/**
* Suggested information options
*/
export interface SuggestionOptions {
/**
* Return true to keep the keyword, otherwise remove it
*/
keywordFilter?: (keyword: string) => boolean;
}

export type LOCALE_TYPE = 'zh_CN' | 'en_US';

export interface SemanticContext {
Expand Down
Loading
Loading