Spaces:
Sleeping

File size: 19,606 Bytes
ba7a1a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
import os
import sqlite3
import tempfile
import shutil
from datetime import datetime

import pandas as pd
import gradio as gr

# =========================
# CONFIGURAÇÕES
# =========================
DEFAULT_DB_PATH = "data/base_treinamento.db"


# =========================
# FUNÇÕES AUXILIARES
# =========================
def ensure_default_db():
    """
    Garante que exista um banco padrão mínimo para o app iniciar.
    Se você já tiver o seu .db real, basta colocá-lo em:
    data/base_treinamento.db
    """
    if os.path.exists(DEFAULT_DB_PATH):
        return

    os.makedirs(os.path.dirname(DEFAULT_DB_PATH), exist_ok=True)

    conn = sqlite3.connect(DEFAULT_DB_PATH)
    cur = conn.cursor()

    cur.executescript(
        """
        PRAGMA foreign_keys = ON;

        CREATE TABLE IF NOT EXISTS Categorias (
            CategoriaID INTEGER PRIMARY KEY,
            Departamento TEXT,
            Categoria TEXT,
            MargemAlvoPct REAL
        );

        CREATE TABLE IF NOT EXISTS Clientes (
            ClienteID INTEGER PRIMARY KEY,
            Nome TEXT,
            Genero TEXT,
            DataNascimento TEXT,
            Cidade TEXT,
            Estado TEXT,
            Regiao TEXT,
            SegmentoCliente TEXT,
            FaixaRenda TEXT,
            DataCadastro TEXT,
            ScoreFidelidade INTEGER,
            Email TEXT
        );

        CREATE TABLE IF NOT EXISTS Fornecedores (
            FornecedorID INTEGER PRIMARY KEY,
            Fornecedor TEXT,
            PaisOrigem TEXT,
            Segmento TEXT,
            PrazoMedioDias INTEGER,
            Rating REAL
        );

        CREATE TABLE IF NOT EXISTS Lojas (
            LojaID INTEGER PRIMARY KEY,
            CodigoLoja TEXT,
            TipoLoja TEXT,
            Cidade TEXT,
            Estado TEXT,
            Regiao TEXT,
            DataAbertura TEXT,
            AreaM2 INTEGER,
            MetaMensal REAL
        );

        CREATE TABLE IF NOT EXISTS Funcionarios (
            FuncionarioID INTEGER PRIMARY KEY,
            LojaID INTEGER,
            Nome TEXT,
            Cargo TEXT,
            DataAdmissao TEXT,
            SalarioBase REAL,
            MetaMensal REAL,
            Turno TEXT,
            Status TEXT,
            FOREIGN KEY (LojaID) REFERENCES Lojas(LojaID)
        );

        CREATE TABLE IF NOT EXISTS Produtos (
            ProdutoID INTEGER PRIMARY KEY,
            SKU TEXT,
            Produto TEXT,
            Marca TEXT,
            CategoriaID INTEGER,
            FornecedorID INTEGER,
            CustoUnitario REAL,
            PrecoLista REAL,
            AtivoDesde TEXT,
            PesoKg REAL,
            StatusProduto TEXT,
            FOREIGN KEY (CategoriaID) REFERENCES Categorias(CategoriaID),
            FOREIGN KEY (FornecedorID) REFERENCES Fornecedores(FornecedorID)
        );

        CREATE TABLE IF NOT EXISTS Pedidos (
            PedidoID INTEGER PRIMARY KEY,
            DataPedido TEXT,
            ClienteID INTEGER,
            LojaID INTEGER,
            FuncionarioID INTEGER,
            CanalVenda TEXT,
            StatusPedido TEXT,
            Cupom TEXT,
            Frete REAL,
            DescontoPedido REAL,
            ValorItens REAL,
            ValorTotal REAL,
            FOREIGN KEY (ClienteID) REFERENCES Clientes(ClienteID),
            FOREIGN KEY (LojaID) REFERENCES Lojas(LojaID),
            FOREIGN KEY (FuncionarioID) REFERENCES Funcionarios(FuncionarioID)
        );

        CREATE TABLE IF NOT EXISTS ItensPedido (
            ItemID INTEGER,
            PedidoID INTEGER,
            ProdutoID INTEGER,
            Quantidade INTEGER,
            PrecoUnitario REAL,
            DescontoItemPct REAL,
            CustoUnitario REAL,
            FOREIGN KEY (PedidoID) REFERENCES Pedidos(PedidoID),
            FOREIGN KEY (ProdutoID) REFERENCES Produtos(ProdutoID)
        );

        CREATE TABLE IF NOT EXISTS Pagamentos (
            PagamentoID INTEGER,
            PedidoID INTEGER,
            SequenciaPagamento INTEGER,
            MetodoPagamento TEXT,
            Parcelas INTEGER,
            ValorPago REAL,
            StatusPagamento TEXT,
            DataPagamento TEXT,
            Gateway TEXT,
            FOREIGN KEY (PedidoID) REFERENCES Pedidos(PedidoID)
        );
        """
    )

    cur.executescript(
        """
        INSERT INTO Categorias VALUES
        (1, 'Mercearia', 'Alimentos', 0.30),
        (2, 'Bebidas', 'Refrigerantes', 0.25),
        (3, 'Higiene', 'Perfumaria', 0.35);

        INSERT INTO Fornecedores VALUES
        (1, 'Fornecedor Alfa', 'Brasil', 'Nacional', 15, 4.5),
        (2, 'Fornecedor Beta', 'Argentina', 'Importado', 22, 4.2);

        INSERT INTO Lojas VALUES
        (1, 'LJ001', 'Rua', 'São Paulo', 'SP', 'Sudeste', '2022-01-10', 300, 120000),
        (2, 'LJ002', 'Shopping', 'Campinas', 'SP', 'Sudeste', '2023-05-20', 180, 90000);

        INSERT INTO Clientes VALUES
        (1, 'Ana Souza', 'F', '1990-05-10', 'São Paulo', 'SP', 'Sudeste', 'Premium', 'Alta', '2024-01-10', 95, 'ana@email.com'),
        (2, 'Bruno Lima', 'M', '1988-08-20', 'Campinas', 'SP', 'Sudeste', 'Regular', 'Media', '2024-02-11', 80, 'bruno@email.com'),
        (3, 'Carla Mendes', 'F', '1995-02-15', 'Jundiaí', 'SP', 'Sudeste', 'Premium', 'Alta', '2024-03-01', 91, 'carla@email.com');

        INSERT INTO Funcionarios VALUES
        (1, 1, 'Mariana Costa', 'Vendedora', '2023-01-05', 2500, 30000, 'Manhã', 'Ativo'),
        (2, 1, 'João Alves', 'Caixa', '2023-03-12', 2200, 20000, 'Tarde', 'Ativo'),
        (3, 2, 'Fernanda Rocha', 'Gerente', '2022-10-01', 5500, 60000, 'Integral', 'Ativo');

        INSERT INTO Produtos VALUES
        (1, 'SKU001', 'Arroz 5kg', 'Marca A', 1, 1, 18.00, 27.90, '2023-01-01', 5.0, 'Ativo'),
        (2, 'SKU002', 'Refrigerante 2L', 'Marca B', 2, 2, 4.50, 8.99, '2023-01-01', 2.0, 'Ativo'),
        (3, 'SKU003', 'Shampoo 400ml', 'Marca C', 3, 1, 9.00, 18.50, '2023-01-01', 0.4, 'Ativo');

        INSERT INTO Pedidos VALUES
        (1, '2026-04-01', 1, 1, 1, 'Loja Física', 'Concluído', 'DESC10', 5.00, 2.00, 45.88, 48.88),
        (2, '2026-04-02', 2, 1, 2, 'Site', 'Concluído', NULL, 8.00, 0.00, 27.90, 35.90),
        (3, '2026-04-03', 3, 2, 3, 'App', 'Concluído', 'APP5', 6.00, 1.50, 18.50, 23.00);

        INSERT INTO ItensPedido VALUES
        (1, 1, 2, 2, 8.99, 0.00, 4.50),
        (2, 1, 3, 1, 18.50, 0.10, 9.00),
        (3, 2, 1, 1, 27.90, 0.00, 18.00),
        (4, 3, 3, 1, 18.50, 0.00, 9.00);

        INSERT INTO Pagamentos VALUES
        (1, 1, 1, 'Cartão', 1, 48.88, 'Aprovado', '2026-04-01', 'GatewayX'),
        (2, 2, 1, 'Pix', 1, 35.90, 'Aprovado', '2026-04-02', 'GatewayY'),
        (3, 3, 1, 'Cartão', 2, 23.00, 'Aprovado', '2026-04-03', 'GatewayX');
        """
    )

    conn.commit()
    conn.close()


