Skip to content

Commit f8772ed

Browse files
author
koillinjag-tech
committed
feat: add smart SQL completion with frequency-based sorting
- Add history frequency tracking for SQL keywords - Store frequency data in ~/.config/pgcli/history_freq.db - Support runtime toggle via \\set smart_completion_freq on/off - Default disabled, compatible with existing prompt_toolkit completion
1 parent fb639d2 commit f8772ed

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

pgcli/main.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,7 @@ def __init__(
282282
"less_chatty": less_chatty,
283283
"keyword_casing": keyword_casing,
284284
"alias_map_file": c["main"]["alias_map_file"] or None,
285+
"smart_completion_freq": c["main"].as_bool("smart_completion_freq"),
285286
}
286287

287288
completer = PGCompleter(smart_completion, pgspecial=self.pgspecial, settings=self.settings)

pgcli/packages/history_freq.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,23 @@ def record_keyword_usage(self, keyword):
9191
def record_keywords_batch(self, keywords):
9292
if not keywords:
9393
return
94+
keyword_counts = defaultdict(int)
9495
for keyword in keywords:
95-
self.record_keyword_usage(keyword)
96+
if keyword and isinstance(keyword, str):
97+
kw = keyword.upper().strip()
98+
if kw:
99+
keyword_counts[kw] += 1
100+
if not keyword_counts:
101+
return
102+
with self._get_cursor() as cursor:
103+
for keyword, count in keyword_counts.items():
104+
cursor.execute("""
105+
INSERT INTO keyword_frequency (keyword, frequency, last_used)
106+
VALUES (?, ?, CURRENT_TIMESTAMP)
107+
ON CONFLICT(keyword) DO UPDATE SET
108+
frequency = frequency + ?,
109+
last_used = CURRENT_TIMESTAMP
110+
""", (keyword, count, count))
96111

97112
def get_keyword_frequency(self, keyword):
98113
if not keyword:

pgcli/packages/prioritization.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,13 @@ def clear_names(self):
5353
self.name_counts = defaultdict(int)
5454

5555
def update_keywords(self, text):
56+
found_keywords = []
5657
for keyword, regex in keyword_regexs.items():
5758
for _ in regex.finditer(text):
5859
self.keyword_counts[keyword] += 1
60+
found_keywords.append(keyword)
61+
if self.smart_completion_freq and self._history_freq_manager and found_keywords:
62+
self._history_freq_manager.record_keywords_batch(found_keywords)
5963

6064
def keyword_count(self, keyword):
6165
session_count = self.keyword_counts[keyword]

0 commit comments

Comments
 (0)