samarth upadhyay commited on
Commit
b597938
·
verified ·
1 Parent(s): 3b9735e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -118
app.py CHANGED
@@ -1,153 +1,218 @@
1
- import sqlite3
2
- import os
3
  import sys
 
 
 
 
 
4
  from flask import Flask, request, jsonify
5
  from flask_cors import CORS
6
 
7
  app = Flask(__name__)
8
  CORS(app)
9
 
10
- # Store databases in a temporary directory
11
- DB_STORAGE_PATH = "/tmp"
 
 
 
 
 
 
12
 
13
- def get_db_path(session_id):
14
- # Security: Ensure session_id is alphanumeric only to prevent path traversal
15
- safe_id = "".join(x for x in session_id if x.isalnum())
16
- return os.path.join(DB_STORAGE_PATH, f"{safe_id}.db")
17
 
18
- def create_sample_db(path):
19
- """Creates a dummy database with Employees and Departments"""
20
- if os.path.exists(path):
21
- os.remove(path)
22
-
23
- conn = sqlite3.connect(path)
24
- cursor = conn.cursor()
25
-
26
- # Create Tables
27
- cursor.execute('''CREATE TABLE Departments (id INTEGER PRIMARY KEY, name TEXT, budget INTEGER)''')
28
- cursor.execute('''CREATE TABLE Employees (id INTEGER PRIMARY KEY, name TEXT, role TEXT, salary INTEGER, dept_id INTEGER, FOREIGN KEY(dept_id) REFERENCES Departments(id))''')
29
-
30
- # Insert Data
31
- cursor.executemany('INSERT INTO Departments VALUES (?,?,?)', [
32
- (1, 'Engineering', 150000),
33
- (2, 'Marketing', 80000),
34
- (3, 'HR', 50000)
35
- ])
36
- cursor.executemany('INSERT INTO Employees VALUES (?,?,?,?,?)', [
37
- (101, 'Alice', 'Engineer', 90000, 1),
38
- (102, 'Bob', 'Manager', 95000, 2),
39
- (103, 'Charlie', 'Analyst', 60000, 2),
40
- (104, 'David', 'Engineer', 88000, 1),
41
- (105, 'Eve', 'Recruiter', 55000, 3)
42
- ])
43
- conn.commit()
44
- conn.close()
45
 
46
  @app.route('/')
47
  def home():
48
- return jsonify({"status": "ok", "message": "SQL Compiler with File Persistence Ready"})
49
 
50
- @app.route('/api/session/init', methods=['POST'])
51
- def init_session():
52
- # Allows user to request a fresh sample DB
53
- session_id = request.json.get('session_id')
54
- if not session_id: return jsonify({'error': 'Missing session_id'}), 400
55
-
56
- db_path = get_db_path(session_id)
57
- create_sample_db(db_path)
58
- return jsonify({'status': 'initialized', 'message': 'Sample Database Loaded'})
59
-
60
- @app.route('/api/session/upload', methods=['POST'])
61
- def upload_db():
62
- session_id = request.form.get('session_id')
63
- file = request.files.get('file')
64
-
65
- if not session_id or not file:
66
- return jsonify({'error': 'Missing session_id or file'}), 400
67
-
68
- db_path = get_db_path(session_id)
69
- file.save(db_path)
70
- return jsonify({'status': 'uploaded', 'message': 'Database Uploaded Successfully'})
71
-
72
- @app.route('/api/schema', methods=['POST'])
73
- def get_schema():
74
- """Returns list of tables and columns for the sidebar"""
75
- session_id = request.json.get('session_id')
76
- db_path = get_db_path(session_id)
77
-
78
- if not os.path.exists(db_path):
79
- return jsonify({'error': 'No database found for this session'}), 404
80
 
 
 
81
  try:
82
- conn = sqlite3.connect(db_path)
83
- cursor = conn.cursor()
 
 
 
84
 
85
- # Get all tables
86
- cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
87
- tables = [row[0] for row in cursor.fetchall()]
 
 
 
 
88
 
