Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,12 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import shutil
|
| 3 |
import sqlite3
|
| 4 |
import pandas as pd
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
DB_PATH = "loja.db"
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
def _connect():
|
|
@@ -16,10 +18,28 @@ def _looks_like_select(sql: str) -> bool:
|
|
| 16 |
return s.startswith(("select", "with", "pragma", "explain"))
|
| 17 |
|
| 18 |
|
| 19 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
sql = (sql or "").strip()
|
| 21 |
if not sql:
|
| 22 |
-
return "⚠️ Cole um comando SQL.", None
|
| 23 |
|
| 24 |
try:
|
| 25 |
con = _connect()
|
|
@@ -28,16 +48,27 @@ def executar_sql(sql: str):
|
|
| 28 |
if _looks_like_select(sql):
|
| 29 |
df = pd.read_sql_query(sql, con)
|
| 30 |
con.close()
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
# Para comandos não-SELECT (DDL/DML), aceita múltiplas instruções com ;
|
| 34 |
cur.executescript(sql)
|
| 35 |
con.commit()
|
| 36 |
con.close()
|
| 37 |
-
return "✅ Comando executado e commit realizado.", None
|
| 38 |
|
| 39 |
except Exception as e:
|
| 40 |
-
return f"❌ Erro ao executar SQL:\n{e}", None
|
| 41 |
|
| 42 |
|
| 43 |
def reset_db():
|
|
@@ -77,6 +108,8 @@ with gr.Blocks(title="SQLite — Execução de SQL (loja.db)") as demo:
|
|
| 77 |
Cole seus comandos SQL e execute direto no arquivo `loja.db`.
|
| 78 |
|
| 79 |
**Dica:** Para múltiplos comandos (ex.: vários CREATE/INSERT), separe por `;`.
|
|
|
|
|
|
|
| 80 |
"""
|
| 81 |
)
|
| 82 |
|
|
@@ -86,11 +119,27 @@ Cole seus comandos SQL e execute direto no arquivo `loja.db`.
|
|
| 86 |
placeholder="Ex.: CREATE TABLE ...; ou SELECT * FROM ...;",
|
| 87 |
lines=10,
|
| 88 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
run_btn = gr.Button("Executar")
|
| 90 |
status = gr.Textbox(label="Status", lines=3)
|
| 91 |
tabela = gr.Dataframe(label="Resultado (se houver)", interactive=False)
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
with gr.Tab("Banco de Dados (Upload/Download/Reset)"):
|
| 96 |
gr.Markdown("### Upload de um banco existente (.db)")
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import shutil
|
| 4 |
import sqlite3
|
| 5 |
import pandas as pd
|
| 6 |
import gradio as gr
|
| 7 |
|
| 8 |
DB_PATH = "loja.db"
|
| 9 |
+
EXPORT_DIR = "exports"
|
| 10 |
|
| 11 |
|
| 12 |
def _connect():
|
|
|
|
| 18 |
return s.startswith(("select", "with", "pragma", "explain"))
|
| 19 |
|
| 20 |
|
| 21 |
+
def _safe_filename(name: str) -> str:
|
| 22 |
+
name = (name or "").strip()
|
| 23 |
+
if not name:
|
| 24 |
+
name = "resultado"
|
| 25 |
+
# remove caracteres ruins e espaços excessivos
|
| 26 |
+
name = re.sub(r"[^\w\-\.]+", "_", name, flags=re.UNICODE)
|
| 27 |
+
name = name.strip("._-")
|
| 28 |
+
return name or "resultado"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _save_df_to_csv(df: pd.DataFrame, filename_base: str) -> str:
|
| 32 |
+
os.makedirs(EXPORT_DIR, exist_ok=True)
|
| 33 |
+
base = _safe_filename(filename_base)
|
| 34 |
+
csv_path = os.path.join(EXPORT_DIR, f"{base}.csv")
|
| 35 |
+
df.to_csv(csv_path, index=False, encoding="utf-8-sig") # BOM ajuda no Excel
|
| 36 |
+
return csv_path
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def executar_sql(sql: str, salvar_csv: bool, nome_csv: str):
|
| 40 |
sql = (sql or "").strip()
|
| 41 |
if not sql:
|
| 42 |
+
return "⚠️ Cole um comando SQL.", None, None
|
| 43 |
|
| 44 |
try:
|
| 45 |
con = _connect()
|
|
|
|
| 48 |
if _looks_like_select(sql):
|
| 49 |
df = pd.read_sql_query(sql, con)
|
| 50 |
con.close()
|
| 51 |
+
|
| 52 |
+
csv_file = None
|
| 53 |
+
if salvar_csv:
|
| 54 |
+
if df is None or df.empty:
|
| 55 |
+
# Ainda assim você pode preferir salvar vazio; aqui eu aviso e não gero arquivo.
|
| 56 |
+
return "⚠️ Consulta executada, mas não retornou linhas (CSV não gerado).", df, None
|
| 57 |
+
csv_file = _save_df_to_csv(df, nome_csv)
|
| 58 |
+
|
| 59 |
+
msg = "✅ Consulta executada com sucesso."
|
| 60 |
+
if csv_file:
|
| 61 |
+
msg += f" CSV gerado em: {csv_file}"
|
| 62 |
+
return msg, df, csv_file
|
| 63 |
|
| 64 |
# Para comandos não-SELECT (DDL/DML), aceita múltiplas instruções com ;
|
| 65 |
cur.executescript(sql)
|
| 66 |
con.commit()
|
| 67 |
con.close()
|
| 68 |
+
return "✅ Comando executado e commit realizado.", None, None
|
| 69 |
|
| 70 |
except Exception as e:
|
| 71 |
+
return f"❌ Erro ao executar SQL:\n{e}", None, None
|
| 72 |
|
| 73 |
|
| 74 |
def reset_db():
|
|
|
|
| 108 |
Cole seus comandos SQL e execute direto no arquivo `loja.db`.
|
| 109 |
|
| 110 |
**Dica:** Para múltiplos comandos (ex.: vários CREATE/INSERT), separe por `;`.
|
| 111 |
+
|
| 112 |
+
✅ **Novo:** marque *Salvar resultado em CSV* para exportar o resultado de consultas `SELECT`.
|
| 113 |
"""
|
| 114 |
)
|
| 115 |
|
|
|
|
| 119 |
placeholder="Ex.: CREATE TABLE ...; ou SELECT * FROM ...;",
|
| 120 |
lines=10,
|
| 121 |
)
|
| 122 |
+
|
| 123 |
+
with gr.Row():
|
| 124 |
+
salvar_csv = gr.Checkbox(label="Salvar resultado em CSV (apenas SELECT)", value=False)
|
| 125 |
+
nome_csv = gr.Textbox(
|
| 126 |
+
label="Nome do CSV (sem extensão)",
|
| 127 |
+
placeholder="Ex.: clientes_ativos",
|
| 128 |
+
value="resultado_query",
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
run_btn = gr.Button("Executar")
|
| 132 |
status = gr.Textbox(label="Status", lines=3)
|
| 133 |
tabela = gr.Dataframe(label="Resultado (se houver)", interactive=False)
|
| 134 |
|
| 135 |
+
gr.Markdown("### Download do resultado (CSV)")
|
| 136 |
+
csv_file = gr.File(label="Baixar CSV gerado")
|
| 137 |
+
|
| 138 |
+
run_btn.click(
|
| 139 |
+
executar_sql,
|
| 140 |
+
inputs=[sql_in, salvar_csv, nome_csv],
|
| 141 |
+
outputs=[status, tabela, csv_file],
|
| 142 |
+
)
|
| 143 |
|
| 144 |
with gr.Tab("Banco de Dados (Upload/Download/Reset)"):
|
| 145 |
gr.Markdown("### Upload de um banco existente (.db)")
|