Spaces:
Sleeping

douglasribeiro commited on
Commit
ba7a1a9
路
verified 路
1 Parent(s): 33be89f

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +658 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sqlite3
3
+ import tempfile
4
+ import shutil
5
+ from datetime import datetime
6
+
7
+ import pandas as pd
8
+ import gradio as gr
9
+
10
+ # =========================
11
+ # CONFIGURA脟脮ES
12
+ # =========================
13
+ DEFAULT_DB_PATH = "data/base_treinamento.db"
14
+
15
+
16
+ # =========================
17
+ # FUN脟脮ES AUXILIARES
18
+ # =========================
19
+ def ensure_default_db():
20
+ """
21
+ Garante que exista um banco padr茫o m铆nimo para o app iniciar.
22
+ Se voc锚 j谩 tiver o seu .db real, basta coloc谩-lo em:
23
+ data/base_treinamento.db
24
+ """
25
+ if os.path.exists(DEFAULT_DB_PATH):
26
+ return
27
+
28
+ os.makedirs(os.path.dirname(DEFAULT_DB_PATH), exist_ok=True)
29
+
30
+ conn = sqlite3.connect(DEFAULT_DB_PATH)
31
+ cur = conn.cursor()
32
+
33
+ cur.executescript(
34
+ """
35
+ PRAGMA foreign_keys = ON;
36
+
37
+ CREATE TABLE IF NOT EXISTS Categorias (
38
+ CategoriaID INTEGER PRIMARY KEY,
39
+ Departamento TEXT,
40
+ Categoria TEXT,
41
+ MargemAlvoPct REAL
42
+ );
43
+
44
+ CREATE TABLE IF NOT EXISTS Clientes (
45
+ ClienteID INTEGER PRIMARY KEY,
46
+ Nome TEXT,
47
+ Genero TEXT,
48
+ DataNascimento TEXT,
49
+ Cidade TEXT,
50
+ Estado TEXT,
51
+ Regiao TEXT,
52
+ SegmentoCliente TEXT,
53
+ FaixaRenda TEXT,
54
+ DataCadastro TEXT,
55
+ ScoreFidelidade INTEGER,
56
+ Email TEXT
57
+ );
58
+
59
+ CREATE TABLE IF NOT EXISTS Fornecedores (
60
+ FornecedorID INTEGER PRIMARY KEY,
61
+ Fornecedor TEXT,
62
+ PaisOrigem TEXT,
63
+ Segmento TEXT,
64
+ PrazoMedioDias INTEGER,
65
+ Rating REAL
66
+ );
67
+
68
+ CREATE TABLE IF NOT EXISTS Lojas (
69
+ LojaID INTEGER PRIMARY KEY,
70
+ CodigoLoja TEXT,
71
+ TipoLoja TEXT,
72
+ Cidade TEXT,
73
+ Estado TEXT,
74
+ Regiao TEXT,
75
+ DataAbertura TEXT,
76
+ AreaM2 INTEGER,
77
+ MetaMensal REAL
78
+ );
79
+
80
+ CREATE TABLE IF NOT EXISTS Funcionarios (
81
+ FuncionarioID INTEGER PRIMARY KEY,
82
+ LojaID INTEGER,
83
+ Nome TEXT,
84
+ Cargo TEXT,
85
+ DataAdmissao TEXT,
86
+ SalarioBase REAL,
87
+ MetaMensal REAL,
88
+ Turno TEXT,
89
+ Status TEXT,
90
+ FOREIGN KEY (LojaID) REFERENCES Lojas(LojaID)
91
+ );
92
+
93
+ CREATE TABLE IF NOT EXISTS Produtos (
94
+ ProdutoID INTEGER PRIMARY KEY,
95
+ SKU TEXT,
96
+ Produto TEXT,
97
+ Marca TEXT,
98
+ CategoriaID INTEGER,
99
+ FornecedorID INTEGER,
100
+ CustoUnitario REAL,
101
+ PrecoLista REAL,
102
+ AtivoDesde TEXT,
103
+ PesoKg REAL,
104
+ StatusProduto TEXT,
105
+ FOREIGN KEY (CategoriaID) REFERENCES Categorias(CategoriaID),
106
+ FOREIGN KEY (FornecedorID) REFERENCES Fornecedores(FornecedorID)
107
+ );
108
+
109
+ CREATE TABLE IF NOT EXISTS Pedidos (
110
+ PedidoID INTEGER PRIMARY KEY,
111
+ DataPedido TEXT,
112
+ ClienteID INTEGER,
113
+ LojaID INTEGER,
114
+ FuncionarioID INTEGER,
115
+ CanalVenda TEXT,
116
+ StatusPedido TEXT,
117
+ Cupom TEXT,
118
+ Frete REAL,
119
+ DescontoPedido REAL,
120
+ ValorItens REAL,
121
+ ValorTotal REAL,
122
+ FOREIGN KEY (ClienteID) REFERENCES Clientes(ClienteID),
123
+ FOREIGN KEY (LojaID) REFERENCES Lojas(LojaID),
124
+ FOREIGN KEY (FuncionarioID) REFERENCES Funcionarios(FuncionarioID)
125
+ );
126
+
127
+ CREATE TABLE IF NOT EXISTS ItensPedido (
128
+ ItemID INTEGER,
129
+ PedidoID INTEGER,
130
+ ProdutoID INTEGER,
131
+ Quantidade INTEGER,
132
+ PrecoUnitario REAL,
133
+ DescontoItemPct REAL,
134
+ CustoUnitario REAL,
135
+ FOREIGN KEY (PedidoID) REFERENCES Pedidos(PedidoID),
136
+ FOREIGN KEY (ProdutoID) REFERENCES Produtos(ProdutoID)
137
+ );
138
+
139
+ CREATE TABLE IF NOT EXISTS Pagamentos (
140
+ PagamentoID INTEGER,
141
+ PedidoID INTEGER,
142
+ SequenciaPagamento INTEGER,
143
+ MetodoPagamento TEXT,
144
+ Parcelas INTEGER,
145
+ ValorPago REAL,
146
+ StatusPagamento TEXT,
147
+ DataPagamento TEXT,
148
+ Gateway TEXT,
149
+ FOREIGN KEY (PedidoID) REFERENCES Pedidos(PedidoID)
150
+ );
151
+ """
152
+ )
153
+
154
+ cur.executescript(
155
+ """
156
+ INSERT INTO Categorias VALUES
157
+ (1, 'Mercearia', 'Alimentos', 0.30),
158
+ (2, 'Bebidas', 'Refrigerantes', 0.25),
159
+ (3, 'Higiene', 'Perfumaria', 0.35);
160
+
161
+ INSERT INTO Fornecedores VALUES
162
+ (1, 'Fornecedor Alfa', 'Brasil', 'Nacional', 15, 4.5),
163
+ (2, 'Fornecedor Beta', 'Argentina', 'Importado', 22, 4.2);
164
+
165
+ INSERT INTO Lojas VALUES
166
+ (1, 'LJ001', 'Rua', 'S茫o Paulo', 'SP', 'Sudeste', '2022-01-10', 300, 120000),
167
+ (2, 'LJ002', 'Shopping', 'Campinas', 'SP', 'Sudeste', '2023-05-20', 180, 90000);
168
+
169
+ INSERT INTO Clientes VALUES
170
+ (1, 'Ana Souza', 'F', '1990-05-10', 'S茫o Paulo', 'SP', 'Sudeste', 'Premium', 'Alta', '2024-01-10', 95, 'ana@email.com'),
171
+ (2, 'Bruno Lima', 'M', '1988-08-20', 'Campinas', 'SP', 'Sudeste', 'Regular', 'Media', '2024-02-11', 80, 'bruno@email.com'),
172
+ (3, 'Carla Mendes', 'F', '1995-02-15', 'Jundia铆', 'SP', 'Sudeste', 'Premium', 'Alta', '2024-03-01', 91, 'carla@email.com');
173
+
174
+ INSERT INTO Funcionarios VALUES
175
+ (1, 1, 'Mariana Costa', 'Vendedora', '2023-01-05', 2500, 30000, 'Manh茫', 'Ativo'),
176
+ (2, 1, 'Jo茫o Alves', 'Caixa', '2023-03-12', 2200, 20000, 'Tarde', 'Ativo'),
177
+ (3, 2, 'Fernanda Rocha', 'Gerente', '2022-10-01', 5500, 60000, 'Integral', 'Ativo');
178
+
179
+ INSERT INTO Produtos VALUES
180
+ (1, 'SKU001', 'Arroz 5kg', 'Marca A', 1, 1, 18.00, 27.90, '2023-01-01', 5.0, 'Ativo'),
181
+ (2, 'SKU002', 'Refrigerante 2L', 'Marca B', 2, 2, 4.50, 8.99, '2023-01-01', 2.0, 'Ativo'),
182
+ (3, 'SKU003', 'Shampoo 400ml', 'Marca C', 3, 1, 9.00, 18.50, '2023-01-01', 0.4, 'Ativo');
183
+
184
+ INSERT INTO Pedidos VALUES
185
+ (1, '2026-04-01', 1, 1, 1, 'Loja F铆sica', 'Conclu铆do', 'DESC10', 5.00, 2.00, 45.88, 48.88),
186
+ (2, '2026-04-02', 2, 1, 2, 'Site', 'Conclu铆do', NULL, 8.00, 0.00, 27.90, 35.90),
187
+ (3, '2026-04-03', 3, 2, 3, 'App', 'Conclu铆do', 'APP5', 6.00, 1.50, 18.50, 23.00);
188
+
189
+ INSERT INTO ItensPedido VALUES
190
+ (1, 1, 2, 2, 8.99, 0.00, 4.50),
191
+ (2, 1, 3, 1, 18.50, 0.10, 9.00),
192
+ (3, 2, 1, 1, 27.90, 0.00, 18.00),
193
+ (4, 3, 3, 1, 18.50, 0.00, 9.00);
194
+
195
+ INSERT INTO Pagamentos VALUES
196
+ (1, 1, 1, 'Cart茫o', 1, 48.88, 'Aprovado', '2026-04-01', 'GatewayX'),
197
+ (2, 2, 1, 'Pix', 1, 35.90, 'Aprovado', '2026-04-02', 'GatewayY'),
198
+ (3, 3, 1, 'Cart茫o', 2, 23.00, 'Aprovado', '2026-04-03', 'GatewayX');
199
+ """
200
+ )
201
+
202
+ conn.commit()
203
+ conn.close()
204
+
205
+
206
+ def create_lab_copy(source_db_path: str):
207
+ """
208
+ Cria uma c贸pia tempor谩ria do banco para o modo laborat贸rio.
209
+ """
210
+ temp_dir = tempfile.mkdtemp(prefix="sql_lab_")
211
+ lab_db_path = os.path.join(temp_dir, "lab.db")
212
+ shutil.copy2(source_db_path, lab_db_path)
213
+ return temp_dir, lab_db_path
214
+
215
+
216
+ def connect_db(db_path: str):
217
+ conn = sqlite3.connect(db_path, check_same_thread=False)
218
+ conn.execute("PRAGMA foreign_keys = ON;")
219
+ return conn
220
+
221
+
222
+ def list_tables_and_columns(db_path: str) -> str:
223
+ conn = connect_db(db_path)
224
+ cur = conn.cursor()
225
+
226
+ try:
227
+ tables = cur.execute(
228
+ """
229
+ SELECT name
230
+ FROM sqlite_master
231
+ WHERE type='table'
232
+ AND name NOT LIKE 'sqlite_%'
233
+ ORDER BY name;
234
+ """
235
+ ).fetchall()
236
+
237
+ lines = []
238
+ for (table_name,) in tables:
239
+ lines.append(f"馃摝 {table_name}")
240
+ cols = cur.execute(f'PRAGMA table_info("{table_name}")').fetchall()
241
+ for col in cols:
242
+ _, name, col_type, notnull, _, pk = col
243
+ pk_txt = " [PK]" if pk else ""
244
+ nn_txt = " NOT NULL" if notnull else ""
245
+ lines.append(f" - {name} ({col_type}){pk_txt}{nn_txt}")
246
+ lines.append("")
247
+
248
+ return "\n".join(lines).strip() if lines else "Nenhuma tabela encontrada."
249
+ finally:
250
+ conn.close()
251
+
252
+
253
+ def list_relationships(db_path: str) -> str:
254
+ conn = connect_db(db_path)
255
+ cur = conn.cursor()
256
+
257
+ try:
258
+ tables = cur.execute(
259
+ """
260
+ SELECT name
261
+ FROM sqlite_master
262
+ WHERE type='table'
263
+ AND name NOT LIKE 'sqlite_%'
264
+ ORDER BY name;
265
+ """
266
+ ).fetchall()
267
+
268
+ lines = []
269
+ for (table_name,) in tables:
270
+ fks = cur.execute(f'PRAGMA foreign_key_list("{table_name}")').fetchall()
271
+ if fks:
272
+ lines.append(f"馃敆 {table_name}")
273
+ for fk in fks:
274
+ _, _, ref_table, from_col, to_col, on_update, on_delete, _ = fk
275
+ lines.append(
276
+ f" - {from_col} -> {ref_table}.{to_col} "
277
+ f"(ON UPDATE {on_update}, ON DELETE {on_delete})"
278
+ )
279
+ lines.append("")
280
+
281
+ return "\n".join(lines).strip() if lines else "Nenhum relacionamento encontrado."
282
+ finally:
283
+ conn.close()
284
+
285
+
286
+ def get_examples():
287
+ return {
288
+ "SELECT b谩sico": "SELECT * FROM Produtos LIMIT 10;",
289
+ "WHERE": "SELECT * FROM Clientes WHERE Cidade = 'S茫o Paulo';",
290
+ "ORDER BY": "SELECT Produto, PrecoLista FROM Produtos ORDER BY PrecoLista DESC;",
291
+ "GROUP BY": """
292
+ SELECT MetodoPagamento, SUM(ValorPago) AS TotalPago
293
+ FROM Pagamentos
294
+ GROUP BY MetodoPagamento;
295
+ """.strip(),
296
+ "JOIN": """
297
+ SELECT
298
+ p.PedidoID,
299
+ c.Nome AS Cliente,
300
+ l.CodigoLoja,
301
+ f.Nome AS Funcionario
302
+ FROM Pedidos p
303
+ JOIN Clientes c ON p.ClienteID = c.ClienteID
304
+ JOIN Lojas l ON p.LojaID = l.LojaID
305
+ JOIN Funcionarios f ON p.FuncionarioID = f.FuncionarioID;
306
+ """.strip(),
307
+ "JOIN com agrega莽茫o": """
308
+ SELECT
309
+ pr.Produto,
310
+ SUM(ip.Quantidade) AS QuantidadeVendida
311
+ FROM ItensPedido ip
312
+ JOIN Produtos pr ON ip.ProdutoID = pr.ProdutoID
313
+ GROUP BY pr.Produto
314
+ ORDER BY QuantidadeVendida DESC;
315
+ """.strip(),
316
+ "HAVING": """
317
+ SELECT
318
+ MetodoPagamento,
319
+ SUM(ValorPago) AS Total
320
+ FROM Pagamentos
321
+ GROUP BY MetodoPagamento
322
+ HAVING SUM(ValorPago) > 20;
323
+ """.strip(),
324
+ "Subquery": """
325
+ SELECT *
326
+ FROM Produtos
327
+ WHERE PrecoLista > (
328
+ SELECT AVG(PrecoLista) FROM Produtos
329
+ );
330
+ """.strip(),
331
+ "CTE": """
332
+ WITH TotalPorCliente AS (
333
+ SELECT
334
+ c.ClienteID,
335
+ c.Nome,
336
+ SUM(p.ValorTotal) AS TotalGasto
337
+ FROM Clientes c
338
+ JOIN Pedidos p ON c.ClienteID = p.ClienteID
339
+ GROUP BY c.ClienteID, c.Nome
340
+ )
341
+ SELECT *
342
+ FROM TotalPorCliente
343
+ ORDER BY TotalGasto DESC;
344
+ """.strip(),
345
+ "INSERT": """
346
+ INSERT INTO Categorias (CategoriaID, Departamento, Categoria, MargemAlvoPct)
347
+ VALUES (99, 'Teste', 'Categoria Teste', 0.20);
348
+ """.strip(),
349
+ "UPDATE": """
350
+ UPDATE Produtos
351
+ SET PrecoLista = PrecoLista * 1.10
352
+ WHERE CategoriaID = 1;
353
+ """.strip(),
354
+ "DELETE": """
355
+ DELETE FROM Pagamentos
356
+ WHERE PagamentoID = 999;
357
+ """.strip(),
358
+ "CREATE TABLE": """
359
+ CREATE TABLE Exemplo (
360
+ ID INTEGER PRIMARY KEY,
361
+ Nome TEXT,
362
+ Nota REAL
363
+ );
364
+ """.strip(),
365
+ }
366
+
367
+
368
+ def load_example(example_name: str) -> str:
369
+ return get_examples().get(example_name, "")
370
+
371
+
372
+ def history_to_text(history):
373
+ if not history:
374
+ return "Nenhuma query executada ainda."
375
+ return "\n\n".join(
376
+ [f"[{item['horario']}] {item['sql']}" for item in history]
377
+ )
378
+
379
+
380
+ def normalize_query(sql_text: str) -> str:
381
+ return (sql_text or "").strip()
382
+
383
+
384
+ def is_select_like(sql_text: str) -> bool:
385
+ sql_upper = sql_text.strip().upper()
386
+ return (
387
+ sql_upper.startswith("SELECT")
388
+ or sql_upper.startswith("WITH")
389
+ or sql_upper.startswith("PRAGMA")
390
+ or sql_upper.startswith("EXPLAIN")
391
+ )
392
+
393
+
394
+ def dataframe_to_csv_file(df: pd.DataFrame):
395
+ """
396
+ Salva o DataFrame em CSV tempor谩rio e devolve o caminho para download.
397
+ """
398
+ if df is None or df.empty:
399
+ return None
400
+
401
+ temp_dir = tempfile.mkdtemp(prefix="sql_csv_")
402
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
403
+ file_path = os.path.join(temp_dir, f"resultado_query_{timestamp}.csv")
404
+ df.to_csv(file_path, index=False, encoding="utf-8-sig")
405
+ return file_path
406
+
407
+
408
+ def run_sql(sql_text: str, db_path: str, history):
409
+ sql_text = normalize_query(sql_text)
410
+
411
+ if not sql_text:
412
+ return pd.DataFrame(), "Digite uma query SQL.", history, None
413
+
414
+ conn = connect_db(db_path)
415
+ cur = conn.cursor()
416
+
417
+ try:
418
+ if is_select_like(sql_text):
419
+ df = pd.read_sql_query(sql_text, conn)
420
+ msg = f"Consulta executada com sucesso. {len(df)} linha(s) retornada(s)."
421
+ csv_file = dataframe_to_csv_file(df)
422
+ else:
423
+ cur.executescript(sql_text)
424
+ conn.commit()
425
+ df = pd.DataFrame({"status": ["OK"]})
426
+ msg = "Comando executado com sucesso."
427
+ csv_file = None
428
+
429
+ history = history or []
430
+ history.insert(
431
+ 0,
432
+ {
433
+ "horario": datetime.now().strftime("%d/%m/%Y %H:%M:%S"),
434
+ "sql": sql_text,
435
+ },
436
+ )
437
+ history = history[:30]
438
+
439
+ return df, msg, history, csv_file
440
+
441
+ except Exception as e:
442
+ return pd.DataFrame(), f"Erro ao executar SQL: {e}", history, None
443
+
444
+ finally:
445
+ conn.close()
446
+
447
+
448
+ def use_uploaded_db(uploaded_file):
449
+ if uploaded_file is None:
450
+ return None, "Nenhum arquivo enviado."
451
+
452
+ temp_dir = tempfile.mkdtemp(prefix="sql_upload_")
453
+ target_path = os.path.join(temp_dir, "uploaded.db")
454
+ shutil.copy2(uploaded_file.name, target_path)
455
+
456
+ return target_path, f"Banco enviado carregado com sucesso: {os.path.basename(uploaded_file.name)}"
457
+
458
+
459
+ def reset_lab(default_source_db: str):
460
+ _, lab_db = create_lab_copy(default_source_db)
461
+ schema = list_tables_and_columns(lab_db)
462
+ relationships = list_relationships(lab_db)
463
+ return lab_db, schema, relationships, "Banco de laborat贸rio resetado com sucesso."
464
+
465
+
466
+ # =========================
467
+ # INICIALIZA脟脙O
468
+ # =========================
469
+ ensure_default_db()
470
+
471
+ _, initial_lab_db = create_lab_copy(DEFAULT_DB_PATH)
472
+ initial_schema = list_tables_and_columns(initial_lab_db)
473
+ initial_relationships = list_relationships(initial_lab_db)
474
+ example_names = list(get_examples().keys())
475
+
476
+
477
+ # =========================
478
+ # INTERFACE
479
+ # =========================
480
+ with gr.Blocks(title="Laborat贸rio SQL com SQLite") as demo:
481
+ gr.Markdown(
482
+ """
483
+ # Laborat贸rio SQL com SQLite
484
+
485
+ Treine SQL em um banco SQLite real.
486
+
487
+ ### Recursos
488
+ - carregamento autom谩tico do banco `.db`
489
+ - upload de outro banco SQLite
490
+ - editor SQL livre
491
+ - execu莽茫o de consultas
492
+ - schema das tabelas
493
+ - relacionamentos detectados
494
+ - hist贸rico de queries
495
+ - exporta莽茫o do resultado em CSV
496
+ - reset do ambiente de laborat贸rio
497
+ """
498
+ )
499
+
500
+ db_state = gr.State(initial_lab_db)
501
+ history_state = gr.State([])
502
+
503
+ with gr.Row():
504
+ with gr.Column(scale=1):
505
+ gr.Markdown("## Base de dados")
506
+ upload_db = gr.File(
507
+ label="Enviar outro arquivo .db ou .sqlite",
508
+ file_types=[".db", ".sqlite"],
509
+ )
510
+ btn_use_upload = gr.Button("Usar banco enviado")
511
+ btn_reset = gr.Button("Resetar banco de laborat贸rio")
512
+ db_status = gr.Textbox(
513
+ label="Status do banco",
514
+ value="Banco padr茫o carregado.",
515
+ interactive=False,
516
+ )
517
+
518
+ gr.Markdown("## Exemplos")
519
+ example_dropdown = gr.Dropdown(
520
+ choices=example_names,
521
+ label="Escolha um exemplo",
522
+ value=example_names[0] if example_names else None,
523
+ )
524
+ btn_load_example = gr.Button("Carregar exemplo no editor")
525
+
526
+ with gr.Column(scale=2):
527
+ gr.Markdown("## Editor SQL")
528
+ sql_input = gr.Code(
529
+ label="Digite sua query SQL",
530
+ language="sql",
531
+ value="SELECT * FROM Produtos LIMIT 10;",
532
+ lines=16,
533
+ )
534
+ btn_run = gr.Button("Executar SQL", variant="primary")
535
+ sql_message = gr.Textbox(label="Mensagem", interactive=False)
536
+
537
+ with gr.Row():
538
+ with gr.Column(scale=2):
539
+ result_df = gr.Dataframe(label="Resultado da query", wrap=True)
540
+ download_csv = gr.File(label="Baixar resultado em CSV")
541
+ with gr.Column(scale=1):
542
+ schema_box = gr.Textbox(
543
+ label="Schema das tabelas",
544
+ value=initial_schema,
545
+ lines=22,
546
+ interactive=False,
547
+ )
548
+
549
+ with gr.Row():
550
+ with gr.Column():
551
+ rel_box = gr.Textbox(
552
+ label="Relacionamentos detectados",
553
+ value=initial_relationships,
554
+ lines=12,
555
+ interactive=False,
556
+ )
557
+ with gr.Column():
558
+ history_box = gr.Textbox(
559
+ label="Hist贸rico das queries",
560
+ value="Nenhuma query executada ainda.",
561
+ lines=12,
562
+ interactive=False,
563
+ )
564
+
565
+ def handle_run(sql_text, current_db, history):
566
+ df, msg, new_history, csv_file = run_sql(sql_text, current_db, history)
567
+ schema = list_tables_and_columns(current_db)
568
+ relationships = list_relationships(current_db)
569
+ history_text = history_to_text(new_history)
570
+ return df, msg, schema, relationships, new_history, history_text, csv_file
571
+
572
+ btn_run.click(
573
+ fn=handle_run,
574
+ inputs=[sql_input, db_state, history_state],
575
+ outputs=[
576
+ result_df,
577
+ sql_message,
578
+ schema_box,
579
+ rel_box,
580
+ history_state,
581
+ history_box,
582
+ download_csv,
583
+ ],
584
+ )
585
+
586
+ btn_load_example.click(
587
+ fn=load_example,
588
+ inputs=[example_dropdown],
589
+ outputs=[sql_input],
590
+ )
591
+
592
+ def handle_upload(uploaded_file):
593
+ uploaded_db_path, msg = use_uploaded_db(uploaded_file)
594
+ if uploaded_db_path is None:
595
+ return (
596
+ gr.update(),
597
+ msg,
598
+ gr.update(),
599
+ gr.update(),
600
+ [],
601
+ "Nenhuma query executada ainda.",
602
+ None,
603
+ )
604
+
605
+ schema = list_tables_and_columns(uploaded_db_path)
606
+ relationships = list_relationships(uploaded_db_path)
607
+
608
+ return (
609
+ uploaded_db_path,
610
+ msg,
611
+ schema,
612
+ relationships,
613
+ [],
614
+ "Nenhuma query executada ainda.",
615
+ None,
616
+ )
617
+
618
+ btn_use_upload.click(
619
+ fn=handle_upload,
620
+ inputs=[upload_db],
621
+ outputs=[
622
+ db_state,
623
+ db_status,
624
+ schema_box,
625
+ rel_box,
626
+ history_state,
627
+ history_box,
628
+ download_csv,
629
+ ],
630
+ )
631
+
632
+ def handle_reset():
633
+ lab_db, schema, relationships, msg = reset_lab(DEFAULT_DB_PATH)
634
+ return (
635
+ lab_db,
636
+ schema,
637
+ relationships,
638
+ msg,
639
+ [],
640
+ "Nenhuma query executada ainda.",
641
+ None,
642
+ )
643
+
644
+ btn_reset.click(
645
+ fn=handle_reset,
646
+ inputs=[],
647
+ outputs=[
648
+ db_state,
649
+ schema_box,
650
+ rel_box,
651
+ db_status,
652
+ history_state,
653
+ history_box,
654
+ download_csv,
655
+ ],
656
+ )
657
+
658
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=5.0.0
2
+ pandas>=2.0.0
3
+ openpyxl>=3.1.0