File size: 8,745 Bytes
eeb9404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use client';

import React, { useState, useEffect, useCallback } from 'react';
import MonacoEditor from '@monaco-editor/react';
import { Play, Loader2, AlertCircle, CheckCircle2, History, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useTheme } from 'next-themes';
import { cn } from '@/lib/utils';

interface SqlEditorProps {
  deploymentId?: string;
  queryEndpoint?: string;
  workspaceId?: string;
}

interface QueryResult {
  success: boolean;
  columns?: string[];
  rows?: unknown[][];
  rowsAffected?: number;
  error?: string;
  executionTime?: number;
}

const HISTORY_KEY = 'osw-sql-history';
const MAX_HISTORY = 20;

export function SqlEditor({ deploymentId, queryEndpoint, workspaceId }: SqlEditorProps) {
  const apiBase = workspaceId ? `/api/w/${workspaceId}` : '/api';
  const [sql, setSql] = useState('SELECT * FROM ');
  const [executing, setExecuting] = useState(false);
  const [result, setResult] = useState<QueryResult | null>(null);
  const [history, setHistory] = useState<string[]>([]);
  const [showHistory, setShowHistory] = useState(false);
  const { resolvedTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    // Load history from localStorage
    const savedHistory = localStorage.getItem(HISTORY_KEY);
    if (savedHistory) {
      try {
        setHistory(JSON.parse(savedHistory));
      } catch {
        // Ignore invalid JSON
      }
    }
  }, []);

  const saveToHistory = useCallback((query: string) => {
    setHistory(prev => {
      const newHistory = [query, ...prev.filter(q => q !== query)].slice(0, MAX_HISTORY);
      localStorage.setItem(HISTORY_KEY, JSON.stringify(newHistory));
      return newHistory;
    });
  }, []);

  const executeQuery = useCallback(async () => {
    if (!sql.trim()) return;

    setExecuting(true);
    setResult(null);
    const startTime = Date.now();

    try {
      const endpoint = queryEndpoint || `${apiBase}/admin/deployments/${deploymentId}/database/query`;
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sql: sql.trim() }),
      });

      const data = await res.json();
      const executionTime = Date.now() - startTime;

      if (!res.ok) {
        setResult({
          success: false,
          error: data.error || 'Query failed',
          executionTime,
        });
      } else {
        setResult({
          success: true,
          columns: data.columns,
          rows: data.rows,
          rowsAffected: data.rowsAffected,
          executionTime,
        });
        saveToHistory(sql.trim());
      }
    } catch (err) {
      setResult({
        success: false,
        error: err instanceof Error ? err.message : 'Query failed',
        executionTime: Date.now() - startTime,
      });
    } finally {
      setExecuting(false);
    }
  }, [sql, deploymentId, saveToHistory]);

  // Handle keyboard shortcut
  const handleEditorMount = useCallback((editor: unknown) => {
    const monacoEditor = editor as { addCommand: (keybinding: number, handler: () => void) => void };
    // Cmd/Ctrl + Enter to execute
    monacoEditor.addCommand(2048 | 3, () => { // KeyMod.CtrlCmd | KeyCode.Enter
      executeQuery();
    });
  }, [executeQuery]);

  if (!mounted) {
    return <div className="h-full flex items-center justify-center">
      <Loader2 className="h-6 w-6 animate-spin" />
    </div>;
  }

  return (
    <div className="h-full flex flex-col gap-4">
      {/* Editor Section */}
      <div className="flex flex-col gap-2">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Button
              onClick={executeQuery}
              disabled={executing || !sql.trim()}
              size="sm"
            >
              {executing ? (
                <Loader2 className="h-4 w-4 animate-spin mr-1" />
              ) : (
                <Play className="h-4 w-4 mr-1" />
              )}
              Execute
            </Button>
            <span className="text-xs text-muted-foreground">
              Ctrl/Cmd + Enter
            </span>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setShowHistory(!showHistory)}
          >
            <History className="h-4 w-4 mr-1" />
            History
          </Button>
        </div>

        {/* History dropdown */}
        {showHistory && history.length > 0 && (
          <div className="border rounded-lg bg-background shadow-lg max-h-40 overflow-auto">
            {history.map((query, i) => (
              <button
                key={i}
                onClick={() => {
                  setSql(query);
                  setShowHistory(false);
                }}
                className="w-full text-left px-3 py-2 text-sm font-mono hover:bg-muted border-b last:border-0 truncate"
              >
                {query}
              </button>
            ))}
          </div>
        )}

        <div className="h-32 border rounded-lg overflow-hidden">
          <MonacoEditor
            language="sql"
            theme={resolvedTheme === 'dark' ? 'vs-dark' : 'light'}
            value={sql}
            onChange={value => setSql(value || '')}
            onMount={handleEditorMount}
            options={{
              minimap: { enabled: false },
              fontSize: 13,
              lineNumbers: 'off',
              folding: false,
              scrollBeyondLastLine: false,
              wordWrap: 'on',
              automaticLayout: true,
            }}
          />
        </div>
      </div>

      {/* Results Section */}
      <div className="flex-1 overflow-hidden border rounded-lg">
        {result === null ? (
          <div className="h-full flex items-center justify-center text-muted-foreground text-sm">
            Execute a query to see results
          </div>
        ) : result.success ? (
          <div className="h-full flex flex-col">
            {/* Status bar */}
            <div className="flex items-center gap-2 px-3 py-2 bg-muted/30 border-b text-sm">
              <CheckCircle2 className="h-4 w-4 text-green-500" />
              {result.rows && result.rows.length > 0 ? (
                <span>{result.rows.length} row{result.rows.length !== 1 ? 's' : ''}</span>
              ) : result.rowsAffected !== undefined && result.rowsAffected > 0 ? (
                <span>{result.rowsAffected} row{result.rowsAffected !== 1 ? 's' : ''} affected</span>
              ) : (
                <span>Query executed successfully</span>
              )}
              <span className="text-muted-foreground">({result.executionTime}ms)</span>
            </div>

            {/* Results table */}
            {result.columns && result.columns.length > 0 && result.rows ? (
              <div className="flex-1 overflow-auto">
                <table className="w-full text-sm">
                  <thead className="sticky top-0 bg-muted">
                    <tr>
                      {result.columns.map((col, i) => (
                        <th key={i} className="text-left p-2 font-medium border-r last:border-0">
                          {col}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {result.rows.map((row, i) => (
                      <tr key={i} className="border-t hover:bg-muted/30">
                        {row.map((cell, j) => (
                          <td key={j} className="p-2 font-mono text-xs border-r last:border-0 max-w-xs truncate">
                            {cell === null ? (
                              <span className="text-muted-foreground italic">NULL</span>
                            ) : typeof cell === 'object' ? (
                              JSON.stringify(cell)
                            ) : (
                              String(cell)
                            )}
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : null}
          </div>
        ) : (
          <div className="h-full flex flex-col items-center justify-center gap-2 p-4">
            <AlertCircle className="h-6 w-6 text-destructive" />
            <p className="text-sm text-destructive font-medium">Query Error</p>
            <p className="text-sm text-muted-foreground text-center max-w-md">
              {result.error}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}