File size: 6,243 Bytes
e7addf3
 
 
 
 
 
 
 
 
 
 
 
b3c94ce
 
e7addf3
16eff4c
00a3b3a
dfabb80
e7addf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify, send_from_directory, render_template
import os
import sqlite3
import subprocess
import threading
import queue
from flask import Response
from flask_cors import CORS
import json
import re
from datetime import datetime
from flask_socketio import SocketIO, emit


event_queue = queue.Queue()

app = Flask(__name__, static_folder='../frontend/app/dist', static_url_path='/')

socketio = SocketIO(app, cors_allowed_origins="*")

__all__ = ["app", "socketio"]


from codeagent.src.codeagent.main import CodeAgentFlow

CORS(app)

SQL_FILES_DIR = 'sql_files'
os.makedirs(SQL_FILES_DIR, exist_ok=True)
DB_FILE = 'app.db'

@app.route('/')
def index():
    return send_from_directory(app.static_folder, 'index.html')

@app.route('/files', methods=['GET'])
def get_files():
    files = os.listdir(SQL_FILES_DIR)
    return jsonify([{'name': f} for f in files])

@app.route('/files', methods=['POST'])
def create_file():
    data = request.json
    filename = data['filename']
    content = data.get('content', '')
    filepath = os.path.join(SQL_FILES_DIR, filename)
    with open(filepath, 'w') as f:
        f.write(content)
    return jsonify({"status": "created", "file": filename})

@app.route('/files/<filename>', methods=['PUT'])
def update_file(filename):
    content = request.json.get('content', '')
    filepath = os.path.join(SQL_FILES_DIR, filename)
    if not os.path.exists(filepath):
        return jsonify({"error": "file not found"}), 404
    with open(filepath, 'w') as f:
        f.write(content)
    return jsonify({"status": "updated", "file": filename})

@app.route('/files/<filename>', methods=['GET'])
def get_file_content(filename):
    filepath = os.path.join(SQL_FILES_DIR, filename)
    if os.path.exists(filepath):
        with open(filepath, 'r') as f:
            content = f.read()
        return jsonify({"filename": filename, "content": content})
    return jsonify({"error": "file not found"}), 404

@app.route('/files/<filename>', methods=['DELETE'])
def delete_file(filename):
    filepath = os.path.join(SQL_FILES_DIR, filename)
    if os.path.exists(filepath):
        os.remove(filepath)
        return jsonify({"status": "deleted", "file": filename})
    return jsonify({"error": "file not found"}), 404


def get_db_connection():
    conn = sqlite3.connect(os.path.join(SQL_FILES_DIR,DB_FILE))
    conn.row_factory = sqlite3.Row
    return conn

@app.route('/tables', methods=['GET'])
def get_tables():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = [row['name'] for row in cursor.fetchall()]
    conn.close()
    return jsonify(tables)

recent_result = None
@app.route('/query', methods=['POST'])
def run_query():
    query = request.json.get('query', '')
    print(query)
    conn = get_db_connection()
    cursor = conn.cursor()
    try:
        query_lc = str(query).strip().lower()

        if ";" in query.strip() and not query_lc.startswith("select") and not query_lc.startswith("pragma"):
            # Multiple statements → executescript
            cursor.executescript(query)
            conn.commit()
            result = {"rows_affected": cursor.rowcount}
        else:
            cursor.execute(query)

            if query_lc.startswith("pragma"):
                rows = cursor.fetchall()
                result = [dict(row) for row in rows] if rows else []
            elif query_lc.startswith("select"):
                result = [dict(row) for row in cursor.fetchall()]
            else:
                conn.commit()
                result = {"rows_affected": cursor.rowcount}

        conn.close()
        global recent_result
        recent_result = {"query": query, "result": result}

        return jsonify(result)
    except Exception as e:
        conn.close()
        return jsonify({"error": str(e)}), 400

@app.route('/recent_query', methods=['GET'])
def recent_query():
    return jsonify(recent_result)

@app.route('/execute_file', methods=['POST'])
def execute_file():
    """
    Execute a .sql file located in SQL_FILES_DIR using sqlite3.executescript.
    Accepts: { "filename": "schema.sql" }
    Returns: { "status": "success", "file": "...", "started_at": "...", "finished_at": "..."}
             or { "error": "message" }
    """
    data = request.json or {}
    filename = data.get('filename')
    if not filename:
        return jsonify({"error": "filename is required"}), 400

    filepath = os.path.join(SQL_FILES_DIR, filename)
    if not os.path.exists(filepath):
        return jsonify({"error": f"file not found: {filename}"}), 404

    started_at = datetime.utcnow().isoformat()
    conn = get_db_connection()
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            sql_text = f.read()

        conn.executescript(sql_text)
        conn.commit()
        finished_at = datetime.utcnow().isoformat()
        return jsonify({
            "status": "success",
            "file": filename,
            "started_at": started_at,
            "finished_at": finished_at
        })
    except Exception as e:
        conn.rollback()
        return jsonify({"error": str(e), "file": filename}), 400
    finally:
        conn.close()

def run_crew_task(user_input):
    codeAgent = CodeAgentFlow(user_input=user_input)
    codeAgent.kickoff()

@app.route('/run_crew', methods=['POST'])
def run_crew():
    instructions = request.json.get('instructions', '')
    threading.Thread(target=run_crew_task, args=(instructions,)).start()
    return jsonify({"status": "Crew is Working..."})

def send_event(msg):
    socketio.emit("event", msg)

@app.route('/send')
def sendSSE():
    msg = {
        "filename": "Users_query.sql",
        "proposedCode": "SELECT * FROM Users;",
        "isNew": False,
        "newFileName": "Users_query.sql",
        "kind": "code_change"
    }
    send_event(msg)
    return "sent"

@socketio.on('connect')
def handle_connect():
    print("Client connected")
    emit("event", {"status": "connected"})

@socketio.on('disconnect')
def handle_disconnect():
    print("Client disconnected")

if __name__ == '__main__':
    socketio.run(app, host="0.0.0.0", port=7860, debug=False)