codis 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/ui/sql_studio.py
ADDED
|
@@ -0,0 +1,1815 @@
|
|
|
1
|
+
"""Codis - SQL Studio.
|
|
2
|
+
|
|
3
|
+
Motor de banco de dados integrado ao editor.
|
|
4
|
+
Drivers suportados (instalação opcional via pip):
|
|
5
|
+
- SQLite - embutido no Python, zero dependências
|
|
6
|
+
- PostgreSQL - psycopg2 (pip install psycopg2-binary)
|
|
7
|
+
- MySQL/MariaDB - pymysql (pip install pymysql)
|
|
8
|
+
- DuckDB - duckdb (pip install duckdb)
|
|
9
|
+
|
|
10
|
+
Funcionalidades:
|
|
11
|
+
- Browser de esquema: databases -> tabelas -> colunas / índices / FKs
|
|
12
|
+
- Editor SQL multi-linha com syntax highlighting e autocomplete
|
|
13
|
+
- Execução de query ou seleção atual (Ctrl+Enter / F5)
|
|
14
|
+
- Grid de resultados com ordenação por coluna, exportação CSV/JSON
|
|
15
|
+
- Histórico persistente de queries com favoritos
|
|
16
|
+
- Múltiplas conexões salvas em ~/.codis/sql_connections.json
|
|
17
|
+
- Suporte a apply_theme(tmgr) para recoloração dinâmica
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import contextlib
|
|
23
|
+
import csv as _csv
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
import re
|
|
27
|
+
import sqlite3
|
|
28
|
+
import threading
|
|
29
|
+
import time
|
|
30
|
+
import tkinter as tk
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from tkinter import filedialog, messagebox, ttk
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from src.constants import CONFIG_DIR, FONT_MONO, FONT_UI
|
|
37
|
+
from src.i18n import _t
|
|
38
|
+
from src.theme.utils import make_toolbar_button
|
|
39
|
+
from src.ui._persistence_utils import load_dataclass_list, save_dataclass_list
|
|
40
|
+
from src.ui.grab_safe import safe_grab_set
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger("Codis.SQLStudio")
|
|
43
|
+
|
|
44
|
+
_CONNS_FILE = CONFIG_DIR / "sql_connections.json"
|
|
45
|
+
_HISTORY_FILE = CONFIG_DIR / "sql_history.json"
|
|
46
|
+
_MAX_HISTORY = 500
|
|
47
|
+
_MAX_ROWS_GRID = 5000
|
|
48
|
+
|
|
49
|
+
_SQL_KW = [
|
|
50
|
+
"SELECT",
|
|
51
|
+
"FROM",
|
|
52
|
+
"WHERE",
|
|
53
|
+
"INSERT",
|
|
54
|
+
"INTO",
|
|
55
|
+
"VALUES",
|
|
56
|
+
"UPDATE",
|
|
57
|
+
"SET",
|
|
58
|
+
"DELETE",
|
|
59
|
+
"CREATE",
|
|
60
|
+
"TABLE",
|
|
61
|
+
"DROP",
|
|
62
|
+
"ALTER",
|
|
63
|
+
"ADD",
|
|
64
|
+
"COLUMN",
|
|
65
|
+
"INDEX",
|
|
66
|
+
"JOIN",
|
|
67
|
+
"LEFT",
|
|
68
|
+
"RIGHT",
|
|
69
|
+
"INNER",
|
|
70
|
+
"OUTER",
|
|
71
|
+
"FULL",
|
|
72
|
+
"ON",
|
|
73
|
+
"AS",
|
|
74
|
+
"AND",
|
|
75
|
+
"OR",
|
|
76
|
+
"NOT",
|
|
77
|
+
"NULL",
|
|
78
|
+
"IS",
|
|
79
|
+
"IN",
|
|
80
|
+
"LIKE",
|
|
81
|
+
"BETWEEN",
|
|
82
|
+
"ORDER",
|
|
83
|
+
"BY",
|
|
84
|
+
"GROUP",
|
|
85
|
+
"HAVING",
|
|
86
|
+
"LIMIT",
|
|
87
|
+
"OFFSET",
|
|
88
|
+
"DISTINCT",
|
|
89
|
+
"COUNT",
|
|
90
|
+
"SUM",
|
|
91
|
+
"AVG",
|
|
92
|
+
"MIN",
|
|
93
|
+
"MAX",
|
|
94
|
+
"CASE",
|
|
95
|
+
"WHEN",
|
|
96
|
+
"THEN",
|
|
97
|
+
"ELSE",
|
|
98
|
+
"END",
|
|
99
|
+
"WITH",
|
|
100
|
+
"UNION",
|
|
101
|
+
"ALL",
|
|
102
|
+
"EXCEPT",
|
|
103
|
+
"INTERSECT",
|
|
104
|
+
"EXISTS",
|
|
105
|
+
"UNIQUE",
|
|
106
|
+
"PRIMARY",
|
|
107
|
+
"KEY",
|
|
108
|
+
"FOREIGN",
|
|
109
|
+
"REFERENCES",
|
|
110
|
+
"CASCADE",
|
|
111
|
+
"DEFAULT",
|
|
112
|
+
"CHECK",
|
|
113
|
+
"NOT NULL",
|
|
114
|
+
"AUTO_INCREMENT",
|
|
115
|
+
"AUTOINCREMENT",
|
|
116
|
+
"PRAGMA",
|
|
117
|
+
"EXPLAIN",
|
|
118
|
+
"ANALYZE",
|
|
119
|
+
"BEGIN",
|
|
120
|
+
"COMMIT",
|
|
121
|
+
"ROLLBACK",
|
|
122
|
+
"TRANSACTION",
|
|
123
|
+
"SAVEPOINT",
|
|
124
|
+
"RELEASE",
|
|
125
|
+
"VACUUM",
|
|
126
|
+
"ATTACH",
|
|
127
|
+
"DETACH",
|
|
128
|
+
"RETURNING",
|
|
129
|
+
"ILIKE",
|
|
130
|
+
"SIMILAR",
|
|
131
|
+
"COALESCE",
|
|
132
|
+
"NULLIF",
|
|
133
|
+
"CAST",
|
|
134
|
+
"CONVERT",
|
|
135
|
+
"SUBSTR",
|
|
136
|
+
"LENGTH",
|
|
137
|
+
"TRIM",
|
|
138
|
+
"UPPER",
|
|
139
|
+
"LOWER",
|
|
140
|
+
"REPLACE",
|
|
141
|
+
"STRFTIME",
|
|
142
|
+
"DATE",
|
|
143
|
+
"TIME",
|
|
144
|
+
"DATETIME",
|
|
145
|
+
"CURRENT_TIMESTAMP",
|
|
146
|
+
"CURRENT_DATE",
|
|
147
|
+
"CURRENT_TIME",
|
|
148
|
+
]
|
|
149
|
+
|
|
150
|
+
DRIVERS: dict[str, dict[str, Any]] = {
|
|
151
|
+
"sqlite": {"label": "SQLite", "module": None, "builtin": True},
|
|
152
|
+
"postgres": {"label": "PostgreSQL", "module": "psycopg2", "builtin": False},
|
|
153
|
+
"mysql": {"label": "MySQL", "module": "pymysql", "builtin": False},
|
|
154
|
+
"duckdb": {"label": "DuckDB", "module": "duckdb", "builtin": False},
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
_DEFAULT_PORTS: dict[str, int] = {
|
|
158
|
+
"postgres": 5432,
|
|
159
|
+
"mysql": 3306,
|
|
160
|
+
"duckdb": 0,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _driver_available(key: str) -> bool:
|
|
165
|
+
info = DRIVERS.get(key, {})
|
|
166
|
+
if info.get("builtin"):
|
|
167
|
+
return True
|
|
168
|
+
mod = info.get("module")
|
|
169
|
+
if not mod:
|
|
170
|
+
return False
|
|
171
|
+
try:
|
|
172
|
+
__import__(mod)
|
|
173
|
+
return True
|
|
174
|
+
except ImportError:
|
|
175
|
+
return False
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _quote_ident(name: str) -> str:
|
|
179
|
+
"""Escapa um identificador SQL (tabela/coluna) para uso entre aspas duplas.
|
|
180
|
+
|
|
181
|
+
Nomes de tabela/coluna vêm do schema introspectado, mas SQLite/Postgres
|
|
182
|
+
aceitam identificadores com aspas duplas embutidas
|
|
183
|
+
(ex.: ``foo" ; DROP TABLE bar; --``), o que quebraria o SQL gerado.
|
|
184
|
+
Dobra cada ``"`` interna, seguindo a regra padrão SQL de escape de
|
|
185
|
+
identificador entre aspas.
|
|
186
|
+
"""
|
|
187
|
+
return name.replace('"', '""')
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _quote_backtick_ident(name: str) -> str:
|
|
191
|
+
"""Escapa um identificador SQL para uso entre backticks (dialeto MySQL/MariaDB).
|
|
192
|
+
|
|
193
|
+
Mesmo racional de ``_quote_ident``, mas para o delimitador de
|
|
194
|
+
identificador do MySQL/MariaDB (crase em vez de aspas duplas).
|
|
195
|
+
"""
|
|
196
|
+
return name.replace("`", "``")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@dataclass
|
|
200
|
+
class Connection:
|
|
201
|
+
"""Perfil de conexão salvo."""
|
|
202
|
+
|
|
203
|
+
id: str = field(default_factory=lambda: f"conn_{int(time.time())}")
|
|
204
|
+
name: str = "Nova Conexão"
|
|
205
|
+
driver: str = "sqlite"
|
|
206
|
+
filepath: str = ""
|
|
207
|
+
host: str = "localhost"
|
|
208
|
+
port: int = 5432
|
|
209
|
+
database: str = ""
|
|
210
|
+
user: str = ""
|
|
211
|
+
password: str = ""
|
|
212
|
+
readonly: bool = False
|
|
213
|
+
|
|
214
|
+
@property
|
|
215
|
+
def display(self) -> str:
|
|
216
|
+
"""Exibe o resultado da query no widget de saída."""
|
|
217
|
+
if self.driver in ("sqlite", "duckdb"):
|
|
218
|
+
label = DRIVERS[self.driver]["label"]
|
|
219
|
+
name = Path(self.filepath).name or ":memory:"
|
|
220
|
+
return f"{label} - {name}"
|
|
221
|
+
return (
|
|
222
|
+
f"{DRIVERS[self.driver]['label']} - {self.user}@{self.host}/{self.database}"
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _load_connections() -> list[Connection]:
|
|
227
|
+
return load_dataclass_list(_CONNS_FILE, Connection, logger=logger)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _save_connections(conns: list[Connection]) -> None:
|
|
231
|
+
save_dataclass_list(_CONNS_FILE, conns)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _load_history() -> list[dict]:
|
|
235
|
+
if not _HISTORY_FILE.exists():
|
|
236
|
+
return []
|
|
237
|
+
try:
|
|
238
|
+
return json.loads(_HISTORY_FILE.read_text(encoding="utf-8"))
|
|
239
|
+
except (OSError, ValueError) as exc:
|
|
240
|
+
logger.warning("Falha ao carregar histórico SQL: %s",
|
|
241
|
+
exc, exc_info=True)
|
|
242
|
+
return []
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _save_history(hist: list[dict]) -> None:
|
|
246
|
+
_HISTORY_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
247
|
+
_HISTORY_FILE.write_text(
|
|
248
|
+
json.dumps(hist[-_MAX_HISTORY:], indent=2, ensure_ascii=False), encoding="utf-8"
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class DBConnection:
|
|
253
|
+
"""Abstração sobre diferentes drivers de BD."""
|
|
254
|
+
|
|
255
|
+
def __init__(self, profile: Connection) -> None:
|
|
256
|
+
self._profile = profile
|
|
257
|
+
self._conn: Any = None
|
|
258
|
+
self._driver = profile.driver
|
|
259
|
+
self._lock = threading.Lock()
|
|
260
|
+
|
|
261
|
+
def connect(self) -> None:
|
|
262
|
+
"""Estabelece a conexão com o banco de dados."""
|
|
263
|
+
p = self._profile
|
|
264
|
+
if p.driver == "sqlite":
|
|
265
|
+
path = p.filepath or ":memory:"
|
|
266
|
+
flags = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
|
|
267
|
+
if p.readonly:
|
|
268
|
+
uri = f"file:{path}?mode=ro"
|
|
269
|
+
self._conn = sqlite3.connect(
|
|
270
|
+
uri, uri=True, detect_types=flags, check_same_thread=False
|
|
271
|
+
)
|
|
272
|
+
else:
|
|
273
|
+
self._conn = sqlite3.connect(
|
|
274
|
+
path, detect_types=flags, check_same_thread=False
|
|
275
|
+
)
|
|
276
|
+
self._conn.row_factory = sqlite3.Row
|
|
277
|
+
elif p.driver == "postgres":
|
|
278
|
+
import base64
|
|
279
|
+
|
|
280
|
+
import psycopg2 # type: ignore[import]
|
|
281
|
+
|
|
282
|
+
pw = base64.b64decode(p.password).decode() if p.password else ""
|
|
283
|
+
self._conn = psycopg2.connect(
|
|
284
|
+
host=p.host,
|
|
285
|
+
port=p.port,
|
|
286
|
+
dbname=p.database,
|
|
287
|
+
user=p.user,
|
|
288
|
+
password=pw,
|
|
289
|
+
)
|
|
290
|
+
elif p.driver == "mysql":
|
|
291
|
+
import base64
|
|
292
|
+
|
|
293
|
+
import pymysql # type: ignore[import]
|
|
294
|
+
|
|
295
|
+
pw = base64.b64decode(p.password).decode() if p.password else ""
|
|
296
|
+
self._conn = pymysql.connect(
|
|
297
|
+
host=p.host,
|
|
298
|
+
port=p.port,
|
|
299
|
+
database=p.database,
|
|
300
|
+
user=p.user,
|
|
301
|
+
password=pw,
|
|
302
|
+
autocommit=True,
|
|
303
|
+
)
|
|
304
|
+
elif p.driver == "duckdb":
|
|
305
|
+
import duckdb # type: ignore[import]
|
|
306
|
+
|
|
307
|
+
path = p.filepath or ":memory:"
|
|
308
|
+
self._conn = duckdb.connect(path, read_only=p.readonly)
|
|
309
|
+
else:
|
|
310
|
+
raise ValueError(f"Driver desconhecido: {p.driver}")
|
|
311
|
+
|
|
312
|
+
def close(self) -> None:
|
|
313
|
+
"""Encerra a conexão com o banco de dados."""
|
|
314
|
+
try:
|
|
315
|
+
if self._conn:
|
|
316
|
+
self._conn.close()
|
|
317
|
+
except Exception:
|
|
318
|
+
logger.debug(
|
|
319
|
+
"Falha ao fechar conexão com o banco de dados.", exc_info=True)
|
|
320
|
+
self._conn = None
|
|
321
|
+
|
|
322
|
+
@property
|
|
323
|
+
def connected(self) -> bool:
|
|
324
|
+
"""Retorna ``True`` se a conexão está ativa."""
|
|
325
|
+
return self._conn is not None
|
|
326
|
+
|
|
327
|
+
def execute(
|
|
328
|
+
self, sql: str, params: tuple = ()
|
|
329
|
+
) -> tuple[list[str], list[tuple], str]:
|
|
330
|
+
"""Executa SQL. Retorna (colunas, linhas, mensagem)."""
|
|
331
|
+
if not self._conn:
|
|
332
|
+
return [], [], _t("sql.not_connected", "Não conectado.")
|
|
333
|
+
with self._lock:
|
|
334
|
+
try:
|
|
335
|
+
cur = self._conn.cursor()
|
|
336
|
+
t0 = time.perf_counter()
|
|
337
|
+
cur.execute(sql, params)
|
|
338
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000
|
|
339
|
+
|
|
340
|
+
if cur.description:
|
|
341
|
+
cols = [d[0] for d in cur.description]
|
|
342
|
+
rows = cur.fetchmany(_MAX_ROWS_GRID)
|
|
343
|
+
rows = [tuple(r) for r in rows]
|
|
344
|
+
n_rows = len(rows)
|
|
345
|
+
msg = _t(
|
|
346
|
+
"sql.rows_fetched", n=n_rows, ms=f"{elapsed_ms:.1f}"
|
|
347
|
+
)
|
|
348
|
+
else:
|
|
349
|
+
cols = []
|
|
350
|
+
rows = []
|
|
351
|
+
count = getattr(cur, "rowcount", 0) or 0
|
|
352
|
+
msg = _t(
|
|
353
|
+
"sql.rows_affected", n=count, ms=f"{elapsed_ms:.1f}"
|
|
354
|
+
)
|
|
355
|
+
with contextlib.suppress(Exception):
|
|
356
|
+
self._conn.commit()
|
|
357
|
+
cur.close()
|
|
358
|
+
return cols, rows, msg
|
|
359
|
+
except Exception as exc:
|
|
360
|
+
with contextlib.suppress(Exception):
|
|
361
|
+
self._conn.rollback()
|
|
362
|
+
return [], [], f"❌ {exc}"
|
|
363
|
+
|
|
364
|
+
def get_schema(self) -> dict[str, list[dict]]:
|
|
365
|
+
"""Retorna esquema: {tabela: [{name, type, pk, notnull, default}]}."""
|
|
366
|
+
if not self._conn:
|
|
367
|
+
return {}
|
|
368
|
+
schema: dict[str, list[dict]] = {}
|
|
369
|
+
with self._lock:
|
|
370
|
+
try:
|
|
371
|
+
drv = self._driver
|
|
372
|
+
cur = self._conn.cursor()
|
|
373
|
+
if drv == "sqlite":
|
|
374
|
+
cur.execute(
|
|
375
|
+
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
|
|
376
|
+
)
|
|
377
|
+
tables = [r[0] for r in cur.fetchall()]
|
|
378
|
+
for tbl in tables:
|
|
379
|
+
cur.execute(
|
|
380
|
+
f'PRAGMA table_info("{_quote_ident(tbl)}")')
|
|
381
|
+
schema[tbl] = [
|
|
382
|
+
{
|
|
383
|
+
"name": r[1],
|
|
384
|
+
"type": r[2],
|
|
385
|
+
"notnull": bool(r[3]),
|
|
386
|
+
"default": r[4],
|
|
387
|
+
"pk": bool(r[5]),
|
|
388
|
+
}
|
|
389
|
+
for r in cur.fetchall()
|
|
390
|
+
]
|
|
391
|
+
elif drv == "postgres":
|
|
392
|
+
cur.execute(
|
|
393
|
+
"SELECT table_name FROM information_schema.tables "
|
|
394
|
+
"WHERE table_schema='public' ORDER BY table_name"
|
|
395
|
+
)
|
|
396
|
+
tables = [r[0] for r in cur.fetchall()]
|
|
397
|
+
for tbl in tables:
|
|
398
|
+
cur.execute(
|
|
399
|
+
"SELECT column_name, data_type, is_nullable, "
|
|
400
|
+
"column_default FROM information_schema.columns "
|
|
401
|
+
"WHERE table_name=%s ORDER BY ordinal_position",
|
|
402
|
+
(tbl,),
|
|
403
|
+
)
|
|
404
|
+
schema[tbl] = [
|
|
405
|
+
{
|
|
406
|
+
"name": r[0],
|
|
407
|
+
"type": r[1],
|
|
408
|
+
"notnull": r[2] == "NO",
|
|
409
|
+
"default": r[3],
|
|
410
|
+
"pk": False,
|
|
411
|
+
}
|
|
412
|
+
for r in cur.fetchall()
|
|
413
|
+
]
|
|
414
|
+
elif drv in ("mysql", "mariadb"):
|
|
415
|
+
cur.execute("SHOW TABLES")
|
|
416
|
+
tables = [r[0] for r in cur.fetchall()]
|
|
417
|
+
for tbl in tables:
|
|
418
|
+
cur.execute(f"DESCRIBE `{_quote_backtick_ident(tbl)}`")
|
|
419
|
+
schema[tbl] = [
|
|
420
|
+
{
|
|
421
|
+
"name": r[0],
|
|
422
|
+
"type": r[1],
|
|
423
|
+
"notnull": r[2] == "NO",
|
|
424
|
+
"default": r[4],
|
|
425
|
+
"pk": r[3] == "PRI",
|
|
426
|
+
}
|
|
427
|
+
for r in cur.fetchall()
|
|
428
|
+
]
|
|
429
|
+
elif drv == "duckdb":
|
|
430
|
+
cur.execute("SHOW ALL TABLES")
|
|
431
|
+
tables = [r[2] for r in cur.fetchall()]
|
|
432
|
+
for tbl in tables:
|
|
433
|
+
cur.execute(f'DESCRIBE "{_quote_ident(tbl)}"')
|
|
434
|
+
schema[tbl] = [
|
|
435
|
+
{
|
|
436
|
+
"name": r[0],
|
|
437
|
+
"type": r[1],
|
|
438
|
+
"notnull": False,
|
|
439
|
+
"default": None,
|
|
440
|
+
"pk": False,
|
|
441
|
+
}
|
|
442
|
+
for r in cur.fetchall()
|
|
443
|
+
]
|
|
444
|
+
cur.close()
|
|
445
|
+
except Exception as exc:
|
|
446
|
+
logger.warning("get_schema falhou: %s", exc)
|
|
447
|
+
return schema
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
class SQLStudioPanel(tk.Frame):
|
|
451
|
+
"""SQL Studio integrado ao Codis."""
|
|
452
|
+
|
|
453
|
+
def __init__(self, parent: tk.Widget, tmgr: Any, cfg: Any) -> None:
|
|
454
|
+
t = tmgr.theme
|
|
455
|
+
super().__init__(parent, bg=t.panel_bg)
|
|
456
|
+
self._tmgr = tmgr
|
|
457
|
+
self._cfg = cfg
|
|
458
|
+
|
|
459
|
+
self._connections = _load_connections()
|
|
460
|
+
self._history = _load_history()
|
|
461
|
+
self._active_conn: DBConnection | None = None
|
|
462
|
+
self._active_profile: Connection | None = None
|
|
463
|
+
self._schema: dict[str, list[dict]] = {}
|
|
464
|
+
self._busy = False
|
|
465
|
+
|
|
466
|
+
self._build(t)
|
|
467
|
+
|
|
468
|
+
def apply_theme(self, tmgr: Any) -> None:
|
|
469
|
+
"""Reaplica tema visualmente sem recriar widgets."""
|
|
470
|
+
self._tmgr = tmgr
|
|
471
|
+
t = tmgr.theme
|
|
472
|
+
for w in self.winfo_children():
|
|
473
|
+
w.destroy()
|
|
474
|
+
self.config(bg=t.panel_bg)
|
|
475
|
+
self._build(t)
|
|
476
|
+
|
|
477
|
+
def _build(self, t: Any) -> None:
|
|
478
|
+
for child in self.winfo_children():
|
|
479
|
+
with contextlib.suppress(tk.TclError):
|
|
480
|
+
child.destroy()
|
|
481
|
+
|
|
482
|
+
hdr = tk.Frame(self, bg=t.activity_bg, height=52)
|
|
483
|
+
hdr.pack(fill="x")
|
|
484
|
+
hdr.pack_propagate(False)
|
|
485
|
+
tk.Label(hdr, text="🗄", bg=t.activity_bg, fg=t.accent, font=(FONT_UI, 18)).pack(
|
|
486
|
+
side="left", padx=(12, 4), pady=8
|
|
487
|
+
)
|
|
488
|
+
tk.Label(
|
|
489
|
+
hdr,
|
|
490
|
+
text=_t("sql.title", "SQL Studio"),
|
|
491
|
+
bg=t.activity_bg,
|
|
492
|
+
fg=t.fg,
|
|
493
|
+
font=(FONT_UI, 13, "bold"),
|
|
494
|
+
).pack(side="left")
|
|
495
|
+
|
|
496
|
+
self._conn_badge = tk.Label(
|
|
497
|
+
hdr,
|
|
498
|
+
text=_t("sql.no_connection", "● sem conexão"),
|
|
499
|
+
bg=t.activity_bg,
|
|
500
|
+
fg=t.fg_muted,
|
|
501
|
+
font=(FONT_UI, 8),
|
|
502
|
+
)
|
|
503
|
+
self._conn_badge.pack(side="right", padx=12)
|
|
504
|
+
|
|
505
|
+
tk.Frame(self, bg=t.border, height=1).pack(fill="x")
|
|
506
|
+
|
|
507
|
+
conn_bar = tk.Frame(self, bg=t.sidebar_bg)
|
|
508
|
+
conn_bar.pack(fill="x")
|
|
509
|
+
self._build_connection_bar(t, conn_bar)
|
|
510
|
+
|
|
511
|
+
tk.Frame(self, bg=t.border, height=1).pack(fill="x")
|
|
512
|
+
|
|
513
|
+
paned = tk.PanedWindow(
|
|
514
|
+
self, orient="horizontal", bg=t.border, sashwidth=4, sashrelief="flat"
|
|
515
|
+
)
|
|
516
|
+
paned.pack(fill="both", expand=True)
|
|
517
|
+
|
|
518
|
+
left = tk.Frame(paned, bg=t.panel_bg)
|
|
519
|
+
paned.add(left, minsize=160, width=220)
|
|
520
|
+
self._build_schema_browser(t, left)
|
|
521
|
+
|
|
522
|
+
right = tk.Frame(paned, bg=t.panel_bg)
|
|
523
|
+
paned.add(right, minsize=400)
|
|
524
|
+
self._build_editor_area(t, right)
|
|
525
|
+
|
|
526
|
+
def _build_connection_bar(self, t: Any, parent: tk.Widget) -> None:
|
|
527
|
+
tk.Label(
|
|
528
|
+
parent,
|
|
529
|
+
text=_t("sql.connection", "Conexão:"),
|
|
530
|
+
bg=t.sidebar_bg,
|
|
531
|
+
fg=t.fg_muted,
|
|
532
|
+
font=(FONT_UI, 8),
|
|
533
|
+
).pack(side="left", padx=(8, 4), pady=5)
|
|
534
|
+
|
|
535
|
+
self._conn_var = tk.StringVar()
|
|
536
|
+
self._conn_cb = ttk.Combobox(
|
|
537
|
+
parent,
|
|
538
|
+
textvariable=self._conn_var,
|
|
539
|
+
state="readonly",
|
|
540
|
+
width=26,
|
|
541
|
+
font=(FONT_UI, 8),
|
|
542
|
+
)
|
|
543
|
+
self._conn_cb.pack(side="left", pady=5)
|
|
544
|
+
self._refresh_conn_combo()
|
|
545
|
+
|
|
546
|
+
def _btn(lbl: str, cmd: Any, accent: bool = False) -> tk.Label:
|
|
547
|
+
return make_toolbar_button(parent, t, lbl, cmd, accent=accent, outer_pady=5)
|
|
548
|
+
|
|
549
|
+
_btn(_t("sql.connect_btn", "▶ Conectar"), self._on_connect, accent=True)
|
|
550
|
+
_btn(_t("sql.disconnect_btn", "⏹ Desconectar"), self._on_disconnect)
|
|
551
|
+
_btn(_t("sql.new_conn", "+ Nova"), self._new_connection)
|
|
552
|
+
_btn(_t("sql.edit_conn", "✏ Editar"), self._edit_connection)
|
|
553
|
+
_btn(_t("sql.del_conn", "🗑"), self._delete_connection)
|
|
554
|
+
|
|
555
|
+
self._status_var = tk.StringVar(value=_t("sql.ready", "Pronto."))
|
|
556
|
+
tk.Label(
|
|
557
|
+
parent,
|
|
558
|
+
textvariable=self._status_var,
|
|
559
|
+
bg=t.sidebar_bg,
|
|
560
|
+
fg=t.fg_muted,
|
|
561
|
+
font=(FONT_UI, 7),
|
|
562
|
+
).pack(side="right", padx=12)
|
|
563
|
+
|
|
564
|
+
def _refresh_conn_combo(self) -> None:
|
|
565
|
+
values = [c.display for c in self._connections]
|
|
566
|
+
self._conn_cb["values"] = values
|
|
567
|
+
if values:
|
|
568
|
+
self._conn_cb.current(0)
|
|
569
|
+
|
|
570
|
+
def _build_schema_browser(self, t: Any, parent: tk.Widget) -> None:
|
|
571
|
+
hdr = tk.Frame(parent, bg=t.sidebar_bg)
|
|
572
|
+
hdr.pack(fill="x")
|
|
573
|
+
tk.Label(
|
|
574
|
+
hdr,
|
|
575
|
+
text=_t("sql.schema_browser", "Esquema"),
|
|
576
|
+
bg=t.sidebar_bg,
|
|
577
|
+
fg=t.fg_muted,
|
|
578
|
+
font=(FONT_UI, 7, "bold"),
|
|
579
|
+
).pack(side="left", padx=8, pady=3)
|
|
580
|
+
|
|
581
|
+
refresh_l = tk.Label(
|
|
582
|
+
hdr,
|
|
583
|
+
text="↻",
|
|
584
|
+
bg=t.sidebar_bg,
|
|
585
|
+
fg=t.fg_muted,
|
|
586
|
+
font=(FONT_UI, 9),
|
|
587
|
+
cursor="hand2",
|
|
588
|
+
)
|
|
589
|
+
refresh_l.pack(side="right", padx=6)
|
|
590
|
+
refresh_l.bind("<Button-1>", lambda _: self._refresh_schema())
|
|
591
|
+
|
|
592
|
+
self._schema_search_var = tk.StringVar()
|
|
593
|
+
srch = tk.Entry(
|
|
594
|
+
parent,
|
|
595
|
+
textvariable=self._schema_search_var,
|
|
596
|
+
bg=t.editor_bg,
|
|
597
|
+
fg=t.fg,
|
|
598
|
+
insertbackground=t.cursor,
|
|
599
|
+
relief="flat",
|
|
600
|
+
bd=4,
|
|
601
|
+
font=(FONT_UI, 8),
|
|
602
|
+
highlightthickness=0,
|
|
603
|
+
)
|
|
604
|
+
srch.pack(fill="x", padx=4, pady=(2, 0))
|
|
605
|
+
srch.bind("<KeyRelease>", lambda _: self._filter_schema())
|
|
606
|
+
|
|
607
|
+
self._schema_tree = ttk.Treeview(
|
|
608
|
+
parent, show="tree", selectmode="browse")
|
|
609
|
+
schema_vsb = ttk.Scrollbar(
|
|
610
|
+
parent, orient="vertical", command=self._schema_tree.yview
|
|
611
|
+
)
|
|
612
|
+
self._schema_tree.configure(yscrollcommand=schema_vsb.set)
|
|
613
|
+
schema_vsb.pack(side="right", fill="y")
|
|
614
|
+
self._schema_tree.pack(fill="both", expand=True, padx=(4, 0))
|
|
615
|
+
|
|
616
|
+
self._schema_tree.bind("<Double-1>", self._on_schema_double)
|
|
617
|
+
self._schema_tree.bind("<Button-3>", self._schema_context_menu)
|
|
618
|
+
|
|
619
|
+
def _refresh_schema(self) -> None:
|
|
620
|
+
if not self._active_conn or not self._active_conn.connected:
|
|
621
|
+
return
|
|
622
|
+
self._set_status(_t("sql.loading_schema", "Carregando esquema..."))
|
|
623
|
+
|
|
624
|
+
def _work() -> None:
|
|
625
|
+
schema = self._active_conn.get_schema() # type: ignore[union-attr]
|
|
626
|
+
self.after(0, lambda: self._populate_schema(schema))
|
|
627
|
+
|
|
628
|
+
threading.Thread(target=_work, daemon=True).start()
|
|
629
|
+
|
|
630
|
+
def _populate_schema(self, schema: dict[str, list[dict]]) -> None:
|
|
631
|
+
self._schema = schema
|
|
632
|
+
self._render_schema(schema)
|
|
633
|
+
self._set_status(
|
|
634
|
+
_t("sql.schema_loaded", n=len(schema))
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
def _render_schema(self, schema: dict[str, list[dict]]) -> None:
|
|
638
|
+
self._schema_tree.delete(*self._schema_tree.get_children())
|
|
639
|
+
q = self._schema_search_var.get().lower()
|
|
640
|
+
|
|
641
|
+
for tbl, cols in sorted(schema.items()):
|
|
642
|
+
if q and q not in tbl.lower():
|
|
643
|
+
continue
|
|
644
|
+
node = self._schema_tree.insert(
|
|
645
|
+
"", "end", iid=f"tbl:{tbl}", text=f"📋 {tbl}", open=False
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
for col in cols:
|
|
649
|
+
pk_icon = "🔑 " if col.get("pk") else ""
|
|
650
|
+
nn_icon = "!" if col.get("notnull") else ""
|
|
651
|
+
col_text = f" {pk_icon}{col['name']} {col['type']}{nn_icon}"
|
|
652
|
+
self._schema_tree.insert(
|
|
653
|
+
node, "end", iid=f"col:{tbl}.{col['name']}", text=col_text
|
|
654
|
+
)
|
|
655
|
+
|
|
656
|
+
def _filter_schema(self) -> None:
|
|
657
|
+
self._render_schema(self._schema)
|
|
658
|
+
|
|
659
|
+
def _on_schema_double(self, _e: Any) -> None:
|
|
660
|
+
sel = self._schema_tree.selection()
|
|
661
|
+
if not sel:
|
|
662
|
+
return
|
|
663
|
+
iid = sel[0]
|
|
664
|
+
if iid.startswith("tbl:"):
|
|
665
|
+
tbl = iid[4:]
|
|
666
|
+
self._insert_to_editor(
|
|
667
|
+
f'SELECT * FROM "{_quote_ident(tbl)}" LIMIT 100;')
|
|
668
|
+
elif iid.startswith("col:"):
|
|
669
|
+
col = iid[4:].split(".")[1]
|
|
670
|
+
self._insert_to_editor(col)
|
|
671
|
+
|
|
672
|
+
def _schema_context_menu(self, event: Any) -> None:
|
|
673
|
+
iid = self._schema_tree.identify_row(event.y)
|
|
674
|
+
if not iid:
|
|
675
|
+
return
|
|
676
|
+
self._schema_tree.selection_set(iid)
|
|
677
|
+
t = self._tmgr.theme
|
|
678
|
+
menu = tk.Menu(self, tearoff=False, bg=t.panel_bg, fg=t.fg)
|
|
679
|
+
|
|
680
|
+
if iid.startswith("tbl:"):
|
|
681
|
+
tbl = iid[4:]
|
|
682
|
+
menu.add_command(
|
|
683
|
+
label=_t("sql.ctx_select", "SELECT * FROM ..."),
|
|
684
|
+
command=lambda: self._insert_to_editor(
|
|
685
|
+
f'SELECT * FROM "{_quote_ident(tbl)}" LIMIT 100;'
|
|
686
|
+
),
|
|
687
|
+
)
|
|
688
|
+
menu.add_command(
|
|
689
|
+
label=_t("sql.ctx_count", "COUNT(*)"),
|
|
690
|
+
command=lambda: self._insert_to_editor(
|
|
691
|
+
f'SELECT COUNT(*) FROM "{_quote_ident(tbl)}";'
|
|
692
|
+
),
|
|
693
|
+
)
|
|
694
|
+
menu.add_command(
|
|
695
|
+
label=_t("sql.ctx_drop", "DROP TABLE ..."),
|
|
696
|
+
command=lambda: self._insert_to_editor(
|
|
697
|
+
f'DROP TABLE "{_quote_ident(tbl)}";'
|
|
698
|
+
),
|
|
699
|
+
)
|
|
700
|
+
menu.add_command(
|
|
701
|
+
label=_t("sql.ctx_schema", "Ver esquema"),
|
|
702
|
+
command=lambda: self._show_table_schema(tbl),
|
|
703
|
+
)
|
|
704
|
+
|
|
705
|
+
menu.tk_popup(event.x_root, event.y_root)
|
|
706
|
+
|
|
707
|
+
def _show_table_schema(self, tbl: str) -> None:
|
|
708
|
+
cols = self._schema.get(tbl, [])
|
|
709
|
+
lines = [f"-- {tbl}", f'CREATE TABLE "{_quote_ident(tbl)}" (']
|
|
710
|
+
for i, col in enumerate(cols):
|
|
711
|
+
pk = " PRIMARY KEY" if col.get("pk") else ""
|
|
712
|
+
nn = " NOT NULL" if col.get("notnull") else ""
|
|
713
|
+
df = f" DEFAULT {col['default']}" if col.get("default") else ""
|
|
714
|
+
sep = "," if i < len(cols) - 1 else ""
|
|
715
|
+
lines.append(
|
|
716
|
+
f' "{_quote_ident(col["name"])}" {col["type"]}{pk}{nn}{df}{sep}'
|
|
717
|
+
)
|
|
718
|
+
lines.append(");")
|
|
719
|
+
self._set_editor_text("\n".join(lines))
|
|
720
|
+
|
|
721
|
+
def _build_editor_area(self, t: Any, parent: tk.Widget) -> None:
|
|
722
|
+
vpaned = tk.PanedWindow(
|
|
723
|
+
parent, orient="vertical", bg=t.border, sashwidth=4)
|
|
724
|
+
vpaned.pack(fill="both", expand=True)
|
|
725
|
+
|
|
726
|
+
editor_frame = tk.Frame(vpaned, bg=t.panel_bg)
|
|
727
|
+
vpaned.add(editor_frame, minsize=100, height=260)
|
|
728
|
+
self._build_editor(t, editor_frame)
|
|
729
|
+
|
|
730
|
+
result_frame = tk.Frame(vpaned, bg=t.panel_bg)
|
|
731
|
+
vpaned.add(result_frame, minsize=80)
|
|
732
|
+
self._build_results(t, result_frame)
|
|
733
|
+
|
|
734
|
+
def _build_editor(self, t: Any, parent: tk.Widget) -> None:
|
|
735
|
+
toolbar = tk.Frame(parent, bg=t.sidebar_bg)
|
|
736
|
+
toolbar.pack(fill="x")
|
|
737
|
+
|
|
738
|
+
def _btn(lbl: str, cmd: Any, accent: bool = False) -> tk.Label:
|
|
739
|
+
return make_toolbar_button(
|
|
740
|
+
toolbar, t, lbl, cmd, accent=accent, outer_pady=3
|
|
741
|
+
)
|
|
742
|
+
|
|
743
|
+
_btn(_t("sql.run_btn", "▶ Executar F5"), self._run_query, accent=True)
|
|
744
|
+
_btn(_t("sql.run_sel_btn", "▶ Seleção"), self._run_selection)
|
|
745
|
+
_btn(_t("sql.format_btn", "⬛ Formatar"), self._format_sql)
|
|
746
|
+
_btn(_t("sql.explain_btn", "📊 EXPLAIN"), self._explain_query)
|
|
747
|
+
_btn(_t("sql.clear_btn", "🗑 Limpar"), self._clear_editor)
|
|
748
|
+
_btn(_t("sql.history_btn", "⏱ Histórico"), self._show_history)
|
|
749
|
+
_btn(_t("sql.save_btn", "💾 Salvar .sql"), self._save_sql)
|
|
750
|
+
_btn(_t("sql.open_btn", "📂 Abrir .sql"), self._open_sql)
|
|
751
|
+
|
|
752
|
+
self._editor_info = tk.Label(
|
|
753
|
+
toolbar, text="", bg=t.sidebar_bg, fg=t.fg_muted, font=(FONT_UI, 7)
|
|
754
|
+
)
|
|
755
|
+
self._editor_info.pack(side="right", padx=8)
|
|
756
|
+
|
|
757
|
+
editor_wrap = tk.Frame(parent, bg=t.editor_bg)
|
|
758
|
+
editor_wrap.pack(fill="both", expand=True)
|
|
759
|
+
|
|
760
|
+
self._line_nums = tk.Text(
|
|
761
|
+
editor_wrap,
|
|
762
|
+
width=4,
|
|
763
|
+
bg=t.sidebar_bg,
|
|
764
|
+
fg=t.fg_muted,
|
|
765
|
+
font=(FONT_MONO, 10),
|
|
766
|
+
relief="flat",
|
|
767
|
+
state="disabled",
|
|
768
|
+
padx=4,
|
|
769
|
+
pady=4,
|
|
770
|
+
wrap="none",
|
|
771
|
+
)
|
|
772
|
+
self._line_nums.pack(side="left", fill="y")
|
|
773
|
+
|
|
774
|
+
self._editor = tk.Text(
|
|
775
|
+
editor_wrap,
|
|
776
|
+
bg=t.editor_bg,
|
|
777
|
+
fg=t.fg,
|
|
778
|
+
insertbackground=t.cursor,
|
|
779
|
+
font=(FONT_MONO, 10),
|
|
780
|
+
relief="flat",
|
|
781
|
+
bd=0,
|
|
782
|
+
padx=8,
|
|
783
|
+
pady=4,
|
|
784
|
+
wrap="none",
|
|
785
|
+
selectbackground=t.sel_bg,
|
|
786
|
+
undo=True,
|
|
787
|
+
)
|
|
788
|
+
vsb = ttk.Scrollbar(editor_wrap, orient="vertical",
|
|
789
|
+
command=self._editor.yview)
|
|
790
|
+
hsb = ttk.Scrollbar(parent, orient="horizontal",
|
|
791
|
+
command=self._editor.xview)
|
|
792
|
+
self._editor.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
|
|
793
|
+
vsb.pack(side="right", fill="y")
|
|
794
|
+
self._editor.pack(fill="both", expand=True)
|
|
795
|
+
hsb.pack(fill="x")
|
|
796
|
+
|
|
797
|
+
self._editor.tag_configure(
|
|
798
|
+
"kw", foreground="#569cd6", font=(FONT_MONO, 10, "bold")
|
|
799
|
+
)
|
|
800
|
+
self._editor.tag_configure("str", foreground="#ce9178")
|
|
801
|
+
self._editor.tag_configure("num", foreground="#b5cea8")
|
|
802
|
+
self._editor.tag_configure(
|
|
803
|
+
"cmt", foreground="#6a9955", font=(FONT_MONO, 10, "italic")
|
|
804
|
+
)
|
|
805
|
+
|
|
806
|
+
self._editor.bind("<KeyRelease>", self._on_key_release)
|
|
807
|
+
self._editor.bind("<F5>", lambda _: self._run_query())
|
|
808
|
+
self._editor.bind("<Control-Return>", lambda _: self._run_query())
|
|
809
|
+
self._editor.bind("<Control-space>", self._show_autocomplete)
|
|
810
|
+
self._editor.bind("<Tab>", self._handle_tab)
|
|
811
|
+
|
|
812
|
+
self._ac_popup: tk.Toplevel | None = None
|
|
813
|
+
|
|
814
|
+
self._editor.insert(
|
|
815
|
+
"end",
|
|
816
|
+
"-- "
|
|
817
|
+
+ _t("sql.editor_hint",
|
|
818
|
+
"Escreva SQL aqui. F5 ou Ctrl+Enter para executar.")
|
|
819
|
+
+ "\n"
|
|
820
|
+
"SELECT sqlite_version();\n",
|
|
821
|
+
)
|
|
822
|
+
self._update_line_numbers()
|
|
823
|
+
|
|
824
|
+
def _on_key_release(self, _e: Any = None) -> None:
|
|
825
|
+
self._update_line_numbers()
|
|
826
|
+
self._highlight_syntax()
|
|
827
|
+
self._update_editor_info()
|
|
828
|
+
|
|
829
|
+
def _update_line_numbers(self) -> None:
|
|
830
|
+
self._line_nums.config(state="normal")
|
|
831
|
+
self._line_nums.delete("1.0", "end")
|
|
832
|
+
count = int(self._editor.index("end-1c").split(".")[0])
|
|
833
|
+
self._line_nums.insert("end", "\n".join(str(i)
|
|
834
|
+
for i in range(1, count + 1)))
|
|
835
|
+
self._line_nums.config(state="disabled")
|
|
836
|
+
|
|
837
|
+
def _update_editor_info(self) -> None:
|
|
838
|
+
idx = self._editor.index("insert")
|
|
839
|
+
line, col = idx.split(".")
|
|
840
|
+
total = int(self._editor.index("end-1c").split(".")[0])
|
|
841
|
+
self._editor_info.config(text=f"L{line}:C{col} | {total} linhas")
|
|
842
|
+
|
|
843
|
+
def _highlight_syntax(self) -> None:
|
|
844
|
+
txt = self._editor
|
|
845
|
+
for tag in ("kw", "str", "num", "cmt"):
|
|
846
|
+
txt.tag_remove(tag, "1.0", "end")
|
|
847
|
+
|
|
848
|
+
content = txt.get("1.0", "end")
|
|
849
|
+
|
|
850
|
+
kw_pattern = r"\b(" + "|".join(_SQL_KW) + r")\b"
|
|
851
|
+
for m in re.finditer(kw_pattern, content, re.IGNORECASE):
|
|
852
|
+
txt.tag_add("kw", f"1.0+{m.start()}c", f"1.0+{m.end()}c")
|
|
853
|
+
|
|
854
|
+
for m in re.finditer(r"'[^']*'|\"[^\"]*\"", content):
|
|
855
|
+
txt.tag_add("str", f"1.0+{m.start()}c", f"1.0+{m.end()}c")
|
|
856
|
+
|
|
857
|
+
for m in re.finditer(r"\b\d+(\.\d+)?\b", content):
|
|
858
|
+
txt.tag_add("num", f"1.0+{m.start()}c", f"1.0+{m.end()}c")
|
|
859
|
+
|
|
860
|
+
for m in re.finditer(r"--[^\n]*", content):
|
|
861
|
+
txt.tag_add("cmt", f"1.0+{m.start()}c", f"1.0+{m.end()}c")
|
|
862
|
+
|
|
863
|
+
for m in re.finditer(r"/\*.*?\*/", content, re.DOTALL):
|
|
864
|
+
txt.tag_add("cmt", f"1.0+{m.start()}c", f"1.0+{m.end()}c")
|
|
865
|
+
|
|
866
|
+
def _handle_tab(self, event: Any) -> str:
|
|
867
|
+
self._editor.insert("insert", " ")
|
|
868
|
+
return "break"
|
|
869
|
+
|
|
870
|
+
def _insert_to_editor(self, text: str) -> None:
|
|
871
|
+
self._editor.insert("insert", text)
|
|
872
|
+
self._editor.focus_set()
|
|
873
|
+
self._on_key_release()
|
|
874
|
+
|
|
875
|
+
def _set_editor_text(self, text: str) -> None:
|
|
876
|
+
self._editor.delete("1.0", "end")
|
|
877
|
+
self._editor.insert("1.0", text)
|
|
878
|
+
self._on_key_release()
|
|
879
|
+
|
|
880
|
+
def _get_editor_text(self) -> str:
|
|
881
|
+
return self._editor.get("1.0", "end-1c")
|
|
882
|
+
|
|
883
|
+
def _clear_editor(self) -> None:
|
|
884
|
+
self._editor.delete("1.0", "end")
|
|
885
|
+
self._on_key_release()
|
|
886
|
+
|
|
887
|
+
def _save_sql(self) -> None:
|
|
888
|
+
path = filedialog.asksaveasfilename(
|
|
889
|
+
defaultextension=".sql",
|
|
890
|
+
filetypes=[("SQL", "*.sql"),
|
|
891
|
+
(_t("sql.all_files", "Todos"), "*.*")],
|
|
892
|
+
)
|
|
893
|
+
if path:
|
|
894
|
+
Path(path).write_text(self._get_editor_text(), encoding="utf-8")
|
|
895
|
+
|
|
896
|
+
def _open_sql(self) -> None:
|
|
897
|
+
path = filedialog.askopenfilename(
|
|
898
|
+
filetypes=[
|
|
899
|
+
("SQL", "*.sql"),
|
|
900
|
+
("Text", "*.txt"),
|
|
901
|
+
(_t("sql.all_files", "Todos"), "*.*"),
|
|
902
|
+
]
|
|
903
|
+
)
|
|
904
|
+
if path:
|
|
905
|
+
self._set_editor_text(
|
|
906
|
+
Path(path).read_text(encoding="utf-8", errors="replace")
|
|
907
|
+
)
|
|
908
|
+
|
|
909
|
+
def _show_autocomplete(self, event: Any = None) -> str:
|
|
910
|
+
if self._ac_popup:
|
|
911
|
+
self._ac_popup.destroy()
|
|
912
|
+
self._ac_popup = None
|
|
913
|
+
|
|
914
|
+
idx = self._editor.index("insert")
|
|
915
|
+
line_text = self._editor.get(f"{idx.split('.')[0]}.0", idx)
|
|
916
|
+
m = re.search(r"[\w.]+$", line_text)
|
|
917
|
+
prefix = m.group(0).upper() if m else ""
|
|
918
|
+
|
|
919
|
+
candidates: list[str] = []
|
|
920
|
+
for kw in _SQL_KW:
|
|
921
|
+
if kw.startswith(prefix):
|
|
922
|
+
candidates.append(kw)
|
|
923
|
+
for tbl in self._schema:
|
|
924
|
+
if tbl.upper().startswith(prefix):
|
|
925
|
+
candidates.append(tbl)
|
|
926
|
+
for col in self._schema[tbl]:
|
|
927
|
+
cn = col["name"]
|
|
928
|
+
if cn.upper().startswith(prefix):
|
|
929
|
+
candidates.append(cn)
|
|
930
|
+
candidates = sorted(set(candidates))[:20]
|
|
931
|
+
|
|
932
|
+
if not candidates:
|
|
933
|
+
return "break"
|
|
934
|
+
|
|
935
|
+
t = self._tmgr.theme
|
|
936
|
+
x = self._editor.winfo_rootx() + 40
|
|
937
|
+
y = (
|
|
938
|
+
self._editor.winfo_rooty()
|
|
939
|
+
+ int(self._editor.index("insert").split(".")[0]) * 16
|
|
940
|
+
)
|
|
941
|
+
|
|
942
|
+
popup = tk.Toplevel(self)
|
|
943
|
+
popup.wm_overrideredirect(True)
|
|
944
|
+
popup.geometry(f"+{x}+{y}")
|
|
945
|
+
popup.config(bg=t.border)
|
|
946
|
+
self._ac_popup = popup
|
|
947
|
+
|
|
948
|
+
lb = tk.Listbox(
|
|
949
|
+
popup,
|
|
950
|
+
bg=t.panel_bg,
|
|
951
|
+
fg=t.fg,
|
|
952
|
+
font=(FONT_MONO, 9),
|
|
953
|
+
selectbackground=t.accent,
|
|
954
|
+
relief="flat",
|
|
955
|
+
bd=1,
|
|
956
|
+
activestyle="none",
|
|
957
|
+
width=28,
|
|
958
|
+
height=min(8, len(candidates)),
|
|
959
|
+
)
|
|
960
|
+
lb.pack(padx=1, pady=1)
|
|
961
|
+
for c in candidates:
|
|
962
|
+
lb.insert("end", c)
|
|
963
|
+
lb.selection_set(0)
|
|
964
|
+
|
|
965
|
+
def _commit(_e: Any = None) -> None:
|
|
966
|
+
sel = lb.curselection()
|
|
967
|
+
if not sel:
|
|
968
|
+
return
|
|
969
|
+
word = lb.get(sel[0])
|
|
970
|
+
start = self._editor.index("insert")
|
|
971
|
+
if prefix:
|
|
972
|
+
col_offset = int(start.split(".")[1])
|
|
973
|
+
new_col = col_offset - len(prefix)
|
|
974
|
+
start = f"{start.split('.')[0]}.{max(0, new_col)}"
|
|
975
|
+
self._editor.delete(start, "insert")
|
|
976
|
+
self._editor.insert("insert", word)
|
|
977
|
+
popup.destroy()
|
|
978
|
+
self._ac_popup = None
|
|
979
|
+
|
|
980
|
+
lb.bind("<Return>", _commit)
|
|
981
|
+
lb.bind("<Tab>", _commit)
|
|
982
|
+
lb.bind("<Double-1>", _commit)
|
|
983
|
+
lb.bind("<Escape>", lambda _: popup.destroy())
|
|
984
|
+
lb.focus_set()
|
|
985
|
+
|
|
986
|
+
return "break"
|
|
987
|
+
|
|
988
|
+
def _build_results(self, t: Any, parent: tk.Widget) -> None:
|
|
989
|
+
result_hdr = tk.Frame(parent, bg=t.sidebar_bg)
|
|
990
|
+
result_hdr.pack(fill="x")
|
|
991
|
+
tk.Label(
|
|
992
|
+
result_hdr,
|
|
993
|
+
text=_t("sql.results", "Resultados"),
|
|
994
|
+
bg=t.sidebar_bg,
|
|
995
|
+
fg=t.fg_muted,
|
|
996
|
+
font=(FONT_UI, 7, "bold"),
|
|
997
|
+
).pack(side="left", padx=8, pady=3)
|
|
998
|
+
|
|
999
|
+
self._result_info = tk.Label(
|
|
1000
|
+
result_hdr, text="", bg=t.sidebar_bg, fg=t.fg_muted, font=(FONT_UI, 7)
|
|
1001
|
+
)
|
|
1002
|
+
self._result_info.pack(side="left", padx=6)
|
|
1003
|
+
|
|
1004
|
+
def _exp_btn(lbl: str, cmd: Any) -> tk.Label:
|
|
1005
|
+
b = tk.Label(
|
|
1006
|
+
result_hdr,
|
|
1007
|
+
text=lbl,
|
|
1008
|
+
bg=t.sidebar_bg,
|
|
1009
|
+
fg=t.fg_muted,
|
|
1010
|
+
font=(FONT_UI, 7),
|
|
1011
|
+
padx=6,
|
|
1012
|
+
pady=2,
|
|
1013
|
+
cursor="hand2",
|
|
1014
|
+
)
|
|
1015
|
+
b.pack(side="right", padx=2)
|
|
1016
|
+
b.bind("<Button-1>", lambda _: cmd())
|
|
1017
|
+
return b
|
|
1018
|
+
|
|
1019
|
+
_exp_btn(_t("sql.export_csv", "📤 CSV"), self._export_csv)
|
|
1020
|
+
_exp_btn(_t("sql.export_json", "📤 JSON"), self._export_json)
|
|
1021
|
+
|
|
1022
|
+
grid_wrap = tk.Frame(parent, bg=t.panel_bg)
|
|
1023
|
+
grid_wrap.pack(fill="both", expand=True)
|
|
1024
|
+
|
|
1025
|
+
self._result_tree = ttk.Treeview(
|
|
1026
|
+
grid_wrap, show="headings", selectmode="extended"
|
|
1027
|
+
)
|
|
1028
|
+
self._result_vsb = ttk.Scrollbar(
|
|
1029
|
+
grid_wrap, orient="vertical", command=self._result_tree.yview
|
|
1030
|
+
)
|
|
1031
|
+
self._result_hsb = ttk.Scrollbar(
|
|
1032
|
+
grid_wrap, orient="horizontal", command=self._result_tree.xview
|
|
1033
|
+
)
|
|
1034
|
+
self._result_tree.configure(
|
|
1035
|
+
yscrollcommand=self._result_vsb.set, xscrollcommand=self._result_hsb.set
|
|
1036
|
+
)
|
|
1037
|
+
|
|
1038
|
+
self._result_vsb.pack(side="right", fill="y")
|
|
1039
|
+
self._result_tree.pack(fill="both", expand=True, padx=(8, 0))
|
|
1040
|
+
self._result_hsb.pack(fill="x", padx=8)
|
|
1041
|
+
|
|
1042
|
+
self._msg_lbl = tk.Label(
|
|
1043
|
+
parent,
|
|
1044
|
+
text="",
|
|
1045
|
+
bg=t.editor_bg,
|
|
1046
|
+
fg=t.fg_muted,
|
|
1047
|
+
font=(FONT_MONO, 8),
|
|
1048
|
+
anchor="w",
|
|
1049
|
+
)
|
|
1050
|
+
self._msg_lbl.pack(fill="x", padx=8, pady=2)
|
|
1051
|
+
|
|
1052
|
+
self._result_cols: list[str] = []
|
|
1053
|
+
self._result_rows: list[tuple] = []
|
|
1054
|
+
|
|
1055
|
+
def _show_results(self, cols: list[str], rows: list[tuple], msg: str) -> None:
|
|
1056
|
+
t = self._tmgr.theme
|
|
1057
|
+
self._result_cols = cols
|
|
1058
|
+
self._result_rows = rows
|
|
1059
|
+
|
|
1060
|
+
ok = "linha" in msg.lower() or "ok" in msg.lower()
|
|
1061
|
+
err = "❌" in msg
|
|
1062
|
+
fg = "#a6e3a1" if ok else "#f38ba8" if err else t.fg_muted
|
|
1063
|
+
self._msg_lbl.config(text=msg, fg=fg)
|
|
1064
|
+
|
|
1065
|
+
self._result_tree.delete(*self._result_tree.get_children())
|
|
1066
|
+
if not cols:
|
|
1067
|
+
self._result_info.config(text="")
|
|
1068
|
+
return
|
|
1069
|
+
|
|
1070
|
+
self._result_tree["columns"] = cols
|
|
1071
|
+
for col in cols:
|
|
1072
|
+
self._result_tree.heading(
|
|
1073
|
+
col, text=col, command=lambda c=col: self._sort_by(c)
|
|
1074
|
+
)
|
|
1075
|
+
self._result_tree.column(col, width=120, minwidth=50, stretch=True)
|
|
1076
|
+
|
|
1077
|
+
for i, row in enumerate(rows):
|
|
1078
|
+
tag = "even" if i % 2 == 0 else "odd"
|
|
1079
|
+
self._result_tree.insert(
|
|
1080
|
+
"",
|
|
1081
|
+
"end",
|
|
1082
|
+
values=[str(v) if v is not None else "NULL" for v in row],
|
|
1083
|
+
tags=(tag,),
|
|
1084
|
+
)
|
|
1085
|
+
|
|
1086
|
+
self._result_tree.tag_configure("even", background=t.editor_bg)
|
|
1087
|
+
self._result_tree.tag_configure("odd", background=t.panel_bg)
|
|
1088
|
+
self._result_info.config(text=f"{len(rows)} × {len(cols)}")
|
|
1089
|
+
|
|
1090
|
+
def _sort_by(self, col: str) -> None:
|
|
1091
|
+
if not self._result_rows:
|
|
1092
|
+
return
|
|
1093
|
+
try:
|
|
1094
|
+
idx = self._result_cols.index(col)
|
|
1095
|
+
except ValueError:
|
|
1096
|
+
return
|
|
1097
|
+
|
|
1098
|
+
def _key(row: tuple) -> Any:
|
|
1099
|
+
v = row[idx]
|
|
1100
|
+
try:
|
|
1101
|
+
return (0, float(str(v)))
|
|
1102
|
+
except (ValueError, TypeError):
|
|
1103
|
+
return (1, str(v).lower())
|
|
1104
|
+
|
|
1105
|
+
self._result_rows = sorted(self._result_rows, key=_key)
|
|
1106
|
+
self._show_results(
|
|
1107
|
+
self._result_cols, self._result_rows, self._msg_lbl.cget("text")
|
|
1108
|
+
)
|
|
1109
|
+
|
|
1110
|
+
def _export_csv(self) -> None:
|
|
1111
|
+
if not self._result_rows:
|
|
1112
|
+
return
|
|
1113
|
+
path = filedialog.asksaveasfilename(
|
|
1114
|
+
defaultextension=".csv",
|
|
1115
|
+
filetypes=[("CSV", "*.csv"),
|
|
1116
|
+
(_t("sql.all_files", "Todos"), "*.*")],
|
|
1117
|
+
)
|
|
1118
|
+
if not path:
|
|
1119
|
+
return
|
|
1120
|
+
with open(path, "w", newline="", encoding="utf-8") as f:
|
|
1121
|
+
w = _csv.writer(f)
|
|
1122
|
+
w.writerow(self._result_cols)
|
|
1123
|
+
w.writerows(self._result_rows)
|
|
1124
|
+
self._set_status(f"CSV exportado: {path}")
|
|
1125
|
+
|
|
1126
|
+
def _export_json(self) -> None:
|
|
1127
|
+
if not self._result_rows:
|
|
1128
|
+
return
|
|
1129
|
+
path = filedialog.asksaveasfilename(
|
|
1130
|
+
defaultextension=".json",
|
|
1131
|
+
filetypes=[("JSON", "*.json"),
|
|
1132
|
+
(_t("sql.all_files", "Todos"), "*.*")],
|
|
1133
|
+
)
|
|
1134
|
+
if not path:
|
|
1135
|
+
return
|
|
1136
|
+
data = [
|
|
1137
|
+
dict(zip(self._result_cols, row, strict=False)) for row in self._result_rows
|
|
1138
|
+
]
|
|
1139
|
+
Path(path).write_text(
|
|
1140
|
+
json.dumps(data, indent=2, ensure_ascii=False, default=str),
|
|
1141
|
+
encoding="utf-8",
|
|
1142
|
+
)
|
|
1143
|
+
self._set_status(f"JSON exportado: {path}")
|
|
1144
|
+
|
|
1145
|
+
def _run_query(self) -> None:
|
|
1146
|
+
sql = self._get_editor_text().strip()
|
|
1147
|
+
if sql:
|
|
1148
|
+
self._execute_sql(sql)
|
|
1149
|
+
|
|
1150
|
+
def _run_selection(self) -> None:
|
|
1151
|
+
try:
|
|
1152
|
+
sql = self._editor.get("sel.first", "sel.last").strip()
|
|
1153
|
+
except tk.TclError:
|
|
1154
|
+
sql = self._get_editor_text().strip()
|
|
1155
|
+
if sql:
|
|
1156
|
+
self._execute_sql(sql)
|
|
1157
|
+
|
|
1158
|
+
def _explain_query(self) -> None:
|
|
1159
|
+
sql = self._get_editor_text().strip()
|
|
1160
|
+
if sql:
|
|
1161
|
+
self._execute_sql(f"EXPLAIN QUERY PLAN {sql}")
|
|
1162
|
+
|
|
1163
|
+
def _execute_sql(self, sql: str) -> None:
|
|
1164
|
+
if not self._active_conn or not self._active_conn.connected:
|
|
1165
|
+
messagebox.showwarning(
|
|
1166
|
+
_t("sql.not_connected_title", "Sem conexão"),
|
|
1167
|
+
_t("sql.connect_first", "Conecte a um banco de dados primeiro."),
|
|
1168
|
+
)
|
|
1169
|
+
return
|
|
1170
|
+
if self._busy:
|
|
1171
|
+
return
|
|
1172
|
+
|
|
1173
|
+
self._busy = True
|
|
1174
|
+
self._set_status(_t("sql.running", "Executando..."))
|
|
1175
|
+
self._history_add(sql)
|
|
1176
|
+
|
|
1177
|
+
def _work() -> None:
|
|
1178
|
+
cols, rows, msg = self._active_conn.execute(
|
|
1179
|
+
sql) # type: ignore[union-attr]
|
|
1180
|
+
self.after(0, lambda: self._on_query_done(cols, rows, msg))
|
|
1181
|
+
|
|
1182
|
+
threading.Thread(target=_work, daemon=True).start()
|
|
1183
|
+
|
|
1184
|
+
def _on_query_done(self, cols: list[str], rows: list[tuple], msg: str) -> None:
|
|
1185
|
+
self._busy = False
|
|
1186
|
+
self._show_results(cols, rows, msg)
|
|
1187
|
+
self._set_status(msg)
|
|
1188
|
+
if any(kw in msg.upper() for kw in ("CREATE", "DROP", "ALTER", "RENAME")):
|
|
1189
|
+
self.after(300, self._refresh_schema)
|
|
1190
|
+
|
|
1191
|
+
def _format_sql(self) -> None:
|
|
1192
|
+
sql = self._get_editor_text()
|
|
1193
|
+
if not sql.strip():
|
|
1194
|
+
return
|
|
1195
|
+
|
|
1196
|
+
kws = "|".join(_SQL_KW)
|
|
1197
|
+
formatted = re.sub(
|
|
1198
|
+
rf"\b({kws})\b",
|
|
1199
|
+
lambda m: m.group(0).upper(),
|
|
1200
|
+
sql,
|
|
1201
|
+
flags=re.IGNORECASE,
|
|
1202
|
+
)
|
|
1203
|
+
for kw in (
|
|
1204
|
+
"SELECT",
|
|
1205
|
+
"FROM",
|
|
1206
|
+
"WHERE",
|
|
1207
|
+
"JOIN",
|
|
1208
|
+
"LEFT JOIN",
|
|
1209
|
+
"RIGHT JOIN",
|
|
1210
|
+
"INNER JOIN",
|
|
1211
|
+
"OUTER JOIN",
|
|
1212
|
+
"GROUP BY",
|
|
1213
|
+
"ORDER BY",
|
|
1214
|
+
"HAVING",
|
|
1215
|
+
"LIMIT",
|
|
1216
|
+
"UNION",
|
|
1217
|
+
"EXCEPT",
|
|
1218
|
+
"INTERSECT",
|
|
1219
|
+
"VALUES",
|
|
1220
|
+
):
|
|
1221
|
+
formatted = re.sub(
|
|
1222
|
+
rf"(?<!\n)\b{kw}\b", f"\n{kw}", formatted, flags=re.IGNORECASE
|
|
1223
|
+
)
|
|
1224
|
+
self._set_editor_text(formatted.strip())
|
|
1225
|
+
|
|
1226
|
+
def _history_add(self, sql: str) -> None:
|
|
1227
|
+
entry = {"sql": sql, "ts": time.strftime(
|
|
1228
|
+
"%Y-%m-%d %H:%M:%S"), "fav": False}
|
|
1229
|
+
if self._history and self._history[-1]["sql"] == sql:
|
|
1230
|
+
return
|
|
1231
|
+
self._history.append(entry)
|
|
1232
|
+
_save_history(self._history)
|
|
1233
|
+
|
|
1234
|
+
def _show_history(self) -> None:
|
|
1235
|
+
_HistoryWindow(self, self._tmgr, self._history,
|
|
1236
|
+
on_select=self._set_editor_text)
|
|
1237
|
+
|
|
1238
|
+
def _on_connect(self) -> None:
|
|
1239
|
+
idx = self._conn_cb.current()
|
|
1240
|
+
if idx < 0 or idx >= len(self._connections):
|
|
1241
|
+
if not self._connections:
|
|
1242
|
+
self._new_connection()
|
|
1243
|
+
return
|
|
1244
|
+
profile = self._connections[idx]
|
|
1245
|
+
self._set_status(
|
|
1246
|
+
_t("sql.connecting", f"Conectando a {profile.display}..."))
|
|
1247
|
+
|
|
1248
|
+
def _work() -> None:
|
|
1249
|
+
conn = DBConnection(profile)
|
|
1250
|
+
try:
|
|
1251
|
+
conn.connect()
|
|
1252
|
+
self.after(0, lambda: self._on_connected(conn, profile))
|
|
1253
|
+
except Exception as exc:
|
|
1254
|
+
err = str(exc)
|
|
1255
|
+
self.after(0, lambda: self._on_connect_error(err))
|
|
1256
|
+
|
|
1257
|
+
threading.Thread(target=_work, daemon=True).start()
|
|
1258
|
+
|
|
1259
|
+
def _on_connected(self, conn: DBConnection, profile: Connection) -> None:
|
|
1260
|
+
if self._active_conn:
|
|
1261
|
+
self._active_conn.close()
|
|
1262
|
+
self._active_conn = conn
|
|
1263
|
+
self._active_profile = profile
|
|
1264
|
+
t = self._tmgr.theme
|
|
1265
|
+
self._conn_badge.config(text=f"● {profile.display}", fg=t.t_func)
|
|
1266
|
+
self._set_status(
|
|
1267
|
+
_t("sql.connected_ok", f"Conectado a {profile.display}"))
|
|
1268
|
+
self._refresh_schema()
|
|
1269
|
+
|
|
1270
|
+
def _on_connect_error(self, err: str) -> None:
|
|
1271
|
+
err_lower = err.lower()
|
|
1272
|
+
if "connection refused" in err_lower:
|
|
1273
|
+
hint = _t(
|
|
1274
|
+
"sql.err_refused",
|
|
1275
|
+
"Conexão recusada - servidor não está rodando ou porta/host incorretos.",
|
|
1276
|
+
)
|
|
1277
|
+
elif "permission denied" in err_lower or "access denied" in err_lower:
|
|
1278
|
+
hint = _t("sql.err_access",
|
|
1279
|
+
"Permissão negada - verifique usuário e senha.")
|
|
1280
|
+
elif "does not exist" in err_lower or "unknown database" in err_lower:
|
|
1281
|
+
hint = _t(
|
|
1282
|
+
"sql.err_no_db", "Banco não encontrado - verifique o nome do banco."
|
|
1283
|
+
)
|
|
1284
|
+
elif "no such file" in err_lower:
|
|
1285
|
+
hint = _t(
|
|
1286
|
+
"sql.err_no_file", "Arquivo não encontrado - verifique o caminho."
|
|
1287
|
+
)
|
|
1288
|
+
elif "module" in err_lower and "import" in err_lower:
|
|
1289
|
+
hint = _t(
|
|
1290
|
+
"sql.err_driver",
|
|
1291
|
+
"Driver não instalado - execute: pip install <driver>.",
|
|
1292
|
+
)
|
|
1293
|
+
elif "could not connect" in err_lower or "network" in err_lower:
|
|
1294
|
+
hint = _t(
|
|
1295
|
+
"sql.err_network", "Erro de rede - verifique host, porta e firewall."
|
|
1296
|
+
)
|
|
1297
|
+
else:
|
|
1298
|
+
hint = err
|
|
1299
|
+
detail = (
|
|
1300
|
+
(hint + "\n\n" + _t("sql.err_detail", "Detalhe:") + " " + err)
|
|
1301
|
+
if hint != err
|
|
1302
|
+
else err
|
|
1303
|
+
)
|
|
1304
|
+
self._set_status(f"\u274c {hint}")
|
|
1305
|
+
messagebox.showerror(
|
|
1306
|
+
_t("sql.error_title", "Erro de conexão"), detail, parent=self
|
|
1307
|
+
)
|
|
1308
|
+
|
|
1309
|
+
def _on_disconnect(self) -> None:
|
|
1310
|
+
if self._active_conn:
|
|
1311
|
+
self._active_conn.close()
|
|
1312
|
+
self._active_conn = None
|
|
1313
|
+
self._active_profile = None
|
|
1314
|
+
t = self._tmgr.theme
|
|
1315
|
+
self._conn_badge.config(
|
|
1316
|
+
text=_t("sql.no_connection", "● sem conexão"), fg=t.fg_muted
|
|
1317
|
+
)
|
|
1318
|
+
self._schema_tree.delete(*self._schema_tree.get_children())
|
|
1319
|
+
self._set_status(_t("sql.disconnected", "Desconectado."))
|
|
1320
|
+
|
|
1321
|
+
def _new_connection(self) -> None:
|
|
1322
|
+
_ConnectionDialog(self, self._tmgr, None, on_save=self._on_conn_saved)
|
|
1323
|
+
|
|
1324
|
+
def _edit_connection(self) -> None:
|
|
1325
|
+
idx = self._conn_cb.current()
|
|
1326
|
+
if 0 <= idx < len(self._connections):
|
|
1327
|
+
_ConnectionDialog(
|
|
1328
|
+
self, self._tmgr, self._connections[idx], on_save=self._on_conn_saved
|
|
1329
|
+
)
|
|
1330
|
+
|
|
1331
|
+
def _delete_connection(self) -> None:
|
|
1332
|
+
idx = self._conn_cb.current()
|
|
1333
|
+
if idx < 0 or idx >= len(self._connections):
|
|
1334
|
+
return
|
|
1335
|
+
name = self._connections[idx].name
|
|
1336
|
+
if messagebox.askyesno(
|
|
1337
|
+
_t("sql.del_conn_title", "Remover"),
|
|
1338
|
+
_t("sql.del_conn_confirm", name=name),
|
|
1339
|
+
):
|
|
1340
|
+
self._connections.pop(idx)
|
|
1341
|
+
_save_connections(self._connections)
|
|
1342
|
+
self._refresh_conn_combo()
|
|
1343
|
+
|
|
1344
|
+
def _on_conn_saved(self, conn: Connection) -> None:
|
|
1345
|
+
existing = next(
|
|
1346
|
+
(i for i, c in enumerate(self._connections) if c.id == conn.id), None
|
|
1347
|
+
)
|
|
1348
|
+
if existing is not None:
|
|
1349
|
+
self._connections[existing] = conn
|
|
1350
|
+
else:
|
|
1351
|
+
self._connections.append(conn)
|
|
1352
|
+
_save_connections(self._connections)
|
|
1353
|
+
self._refresh_conn_combo()
|
|
1354
|
+
|
|
1355
|
+
def _set_status(self, msg: str) -> None:
|
|
1356
|
+
self._status_var.set(msg)
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
class _HistoryWindow(tk.Toplevel):
|
|
1360
|
+
def __init__(
|
|
1361
|
+
self, parent: tk.Widget, tmgr: Any, history: list[dict], on_select: Any
|
|
1362
|
+
) -> None:
|
|
1363
|
+
super().__init__(parent)
|
|
1364
|
+
t = tmgr.theme
|
|
1365
|
+
self.title(_t("sql.history_title", "Histórico de Queries"))
|
|
1366
|
+
self.geometry("680x500")
|
|
1367
|
+
self.config(bg=t.panel_bg)
|
|
1368
|
+
safe_grab_set(self)
|
|
1369
|
+
|
|
1370
|
+
hdr = tk.Frame(self, bg=t.activity_bg)
|
|
1371
|
+
hdr.pack(fill="x")
|
|
1372
|
+
tk.Label(
|
|
1373
|
+
hdr,
|
|
1374
|
+
text=_t("sql.history_title", "Histórico"),
|
|
1375
|
+
bg=t.activity_bg,
|
|
1376
|
+
fg=t.fg,
|
|
1377
|
+
font=(FONT_UI, 11, "bold"),
|
|
1378
|
+
).pack(side="left", padx=12, pady=8)
|
|
1379
|
+
tk.Label(
|
|
1380
|
+
hdr,
|
|
1381
|
+
text=_t("sql.history_hint", "Duplo clique para inserir no editor"),
|
|
1382
|
+
bg=t.activity_bg,
|
|
1383
|
+
fg=t.fg_muted,
|
|
1384
|
+
font=(FONT_UI, 8),
|
|
1385
|
+
).pack(side="left")
|
|
1386
|
+
|
|
1387
|
+
tk.Frame(self, bg=t.border, height=1).pack(fill="x")
|
|
1388
|
+
|
|
1389
|
+
paned = tk.PanedWindow(self, orient="horizontal",
|
|
1390
|
+
bg=t.border, sashwidth=3)
|
|
1391
|
+
paned.pack(fill="both", expand=True)
|
|
1392
|
+
|
|
1393
|
+
list_frame = tk.Frame(paned, bg=t.panel_bg)
|
|
1394
|
+
paned.add(list_frame, width=300)
|
|
1395
|
+
|
|
1396
|
+
lb = tk.Listbox(
|
|
1397
|
+
list_frame,
|
|
1398
|
+
bg=t.editor_bg,
|
|
1399
|
+
fg=t.fg,
|
|
1400
|
+
font=(FONT_MONO, 9),
|
|
1401
|
+
relief="flat",
|
|
1402
|
+
bd=0,
|
|
1403
|
+
selectbackground=t.accent,
|
|
1404
|
+
activestyle="none",
|
|
1405
|
+
)
|
|
1406
|
+
vsb = ttk.Scrollbar(list_frame, orient="vertical", command=lb.yview)
|
|
1407
|
+
lb.configure(yscrollcommand=vsb.set)
|
|
1408
|
+
vsb.pack(side="right", fill="y")
|
|
1409
|
+
lb.pack(fill="both", expand=True)
|
|
1410
|
+
|
|
1411
|
+
prev_frame = tk.Frame(paned, bg=t.panel_bg)
|
|
1412
|
+
paned.add(prev_frame)
|
|
1413
|
+
|
|
1414
|
+
prev_txt = tk.Text(
|
|
1415
|
+
prev_frame,
|
|
1416
|
+
bg=t.editor_bg,
|
|
1417
|
+
fg=t.fg,
|
|
1418
|
+
font=(FONT_MONO, 9),
|
|
1419
|
+
relief="flat",
|
|
1420
|
+
bd=8,
|
|
1421
|
+
wrap="word",
|
|
1422
|
+
state="disabled",
|
|
1423
|
+
)
|
|
1424
|
+
prev_txt.pack(fill="both", expand=True)
|
|
1425
|
+
|
|
1426
|
+
for entry in reversed(history):
|
|
1427
|
+
ts = entry.get("ts", "")
|
|
1428
|
+
sql = entry.get("sql", "").replace("\n", " ")[:60]
|
|
1429
|
+
fav = "⭐ " if entry.get("fav") else ""
|
|
1430
|
+
lb.insert("end", f"{fav}{ts} {sql}")
|
|
1431
|
+
|
|
1432
|
+
def _on_sel(_e: Any = None) -> None:
|
|
1433
|
+
sel = lb.curselection()
|
|
1434
|
+
if not sel:
|
|
1435
|
+
return
|
|
1436
|
+
idx = len(history) - 1 - sel[0]
|
|
1437
|
+
entry = history[idx]
|
|
1438
|
+
prev_txt.config(state="normal")
|
|
1439
|
+
prev_txt.delete("1.0", "end")
|
|
1440
|
+
prev_txt.insert("1.0", entry.get("sql", ""))
|
|
1441
|
+
prev_txt.config(state="disabled")
|
|
1442
|
+
|
|
1443
|
+
def _on_double(_e: Any = None) -> None:
|
|
1444
|
+
sel = lb.curselection()
|
|
1445
|
+
if not sel:
|
|
1446
|
+
return
|
|
1447
|
+
idx = len(history) - 1 - sel[0]
|
|
1448
|
+
on_select(history[idx].get("sql", ""))
|
|
1449
|
+
self.destroy()
|
|
1450
|
+
|
|
1451
|
+
lb.bind("<<ListboxSelect>>", _on_sel)
|
|
1452
|
+
lb.bind("<Double-1>", _on_double)
|
|
1453
|
+
|
|
1454
|
+
btn_row = tk.Frame(self, bg=t.panel_bg)
|
|
1455
|
+
btn_row.pack(fill="x", padx=8, pady=6)
|
|
1456
|
+
use_b = tk.Label(
|
|
1457
|
+
btn_row,
|
|
1458
|
+
text=_t("sql.history_use", "↑ Usar no editor"),
|
|
1459
|
+
bg=t.accent,
|
|
1460
|
+
fg="#FFF",
|
|
1461
|
+
font=(FONT_UI, 9),
|
|
1462
|
+
padx=12,
|
|
1463
|
+
pady=5,
|
|
1464
|
+
cursor="hand2",
|
|
1465
|
+
)
|
|
1466
|
+
use_b.pack(side="right", padx=4)
|
|
1467
|
+
use_b.bind("<Button-1>", _on_double)
|
|
1468
|
+
|
|
1469
|
+
|
|
1470
|
+
class _FormRowBuilder:
|
|
1471
|
+
"""Cria labels/entries de formulário empilhados em ``grid()``, uma linha por vez.
|
|
1472
|
+
|
|
1473
|
+
Usado pelo ``_ConnectionDialog`` tanto no formulário estático quanto na
|
|
1474
|
+
área de campos dinâmicos por driver; cada instância mantém o próprio
|
|
1475
|
+
contador ``row`` e é parametrizada pelo frame/tema de destino.
|
|
1476
|
+
"""
|
|
1477
|
+
|
|
1478
|
+
def __init__(self, frame: tk.Widget, theme: Any) -> None:
|
|
1479
|
+
self._frame = frame
|
|
1480
|
+
self._t = theme
|
|
1481
|
+
self.row = 0
|
|
1482
|
+
|
|
1483
|
+
def take_row(self) -> int:
|
|
1484
|
+
"""Retorna a linha atual e avança o contador (para grids manuais)."""
|
|
1485
|
+
r = self.row
|
|
1486
|
+
self.row += 1
|
|
1487
|
+
return r
|
|
1488
|
+
|
|
1489
|
+
def lbl(self, text: str) -> tk.Label:
|
|
1490
|
+
t = self._t
|
|
1491
|
+
w = tk.Label(
|
|
1492
|
+
self._frame,
|
|
1493
|
+
text=text,
|
|
1494
|
+
bg=t.panel_bg,
|
|
1495
|
+
fg=t.fg_muted,
|
|
1496
|
+
font=(FONT_UI, 8),
|
|
1497
|
+
anchor="w",
|
|
1498
|
+
)
|
|
1499
|
+
w.grid(row=self.take_row(), column=0, sticky="w", padx=16, pady=(6, 0))
|
|
1500
|
+
return w
|
|
1501
|
+
|
|
1502
|
+
def ent(self, var: tk.Variable, show: str = "") -> tk.Entry:
|
|
1503
|
+
t = self._t
|
|
1504
|
+
e = tk.Entry(
|
|
1505
|
+
self._frame,
|
|
1506
|
+
textvariable=var,
|
|
1507
|
+
bg=t.editor_bg,
|
|
1508
|
+
fg=t.fg,
|
|
1509
|
+
insertbackground=t.cursor,
|
|
1510
|
+
relief="flat",
|
|
1511
|
+
bd=0,
|
|
1512
|
+
font=(FONT_UI, 10),
|
|
1513
|
+
highlightthickness=1,
|
|
1514
|
+
highlightbackground=t.border,
|
|
1515
|
+
show=show,
|
|
1516
|
+
)
|
|
1517
|
+
e.grid(
|
|
1518
|
+
row=self.take_row(), column=0, sticky="ew", padx=16, pady=(1, 0), ipady=5
|
|
1519
|
+
)
|
|
1520
|
+
return e
|
|
1521
|
+
|
|
1522
|
+
|
|
1523
|
+
class _ConnectionDialog(tk.Toplevel):
|
|
1524
|
+
def __init__(
|
|
1525
|
+
self, parent: tk.Widget, tmgr: Any, conn: Connection | None, on_save: Any
|
|
1526
|
+
) -> None:
|
|
1527
|
+
super().__init__(parent)
|
|
1528
|
+
t = tmgr.theme
|
|
1529
|
+
self._tmgr = tmgr
|
|
1530
|
+
self._conn = conn or Connection()
|
|
1531
|
+
self._on_save = on_save
|
|
1532
|
+
is_edit = conn is not None
|
|
1533
|
+
|
|
1534
|
+
self.title(
|
|
1535
|
+
_t("sql.edit_conn_title", "Editar Conexão")
|
|
1536
|
+
if is_edit
|
|
1537
|
+
else _t("sql.new_conn_title", "Nova Conexão")
|
|
1538
|
+
)
|
|
1539
|
+
self.geometry("480x500")
|
|
1540
|
+
self.resizable(False, True)
|
|
1541
|
+
self.config(bg=t.panel_bg)
|
|
1542
|
+
safe_grab_set(self)
|
|
1543
|
+
|
|
1544
|
+
self._build(t, is_edit)
|
|
1545
|
+
|
|
1546
|
+
self.update_idletasks()
|
|
1547
|
+
w, h = self.winfo_reqwidth(), self.winfo_reqheight()
|
|
1548
|
+
x = (self.winfo_screenwidth() - w) // 2
|
|
1549
|
+
y = (self.winfo_screenheight() - h) // 2
|
|
1550
|
+
self.geometry(f"480x500+{x}+{y}")
|
|
1551
|
+
|
|
1552
|
+
def _build(self, t: Any, is_edit: bool) -> None:
|
|
1553
|
+
c = self._conn
|
|
1554
|
+
|
|
1555
|
+
hdr = tk.Frame(self, bg=t.activity_bg)
|
|
1556
|
+
hdr.pack(fill="x")
|
|
1557
|
+
tk.Label(
|
|
1558
|
+
hdr,
|
|
1559
|
+
text=(
|
|
1560
|
+
_t("sql.edit_conn_title", "✏ Editar")
|
|
1561
|
+
if is_edit
|
|
1562
|
+
else _t("sql.new_conn_title", "🗄 Nova Conexão")
|
|
1563
|
+
),
|
|
1564
|
+
bg=t.activity_bg,
|
|
1565
|
+
fg=t.fg,
|
|
1566
|
+
font=(FONT_UI, 11, "bold"),
|
|
1567
|
+
).pack(side="left", padx=12, pady=8)
|
|
1568
|
+
tk.Frame(self, bg=t.border, height=1).pack(fill="x")
|
|
1569
|
+
|
|
1570
|
+
form = tk.Frame(self, bg=t.panel_bg)
|
|
1571
|
+
form.pack(fill="both", expand=True)
|
|
1572
|
+
form.columnconfigure(0, weight=1)
|
|
1573
|
+
|
|
1574
|
+
fb = _FormRowBuilder(form, t)
|
|
1575
|
+
|
|
1576
|
+
fb.lbl(_t("sql.field_name", "Nome da conexão"))
|
|
1577
|
+
self._name_var = tk.StringVar(value=c.name)
|
|
1578
|
+
fb.ent(self._name_var)
|
|
1579
|
+
|
|
1580
|
+
fb.lbl(_t("sql.field_driver", "Driver"))
|
|
1581
|
+
self._driver_var = tk.StringVar(value=c.driver)
|
|
1582
|
+
avail = [
|
|
1583
|
+
(
|
|
1584
|
+
k,
|
|
1585
|
+
f"{v['label']}{' ok' if _driver_available(k) else ' (pip install ' + (v['module'] or '') + ')'}",
|
|
1586
|
+
)
|
|
1587
|
+
for k, v in DRIVERS.items()
|
|
1588
|
+
]
|
|
1589
|
+
self._driver_keys = [k for k, _ in avail]
|
|
1590
|
+
driver_cb = ttk.Combobox(
|
|
1591
|
+
form, textvariable=self._driver_var, state="readonly", font=(FONT_UI, 9)
|
|
1592
|
+
)
|
|
1593
|
+
driver_cb["values"] = [v for _, v in avail]
|
|
1594
|
+
try:
|
|
1595
|
+
driver_cb.current(self._driver_keys.index(c.driver))
|
|
1596
|
+
except ValueError:
|
|
1597
|
+
driver_cb.current(0)
|
|
1598
|
+
driver_cb.grid(row=fb.take_row(), column=0,
|
|
1599
|
+
sticky="ew", padx=16, pady=(1, 0))
|
|
1600
|
+
driver_cb.bind("<<ComboboxSelected>>", self._on_driver_changed)
|
|
1601
|
+
|
|
1602
|
+
self._dyn_frame = tk.Frame(form, bg=t.panel_bg)
|
|
1603
|
+
self._dyn_frame.grid(row=fb.take_row(), column=0, sticky="nsew")
|
|
1604
|
+
|
|
1605
|
+
self._readonly_var = tk.BooleanVar(value=c.readonly)
|
|
1606
|
+
tk.Checkbutton(
|
|
1607
|
+
form,
|
|
1608
|
+
text=_t("sql.field_readonly", "Somente leitura"),
|
|
1609
|
+
variable=self._readonly_var,
|
|
1610
|
+
bg=t.panel_bg,
|
|
1611
|
+
fg=t.fg,
|
|
1612
|
+
selectcolor=t.editor_bg,
|
|
1613
|
+
activebackground=t.panel_bg,
|
|
1614
|
+
font=(FONT_UI, 8),
|
|
1615
|
+
).grid(row=fb.row, column=0, sticky="w", padx=16, pady=6)
|
|
1616
|
+
|
|
1617
|
+
btn_row = tk.Frame(self, bg=t.panel_bg)
|
|
1618
|
+
btn_row.pack(fill="x", padx=16, pady=(4, 12))
|
|
1619
|
+
|
|
1620
|
+
test_b = tk.Label(
|
|
1621
|
+
btn_row,
|
|
1622
|
+
text=_t("sql.test_conn", "🔗 Testar"),
|
|
1623
|
+
bg=t.sidebar_bg,
|
|
1624
|
+
fg=t.fg,
|
|
1625
|
+
font=(FONT_UI, 9),
|
|
1626
|
+
padx=10,
|
|
1627
|
+
pady=5,
|
|
1628
|
+
cursor="hand2",
|
|
1629
|
+
)
|
|
1630
|
+
test_b.pack(side="left")
|
|
1631
|
+
test_b.bind("<Button-1>", lambda _: self._test())
|
|
1632
|
+
|
|
1633
|
+
save_b = tk.Label(
|
|
1634
|
+
btn_row,
|
|
1635
|
+
text=_t("sql.save_conn", "Salvar"),
|
|
1636
|
+
bg=t.accent,
|
|
1637
|
+
fg="#FFF",
|
|
1638
|
+
font=(FONT_UI, 9, "bold"),
|
|
1639
|
+
padx=12,
|
|
1640
|
+
pady=5,
|
|
1641
|
+
cursor="hand2",
|
|
1642
|
+
)
|
|
1643
|
+
save_b.pack(side="right", padx=4)
|
|
1644
|
+
save_b.bind("<Button-1>", lambda _: self._save())
|
|
1645
|
+
|
|
1646
|
+
cancel_b = tk.Label(
|
|
1647
|
+
btn_row,
|
|
1648
|
+
text=_t("sql.cancel", "Cancelar"),
|
|
1649
|
+
bg=t.sidebar_bg,
|
|
1650
|
+
fg=t.fg,
|
|
1651
|
+
font=(FONT_UI, 9),
|
|
1652
|
+
padx=10,
|
|
1653
|
+
pady=5,
|
|
1654
|
+
cursor="hand2",
|
|
1655
|
+
)
|
|
1656
|
+
cancel_b.pack(side="right")
|
|
1657
|
+
cancel_b.bind("<Button-1>", lambda _: self.destroy())
|
|
1658
|
+
|
|
1659
|
+
self._rebuild_dyn_fields(c.driver)
|
|
1660
|
+
|
|
1661
|
+
def _on_driver_changed(self, _e: Any = None) -> None:
|
|
1662
|
+
sel_label = self._driver_var.get().split(" ")[0]
|
|
1663
|
+
drv = "sqlite"
|
|
1664
|
+
for k, v in DRIVERS.items():
|
|
1665
|
+
if v["label"] == sel_label:
|
|
1666
|
+
drv = k
|
|
1667
|
+
break
|
|
1668
|
+
self._rebuild_dyn_fields(drv)
|
|
1669
|
+
|
|
1670
|
+
def _rebuild_dyn_fields(self, driver: str) -> None:
|
|
1671
|
+
t = self._tmgr.theme
|
|
1672
|
+
for w in self._dyn_frame.winfo_children():
|
|
1673
|
+
w.destroy()
|
|
1674
|
+
f = self._dyn_frame
|
|
1675
|
+
f.columnconfigure(0, weight=1)
|
|
1676
|
+
|
|
1677
|
+
fb = _FormRowBuilder(f, t)
|
|
1678
|
+
|
|
1679
|
+
c = self._conn
|
|
1680
|
+
|
|
1681
|
+
if driver in ("sqlite", "duckdb"):
|
|
1682
|
+
label = DRIVERS[driver]["label"]
|
|
1683
|
+
hint = _t("sql.field_file",
|
|
1684
|
+
"Arquivo .db (deixe vazio para :memory:)")
|
|
1685
|
+
fb.lbl(f"{label} - {hint}")
|
|
1686
|
+
self._filepath_var = tk.StringVar(value=c.filepath)
|
|
1687
|
+
|
|
1688
|
+
file_row = tk.Frame(f, bg=t.panel_bg)
|
|
1689
|
+
file_row.grid(
|
|
1690
|
+
row=fb.take_row(), column=0, sticky="ew", padx=16, pady=(1, 0)
|
|
1691
|
+
)
|
|
1692
|
+
file_row.columnconfigure(0, weight=1)
|
|
1693
|
+
fe = tk.Entry(
|
|
1694
|
+
file_row,
|
|
1695
|
+
textvariable=self._filepath_var,
|
|
1696
|
+
bg=t.editor_bg,
|
|
1697
|
+
fg=t.fg,
|
|
1698
|
+
insertbackground=t.cursor,
|
|
1699
|
+
relief="flat",
|
|
1700
|
+
bd=0,
|
|
1701
|
+
font=(FONT_UI, 10),
|
|
1702
|
+
highlightthickness=1,
|
|
1703
|
+
highlightbackground=t.border,
|
|
1704
|
+
)
|
|
1705
|
+
fe.grid(row=0, column=0, sticky="ew", ipady=5)
|
|
1706
|
+
browse_b = tk.Label(
|
|
1707
|
+
file_row,
|
|
1708
|
+
text="📂",
|
|
1709
|
+
bg=t.sidebar_bg,
|
|
1710
|
+
fg=t.fg_muted,
|
|
1711
|
+
font=(FONT_UI, 10),
|
|
1712
|
+
cursor="hand2",
|
|
1713
|
+
padx=6,
|
|
1714
|
+
)
|
|
1715
|
+
browse_b.grid(row=0, column=1, padx=(4, 0))
|
|
1716
|
+
browse_b.bind("<Button-1>", lambda _: self._browse_db(driver))
|
|
1717
|
+
|
|
1718
|
+
else:
|
|
1719
|
+
fb.lbl(_t("sql.field_host", "Host"))
|
|
1720
|
+
self._host_var = tk.StringVar(value=c.host)
|
|
1721
|
+
fb.ent(self._host_var)
|
|
1722
|
+
|
|
1723
|
+
fb.lbl(_t("sql.field_port", "Porta"))
|
|
1724
|
+
default_port = _DEFAULT_PORTS.get(driver, c.port)
|
|
1725
|
+
self._port_var = tk.StringVar(value=str(c.port or default_port))
|
|
1726
|
+
fb.ent(self._port_var)
|
|
1727
|
+
|
|
1728
|
+
fb.lbl(_t("sql.field_database", "Database"))
|
|
1729
|
+
self._db_var = tk.StringVar(value=c.database)
|
|
1730
|
+
fb.ent(self._db_var)
|
|
1731
|
+
|
|
1732
|
+
fb.lbl(_t("sql.field_user", "Usuário"))
|
|
1733
|
+
self._user_var = tk.StringVar(value=c.user)
|
|
1734
|
+
fb.ent(self._user_var)
|
|
1735
|
+
|
|
1736
|
+
fb.lbl(_t("sql.field_password", "Senha"))
|
|
1737
|
+
import base64
|
|
1738
|
+
|
|
1739
|
+
try:
|
|
1740
|
+
pw = base64.b64decode(
|
|
1741
|
+
c.password).decode() if c.password else ""
|
|
1742
|
+
except Exception:
|
|
1743
|
+
pw = ""
|
|
1744
|
+
self._pw_var = tk.StringVar(value=pw)
|
|
1745
|
+
fb.ent(self._pw_var, show="●")
|
|
1746
|
+
|
|
1747
|
+
def _browse_db(self, driver: str = "sqlite") -> None:
|
|
1748
|
+
if driver == "duckdb":
|
|
1749
|
+
ftypes = [
|
|
1750
|
+
("DuckDB", "*.duckdb *.db"),
|
|
1751
|
+
(_t("sql.all_files", "Todos"), "*.*"),
|
|
1752
|
+
]
|
|
1753
|
+
else:
|
|
1754
|
+
ftypes = [
|
|
1755
|
+
("SQLite", "*.db *.sqlite *.sqlite3"),
|
|
1756
|
+
(_t("sql.all_files", "Todos"), "*.*"),
|
|
1757
|
+
]
|
|
1758
|
+
path = filedialog.askopenfilename(filetypes=ftypes)
|
|
1759
|
+
if path:
|
|
1760
|
+
self._filepath_var.set(path)
|
|
1761
|
+
|
|
1762
|
+
def _get_driver_key(self) -> str:
|
|
1763
|
+
label = self._driver_var.get().split(" ")[0]
|
|
1764
|
+
for k, v in DRIVERS.items():
|
|
1765
|
+
if v["label"] == label:
|
|
1766
|
+
return k
|
|
1767
|
+
return "sqlite"
|
|
1768
|
+
|
|
1769
|
+
def _collect(self) -> Connection:
|
|
1770
|
+
import base64
|
|
1771
|
+
|
|
1772
|
+
c = self._conn
|
|
1773
|
+
drv = self._get_driver_key()
|
|
1774
|
+
c.name = self._name_var.get().strip() or "Sem nome"
|
|
1775
|
+
c.driver = drv
|
|
1776
|
+
c.readonly = self._readonly_var.get()
|
|
1777
|
+
if drv in ("sqlite", "duckdb"):
|
|
1778
|
+
c.filepath = getattr(self, "_filepath_var",
|
|
1779
|
+
tk.StringVar()).get().strip()
|
|
1780
|
+
else:
|
|
1781
|
+
c.host = getattr(self, "_host_var",
|
|
1782
|
+
tk.StringVar(value="localhost")).get()
|
|
1783
|
+
c.database = getattr(self, "_db_var", tk.StringVar()).get()
|
|
1784
|
+
c.user = getattr(self, "_user_var", tk.StringVar()).get()
|
|
1785
|
+
pw_raw = getattr(self, "_pw_var", tk.StringVar()).get()
|
|
1786
|
+
c.password = base64.b64encode(
|
|
1787
|
+
pw_raw.encode()).decode() if pw_raw else ""
|
|
1788
|
+
try:
|
|
1789
|
+
c.port = int(
|
|
1790
|
+
getattr(self, "_port_var",
|
|
1791
|
+
tk.StringVar(value="5432")).get()
|
|
1792
|
+
)
|
|
1793
|
+
except ValueError:
|
|
1794
|
+
c.port = _DEFAULT_PORTS.get(drv, 5432)
|
|
1795
|
+
return c
|
|
1796
|
+
|
|
1797
|
+
def _test(self) -> None:
|
|
1798
|
+
conn = DBConnection(self._collect())
|
|
1799
|
+
try:
|
|
1800
|
+
conn.connect()
|
|
1801
|
+
conn.execute("SELECT 1 as ok")
|
|
1802
|
+
conn.close()
|
|
1803
|
+
messagebox.showinfo(
|
|
1804
|
+
_t("sql.test_ok_title", "Conexão OK"),
|
|
1805
|
+
_t("sql.test_ok_msg", "Conexão estabelecida com sucesso!"),
|
|
1806
|
+
parent=self,
|
|
1807
|
+
)
|
|
1808
|
+
except Exception as exc:
|
|
1809
|
+
messagebox.showerror(
|
|
1810
|
+
_t("sql.test_fail_title", "Falha"), str(exc), parent=self
|
|
1811
|
+
)
|
|
1812
|
+
|
|
1813
|
+
def _save(self) -> None:
|
|
1814
|
+
self._on_save(self._collect())
|
|
1815
|
+
self.destroy()
|