def create_lab_copy(source_db_path: str):
    """
    Cria uma cópia temporária do banco para o modo laboratório.
    """
    temp_dir = tempfile.mkdtemp(prefix="sql_lab_")
    lab_db_path = os.path.join(temp_dir, "lab.db")
    shutil.copy2(source_db_path, lab_db_path)
    return temp_dir, lab_db_path


def connect_db(db_path: str):
    conn = sqlite3.connect(db_path, check_same_thread=False)
    conn.execute("PRAGMA foreign_keys = ON;")
    return conn


def list_tables_and_columns(db_path: str) -> str:
    conn = connect_db(db_path)
    cur = conn.cursor()

    try:
        tables = cur.execute(
            """
            SELECT name
            FROM sqlite_master
            WHERE type='table'
              AND name NOT LIKE 'sqlite_%'
            ORDER BY name;
            """
        ).fetchall()

        lines = []
        for (table_name,) in tables:
            lines.append(f"📦 {table_name}")
            cols = cur.execute(f'PRAGMA table_info("{table_name}")').fetchall()
            for col in cols:
                _, name, col_type, notnull, _, pk = col
                pk_txt = " [PK]" if pk else ""
                nn_txt = " NOT NULL" if notnull else ""
                lines.append(f"   - {name} ({col_type}){pk_txt}{nn_txt}")
            lines.append("")

        return "\n".join(lines).strip() if lines else "Nenhuma tabela encontrada."
    finally:
        conn.close()


