-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryEditorControl.cs
More file actions
502 lines (444 loc) · 18.3 KB
/
Copy pathQueryEditorControl.cs
File metadata and controls
502 lines (444 loc) · 18.3 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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
using DuckDB.NET.Data;
using DuckSQL.Exceptions;
using DuckSQL.Helpers;
using DuckSQL.Types;
using FastColoredTextBoxNS;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
namespace DuckSQL.Controls
{
internal partial class QueryEditorControl : UserControl
{
private const string QUERY_FORMAT =
@"SELECT {0}
FROM {1}
LIMIT {2}
OFFSET {3} ";
private static bool _wasByteArrayConversionErrorShown = false; //TODO: This should ideally be kept per tab/instance
private CancellationTokenSource? _queryCancellationToken = null;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public EventHandler? QueryTextChanged { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public EventHandler? QueryExecutionStarted { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public EventHandler<QueryExecutedEventArgs>? QueryExecuted { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string QueryText
{
get => this.queryRichTextBox.Text;
set => this.queryRichTextBox.Text = value;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string? CurrentFilePath { get; set; }
public QueryEditorControl()
{
InitializeComponent();
resultsGridView.ShowCopyAsWhereContextMenuItem = true;
resultsGridView.CopyToClipboardIcon = Properties.Resources.copy_clipboard_icon.ToBitmap();
resultsGridView.ColumnNameEscapeFormat = "\"{0}\"";
resultsGridView.DateValueEscapeFormat = "'{0}'";
resultsGridView.DragDrop += (s, args) =>
{
OnDragDrop(args);
};
queryRichTextBox.AllowDrop = true;
queryRichTextBox.DragEnter += (s, args) =>
{
OnDragEnter(args);
};
queryRichTextBox.DragDrop += (s, args) =>
{
OnDragDrop(args);
};
AllowDrop = true;
}
public QueryEditorControl(string filePath, int offset = 0, int limit = 1000) : this()
{
if (Path.GetExtension(filePath).Equals(".sql"))
{
var fileContent = File.ReadAllText(filePath);
QueryText = fileContent;
}
else
{
var queryFields = "*";
var fromClause = $"'{filePath}'";
QueryText = QUERY_FORMAT.Format(queryFields, fromClause, limit, offset);
}
executeQueryButton.Enabled = true;
}
private void QueryEditorControl_Load(object sender, EventArgs e)
{
RefreshControl();
}
public void RefreshControl()
{
SetZoom(AppSettings.QueryEditorZoomLevel ?? 100);
resultsGridView.UpdateDateFormats();
resultsGridView.Refresh();
}
public DataTable GetDataSource() => this.resultsGridView.DataSource as DataTable ?? new DataTable();
private async Task<DataTable> ExecuteQueryAsync(string query, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(query);
QueryExecutionStarted?.Invoke(this, EventArgs.Empty);
var result = new DataTable();
try
{
await Task.Run(() =>
{
using var connection = new DuckDBConnection("Data Source=:memory:");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = query;
using var reader = command.ExecuteReader();
result.Load(reader);
cancellationToken.ThrowIfCancellationRequested();
}, cancellationToken);
}
catch (OperationCanceledException)
{
return result;
}
catch (Exception ex)
{
result.Dispose();
if (ex is InvalidCastException && ex.Message.Contains("The list contains null value"))
{
throw new QueryExecuteException(Resources.Errors.ListsWithNullsErrorTitle, Resources.Errors.ListsWithNullsErrorMessage) { Handled = true };
}
else if (ex is DuckDBException && ex.Message.StartsWith("Parser Error:"))
{
throw new QueryExecuteException(Resources.Errors.InvalidQueryErrorTitle,
$"{Resources.Errors.InvalidQueryErrorMessage}{Env.DoubleNewLine}{ex.Message}")
{ Handled = true };
}
else if (ex is OverflowException && ex.Message.Contains("Value was either too large or too small for a Decimal"))
{
throw new QueryExecuteException(Resources.Errors.DecimalValueTooLargeErrorTitle,
Resources.Errors.DecimalValueUnknownSizeTooLargeErrorMessageFormat
.Format(DecimalOverflowException.MAX_DECIMAL_PRECISION, DecimalOverflowException.MAX_DECIMAL_SCALE))
{ Handled = true };
}
else
{
throw new QueryExecuteException(Resources.Errors.QueryExecutionErrorTitle, ex.Message);
}
}
return result;
}
private async void executeQueryButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(this.queryRichTextBox.Text))
return;
//Cleanup previous results
if (this.resultsGridView.DataSource is DataTable dt)
{
dt.Dispose();
this.resultsGridView.DataSource = null;
}
_queryCancellationToken = new CancellationTokenSource();
Cursor = Cursors.WaitCursor;
queryExecutionStatusLabel.Text = Resources.Strings.QueryRunningStatusText;
timeElapsedLabel.Text = "00:00";
showingCountLabel.Text = "0";
executeQueryButton.Enabled = false;
resultsGridView.Enabled = false;
cancelQueryButton.Enabled = true;
var stopwatch = Stopwatch.StartNew();
var queryTask = ExecuteQueryAsync(this.queryRichTextBox.Text, _queryCancellationToken.Token);
while (!queryTask.IsCompleted && !_queryCancellationToken.IsCancellationRequested)
{
await Task.Delay(50);
this.timeElapsedLabel.Text = stopwatch.Elapsed.ToString("mm\\:ss");
}
stopwatch.Stop();
var queryDuration = stopwatch.Elapsed;
var result = new DataTable();
try
{
if (_queryCancellationToken.IsCancellationRequested)
{
return;
}
result = await queryTask;
stopwatch.Restart();
try
{
//We need to convert complex types like: lists, structs, maps, and byte arrays so we can render them properly
result = ConvertValues(result);
}
catch (Exception ex)
{
throw new QueryExecuteException(Resources.Errors.RenderResultsErrorTitle, $"{ex.Message}{Env.DoubleNewLine}{ex.StackTrace}");
}
stopwatch.Stop();
var conversionDuration = stopwatch.Elapsed;
stopwatch.Restart();
this.resultsGridView.DataSource = result;
stopwatch.Stop();
var renderDuration = stopwatch.Elapsed;
QueryExecuted?.Invoke(this, new QueryExecutedEventArgs(queryDuration, conversionDuration, renderDuration));
}
catch (QueryExecuteException ex)
{
if (ex.Handled)
{
//Don't throw/log errors we can't do anything about
MessageBox.Show(ex.Message, ex.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
throw;
}
}
catch (Exception)
{
throw;
}
finally
{
queryExecutionStatusLabel.Text = _queryCancellationToken.IsCancellationRequested ?
Resources.Strings.QueryCancelledStatusText : Resources.Strings.QueryFinishedStatusText;
timeElapsedLabel.Text = stopwatch.Elapsed.ToString("mm\\:ss");
showingCountLabel.Text = result.Rows.Count.ToString();
executeQueryButton.Enabled = true;
resultsGridView.Enabled = true;
cancelQueryButton.Enabled = false;
Cursor = Cursors.Default;
}
}
private void queryRichTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(this.queryRichTextBox.Text))
executeQueryButton.Enabled = true;
QueryTextChanged?.Invoke(this, EventArgs.Empty);
}
private void queryRichTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Shift && e.KeyCode == Keys.Enter || e.KeyCode == Keys.F5)
{
executeQueryButton.PerformClick();
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.KeyCode == Keys.Escape)
{
_queryCancellationToken?.Cancel();
e.Handled = true;
}
}
private void copyTextMenuItem_Click(object sender, EventArgs e)
{
this.queryRichTextBox.Copy();
}
private void pasteTextMenuItem_Click(object sender, EventArgs e)
{
this.queryRichTextBox.Paste();
}
private static DataTable ConvertValues(DataTable intermediateResult)
{
var hasComplexType = false;
foreach (DataColumn column in intermediateResult.Columns)
{
if (column.DataType.ImplementsInterface<IDictionary>()
|| column.DataType.ImplementsInterface<IList>()
|| column.DataType == typeof(Stream))
{
hasComplexType = true;
break;
}
}
if (!hasComplexType)
{
return intermediateResult;
}
var result = new DataTable();
foreach (DataColumn column in intermediateResult.Columns)
{
if (column.DataType == typeof(Dictionary<string, object?>))
{
result.Columns.Add(new DataColumn(column.ColumnName, typeof(StructValue)));
}
else if (column.DataType.ImplementsInterface<IList>())
{
result.Columns.Add(new DataColumn(column.ColumnName, typeof(ListValue)));
}
else if (column.DataType.ImplementsInterface<IDictionary>())
{
result.Columns.Add(new DataColumn(column.ColumnName, typeof(MapValue)));
}
else if (column.DataType == typeof(Stream))
{
result.Columns.Add(new DataColumn(column.ColumnName, typeof(ByteArrayValue)));
}
else
{
result.Columns.Add(new DataColumn(column.ColumnName, column.DataType));
}
}
result.BeginLoadData();
foreach (DataRow row in intermediateResult.Rows)
{
var newRow = result.NewRow();
for (var i = 0; i < row.ItemArray.Length; i++)
{
var value = row.ItemArray[i];
newRow[i] = ConvertValue(value!);
}
result.Rows.Add(newRow);
}
result.EndLoadData();
return result;
}
private static object ConvertValue(object? value)
{
if (value == DBNull.Value || value is null)
{
return DBNull.Value;
}
else if (value is Dictionary<string, object?> structDictionary)
{
var dataRow = new QueryResultDataRow(structDictionary.Keys.ToList(),
structDictionary.Values.Select(ConvertValue).ToArray());
var structValue = new StructValue(dataRow);
return structValue;
}
else if (value is IList list)
{
var arrayList = new ArrayList(list.Count);
var listType = typeof(object);
for (var i = 0; i < list.Count; i++)
{
var convertedListValue = ConvertValue(list[i]);
arrayList.Add(convertedListValue);
if (convertedListValue != DBNull.Value)
{
listType = convertedListValue.GetType();
}
}
var listValue = new ListValue(arrayList, listType);
return listValue;
}
else if (value is IDictionary dictionary)
{
var keysList = new ArrayList(dictionary.Keys.Count);
var valuesList = new ArrayList(dictionary.Values.Count);
var keysType = typeof(object);
var valuesType = typeof(object);
foreach (var keyValuePair in UtilityMethods.PairEnumerables(
dictionary.Keys.OfType<object?>(),
dictionary.Values.OfType<object?>()))
{
var convertedKey = ConvertValue(keyValuePair.Item1);
var convertedValue = ConvertValue(keyValuePair.Item2);
keysList.Add(convertedKey);
valuesList.Add(convertedValue);
if (convertedKey != DBNull.Value)
{
keysType = convertedKey.GetType();
}
if (convertedValue != DBNull.Value)
{
valuesType = convertedValue.GetType();
}
}
var mapValue = new MapValue(
keysList, keysType,
valuesList, valuesType);
return mapValue;
}
else if (value is Stream byteArray)
{
if (!_wasByteArrayConversionErrorShown)
{
_wasByteArrayConversionErrorShown = true;
MessageBox.Show(
Resources.Errors.ByteArraysNotSupportedErrorMessage,
Resources.Errors.ByteArraysNotSupportedErrorTitle,
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
return DBNull.Value;
}
else
{
return value;
}
}
private void zoomPercentage_Click(object sender, EventArgs e)
{
if (sender is ToolStripMenuItem menuItem && int.TryParse(menuItem.Tag?.ToString(), out int zoomPercentage))
{
SetZoom(zoomPercentage);
AppSettings.QueryEditorZoomLevel = zoomPercentage;
}
}
private void SetZoom(int zoomPercentage)
{
zoomPercentage = Math.Clamp(zoomPercentage, 100, 150);
foreach (ToolStripMenuItem item in this.zoomPercentageDropDown.DropDownItems)
{
item.Checked = zoomPercentage.ToString().Equals(item.Tag?.ToString()) == true;
}
zoomPercentageDropDown.Text = Resources.Strings.QueryZoomStatusTextFormat.Format(zoomPercentage);
queryRichTextBox.Zoom = zoomPercentage;
}
private void cancelQueryButton_Click(object sender, EventArgs e)
{
_queryCancellationToken?.Cancel();
}
private void QueryEditorControl_Resize(object sender, EventArgs e)
{
if (this.ParentForm?.WindowState == FormWindowState.Minimized)
{
//Hide context menu on minimize to avoid a glitch where
//the context menu won't go away until you click on it.
resultsGridView.CloseContextMenu();
}
}
protected override void OnDragEnter(DragEventArgs e)
{
base.OnDragEnter(e);
if (e.Data?.GetDataPresent(DataFormats.FileDrop) == true)
{
var files = e.Data?.GetData(DataFormats.FileDrop) as string[] ?? Enumerable.Empty<string>();
var supportedFiles = files.Select(Path.GetFileName).Where(IsSupportedFileType);
if (supportedFiles.Count() > 0)
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
}
private static bool IsSupportedFileType(string? fileName)
{
if (fileName is null)
return false;
var extension = Path.GetExtension(fileName);
if (extension.Equals(".sql"))
return true;
foreach (var fileType in Enum.GetValues<FileType>())
{
if (fileType.GetExtension().Equals(extension))
{
return true;
}
}
return false;
}
internal class QueryExecutedEventArgs : EventArgs
{
public TimeSpan QueryDuration { get; }
public TimeSpan ConversionDuration { get; }
public TimeSpan RenderDuration { get; }
public QueryExecutedEventArgs(TimeSpan queryDuration, TimeSpan resultConversionDuration, TimeSpan renderDuration)
{
QueryDuration = queryDuration;
ConversionDuration = resultConversionDuration;
RenderDuration = renderDuration;
}
}
}
}