-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathedit-database-schema.component.ts
More file actions
219 lines (197 loc) · 6.56 KB
/
edit-database-schema.component.ts
File metadata and controls
219 lines (197 loc) · 6.56 KB
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
import { AfterViewInit, Component, EventEmitter, Input, OnInit, Output, signal, inject, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MarkdownModule } from 'ngx-markdown';
import { TableSchemaService, SchemaChangeResponse } from 'src/app/services/table-schema.service';
interface ChatMessage {
role: 'user' | 'ai' | 'error' | 'diagram';
text: string;
diagramSource?: string;
changes?: SchemaChangeResponse[];
batchId?: string;
}
@Component({
selector: 'app-edit-database-schema',
templateUrl: './edit-database-schema.component.html',
styleUrls: ['./edit-database-schema.component.css'],
imports: [
CommonModule,
FormsModule,
MarkdownModule,
MatButtonModule,
MatIconModule,
MatFormFieldModule,
MatInputModule,
RouterModule,
],
})
export class EditDatabaseSchemaComponent implements OnInit, AfterViewInit {
@Input() connectionID: string;
@Input() showClose: boolean = false;
@Output() schemaApplied = new EventEmitter<void>();
@Output() closeEditor = new EventEmitter<void>();
private _tableSchema = inject(TableSchemaService);
private _route = inject(ActivatedRoute);
private _router = inject(Router);
protected isRoutedPage = signal(false);
protected messages = signal<ChatMessage[]>([]);
protected userPrompt = signal('');
protected submitting = signal(false);
protected applying = signal(false);
protected applied = signal(false);
protected diagramZoom = signal(1);
protected initialDiagramLoading = signal(false);
private _threadId: string | undefined;
protected pendingBatch = computed(() => {
const msgs = this.messages();
for (let i = msgs.length - 1; i >= 0; i--) {
if (msgs[i].batchId && msgs[i].changes?.length) return msgs[i];
}
return null;
});
async ngAfterViewInit() {
const mermaid = await import('mermaid');
const mermaidAPI = (mermaid.default ?? mermaid) as { initialize: (config: Record<string, unknown>) => void };
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
mermaidAPI.initialize({
startOnLoad: false,
theme: isDark ? 'dark' : 'default',
});
//@ts-expect-error dynamic load of mermaid
window.mermaid = mermaidAPI;
}
ngOnInit(): void {
if (!this.connectionID) {
const id = this._route.snapshot.paramMap.get('connection-id');
if (id) {
this.connectionID = id;
this.isRoutedPage.set(true);
this.showClose = false;
} else {
this._router.navigate(['/connections-list']);
return;
}
}
if (this.showClose || this.isRoutedPage()) {
this._loadDiagram('Current Database Structure');
}
}
async onSubmit() {
const prompt = this.userPrompt().trim();
if (!prompt || this.submitting()) return;
this.messages.update(msgs => [...msgs, { role: 'user', text: prompt }]);
this.userPrompt.set('');
this.submitting.set(true);
try {
const result = await this._tableSchema.generateSchemaChange(this.connectionID, prompt, this._threadId);
if (result.threadId) {
this._threadId = result.threadId;
}
if (result && result.changes.length > 0) {
const summary = result.changes.map(c => `**${c.changeType}** \`${c.targetTableName}\`${c.aiSummary ? ' — ' + c.aiSummary : ''}`).join('\n');
this.messages.update(msgs => [...msgs, {
role: 'ai',
text: `I've generated ${result.changes.length} change(s) for your database:\n\n${summary}\n\nReview the SQL below and approve or reject.`,
changes: result.changes,
batchId: result.batchId,
}]);
} else {
this.messages.update(msgs => [...msgs, {
role: 'ai',
text: 'I could not generate any schema changes for that prompt. Could you describe your database in more detail?',
}]);
}
} catch (err: unknown) {
const error = err as { error?: { message?: string }; message?: string };
this.messages.update(msgs => [...msgs, {
role: 'error',
text: error?.error?.message || error?.message || 'Failed to generate schema changes.',
}]);
} finally {
this.submitting.set(false);
}
}
async onApprove() {
const batch = this.pendingBatch();
if (!batch?.batchId || this.applying()) return;
this.applying.set(true);
try {
const result = await this._tableSchema.approveBatch(batch.batchId, true);
if (result) {
const failed = result.changes.filter(c => c.status === 'failed');
if (failed.length > 0) {
this.messages.update(msgs => [...msgs, {
role: 'error',
text: `${failed.length} change(s) failed: ${failed.map(c => c.executionError).join('; ')}`,
}]);
} else {
this.applied.set(true);
this.messages.update(msgs => [...msgs, {
role: 'ai',
text: 'All changes applied successfully! Your tables have been created.',
}]);
this._loadDiagram('Updated Database Structure');
}
}
} catch (err: unknown) {
const error = err as { error?: { message?: string }; message?: string };
this.messages.update(msgs => [...msgs, {
role: 'error',
text: error?.error?.message || error?.message || 'Failed to apply schema changes.',
}]);
} finally {
this.applying.set(false);
}
}
async onReject() {
const batch = this.pendingBatch();
if (!batch?.batchId) return;
await this._tableSchema.rejectBatch(batch.batchId);
this.messages.update(msgs => msgs.map(m =>
m === batch ? { ...m, batchId: undefined } : m
).concat({
role: 'ai',
text: 'Changes rejected. Feel free to describe what you need differently.',
}));
}
onOpenTables() {
this.schemaApplied.emit();
}
onZoomIn() {
this.diagramZoom.update(z => Math.min(z + 0.25, 3));
}
onZoomOut() {
this.diagramZoom.update(z => Math.max(z - 0.25, 0.25));
}
onZoomReset() {
this.diagramZoom.set(1);
}
onKeydown(event: KeyboardEvent) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
this.onSubmit();
}
}
private async _loadDiagram(label: string) {
this.initialDiagramLoading.set(true);
try {
const diagram = await this._tableSchema.fetchDiagram(this.connectionID);
if (diagram?.diagram) {
this.messages.update(msgs => [...msgs, {
role: 'diagram' as const,
text: label,
diagramSource: '```mermaid\n' + diagram.diagram + '\n```',
}]);
}
} catch {
// Diagram is supplementary - don't show error if it fails
} finally {
this.initialDiagramLoading.set(false);
}
}
}