89
- schema = {}
90
- for table in tables:
91
- cursor.execute(f"PRAGMA table_info({table})")
92
- # Returns (cid, name, type, notnull, dflt_value, pk)
93
- columns = [{"name": col[1], "type": col[2]} for col in cursor.fetchall()]
94
- schema[table] = columns
95
-
96
- conn.close()
97
- return jsonify({'schema': schema})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  except Exception as e:
99
- return jsonify({'error': str(e)}), 500
100
 
101
  @app.route('/api/run-sql', methods=['POST'])
102
  def run_sql():
103
- data = request.json
104
- session_id = data.get('session_id')
105
- sql_code = data.get('code')
 
106
 
107
- if not session_id or not sql_code:
108
- return jsonify({'output': 'Missing session_id or SQL code'}), 400
109
 
110
- db_path = get_db_path(session_id)
 
 
 
 
 
111
 
112
- # If DB doesn't exist yet, create sample
113
- if not os.path.exists(db_path):
114
- create_sample_db(db_path)
 
 
 
 
 
 
 
 
115
 
116
- output = []
117
  try:
118
- conn = sqlite3.connect(db_path)
119
- cursor = conn.cursor()
120
-
121
- # Execute script allows multiple statements
122
- cursor.executescript(sql_code)
123
-
124
- # Check if the last query returned data (SELECT)
125
- if cursor.description:
126
- columns = [desc[0] for desc in cursor.description]
127
- rows = cursor.fetchall()
128
 
129
- # ASCII Table Formatting
130
- output.append(f"| {' | '.join(columns)} |")
131
- output.append("-" * len(output[-1]))
132
- for row in rows:
133
- output.append(f"| {' | '.join(map(str, row))} |")
 
134
 