def list_relationships(db_path: str) -> str:
    conn = connect_db(db_path)
    cur = conn.cursor()

    try:
        tables = cur.execute(
            """
            SELECT name
            FROM sqlite_master
            WHERE type='table'
              AND name NOT LIKE 'sqlite_%'
            ORDER BY name;
            """
        ).fetchall()

        lines = []
        for (table_name,) in tables:
            fks = cur.execute(f'PRAGMA foreign_key_list("{table_name}")').fetchall()
            if fks:
                lines.append(f"🔗 {table_name}")
                for fk in fks:
                    _, _, ref_table, from_col, to_col, on_update, on_delete, _ = fk
                    lines.append(
                        f"   - {from_col} -> {ref_table}.{to_col} "
                        f"(ON UPDATE {on_update}, ON DELETE {on_delete})"
                    )
                lines.append("")

        return "\n".join(lines).strip() if lines else "Nenhum relacionamento encontrado."
    finally:
        conn.close()


def get_examples():
    return {
        "SELECT básico": "SELECT * FROM Produtos LIMIT 10;",
        "WHERE": "SELECT * FROM Clientes WHERE Cidade = 'São Paulo';",
        "ORDER BY": "SELECT Produto, PrecoLista FROM Produtos ORDER BY PrecoLista DESC;",
        "GROUP BY": """
SELECT MetodoPagamento, SUM(ValorPago) AS TotalPago
FROM Pagamentos
GROUP BY MetodoPagamento;
""".strip(),
        "JOIN": """
SELECT
    p.PedidoID,
    c.Nome AS Cliente,
    l.CodigoLoja,
    f.Nome AS Funcionario
FROM Pedidos p
JOIN Clientes c ON p.ClienteID = c.ClienteID
JOIN Lojas l ON p.LojaID = l.LojaID
JOIN Funcionarios f ON p.FuncionarioID = f.FuncionarioID;
""".strip(),
        "JOIN com agregação": """
SELECT
    pr.Produto,
    SUM(ip.Quantidade) AS QuantidadeVendida
FROM ItensPedido ip
JOIN Produtos pr ON ip.ProdutoID = pr.ProdutoID
GROUP BY pr.Produto
ORDER BY QuantidadeVendida DESC;
""".strip(),
        "HAVING": """
SELECT
    MetodoPagamento,
    SUM(ValorPago) AS Total
FROM Pagamentos
GROUP BY MetodoPagamento
HAVING SUM(ValorPago) > 20;
""".strip(),
        "Subquery": """
SELECT *
FROM Produtos
WHERE PrecoLista > (
    SELECT AVG(PrecoLista) FROM Produtos
);
""".strip(),
        "CTE": """
WITH TotalPorCliente AS (
    SELECT
        c.ClienteID,
        c.Nome,
        SUM(p.ValorTotal) AS TotalGasto
    FROM Clientes c
    JOIN Pedidos p ON c.ClienteID = p.ClienteID
    GROUP BY c.ClienteID, c.Nome
)
SELECT *
FROM TotalPorCliente
ORDER BY TotalGasto DESC;
""".strip(),
        "INSERT": """
INSERT INTO Categorias (CategoriaID, Departamento, Categoria, MargemAlvoPct)
VALUES (99, 'Teste', 'Categoria Teste', 0.20);
""".strip(),
        "UPDATE": """
UPDATE Produtos
SET PrecoLista = PrecoLista * 1.10
WHERE CategoriaID = 1;
""".strip(),
        "DELETE": """
DELETE FROM Pagamentos
WHERE PagamentoID = 999;
""".strip(),
        "CREATE TABLE": """
CREATE TABLE Exemplo (
    ID INTEGER PRIMARY KEY,
    Nome TEXT,
    Nota REAL
);
""".strip(),
    }


