| 10 | |
| 11 | |
| 12 | class CompletionRefresher: |
| 13 | refreshers: dict = {} |
| 14 | |
| 15 | def __init__(self) -> None: |
| 16 | self._completer_thread: threading.Thread | None = None |
| 17 | self._restart_refresh = threading.Event() |
| 18 | |
| 19 | def refresh( |
| 20 | self, |
| 21 | executor: SQLExecute, |
| 22 | callbacks: Callable | list[Callable], |
| 23 | completer_options: dict | None = None, |
| 24 | ) -> list[SQLResult]: |
| 25 | """Creates a SQLCompleter object and populates it with the relevant |
| 26 | completion suggestions in a background thread. |
| 27 | |
| 28 | executor - SQLExecute object, used to extract the credentials to connect |
| 29 | to the database. |
| 30 | callbacks - A function or a list of functions to call after the thread |
| 31 | has completed the refresh. The newly created completion |
| 32 | object will be passed in as an argument to each callback. |
| 33 | completer_options - dict of options to pass to SQLCompleter. |
| 34 | |
| 35 | """ |
| 36 | if completer_options is None: |
| 37 | completer_options = {} |
| 38 | |
| 39 | if self.is_refreshing(): |
| 40 | self._restart_refresh.set() |
| 41 | return [SQLResult(status="Auto-completion refresh restarted.")] |
| 42 | else: |
| 43 | self._completer_thread = threading.Thread( |
| 44 | target=self._bg_refresh, args=(executor, callbacks, completer_options), name="completion_refresh" |
| 45 | ) |
| 46 | self._completer_thread.daemon = True |
| 47 | self._completer_thread.start() |
| 48 | return [SQLResult(status="Auto-completion refresh started in the background.")] |
| 49 | |
| 50 | def is_refreshing(self) -> bool: |
| 51 | return bool(self._completer_thread and self._completer_thread.is_alive()) |
| 52 | |
| 53 | def _bg_refresh( |
| 54 | self, |
| 55 | sqlexecute: SQLExecute, |
| 56 | callbacks: Callable | list[Callable], |
| 57 | completer_options: dict, |
| 58 | ) -> None: |
| 59 | completer = SQLCompleter(**completer_options) |
| 60 | |
| 61 | # Create a new sqlexecute method to populate the completions. |
| 62 | e = sqlexecute |
| 63 | try: |
| 64 | executor = SQLExecute( |
| 65 | e.dbname, |
| 66 | e.user, |
| 67 | e.password, |
| 68 | e.host, |
| 69 | e.port, |