File size: 7,776 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
'use client';

import React, { useState, useCallback, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Play, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { SchemaViewer } from '@/components/database-manager/schema-viewer';
import { SqlEditor } from '@/components/database-manager/sql-editor';

interface SchemaEditorProps {
  projectId: string;
  enabled: boolean;
  onSchemaChange?: (schema: string) => void;
  workspaceId?: string;
}

// Keep these exports — used by vfs/index.ts for transient file generation
export function getProjectSchema(projectId: string): string {
  if (typeof window === 'undefined') return '';
  return localStorage.getItem(`osw-db-schema-${projectId}`) || '';
}

export function setProjectSchema(projectId: string, schema: string): void {
  if (typeof window === 'undefined') return;
  if (schema) {
    localStorage.setItem(`osw-db-schema-${projectId}`, schema);
  } else {
    localStorage.removeItem(`osw-db-schema-${projectId}`);
  }
}

/**
 * Save schema to localStorage and apply DDL to the project database (Server Mode only).
 * Used by project-manager and template-manager during project creation.
 */
export async function applyProjectDatabaseSchema(projectId: string, ddl: string, workspaceId?: string): Promise<void> {
  setProjectSchema(projectId, ddl);
  if (process.env.NEXT_PUBLIC_SERVER_MODE === 'true') {
    try {
      const apiBase = workspaceId ? `/api/w/${workspaceId}` : '/api';
      const res = await fetch(`${apiBase}/projects/${projectId}/database/query`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sql: ddl }),
      });
      if (!res.ok) {
        console.warn('[Schema] DDL apply failed — will auto-heal on Schema tab open');
      }
    } catch {
      // Non-fatal — auto-apply on Schema tab open will recover
    }
  }
}

type SubTab = 'tables' | 'sql' | 'ddl';

export function SchemaEditor({ projectId, enabled, onSchemaChange, workspaceId }: SchemaEditorProps) {
  const apiBase = workspaceId ? `/api/w/${workspaceId}` : '/api';
  const [activeSubTab, setActiveSubTab] = useState<SubTab>('tables');
  const [ddl, setDdl] = useState('');
  const [applying, setApplying] = useState(false);
  const [schemaKey, setSchemaKey] = useState(0);
  const autoAppliedRef = useRef<string | null>(null);

  const schemaEndpoint = `${apiBase}/projects/${projectId}/database/schema`;
  const queryEndpoint = `${apiBase}/projects/${projectId}/database/query`;

  // Auto-apply: if localStorage has schema DDL but the project database has no tables,
  // apply the DDL automatically. This self-heals when the initial application during
  // project creation failed (e.g., project not yet synced to SQLite, server restart).
  useEffect(() => {
    if (!enabled) return;
    // Only auto-apply once per projectId
    if (autoAppliedRef.current === projectId) return;

    const storedSchema = getProjectSchema(projectId);
    if (!storedSchema) return;

    const tryAutoApply = async () => {
      try {
        // Check if database already has tables
        const schemaRes = await fetch(schemaEndpoint);
        if (!schemaRes.ok) return;
        const schemaData = await schemaRes.json();
        if (schemaData.tables && schemaData.tables.length > 0) {
          autoAppliedRef.current = projectId;
          return; // Already has tables, nothing to do
        }

        // Database is empty but localStorage has DDL — apply it
        const res = await fetch(queryEndpoint, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ sql: storedSchema }),
        });

        if (res.ok) {
          autoAppliedRef.current = projectId;
          setSchemaKey(prev => prev + 1);
        }
      } catch {
        // Non-fatal — user can manually apply via DDL tab
      }
    };

    tryAutoApply();
  }, [enabled, projectId, schemaEndpoint, queryEndpoint]);

  const applyDDL = useCallback(async () => {
    if (!ddl.trim()) return;

    setApplying(true);
    try {
      const res = await fetch(queryEndpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sql: ddl.trim() }),
      });

      const data = await res.json();
      if (!res.ok) {
        toast.error(data.error || 'Failed to apply DDL');
        return;
      }

      toast.success('DDL applied successfully');

      // Update localStorage schema (append DDL) so AI server context stays in sync
      const existing = getProjectSchema(projectId);
      const updated = existing ? `${existing}\n\n${ddl.trim()}` : ddl.trim();
      setProjectSchema(projectId, updated);
      onSchemaChange?.(updated);

      // Refresh SchemaViewer
      setSchemaKey(prev => prev + 1);
      setDdl('');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to apply DDL');
    } finally {
      setApplying(false);
    }
  }, [ddl, queryEndpoint, projectId, onSchemaChange]);

  if (!enabled) {
    return null;
  }

  return (
    <div className="h-full flex flex-col">
      {/* Sub-tab buttons */}
      <div className="flex items-center gap-1 mb-3 border-b pb-2">
        {(['tables', 'sql', 'ddl'] as const).map(tab => (
          <button
            key={tab}
            onClick={() => setActiveSubTab(tab)}
            className={`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
              activeSubTab === tab
                ? 'bg-primary text-primary-foreground'
                : 'text-muted-foreground hover:text-foreground hover:bg-muted'
            }`}
          >
            {tab === 'tables' ? 'Tables' : tab === 'sql' ? 'SQL' : 'DDL'}
          </button>
        ))}
      </div>

      {/* Sub-tab content */}
      <div className="flex-1 min-h-0">
        {activeSubTab === 'tables' && (
          <SchemaViewer
            key={schemaKey}
            schemaEndpoint={schemaEndpoint}
            showSystemTablesToggle={false}
          />
        )}

        {activeSubTab === 'sql' && (
          <SqlEditor queryEndpoint={queryEndpoint} />
        )}

        {activeSubTab === 'ddl' && (
          <div className="h-full flex flex-col gap-3">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="text-sm font-medium">Apply DDL</h4>
                <p className="text-xs text-muted-foreground mt-0.5">
                  CREATE TABLE, ALTER TABLE, and other DDL statements
                </p>
              </div>
              <Button
                size="sm"
                className="h-7 px-2 text-xs"
                onClick={applyDDL}
                disabled={applying || !ddl.trim()}
              >
                {applying ? (
                  <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                ) : (
                  <Play className="h-3 w-3 mr-1" />
                )}
                Apply
              </Button>
            </div>
            <textarea
              data-schema-editor
              className="flex-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono resize-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring placeholder:text-muted-foreground"
              placeholder={`-- Create or modify tables\nCREATE TABLE IF NOT EXISTS example (\n  id INTEGER PRIMARY KEY AUTOINCREMENT,\n  name TEXT NOT NULL,\n  created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);`}
              value={ddl}
              onChange={(e) => setDdl(e.target.value)}
              spellCheck={false}
            />
          </div>
        )}
      </div>
    </div>
  );
}