135
- output.append(f"\n({len(rows)} rows returned)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  else:
137
- output.append(f"Query executed successfully. (Rows affected: {conn.total_changes})")
138
 
139
- conn.commit()
140
- conn.close()
141
-
142
- except sqlite3.Error as e:
143
- return jsonify({'error': str(e)})
144
  except Exception as e:
145
- return jsonify({'error': f"System Error: {str(e)}"})
 
 
 
146
 
147
- return jsonify({'output': "\n".join(output)})
148
 
149
  if __name__ == '__main__':
150
- # Ensure tmp dir exists
151
- if not os.path.exists(DB_STORAGE_PATH):
152
- os.makedirs(DB_STORAGE_PATH)
153
  app.run(host="0.0.0.0", port=7860)
 
1
+ import subprocess
 
2
  import sys
3
+ import uuid
4
+ import os
5
+ import tempfile
6
+ import io
7
+ import pandas as pd
8
  from flask import Flask, request, jsonify
9
  from flask_cors import CORS
10
 
11
  app = Flask(__name__)
12
  CORS(app)
13
 
14
+ # --- STANDARD SAMPLE DATA (Same for everyone) ---
15
+ SAMPLE_SQL = """
16
+ -- Standard Sample Data
17
+ CREATE TABLE Departments (
18
+ dept_id INT PRIMARY KEY,
19
+ dept_name VARCHAR(50),
20
+ location VARCHAR(50)
21
+ );
22
 
23
+ INSERT INTO Departments VALUES (1, 'Engineering', 'New York');
24
+ INSERT INTO Departments VALUES (2, 'HR', 'London');
25
+ INSERT INTO Departments VALUES (3, 'Marketing', 'San Francisco');
26
+ INSERT INTO Departments VALUES (4, 'Sales', 'Tokyo');
27
 
28
+ CREATE TABLE Employees (
29
+ emp_id INT PRIMARY KEY,
30
+ name VARCHAR(50),
31
+ dept_id INT,
32
+ role VARCHAR(50),
33
+ salary DECIMAL(10, 2)
34
+ -- Note: Foreign keys might be loose depending on DB strictness settings
35
+ );
36
+
37
+ INSERT INTO Employees VALUES (101, 'Alice Smith', 1, 'Engineer', 90000);
38
+ INSERT INTO Employees VALUES (102, 'Bob Jones', 1, 'Senior Engineer', 110000);
39
+ INSERT INTO Employees VALUES (103, 'Charlie Brown', 2, 'Recruiter', 60000);
40
+ INSERT INTO Employees VALUES (104, 'Diana Prince', 3, 'CMO', 150000);
41
+ INSERT INTO Employees VALUES (105, 'Evan Wright', 1, 'Intern', 40000);
42
+ INSERT INTO Employees VALUES (106, 'Fiona Green', 4, 'Sales Rep', 75000);
43
+ """
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  @app.route('/')
46
  def home():
47
+ return jsonify({"status": "ok", "message": "SQL Compiler API Ready"})
48
 
49
+ def run_command(command, input_text=None, timeout=15):
50
+ """Helper to run shell commands safely"""
51
+ try:
52
+ run_process = subprocess.run(
53
+ command,
54
+ input=input_text,
55
+ capture_output=True,
56
+ text=True,
57
+ timeout=timeout
58
+ )
59
+ output = run_process.stdout
60
+ if run_process.stderr:
61
+ output += "\n--- Database Messages/Errors ---\n" + run_process.stderr
62
+ return output
63
+ except subprocess.TimeoutExpired:
64
+ return "Error: Execution timed out (15s limit)."
65
+ except Exception as e:
66
+ return f"System Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ def file_to_sql(file, filename):
69
+ """Converts CSV/Excel file objects to SQL CREATE/INSERT strings"""
70
  try:
71
+ # 1. Read Data
72
+ if filename.lower().endswith('.csv'):
73
+ df = pd.read_csv(file)
74
+ else:
75
+ df = pd.read_excel(file)
76
 
77
+ # 2. Sanitize Table Name (filename without extension, alphanumeric only)
78
+ table_name = os.path.splitext(filename)[0]
79
+ table_name = "".join([c if c.isalnum() else "_" for c in table_name])
80
+ if not table_name: table_name = "uploaded_table"
81
+
82
+ # 3. Sanitize Column Names
83
+ df.columns = ["".join([c if c.isalnum() else "_" for c in str(col)]) for col in df.columns]
84
 
85
+ # 4. Generate CREATE TABLE
86
+ cols = []
87
+ for col, dtype in zip(df.columns, df.dtypes):
88
+ sql_type = "TEXT"
89
+ if "int" in str(dtype): sql_type = "INTEGER"
90
+ elif "float" in str(dtype): sql_type = "DECIMAL(10,2)"
91
+ cols.append(f"{col} {sql_type}")
92
+
93
+ create_stmt = f"CREATE TABLE {table_name} ({', '.join(cols)});\n"
94
+
95
+ # 5. Generate INSERT Statements
96
+ # Note: For very large files, bulk loading is better, but for "Sample" sizes, this is universally compatible
97
+ inserts = []
98
+ for _, row in df.iterrows():
99
+ vals = []
100
+ for v in row:
101
+ if pd.isna(v):
102
+ vals.append("NULL")
103
+ elif isinstance(v, str):
104
+ vals.append(f"'{str(v).replace("'", "''")}'") # Escape single quotes
105
+ else:
106
+ vals.append(str(v))
107
+ inserts.append(f"INSERT INTO {table_name} VALUES ({', '.join(vals)});")
108
+
109
+ return create_stmt + "\n".join(inserts) + "\n", table_name
110
+
111
  except Exception as e:
112
+ return f"-- Error converting file: {str(e)}\n", None
113
 
114
  @app.route('/api/run-sql', methods=['POST'])
115
  def run_sql():
116
+ sql_code = request.form.get('code', '')
117
+ db_type = request.form.get('type', 'sqlite').lower()
118
+ use_sample = request.form.get('use_sample') == 'true'
119
+ uploaded_file = request.files.get('database')
120
 
121
+ if not sql_code:
122
+ return jsonify({'output': 'No SQL code provided'}), 400
123
 
124
+ output = ""
125
+ session_id = uuid.uuid4().hex[:8]
126
+ temp_file_path = None
127
+
128
+ # Prepare Initialization SQL (Sample Data + Uploaded CSV/Excel SQL)
129
+ init_sql = ""
130
 
131
+ if use_sample:
132
+ init_sql += SAMPLE_SQL + "\n"
133
+
134
+ if uploaded_file:
135
+ fname = uploaded_file.filename.lower()
136
+ if fname.endswith('.csv') or fname.endswith('.xlsx') or fname.endswith('.xls'):
137
+ # Convert Data file to SQL
138
+ converted_sql, table_name = file_to_sql(uploaded_file, uploaded_file.filename)
139
+ init_sql += f"-- Imported from {uploaded_file.filename}\n" + converted_sql + "\n"
140
+ # Reset uploaded_file because we consumed it; we don't need to pass it as a binary DB
141
+ uploaded_file = None
142
 
 
143
  try:
144
+ # --- 1. SQLITE LOGIC ---
145
+ if db_type == 'sqlite':
146
+ db_target = ":memory:"
 
 
 
 
 
 
 
147
 
148
+ # If user uploaded a binary .db file (and didn't convert it above)
149
+ if uploaded_file and (uploaded_file.filename.endswith('.db') or uploaded_file.filename.endswith('.sqlite')):
150
+ fd, temp_file_path = tempfile.mkstemp(suffix='.db')
151
+ os.close(fd)
152
+ uploaded_file.save(temp_file_path)
153
+ db_target = temp_file_path
154
 
155
+ cmd = ["sqlite3", db_target]
156
+ header = ".mode column\n.headers on\n"
157
+
158
+ # Combine: Header + Init SQL (Sample/CSV) + User SQL
159
+ full_script = header + init_sql + sql_code
160
+ output = run_command(cmd, input_text=full_script)
161
+
162
+ # --- 2. POSTGRESQL LOGIC ---
163
+ elif db_type in ['postgres', 'postgresql']:
164
+ schema_name = f"sess_{session_id}"
165
+
166
+ # A. Create Schema
167
+ run_command(["psql", "-h", "localhost", "-U", "playground", "-d", "playground", "-c", f"CREATE SCHEMA {schema_name};"])
168
+
169
+ try:
170
+ # B. Handle Binary Dump Upload (if any - distinct from CSV/Excel handled in init_sql)
171
+ if uploaded_file: # If it's a .sql dump
172
+ dump_content = uploaded_file.read().decode('utf-8', errors='ignore')
173
+ init_sql += f"\n{dump_content}\n"
174
+
175
+ # C. Run Everything (Init + User Code) inside Schema
176
+ # We wrap everything in one transaction block pointing to the schema
177
+ full_script = f"SET search_path TO {schema_name};\n{init_sql}\n{sql_code}"
178
+
179
+ output = run_command(["psql", "-h", "localhost", "-U", "playground", "-d", "playground"], input_text=full_script)
180
+
181
+ finally:
182
+ run_command(["psql", "-h", "localhost", "-U", "playground", "-d", "playground", "-c", f"DROP SCHEMA {schema_name} CASCADE;"])
183
+
184
+ # --- 3. MYSQL LOGIC ---
185
+ elif db_type == 'mysql':
186
+ db_name = f"sess_{session_id}"
187
+
188
+ # A. Create DB
189
+ run_command(["mysql", "-h", "localhost", "-u", "playground", "-e", f"CREATE DATABASE {db_name};"])
190
+
191
+ try:
192
+ # B. Handle Binary Dump Upload
193
+ if uploaded_file:
194
+ dump_content = uploaded_file.read().decode('utf-8', errors='ignore')
195
+ init_sql += f"\n{dump_content}\n"
196
+
197
+ # C. Run Everything
198
+ # MySQL accepts multiple statements if we just pipe them
199
+ full_script = f"USE {db_name};\n{init_sql}\n{sql_code}"
200
+
201
+ output = run_command(["mysql", "-h", "localhost", "-u", "playground", "-t"], input_text=full_script)
202
+
203
+ finally:
204
+ run_command(["mysql", "-h", "localhost", "-u", "playground", "-e", f"DROP DATABASE {db_name};"])
205
+
206
  else:
207
+ return jsonify({'output': 'Unsupported database type.'}), 400
208
 
 
 
 
 
 
209
  except Exception as e:
210
+ output = f"Server Error: {str(e)}"
211
+ finally:
212
+ if temp_file_path and os.path.exists(temp_file_path):
213
+ os.remove(temp_file_path)
214
 
215
+ return jsonify({'output': output})
216
 
217
  if __name__ == '__main__':
 
 
 
218
  app.run(host="0.0.0.0", port=7860)