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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import psycopg2
|
| 3 |
+
from contextlib import closing
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
READ_ONLY_KEYWORDS = ("SELECT", "SHOW", "DESCRIBE", "DESC", "EXPLAIN")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_connection():
|
| 12 |
+
"""Create a connection to the database connection"""
|
| 13 |
+
try:
|
| 14 |
+
conn = psycopg2.connect("dbname='db' user='db' host='82.97.247.105' password='db'")
|
| 15 |
+
return conn
|
| 16 |
+
except Exception as e:
|
| 17 |
+
return None, f"Error connecting to database: {e}"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def is_read_only_query(query: str) -> bool:
|
| 21 |
+
"""check if a query is read-only by examining its first word"""
|
| 22 |
+
if not query.strip():
|
| 23 |
+
return False
|
| 24 |
+
first_word = query.strip().split()[0].upper()
|
| 25 |
+
return first_word in READ_ONLY_KEYWORDS
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def list_tables():
|
| 29 |
+
"""Get all tables from the database"""
|
| 30 |
+
try:
|
| 31 |
+
with closing(get_connection()) as conn:
|
| 32 |
+
if conn is None:
|
| 33 |
+
return "Error: Could not connect to database"
|
| 34 |
+
cursor = conn.cursor()
|
| 35 |
+
cursor.execute("SELECT * FROM pg_catalog.pg_tables WHERE schemaname NOT IN ('information_schema', 'pg_catalog');")
|
| 36 |
+
tables = cursor.fetchall()
|
| 37 |
+
|
| 38 |
+
if not tables:
|
| 39 |
+
return "No user tables found in the database"
|
| 40 |
+
|
| 41 |
+
# Format the output nicely
|
| 42 |
+
result = "Tables in database:\n\n"
|
| 43 |
+
for table in tables:
|
| 44 |
+
result += f"Schema: {table[0]}, Table: {table[1]}\n"
|
| 45 |
+
return result
|
| 46 |
+
except Exception as e:
|
| 47 |
+
return f"Error retrieving tables: {str(e)}"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def execute_query(query: str):
|
| 51 |
+
"""Execute a read-only SQL query on the database"""
|
| 52 |
+
if not query.strip():
|
| 53 |
+
return "Error: Please enter a query"
|
| 54 |
+
|
| 55 |
+
if not is_read_only_query(query):
|
| 56 |
+
return "Error: Only read-only queries (SELECT, SHOW, DESCRIBE, DESC, EXPLAIN) are allowed"
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
with closing(get_connection()) as conn:
|
| 60 |
+
if conn is None:
|
| 61 |
+
return "Error: Could not connect to database"
|
| 62 |
+
cursor = conn.cursor()
|
| 63 |
+
cursor.execute(query)
|
| 64 |
+
results = cursor.fetchall()
|
| 65 |
+
|
| 66 |
+
if not results:
|
| 67 |
+
return "Query executed successfully, but returned no results"
|
| 68 |
+
|
| 69 |
+
# Get column names
|
| 70 |
+
column_names = [desc[0] for desc in cursor.description]
|
| 71 |
+
|
| 72 |
+
# Format results as a table
|
| 73 |
+
result = f"Query: {query}\n\n"
|
| 74 |
+
result += "Columns: " + " | ".join(column_names) + "\n"
|
| 75 |
+
result += "-" * (len(" | ".join(column_names)) + 10) + "\n"
|
| 76 |
+
|
| 77 |
+
for row in results:
|
| 78 |
+
result += " | ".join(str(cell) for cell in row) + "\n"
|
| 79 |
+
|
| 80 |
+
result += f"\nTotal rows: {len(results)}"
|
| 81 |
+
return result
|
| 82 |
+
except Exception as e:
|
| 83 |
+
return f"Error executing query: {str(e)}"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_table_schema(table_name: str):
|
| 87 |
+
"""Get schema information for a specific table"""
|
| 88 |
+
if not table_name.strip():
|
| 89 |
+
return "Error: Please enter a table name"
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
with closing(get_connection()) as conn:
|
| 93 |
+
if conn is None:
|
| 94 |
+
return "Error: Could not connect to database"
|
| 95 |
+
cursor = conn.cursor()
|
| 96 |
+
|
| 97 |
+
# Get table structure
|
| 98 |
+
cursor.execute("""
|
| 99 |
+
SELECT column_name, data_type, is_nullable, column_default
|
| 100 |
+
FROM information_schema.columns
|
| 101 |
+
WHERE table_name = %s
|
| 102 |
+
ORDER BY ordinal_position;
|
| 103 |
+
""", (table_name,))
|
| 104 |
+
|
| 105 |
+
columns = cursor.fetchall()
|
| 106 |
+
|
| 107 |
+
if not columns:
|
| 108 |
+
return f"Table '{table_name}' not found or no columns found"
|
| 109 |
+
|
| 110 |
+
result = f"Schema for table '{table_name}':\n\n"
|
| 111 |
+
result += "Column Name | Data Type | Nullable | Default\n"
|
| 112 |
+
result += "-" * 50 + "\n"
|
| 113 |
+
|
| 114 |
+
for col in columns:
|
| 115 |
+
result += f"{col[0]} | {col[1]} | {col[2]} | {col[3] or 'NULL'}\n"
|
| 116 |
+
|
| 117 |
+
return result
|
| 118 |
+
except Exception as e:
|
| 119 |
+
return f"Error getting table schema: {str(e)}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_connection():
|
| 123 |
+
"""Test database connection"""
|
| 124 |
+
try:
|
| 125 |
+
with closing(get_connection()) as conn:
|
| 126 |
+
if conn is None:
|
| 127 |
+
return "β Connection failed"
|
| 128 |
+
cursor = conn.cursor()
|
| 129 |
+
cursor.execute("SELECT version();")
|
| 130 |
+
version = cursor.fetchone()
|
| 131 |
+
return f"β
Connection successful!\nDatabase version: {version[0]}"
|
| 132 |
+
except Exception as e:
|
| 133 |
+
return f"β Connection failed: {str(e)}"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Sample queries for demonstration
|
| 137 |
+
sample_queries = [
|
| 138 |
+
"SELECT * FROM users LIMIT 5;",
|
| 139 |
+
"SELECT COUNT(*) FROM users;",
|
| 140 |
+
"SHOW TABLES;",
|
| 141 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';",
|
| 142 |
+
"DESCRIBE users;"
|
| 143 |
+
]
|
| 144 |
+
|
| 145 |
+
# Create Gradio interface
|
| 146 |
+
with gr.Blocks(title="PostgreSQL Database Explorer", theme=gr.themes.Soft()) as interface:
|
| 147 |
+
gr.Markdown("# ποΈ PostgreSQL Database Explorer")
|
| 148 |
+
gr.Markdown("Secure interface for executing read-only queries to PostgreSQL database")
|
| 149 |
+
|
| 150 |
+
with gr.Tab("π Execute Query"):
|
| 151 |
+
gr.Markdown("### Execute SQL Query")
|
| 152 |
+
gr.Markdown("Only read-only queries are allowed: SELECT, SHOW, DESCRIBE, DESC, EXPLAIN")
|
| 153 |
+
|
| 154 |
+
with gr.Row():
|
| 155 |
+
with gr.Column(scale=2):
|
| 156 |
+
query_input = gr.Textbox(
|
| 157 |
+
label="SQL Query",
|
| 158 |
+
placeholder="Enter your SQL query here...",
|
| 159 |
+
lines=5,
|
| 160 |
+
value="SELECT * FROM users LIMIT 5;"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
with gr.Row():
|
| 164 |
+
execute_btn = gr.Button("π Execute Query", variant="primary")
|
| 165 |
+
clear_btn = gr.Button("ποΈ Clear")
|
| 166 |
+
|
| 167 |
+
gr.Markdown("**Sample queries:**")
|
| 168 |
+
sample_dropdown = gr.Dropdown(
|
| 169 |
+
choices=sample_queries,
|
| 170 |
+
label="Select a sample query",
|
| 171 |
+
value=None
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
with gr.Column(scale=3):
|
| 175 |
+
query_output = gr.Textbox(
|
| 176 |
+
label="Results",
|
| 177 |
+
lines=15,
|
| 178 |
+
max_lines=20,
|
| 179 |
+
interactive=False
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
with gr.Tab("π Tables List"):
|
| 183 |
+
gr.Markdown("### Database Tables List")
|
| 184 |
+
with gr.Row():
|
| 185 |
+
tables_btn = gr.Button("π Get Tables List", variant="primary")
|
| 186 |
+
tables_output = gr.Textbox(
|
| 187 |
+
label="Tables",
|
| 188 |
+
lines=10,
|
| 189 |
+
interactive=False
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
with gr.Tab("ποΈ Table Schema"):
|
| 193 |
+
gr.Markdown("### Table Structure Information")
|
| 194 |
+
with gr.Row():
|
| 195 |
+
with gr.Column(scale=1):
|
| 196 |
+
table_name_input = gr.Textbox(
|
| 197 |
+
label="Table Name",
|
| 198 |
+
placeholder="Enter table name...",
|
| 199 |
+
value="users"
|
| 200 |
+
)
|
| 201 |
+
schema_btn = gr.Button("ποΈ Get Schema", variant="primary")
|
| 202 |
+
|
| 203 |
+
with gr.Column(scale=2):
|
| 204 |
+
schema_output = gr.Textbox(
|
| 205 |
+
label="Table Schema",
|
| 206 |
+
lines=10,
|
| 207 |
+
interactive=False
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
with gr.Tab("π§ Connection Test"):
|
| 211 |
+
gr.Markdown("### Database Connection Test")
|
| 212 |
+
with gr.Row():
|
| 213 |
+
test_btn = gr.Button("π§ Test Connection", variant="primary")
|
| 214 |
+
connection_output = gr.Textbox(
|
| 215 |
+
label="Connection Status",
|
| 216 |
+
lines=5,
|
| 217 |
+
interactive=False
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
# Event handlers
|
| 221 |
+
execute_btn.click(
|
| 222 |
+
fn=execute_query,
|
| 223 |
+
inputs=[query_input],
|
| 224 |
+
outputs=[query_output]
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
clear_btn.click(
|
| 228 |
+
fn=lambda: "",
|
| 229 |
+
outputs=[query_input]
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
sample_dropdown.change(
|
| 233 |
+
fn=lambda x: x if x else "",
|
| 234 |
+
inputs=[sample_dropdown],
|
| 235 |
+
outputs=[query_input]
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
tables_btn.click(
|
| 239 |
+
fn=list_tables,
|
| 240 |
+
outputs=[tables_output]
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
schema_btn.click(
|
| 244 |
+
fn=get_table_schema,
|
| 245 |
+
inputs=[table_name_input],
|
| 246 |
+
outputs=[schema_output]
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
test_btn.click(
|
| 250 |
+
fn=test_connection,
|
| 251 |
+
outputs=[connection_output]
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# Launch the interface
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
interface.launch(mcp_server=True)
|