using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.SQLite; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.Win32; namespace DbReload; public partial class MainViewModel : ObservableObject { [ObservableProperty] private string _sqLiteFile = ""; [ObservableProperty] private string[] _logFiles = []; [ObservableProperty] private string _progress = ""; [ObservableProperty] private List _log = new(); [RelayCommand] private void CreateSQLiteFile() { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "SQLite Files (*.db,*.dbs)|*.db;*.dbs"; dlg.CheckFileExists = false; if (dlg.ShowDialog() == true) SqLiteFile = dlg.FileName; } [RelayCommand] private void SelectLogFiles() { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "SQL Log Files (*.sql)|*.sql"; dlg.Multiselect = true; if (dlg.ShowDialog() == true) LogFiles = dlg.FileNames; } [RelayCommand] private async Task Go() { Progress = "Opening Database File"; Log.Clear(); var sb = new SQLiteConnectionStringBuilder(); sb.DataSource = SqLiteFile; sb.Version = 3; sb.DateTimeFormat = SQLiteDateFormats.Ticks; sb.JournalMode = SQLiteJournalModeEnum.Wal; var conn = sb.ToString(); using var connection = new SQLiteConnection(conn); connection.BusyTimeout = Convert.ToInt32(TimeSpan.FromMinutes(2).TotalMilliseconds); connection.Update += _connection_Update; connection.Trace += _connection_Trace; connection.Open(); using var command = new SQLiteCommand(connection); var ordered = LogFiles.OrderBy(x => x); foreach (var logfile in ordered) { Progress = $"Opening {Path.GetFileName(logfile)}"; var text = await File.ReadAllTextAsync(logfile).ConfigureAwait(false); var statements = SqlTokenizer.SplitStatements(text); int i = 0; foreach (var line in statements) { Progress = $"Processing {Path.GetFileName(logfile)} ({i}/{statements.Count})"; command.CommandText = line; try { await command.ExecuteNonQueryAsync(); } catch (Exception e) { Log.Add($"{Path.GetFileName(logfile)}: \"{e.Message}\" in \"{line}\""); Console.WriteLine(e); //throw; } i++; } } var logFile = Path.Combine( Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location) ?? "", "log.txt"); await File.AppendAllLinesAsync(logFile, new string[] { "", $"Reload at {DateTime.Now:yyyy-MM-dd hh\\:mm\\:ss}" }.Concat(Log)); Progress = "Done"; } private void _connection_Update(object sender, UpdateEventArgs e) { } private void _connection_Trace(object sender, TraceEventArgs e) { Console.WriteLine(e.Statement); } }