-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScanHistoryDatabaseService.cs
More file actions
1665 lines (1406 loc) · 62.3 KB
/
Copy pathScanHistoryDatabaseService.cs
File metadata and controls
1665 lines (1406 loc) · 62.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Data.Sqlite;
namespace c2flux
{
public static class ScanHistoryDatabaseService
{
private const int ScanHistoryVersion = 8;
private const int ChangeTypeUpsert = 1;
private const int ChangeTypeDelete = 2;
private const string DatabaseFileName = "scan_history.db";
private static readonly object SyncRoot = new object();
private static readonly string ScanHistoryDirectoryPath = Path.Combine(
AppContext.BaseDirectory,
"ScanHistory");
private static readonly string DefaultDatabaseFilePath = Path.Combine(
ScanHistoryDirectoryPath,
DatabaseFileName);
private static string databaseFilePath = DefaultDatabaseFilePath;
private static int maximumScansPerPath = 30;
public static string DefaultDatabasePath => DefaultDatabaseFilePath;
public static string DatabasePath => databaseFilePath;
public static void ConfigureDatabasePath(string databasePath)
{
databaseFilePath = NormalizeDatabasePath(databasePath);
}
public static void ConfigureRetention(int maximumScans)
{
maximumScansPerPath = Math.Max(1, maximumScans);
}
public static bool IsMaintenanceRequired()
{
lock (SyncRoot)
{
if (!File.Exists(databaseFilePath))
return false;
using SqliteConnection connection = OpenConnection();
int databaseVersion = GetDatabaseVersion(connection);
return databaseVersion != 0 &&
databaseVersion != ScanHistoryVersion;
}
}
public static string NormalizeDatabasePath(string databasePath)
{
if (string.IsNullOrWhiteSpace(databasePath))
return DefaultDatabaseFilePath;
try
{
return Path.GetFullPath(databasePath.Trim());
}
catch
{
return DefaultDatabaseFilePath;
}
}
public static void MoveDatabase(string targetDatabasePath)
{
lock (SyncRoot)
{
string sourceDatabasePath = NormalizeDatabasePath(databaseFilePath);
string normalizedTargetDatabasePath = NormalizeDatabasePath(targetDatabasePath);
if (string.Equals(
sourceDatabasePath,
normalizedTargetDatabasePath,
StringComparison.OrdinalIgnoreCase))
{
databaseFilePath = normalizedTargetDatabasePath;
return;
}
string targetDirectoryPath = Path.GetDirectoryName(normalizedTargetDatabasePath);
if (string.IsNullOrWhiteSpace(targetDirectoryPath))
throw new IOException("Database directory path is empty.");
Directory.CreateDirectory(targetDirectoryPath);
if (File.Exists(normalizedTargetDatabasePath))
throw new IOException("The selected database file already exists.");
SqliteConnection.ClearAllPools();
MoveDatabaseSidecarFile(sourceDatabasePath, normalizedTargetDatabasePath, string.Empty);
MoveDatabaseSidecarFile(sourceDatabasePath, normalizedTargetDatabasePath, "-wal");
MoveDatabaseSidecarFile(sourceDatabasePath, normalizedTargetDatabasePath, "-shm");
MoveDatabaseSidecarFile(sourceDatabasePath, normalizedTargetDatabasePath, "-journal");
databaseFilePath = normalizedTargetDatabasePath;
}
}
private static void MoveDatabaseSidecarFile(
string sourceDatabasePath,
string targetDatabasePath,
string suffix)
{
string sourcePath = sourceDatabasePath + suffix;
string targetPath = targetDatabasePath + suffix;
if (!File.Exists(sourcePath))
return;
File.Move(sourcePath, targetPath);
}
public static string Save(FileSystemEntry rootEntry, IProgress<int> progress = null)
{
if (rootEntry == null)
throw new ArgumentNullException(nameof(rootEntry));
if (string.IsNullOrWhiteSpace(rootEntry.FullPath))
throw new InvalidOperationException("Scan root path is empty.");
lock (SyncRoot)
{
Stopwatch totalStopwatch = Stopwatch.StartNew();
LogDiagnostic("Save started", rootEntry.FullPath, 0, null);
ReportProgress(progress, 0);
Stopwatch phaseStopwatch = Stopwatch.StartNew();
EnsureDatabase();
LogDiagnostic("EnsureDatabase completed", rootEntry.FullPath, phaseStopwatch.ElapsedMilliseconds, null);
string scanId = Guid.NewGuid().ToString("N");
DateTime createdUtc = DateTime.UtcNow;
phaseStopwatch.Restart();
LogDiagnostic("PrepareEntries started", rootEntry.FullPath, 0, null);
Dictionary<string, EntryData> currentEntries = CollectEntries(
rootEntry,
out int fileCount,
out int directoryCount);
LogDiagnostic(
"PrepareEntries completed",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
"Entries: " + currentEntries.Count +
Environment.NewLine +
"Files: " + fileCount +
Environment.NewLine +
"Directories: " + directoryCount);
ReportProgress(progress, 15);
phaseStopwatch.Restart();
using SqliteConnection connection = OpenConnection();
long rootId = EnsureRoot(connection, rootEntry.FullPath);
ScanKeyInfo previousScan = GetLatestScan(connection, rootId);
Dictionary<long, EntryData> previousEntries =
previousScan == null
? new Dictionary<long, EntryData>()
: LoadEntryState(connection, previousScan.ScanKey);
LogDiagnostic(
"PreviousState completed",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
"Previous entries: " + previousEntries.Count);
ReportProgress(progress, 25);
phaseStopwatch.Restart();
LogDiagnostic("Transaction started", rootEntry.FullPath, 0, null);
using SqliteTransaction transaction = connection.BeginTransaction();
long scanKey = InsertScan(
connection,
transaction,
scanId,
createdUtc,
rootId,
rootEntry,
fileCount,
directoryCount,
previousScan?.ScanKey,
previousScan == null);
using SqliteCommand ensurePathCommand =
CreateEnsurePathCommand(connection, transaction);
using SqliteCommand insertDeltaEntryCommand =
CreateInsertDeltaEntryCommand(connection, transaction);
Dictionary<string, long> pathIds =
CreateKnownPathIds(rootEntry.FullPath, previousEntries);
int totalEntryCount = Math.Max(1, currentEntries.Count + previousEntries.Count);
int processedEntryCount = 0;
int lastReportedProgress = 25;
int pathResolutionCount = 0;
int unchangedEntryCount = 0;
int upsertEntryCount = 0;
int deleteEntryCount = 0;
long pathResolutionTicks = 0;
long versionComparisonTicks = 0;
long upsertInsertTicks = 0;
long deleteLookupTicks = 0;
long deleteInsertTicks = 0;
HashSet<long> currentPathIds = new HashSet<long>();
phaseStopwatch.Restart();
List<KeyValuePair<string, EntryData>> orderedCurrentEntries =
currentEntries
.OrderBy(entry => entry.Value.Depth)
.ThenBy(entry => entry.Value.IsDirectory ? 0 : 1)
.ToList();
LogDiagnostic(
"EntrySort completed",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
"Sorted entries: " + orderedCurrentEntries.Count);
phaseStopwatch.Restart();
LogDiagnostic(
"PathAndEntryInsert started",
rootEntry.FullPath,
0,
"Current entries: " + currentEntries.Count +
Environment.NewLine +
"Previous entries: " + previousEntries.Count);
foreach (KeyValuePair<string, EntryData> currentEntry in orderedCurrentEntries)
{
long operationStarted = Stopwatch.GetTimestamp();
long pathId = EnsurePath(
ensurePathCommand,
rootId,
rootEntry.FullPath,
currentEntry.Value,
pathIds);
pathResolutionTicks += Stopwatch.GetTimestamp() - operationStarted;
pathResolutionCount++;
currentEntry.Value.PathId = pathId;
currentPathIds.Add(pathId);
operationStarted = Stopwatch.GetTimestamp();
bool hasPreviousEntry =
previousEntries.TryGetValue(pathId, out EntryData previousEntry);
bool hasSameVersion =
hasPreviousEntry &&
previousEntry.HasSameVersion(currentEntry.Value);
versionComparisonTicks += Stopwatch.GetTimestamp() - operationStarted;
if (!hasSameVersion)
{
operationStarted = Stopwatch.GetTimestamp();
InsertDeltaEntry(
insertDeltaEntryCommand,
scanKey,
pathId,
currentEntry.Value,
ChangeTypeUpsert);
upsertInsertTicks += Stopwatch.GetTimestamp() - operationStarted;
upsertEntryCount++;
}
else
{
unchangedEntryCount++;
}
processedEntryCount++;
if (processedEntryCount % 100000 == 0)
{
LogDiagnostic(
"PathAndEntryInsert progress",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
"Processed: " + processedEntryCount + " / " + totalEntryCount +
Environment.NewLine +
"Path resolutions: " + pathResolutionCount +
Environment.NewLine +
"Upserts: " + upsertEntryCount +
Environment.NewLine +
"Unchanged: " + unchangedEntryCount +
Environment.NewLine +
"Last path: " + currentEntry.Key);
}
lastReportedProgress = ReportEntryProgress(
progress,
processedEntryCount,
totalEntryCount,
lastReportedProgress);
}
foreach (KeyValuePair<long, EntryData> previousEntry in previousEntries)
{
long operationStarted = Stopwatch.GetTimestamp();
bool existsInCurrentState = currentPathIds.Contains(previousEntry.Key);
deleteLookupTicks += Stopwatch.GetTimestamp() - operationStarted;
if (!existsInCurrentState)
{
operationStarted = Stopwatch.GetTimestamp();
InsertDeltaEntry(
insertDeltaEntryCommand,
scanKey,
previousEntry.Key,
previousEntry.Value,
ChangeTypeDelete);
deleteInsertTicks += Stopwatch.GetTimestamp() - operationStarted;
deleteEntryCount++;
}
processedEntryCount++;
if (processedEntryCount % 100000 == 0)
{
LogDiagnostic(
"DeleteDelta progress",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
"Processed: " + processedEntryCount + " / " + totalEntryCount +
Environment.NewLine +
"Deletes: " + deleteEntryCount +
Environment.NewLine +
"Last path id: " + previousEntry.Key);
}
lastReportedProgress = ReportEntryProgress(
progress,
processedEntryCount,
totalEntryCount,
lastReportedProgress);
}
LogDiagnostic(
"PathAndEntryInsert completed",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
"Path resolutions: " + pathResolutionCount +
Environment.NewLine +
"Path resolution time: " + GetElapsedMilliseconds(pathResolutionTicks) + " ms" +
Environment.NewLine +
"Version comparison time: " + GetElapsedMilliseconds(versionComparisonTicks) + " ms" +
Environment.NewLine +
"Upserts: " + upsertEntryCount +
Environment.NewLine +
"Upsert insert time: " + GetElapsedMilliseconds(upsertInsertTicks) + " ms" +
Environment.NewLine +
"Unchanged: " + unchangedEntryCount +
Environment.NewLine +
"Delete lookups: " + previousEntries.Count +
Environment.NewLine +
"Delete lookup time: " + GetElapsedMilliseconds(deleteLookupTicks) + " ms" +
Environment.NewLine +
"Deletes: " + deleteEntryCount +
Environment.NewLine +
"Delete insert time: " + GetElapsedMilliseconds(deleteInsertTicks) + " ms");
phaseStopwatch.Restart();
LogDiagnostic(
"Commit started",
rootEntry.FullPath,
0,
"Processed entries: " + processedEntryCount);
transaction.Commit();
LogDiagnostic(
"Commit completed",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
null);
ReportProgress(progress, 92);
phaseStopwatch.Restart();
LogDiagnostic("Retention started", rootEntry.FullPath, 0, null);
bool pruned = ApplyRetention(connection, rootId);
LogDiagnostic(
"Retention completed",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
"Pruned: " + pruned);
if (pruned)
{
ReportProgress(progress, 95);
phaseStopwatch.Restart();
LogDiagnostic("Cleanup started", rootEntry.FullPath, 0, null);
CleanupOrphans(connection);
LogDiagnostic(
"Cleanup completed",
rootEntry.FullPath,
phaseStopwatch.ElapsedMilliseconds,
null);
}
ReportProgress(progress, 100);
LogDiagnostic(
"Save completed",
rootEntry.FullPath,
totalStopwatch.ElapsedMilliseconds,
"Scan id: " + scanId);
return scanId;
}
}
private static void LogDiagnostic(
string phase,
string rootPath,
long elapsedMilliseconds,
string details)
{
string message = elapsedMilliseconds > 0
? phase + ": " + elapsedMilliseconds.ToString("N0") + " ms"
: phase;
string diagnosticDetails =
"Root: " + rootPath +
(string.IsNullOrWhiteSpace(details)
? string.Empty
: Environment.NewLine + details);
AppAlertLog.AddVerboseInformation(
"Scan History Diagnostic",
message,
diagnosticDetails);
}
private static long GetElapsedMilliseconds(long elapsedTimestampTicks)
{
return (long)Math.Round(
elapsedTimestampTicks * 1000D / Stopwatch.Frequency,
MidpointRounding.AwayFromZero);
}
private static int ReportEntryProgress(
IProgress<int> progress,
int processedEntryCount,
int totalEntryCount,
int lastReportedProgress)
{
int currentProgress = 25 + (int)Math.Floor(processedEntryCount * 65D / totalEntryCount);
if (currentProgress <= lastReportedProgress)
return lastReportedProgress;
ReportProgress(progress, currentProgress);
return currentProgress;
}
private static void ReportProgress(IProgress<int> progress, int percent)
{
progress?.Report(Math.Max(0, Math.Min(100, percent)));
}
public static IReadOnlyList<ScanHistoryInfo> List()
{
EnsureDatabase();
List<ScanHistoryInfo> scanHistoryInfos = new List<ScanHistoryInfo>();
using SqliteConnection connection = OpenConnection();
using SqliteCommand command = connection.CreateCommand();
command.CommandText =
"SELECT scans.scan_id, scans.created_utc_ticks, roots.root_path, " +
"scans.root_size_bytes, scans.file_count, scans.directory_count " +
"FROM scans " +
"INNER JOIN roots ON roots.root_id = scans.root_id " +
"ORDER BY scans.created_utc_ticks DESC, roots.root_path COLLATE NOCASE ASC;";
using SqliteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string scanId = reader.GetString(0);
scanHistoryInfos.Add(new ScanHistoryInfo
{
FilePath = scanId,
ScanId = scanId,
CreatedUtc = CreateUtcDateTime(reader.GetInt64(1)),
RootPath = reader.GetString(2),
RootSizeBytes = reader.GetInt64(3),
FileCount = reader.GetInt32(4),
DirectoryCount = reader.GetInt32(5)
});
}
return scanHistoryInfos;
}
public static ScanHistorySnapshot Load(string scanId)
{
if (string.IsNullOrWhiteSpace(scanId))
throw new ArgumentException("Scan id is empty.", nameof(scanId));
EnsureDatabase();
using SqliteConnection connection = OpenConnection();
ScanHistorySnapshot snapshot = LoadSnapshotHeader(connection, scanId, out long scanKey);
Dictionary<long, EntryData> entries = LoadEntryState(connection, scanKey);
snapshot.RootEntry = BuildRootEntry(snapshot, entries);
return snapshot;
}
private static void EnsureDatabase()
{
lock (SyncRoot)
{
Directory.CreateDirectory(GetDatabaseDirectoryPath());
using SqliteConnection connection = OpenConnection();
int databaseVersion = GetDatabaseVersion(connection);
if (databaseVersion != 0 && databaseVersion != ScanHistoryVersion)
{
throw new InvalidDataException(
"The selected Scan History database uses an incompatible schema. " +
"Select or create a new empty database.");
}
CreateSchema(connection);
SetDatabaseVersion(connection);
}
}
private static void CreateSchema(SqliteConnection connection)
{
using SqliteCommand command = connection.CreateCommand();
command.CommandText =
"CREATE TABLE IF NOT EXISTS roots (" +
"root_id INTEGER PRIMARY KEY, " +
"root_path TEXT NOT NULL COLLATE NOCASE UNIQUE); " +
"CREATE TABLE IF NOT EXISTS scans (" +
"scan_key INTEGER PRIMARY KEY, " +
"scan_id TEXT NOT NULL UNIQUE, " +
"previous_scan_key INTEGER NULL, " +
"root_id INTEGER NOT NULL, " +
"created_utc_ticks INTEGER NOT NULL, " +
"root_size_bytes INTEGER NOT NULL, " +
"file_count INTEGER NOT NULL, " +
"directory_count INTEGER NOT NULL, " +
"is_baseline INTEGER NOT NULL, " +
"FOREIGN KEY (previous_scan_key) REFERENCES scans(scan_key), " +
"FOREIGN KEY (root_id) REFERENCES roots(root_id)); " +
"CREATE TABLE IF NOT EXISTS paths (" +
"path_id INTEGER PRIMARY KEY, " +
"root_id INTEGER NOT NULL, " +
"parent_path_id INTEGER NOT NULL, " +
"name TEXT NOT NULL COLLATE NOCASE, " +
"is_directory INTEGER NOT NULL, " +
"UNIQUE (root_id, parent_path_id, name, is_directory), " +
"FOREIGN KEY (root_id) REFERENCES roots(root_id)); " +
"CREATE TABLE IF NOT EXISTS scan_entries (" +
"scan_key INTEGER NOT NULL, " +
"path_id INTEGER NOT NULL, " +
"size_bytes INTEGER NULL, " +
"last_write_utc_ticks INTEGER NULL, " +
"change_type INTEGER NOT NULL, " +
"PRIMARY KEY (scan_key, path_id), " +
"FOREIGN KEY (scan_key) REFERENCES scans(scan_key) ON DELETE CASCADE, " +
"FOREIGN KEY (path_id) REFERENCES paths(path_id)) WITHOUT ROWID; " +
"CREATE INDEX IF NOT EXISTS IX_scans_root_created " +
"ON scans (root_id, created_utc_ticks);";
command.ExecuteNonQuery();
}
private static int GetDatabaseVersion(SqliteConnection connection)
{
using SqliteCommand command = connection.CreateCommand();
command.CommandText = "PRAGMA user_version;";
return Convert.ToInt32(command.ExecuteScalar());
}
private static void SetDatabaseVersion(SqliteConnection connection)
{
using SqliteCommand command = connection.CreateCommand();
command.CommandText = "PRAGMA user_version = " + ScanHistoryVersion + ";";
command.ExecuteNonQuery();
}
private static void VacuumDatabase()
{
using SqliteConnection connection = OpenConnection();
using SqliteCommand command = connection.CreateCommand();
command.CommandText = "VACUUM;";
command.ExecuteNonQuery();
}
private static string GetDatabaseDirectoryPath()
{
string directoryPath = Path.GetDirectoryName(databaseFilePath);
if (string.IsNullOrWhiteSpace(directoryPath))
return ScanHistoryDirectoryPath;
return directoryPath;
}
private static SqliteConnection OpenConnection()
{
Directory.CreateDirectory(GetDatabaseDirectoryPath());
SqliteConnectionStringBuilder builder = new SqliteConnectionStringBuilder
{
DataSource = databaseFilePath,
Mode = SqliteOpenMode.ReadWriteCreate,
Cache = SqliteCacheMode.Shared
};
SqliteConnection connection = new SqliteConnection(builder.ToString());
connection.Open();
using SqliteCommand command = connection.CreateCommand();
command.CommandText =
"PRAGMA foreign_keys = ON; " +
"PRAGMA journal_mode = DELETE; " +
"PRAGMA synchronous = NORMAL; " +
"PRAGMA temp_store = MEMORY;";
command.ExecuteNonQuery();
return connection;
}
private static long EnsureRoot(SqliteConnection connection, string rootPath)
{
using SqliteCommand command = connection.CreateCommand();
command.CommandText =
"INSERT INTO roots (root_path) VALUES ($root_path) " +
"ON CONFLICT(root_path) DO UPDATE SET root_path = excluded.root_path " +
"RETURNING root_id;";
command.Parameters.Add("$root_path", SqliteType.Text).Value = rootPath;
return Convert.ToInt64(command.ExecuteScalar());
}
private static long InsertScan(
SqliteConnection connection,
SqliteTransaction transaction,
string scanId,
DateTime createdUtc,
long rootId,
FileSystemEntry rootEntry,
int fileCount,
int directoryCount,
long? previousScanKey,
bool isBaseline)
{
using SqliteCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText =
"INSERT INTO scans " +
"(scan_id, previous_scan_key, root_id, created_utc_ticks, root_size_bytes, " +
"file_count, directory_count, is_baseline) " +
"VALUES ($scan_id, $previous_scan_key, $root_id, $created_utc_ticks, " +
"$root_size_bytes, $file_count, $directory_count, $is_baseline); " +
"SELECT last_insert_rowid();";
command.Parameters.Add("$scan_id", SqliteType.Text).Value = scanId;
command.Parameters.Add("$previous_scan_key", SqliteType.Integer).Value =
previousScanKey.HasValue ? previousScanKey.Value : DBNull.Value;
command.Parameters.Add("$root_id", SqliteType.Integer).Value = rootId;
command.Parameters.Add("$created_utc_ticks", SqliteType.Integer).Value =
createdUtc.Ticks;
command.Parameters.Add("$root_size_bytes", SqliteType.Integer).Value =
rootEntry.SizeBytes;
command.Parameters.Add("$file_count", SqliteType.Integer).Value = fileCount;
command.Parameters.Add("$directory_count", SqliteType.Integer).Value = directoryCount;
command.Parameters.Add("$is_baseline", SqliteType.Integer).Value =
isBaseline ? 1 : 0;
return Convert.ToInt64(command.ExecuteScalar());
}
private static ScanKeyInfo GetLatestScan(
SqliteConnection connection,
long rootId)
{
using SqliteCommand command = connection.CreateCommand();
command.CommandText =
"SELECT scan_key, scan_id " +
"FROM scans " +
"WHERE root_id = $root_id " +
"ORDER BY created_utc_ticks DESC " +
"LIMIT 1;";
command.Parameters.Add("$root_id", SqliteType.Integer).Value = rootId;
using SqliteDataReader reader = command.ExecuteReader();
if (!reader.Read())
return null;
return new ScanKeyInfo
{
ScanKey = reader.GetInt64(0),
ScanId = reader.GetString(1)
};
}
private static SqliteCommand CreateInsertDeltaEntryCommand(
SqliteConnection connection,
SqliteTransaction transaction)
{
SqliteCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText =
"INSERT OR REPLACE INTO scan_entries " +
"(scan_key, path_id, size_bytes, last_write_utc_ticks, change_type) " +
"VALUES ($scan_key, $path_id, $size_bytes, $last_write_utc_ticks, $change_type);";
command.Parameters.Add("$scan_key", SqliteType.Integer);
command.Parameters.Add("$path_id", SqliteType.Integer);
command.Parameters.Add("$size_bytes", SqliteType.Integer);
command.Parameters.Add("$last_write_utc_ticks", SqliteType.Integer);
command.Parameters.Add("$change_type", SqliteType.Integer);
command.Prepare();
return command;
}
private static void InsertDeltaEntry(
SqliteCommand command,
long scanKey,
long pathId,
EntryData entry,
int changeType)
{
command.Parameters["$scan_key"].Value = scanKey;
command.Parameters["$path_id"].Value = pathId;
command.Parameters["$size_bytes"].Value =
changeType == ChangeTypeUpsert ? entry.SizeBytes : DBNull.Value;
command.Parameters["$last_write_utc_ticks"].Value =
changeType == ChangeTypeUpsert ? entry.LastWriteUtcTicks : DBNull.Value;
command.Parameters["$change_type"].Value = changeType;
command.ExecuteNonQuery();
}
private static Dictionary<string, long> CreateKnownPathIds(
string rootPath,
Dictionary<long, EntryData> previousEntries)
{
Dictionary<string, long> pathIds =
new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
if (previousEntries.Count == 0)
return pathIds;
Dictionary<long, string> fullPathsByPathId =
new Dictionary<long, string>();
foreach (long pathId in previousEntries.Keys)
{
string fullPath = ResolveStoredFullPath(
pathId,
rootPath,
previousEntries,
fullPathsByPathId,
new HashSet<long>());
pathIds[fullPath] = pathId;
}
return pathIds;
}
private static string ResolveStoredFullPath(
long pathId,
string rootPath,
Dictionary<long, EntryData> previousEntries,
Dictionary<long, string> fullPathsByPathId,
HashSet<long> visited)
{
if (fullPathsByPathId.TryGetValue(pathId, out string existingFullPath))
return existingFullPath;
if (!visited.Add(pathId))
throw new InvalidDataException(
"Scan History path hierarchy contains a cycle.");
if (!previousEntries.TryGetValue(pathId, out EntryData entry))
throw new InvalidDataException(
"Scan History path entry is missing.");
string fullPath;
if (entry.ParentPathId == 0)
{
fullPath = rootPath;
}
else
{
string parentFullPath = ResolveStoredFullPath(
entry.ParentPathId,
rootPath,
previousEntries,
fullPathsByPathId,
visited);
fullPath = Path.Combine(parentFullPath, entry.Name);
}
visited.Remove(pathId);
fullPathsByPathId[pathId] = fullPath;
return fullPath;
}
private static SqliteCommand CreateEnsurePathCommand(
SqliteConnection connection,
SqliteTransaction transaction)
{
SqliteCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText =
"INSERT INTO paths (root_id, parent_path_id, name, is_directory) " +
"VALUES ($root_id, $parent_path_id, $name, $is_directory) " +
"ON CONFLICT(root_id, parent_path_id, name, is_directory) " +
"DO UPDATE SET name = excluded.name " +
"RETURNING path_id;";
command.Parameters.Add("$root_id", SqliteType.Integer);
command.Parameters.Add("$parent_path_id", SqliteType.Integer);
command.Parameters.Add("$name", SqliteType.Text);
command.Parameters.Add("$is_directory", SqliteType.Integer);
command.Prepare();
return command;
}
private static long EnsurePath(
SqliteCommand command,
long rootId,
string rootPath,
EntryData entry,
Dictionary<string, long> pathIds)
{
if (pathIds.TryGetValue(entry.FullPath, out long existingPathId))
return existingPathId;
long parentPathId = 0;
string name = string.Empty;
if (!string.Equals(
entry.FullPath,
rootPath,
StringComparison.OrdinalIgnoreCase))
{
string parentPath = GetParentPath(entry.FullPath);
if (!pathIds.TryGetValue(parentPath, out parentPathId))
{
throw new InvalidDataException(
"Parent path is missing from the scan result: " + parentPath);
}
name = entry.Name;
}
command.Parameters["$root_id"].Value = rootId;
command.Parameters["$parent_path_id"].Value = parentPathId;
command.Parameters["$name"].Value = name;
command.Parameters["$is_directory"].Value =
entry.IsDirectory ? 1 : 0;
long pathId = Convert.ToInt64(command.ExecuteScalar());
pathIds[entry.FullPath] = pathId;
return pathId;
}
private static Dictionary<string, EntryData> CollectEntries(
FileSystemEntry rootEntry,
out int fileCount,
out int directoryCount)
{
Dictionary<string, EntryData> entries =
new Dictionary<string, EntryData>(StringComparer.OrdinalIgnoreCase);
fileCount = 0;
directoryCount = 0;
string rootPath = Path.GetFullPath(rootEntry.FullPath);
CollectEntriesDiagnostic diagnostic = new CollectEntriesDiagnostic
{
RootPath = rootPath,
Stopwatch = Stopwatch.StartNew()
};
LogDiagnostic("RootFilter started", rootPath, 0, null);
AddEntry(
rootEntry,
rootPath,
entries,
diagnostic,
ref fileCount,
ref directoryCount);
LogDiagnostic(
"RootFilter completed",
rootPath,
diagnostic.Stopwatch.ElapsedMilliseconds,
"Visited references: " + diagnostic.VisitedReferenceCount +
Environment.NewLine +
"Accepted entries: " + entries.Count +
Environment.NewLine +
"Duplicate references: " + diagnostic.DuplicateReferenceCount +
Environment.NewLine +
"Outside root: " + diagnostic.OutsideRootCount +
Environment.NewLine +
"Invalid paths: " + diagnostic.InvalidPathCount +
Environment.NewLine +
"Children references: " + diagnostic.ChildrenReferenceCount +
Environment.NewLine +
"Path filter time: " + GetElapsedMilliseconds(diagnostic.PathFilterTicks) + " ms" +
Environment.NewLine +
"Duplicate lookup time: " + GetElapsedMilliseconds(diagnostic.DuplicateLookupTicks) + " ms" +
Environment.NewLine +
"EntryData creation time: " + GetElapsedMilliseconds(diagnostic.EntryDataCreationTicks) + " ms" +
Environment.NewLine +
"Dictionary insert time: " + GetElapsedMilliseconds(diagnostic.DictionaryInsertTicks) + " ms" +
Environment.NewLine +
"Children traversal dispatch time: " + GetElapsedMilliseconds(diagnostic.ChildrenTraversalTicks) + " ms" +
Environment.NewLine +
"Last path: " + diagnostic.LastPath);
return entries;
}
private static void AddEntry(
FileSystemEntry entry,
string rootPath,
Dictionary<string, EntryData> entries,
CollectEntriesDiagnostic diagnostic,
ref int fileCount,
ref int directoryCount)
{
if (entry == null || string.IsNullOrWhiteSpace(entry.FullPath))
return;
diagnostic.VisitedReferenceCount++;
diagnostic.LastPath = entry.FullPath;
if (diagnostic.VisitedReferenceCount % 100000 == 0)
{
LogDiagnostic(
"RootFilter progress",
rootPath,
diagnostic.Stopwatch.ElapsedMilliseconds,
"Visited references: " + diagnostic.VisitedReferenceCount +
Environment.NewLine +
"Accepted entries: " + entries.Count +
Environment.NewLine +
"Duplicate references: " + diagnostic.DuplicateReferenceCount +
Environment.NewLine +
"Outside root: " + diagnostic.OutsideRootCount +
Environment.NewLine +
"Last path: " + diagnostic.LastPath);
}
long operationStarted = Stopwatch.GetTimestamp();
bool isWithinRoot = TryGetPathWithinRoot(
entry.FullPath,
rootPath,
out string fullPath);
diagnostic.PathFilterTicks += Stopwatch.GetTimestamp() - operationStarted;
if (!isWithinRoot)
{
diagnostic.OutsideRootCount++;
return;
}
if (string.IsNullOrWhiteSpace(fullPath))
{
diagnostic.InvalidPathCount++;
return;
}
operationStarted = Stopwatch.GetTimestamp();
bool isDuplicate = entries.ContainsKey(fullPath);
diagnostic.DuplicateLookupTicks += Stopwatch.GetTimestamp() - operationStarted;
if (isDuplicate)
{
diagnostic.DuplicateReferenceCount++;
return;
}