def load_example(example_name: str) -> str:
    return get_examples().get(example_name, "")


def history_to_text(history):
    if not history:
        return "Nenhuma query executada ainda."
    return "\n\n".join(
        [f"[{item['horario']}] {item['sql']}" for item in history]
    )


def normalize_query(sql_text: str) -> str:
    return (sql_text or "").strip()


def is_select_like(sql_text: str) -> bool:
    sql_upper = sql_text.strip().upper()
    return (
        sql_upper.startswith("SELECT")
        or sql_upper.startswith("WITH")
        or sql_upper.startswith("PRAGMA")
        or sql_upper.startswith("EXPLAIN")
    )


def dataframe_to_csv_file(df: pd.DataFrame):
    """
    Salva o DataFrame em CSV temporário e devolve o caminho para download.
    """
    if df is None or df.empty:
        return None

    temp_dir = tempfile.mkdtemp(prefix="sql_csv_")
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    file_path = os.path.join(temp_dir, f"resultado_query_{timestamp}.csv")
    df.to_csv(file_path, index=False, encoding="utf-8-sig")
    return file_path


def run_sql(sql_text: str, db_path: str, history):
    sql_text = normalize_query(sql_text)

    if not sql_text:
        return pd.DataFrame(), "Digite uma query SQL.", history, None

    conn = connect_db(db_path)
    cur = conn.cursor()

    try:
        if is_select_like(sql_text):
            df = pd.read_sql_query(sql_text, conn)
            msg = f"Consulta executada com sucesso. {len(df)} linha(s) retornada(s)."
            csv_file = dataframe_to_csv_file(df)
        else:
            cur.executescript(sql_text)
            conn.commit()
            df = pd.DataFrame({"status": ["OK"]})
            msg = "Comando executado com sucesso."
            csv_file = None

        history = history or []
        history.insert(
            0,
            {
                "horario": datetime.now().strftime("%d/%m/%Y %H:%M:%S"),
                "sql": sql_text,
            },
        )
        history = history[:30]

        return df, msg, history, csv_file

    except Exception as e:
        return pd.DataFrame(), f"Erro ao executar SQL: {e}", history, None

    finally:
        conn.close()


def use_uploaded_db(uploaded_file):
    if uploaded_file is None:
        return None, "Nenhum arquivo enviado."

    temp_dir = tempfile.mkdtemp(prefix="sql_upload_")
    target_path = os.path.join(temp_dir, "uploaded.db")
    shutil.copy2(uploaded_file.name, target_path)

    return target_path, f"Banco enviado carregado com sucesso: {os.path.basename(uploaded_file.name)}"


def reset_lab(default_source_db: str):
    _, lab_db = create_lab_copy(default_source_db)
    schema = list_tables_and_columns(lab_db)
    relationships = list_relationships(lab_db)
    return lab_db, schema, relationships, "Banco de laboratório resetado com sucesso."


# =========================
# INICIALIZAÇÃO
# =========================
ensure_default_db()

_, initial_lab_db = create_lab_copy(DEFAULT_DB_PATH)
initial_schema = list_tables_and_columns(initial_lab_db)
initial_relationships = list_relationships(initial_lab_db)
example_names = list(get_examples().keys())


