Files
elwig/Elwig/Windows/QueryWindow.xaml.cs

59 lines
2.1 KiB
C#

using Elwig.Helpers;
using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace Elwig.Windows {
public partial class QueryWindow : Window {
public QueryWindow() {
InitializeComponent();
}
private void QueryButton_Click(object sender, RoutedEventArgs evt) {
try {
ExecuteQuery(QueryInput.Text);
} catch (Exception e) {
MessageBox.Show(e.Message, "Fehler beim Ausführen", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void ExecuteQuery(string sqlQuery) {
var rows = new List<object[]>();
IList<DbColumn> header;
using (var cnx = new SqliteConnection(AppDbContext.ConnectionString)) {
cnx.CreateFunction<string, string?, bool?>("REGEXP", (pattern, value) => value == null ? null : Regex.Match(value, pattern).Success, true);
cnx.Open();
var cmd = cnx.CreateCommand();
cmd.CommandText = sqlQuery;
using var reader = cmd.ExecuteReader();
header = reader.GetColumnSchema();
while (reader.Read()) {
var values = new object[reader.FieldCount];
reader.GetValues(values);
rows.Add(values);
}
}
var styleRight = new Style();
styleRight.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
DataList.Columns.Clear();
for (int i = 0; i < header.Count; i++) {
var h = header[i];
DataList.Columns.Add(new DataGridTextColumn {
Header = h.ColumnName,
Binding = new Binding($"[{i}]"),
CellStyle = (h.DataTypeName == "INTEGER" || h.DataTypeName == "REAL") ? styleRight : null,
});
}
DataList.ItemsSource = rows;
}
}
}