File size: 2,118 Bytes
024edca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import duckdb
import pandas as pd
from fastapi import FastAPI
import gradio as gr

con = duckdb.connect(database="./workspace/mydatabase.duckdb")
con.execute("CREATE TABLE IF NOT EXISTS items (id INTEGER, name VARCHAR);")

def setup_database_routes(app: FastAPI):
    def create_item(name):
        con.execute("INSERT INTO items (name) VALUES (?);", (name,))
        con.commit()
        return "Item created successfully!"

    def read_items():
        cursor = con.cursor()
        cursor.execute("SELECT * FROM items;")
        items = cursor.fetchall()
        df = pd.DataFrame(items, columns=["ID", "Name"])
        return df

    def update_item(id, name):
        con.execute("UPDATE items SET name = ? WHERE id = ?;", (name, id))
        con.commit()
        return "Item updated successfully!"

    def delete_item(id):
        con.execute("DELETE FROM items WHERE id = ?;", (id,))
        con.commit()
        return "Item deleted successfully!"

    with gr.Blocks() as appdb:
        gr.Markdown("CRUD Application")
        with gr.Row():
            with gr.Column():
                create_name = gr.Textbox(label="Create Item")
                create_btn = gr.Button("Create")
            with gr.Column():
                read_btn = gr.Button("Read Items")
        with gr.Row():
            with gr.Column():
                update_id = gr.Textbox(label="Update Item ID")
                update_name = gr.Textbox(label="Update Item Name")
                update_btn = gr.Button("Update")
            with gr.Column():
                delete_id = gr.Textbox(label="Delete Item ID")
                delete_btn = gr.Button("Delete")
        output_text = gr.Textbox(label="Output")
        output_table = gr.DataFrame(label="Items")

        create_btn.click(fn=create_item, inputs=create_name, outputs=output_text)
        read_btn.click(fn=read_items, outputs=output_table)
        update_btn.click(fn=update_item, inputs=[update_id, update_name], outputs=output_text)
        delete_btn.click(fn=delete_item, inputs=delete_id, outputs=output_text)

    app.mount("/db", appdb, name="database_app")