# =========================
# INTERFACE
# =========================
with gr.Blocks(title="Laboratório SQL com SQLite") as demo:
    gr.Markdown(
        """
# Laboratório SQL com SQLite

Treine SQL em um banco SQLite real.

### Recursos
- carregamento automático do banco `.db`
- upload de outro banco SQLite
- editor SQL livre
- execução de consultas
- schema das tabelas
- relacionamentos detectados
- histórico de queries
- exportação do resultado em CSV
- reset do ambiente de laboratório
"""
    )

    db_state = gr.State(initial_lab_db)
    history_state = gr.State([])

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("## Base de dados")
            upload_db = gr.File(
                label="Enviar outro arquivo .db ou .sqlite",
                file_types=[".db", ".sqlite"],
            )
            btn_use_upload = gr.Button("Usar banco enviado")
            btn_reset = gr.Button("Resetar banco de laboratório")
            db_status = gr.Textbox(
                label="Status do banco",
                value="Banco padrão carregado.",
                interactive=False,
            )

            gr.Markdown("## Exemplos")
            example_dropdown = gr.Dropdown(
                choices=example_names,
                label="Escolha um exemplo",
                value=example_names[0] if example_names else None,
            )
            btn_load_example = gr.Button("Carregar exemplo no editor")

        with gr.Column(scale=2):
            gr.Markdown("## Editor SQL")
            sql_input = gr.Code(
                label="Digite sua query SQL",
                language="sql",
                value="SELECT * FROM Produtos LIMIT 10;",
                lines=16,
            )
            btn_run = gr.Button("Executar SQL", variant="primary")
            sql_message = gr.Textbox(label="Mensagem", interactive=False)

    with gr.Row():
        with gr.Column(scale=2):
            result_df = gr.Dataframe(label="Resultado da query", wrap=True)
            download_csv = gr.File(label="Baixar resultado em CSV")
        with gr.Column(scale=1):
            schema_box = gr.Textbox(
                label="Schema das tabelas",
                value=initial_schema,
                lines=22,
                interactive=False,
            )

    with gr.Row():
        with gr.Column():
            rel_box = gr.Textbox(
                label="Relacionamentos detectados",
                value=initial_relationships,
                lines=12,
                interactive=False,
            )
        with gr.Column():
            history_box = gr.Textbox(
                label="Histórico das queries",
                value="Nenhuma query executada ainda.",
                lines=12,
                interactive=False,
            )

    def handle_run(sql_text, current_db, history):
        df, msg, new_history, csv_file = run_sql(sql_text, current_db, history)
        schema = list_tables_and_columns(current_db)
        relationships = list_relationships(current_db)
        history_text = history_to_text(new_history)
        return df, msg, schema, relationships, new_history, history_text, csv_file

    btn_run.click(
        fn=handle_run,
        inputs=[sql_input, db_state, history_state],
        outputs=[
            result_df,
            sql_message,
            schema_box,
            rel_box,
            history_state,
            history_box,
            download_csv,
        ],
    )

    btn_load_example.click(
        fn=load_example,
        inputs=[example_dropdown],
        outputs=[sql_input],
    )

    def handle_upload(uploaded_file):
        uploaded_db_path, msg = use_uploaded_db(uploaded_file)
        if uploaded_db_path is None:
            return (
                gr.update(),
                msg,
                gr.update(),
                gr.update(),
                [],
                "Nenhuma query executada ainda.",
                None,
            )

        schema = list_tables_and_columns(uploaded_db_path)
        relationships = list_relationships(uploaded_db_path)

        return (
            uploaded_db_path,
            msg,
            schema,
            relationships,
            [],
            "Nenhuma query executada ainda.",
            None,
        )

    btn_use_upload.click(
        fn=handle_upload,
        inputs=[upload_db],
        outputs=[
            db_state,
            db_status,
            schema_box,
            rel_box,
            history_state,
            history_box,
            download_csv,
        ],
    )

    def handle_reset():
        lab_db, schema, relationships, msg = reset_lab(DEFAULT_DB_PATH)
        return (
            lab_db,
            schema,
            relationships,
            msg,
            [],
            "Nenhuma query executada ainda.",
            None,
        )

    btn_reset.click(
        fn=handle_reset,
        inputs=[],
        outputs=[
            db_state,
            schema_box,
            rel_box,
            db_status,
            history_state,
            history_box,
            download_csv,
        ],
    )

demo.launch()