diff --git a/changelog.md b/changelog.md index eea6f817..8a35b685 100644 --- a/changelog.md +++ b/changelog.md @@ -4,6 +4,7 @@ TBD Features -------- * "Eager" completions for the `source` command, limited to `*.sql` files. +* Suggest column names from all tables in the current database after SELECT (#212) Bug Fixes diff --git a/mycli/sqlcompleter.py b/mycli/sqlcompleter.py index 187c323b..40a7d49d 100644 --- a/mycli/sqlcompleter.py +++ b/mycli/sqlcompleter.py @@ -1087,6 +1087,10 @@ def get_completions( # which should suggest only columns that appear in more than # one table scoped_cols = [col for (col, count) in Counter(scoped_cols).items() if count > 1 and col != "*"] + elif not tables: + # if tables was empty, this is a naked SELECT and we are + # showing all columns. So make them unique and sort them. + scoped_cols = sorted(set(scoped_cols), key=lambda s: s.strip('`')) cols = self.find_matches(word_before_cursor, scoped_cols) completions.extend(cols) @@ -1213,6 +1217,14 @@ def populate_scoped_cols(self, scoped_tbls: list[tuple[str | None, str, str | No columns = [] meta = self.dbmetadata + # if scoped tables is empty, this is just after a SELECT so we + # show all columns for all tables in the schema. + if len(scoped_tbls) == 0 and self.dbname: + for table in meta["tables"][self.dbname]: + columns.extend(meta["tables"][self.dbname][table]) + return columns + + # query includes tables, so use those to populate columns for tbl in scoped_tbls: # A fully qualified schema.relname reference or default_schema # DO NOT escape schema names. diff --git a/test/test_smart_completion_public_schema_only.py b/test/test_smart_completion_public_schema_only.py index 42769d96..0ee337cf 100644 --- a/test/test_smart_completion_public_schema_only.py +++ b/test/test_smart_completion_public_schema_only.py @@ -136,6 +136,7 @@ def test_function_name_completion(completer, complete_event): position = len("SELECT MA") result = completer.get_completions(Document(text=text, cursor_position=position), complete_event) assert list(result) == [ + Completion(text='email', start_position=-2), Completion(text='MAX', start_position=-2), Completion(text='MAKE_SET', start_position=-2), Completion(text='MAKEDATE', start_position=-2),