forked from tedsmith/quickhash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbases_sqlite.pas
executable file
·1867 lines (1737 loc) · 75.9 KB
/
dbases_sqlite.pas
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
{ Quick Hash GUI - A Linux, Windows and Apple Mac GUI for quickly selecting one or more files
and generating hash values for them.
Copyright (C) 2011-2020 Ted Smith www.quickhash-gui.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version. This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You can read a copy of the GNU General Public License at
http://www.gnu.org/licenses/>. Also, http://www.gnu.org/copyleft/gpl.html
Use of the name 'QuickHash GUI' must refer to this utility
only and must not be re-used in another tool if based upon this code.
The code is Copyright of Ted Smith 2011 - 2020 (www.quickhash-gui.org)
}
unit dbases_sqlite; // New to v3.0.0 of QuickHash
{$mode objfpc}{$H+} // {$H+} ensures all strings are of unlimited size, and set as ansistring
interface
uses
{$ifdef Linux}
dl,
{$endif}
{$ifdef Darwin}
dl,
{$endif}
Classes, SysUtils, db, sqldb, sqldblib, fpcsvexport, sqlite3conn, FileUtil,
LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, DBGrids,
sqlite3dyn, clipbrd, DbCtrls, LazUTF8, LazUTF8Classes;
type
{ TfrmSQLiteDBases }
TfrmSQLiteDBases = class(TForm)
CSVExporter1: TCSVExporter; // We use this for users who want to clipboard the results. Works fine if not too many values.
DataSource1: TDataSource;
DataSource2: TDataSource;
DataSource3: TDataSource;
lblConnectionStatus: TLabel;
SQLDBLibraryLoaderLinux: TSQLDBLibraryLoader;
SQLDBLibraryLoaderOSX: TSQLDBLibraryLoader;
SQLDBLibraryLoaderWindows: TSQLDBLibraryLoader;
SQLite3Connection1: TSQLite3Connection;
sqlFILES: TSQLQuery;
sqlCOPY: TSQLQuery;
sqlCOMPARETWOFOLDERS : TSQLQuery;
SQLTransaction1: TSQLTransaction;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure CreateDatabase(DBaseName : string);
procedure WriteFILESValuesToDatabase(Filename, Filepath, HashValue, FileSize : string; KnownHash : boolean);
procedure WriteCOPYValuesToDatabase(Col1, Col2, Col3, Col4, Col5 : string);
procedure Write_INSERT_All_Rows_Required(RowCount : integer);
procedure Write_COMPARE_TWO_FOLDERS_FolderA(Col1, Col2 : string; Counter : integer);
procedure Write_COMPARE_TWO_FOLDERS_FolderB(Col3, Col4 : string; Counter : integer);
procedure EmptyDBTable(TableName : string; DBGrid : TDBGrid);
procedure EmptyDBTableCOPY(TableName : string; DBGrid : TDBGrid);
procedure EmptyDBTableC2F(TableName : string; DBGrid : TDBGrid);
procedure UpdateGridFILES(Sender: TObject);
procedure UpdateGridCOPYTAB(Sender: TObject);
procedure UpdateGridCOMPARETWOFOLDERSTAB(Sender: TObject);
procedure SaveDBToCSV(DBGrid : TDBGrid; Filename : string);
procedure SaveC2FDBToCSV(DBGrid : TDBGrid; Filename : string);
procedure SaveFILESTabToHTML(DBGrid : TDBGrid; Filename : string);
procedure SaveCOPYWindowToHTML(DBGrid : TDBGrid; Filename : string);
procedure SaveC2FWindowToHTML(DBGrid : TDBGrid; Filename : string);
procedure DatasetToClipBoard(DBGrid : TDBGrid);
procedure ShowDuplicates(DBGrid : TDBGrid);
procedure DeleteDuplicates(DBGrid : TDBGrid);
procedure SortByID(DBGrid : TDBGrid);
procedure SortByFileName(DBGrid : TDBGrid);
procedure SortByFilePath(DBGrid : TDBGrid);
procedure SortByHash(DBGrid : TDBGrid);
procedure SoryByHashList(DBGrid : TDBGrid);
procedure FilterOutHashListNO(DBGrid : TDBGrid);
procedure FilterOutHashListYES(DBGrid : TDBGrid);
procedure ShowAll(DBGrid : TDBGrid);
procedure ShowAllCOPYGRID(DBGrid : TDBGrid);
procedure ShowAllC2FGRID(DBGrid : TDBGrid);
procedure CopyFileNameOfSelectedCell(DBGrid : TDBGrid);
procedure CopyFilePathOfSelectedCell(DBGrid : TDBGrid);
procedure CopyHashOfSelectedCell(DBGrid : TDBGrid);
procedure CopyAllHashesFILESTAB(DBGrid : TDBGrid; UseFileFlag : Boolean);
procedure CopySelectedRowFILESTAB(DBGrid : TDBGrid);
procedure CopySelectedRowCOPYTAB(DBGrid : TDBGrid);
procedure CopySelectedRowC2FTAB(DBGrid : TDBGrid);
procedure SortBySourceFilename(DBGrid : TDBGrid);
procedure SortByDestinationFilename(DBGrid : TDBGrid);
procedure SortBySourceHash(DBGrid : TDBGrid);
procedure SortByDestinationHash(DBGrid : TDBGrid);
function CountGridRows(DBGrid : TDBGrid) : integer;
private
{ private declarations }
public
{ public declarations }
const
// More information on the use of these values is below.
// They need not be set as constants in your application. They can be any valid value
application_id = 1189021115; // must be a 32-bit Unsigned Integer (Longword 0 .. 4294967295)
user_version = 23400001; // must be a 32-bit Signed Integer (LongInt -2147483648 .. 2147483647)
end;
var
frmSQLiteDBases: TfrmSQLiteDBases;
implementation
{$R *.lfm}
{ TfrmSQLiteDBases }
uses
Unit2, uDisplayGrid, udisplaygrid3;
procedure TfrmSQLiteDBases.FormCreate(Sender: TObject);
var
guid : TGuid;
SQLiteLibraryPath, strFileNameRandomiser, SafePlaceForDB : string;
{$ifdef Linux}
LibHandle : Pointer;
Pdlinfo : Pdl_info;
PtrSQLiteLibraryPath : PChar;
{$endif}
{$ifdef Darwin}
LibHandle : Pointer;
Pdlinfo : Pdl_info;
PtrSQLiteLibraryPath : PChar;
{$endif}
begin
// SQLiteDefaultLibrary is from the sqlite3dyn unit, new with FPC3.0
// but didn't seem to work with Linux.
// So SQLDBLibraryLoader instances created for each OS seperately
// and the LibraryName adjusted accordingly from the component default value
{$ifdef windows}
SQLDBLibraryLoaderWindows.ConnectionType := 'SQLite3';
{$ifdef CPU32}
SQLiteLibraryPath := 'sqlite3-win32.dll';
{$else ifdef CPU64}
SQLiteLibraryPath := 'sqlite3-win64.dll';
{$endif}
{$endif}
{$ifdef darwin}
SQLDBLibraryLoaderOSX.ConnectionType := 'SQLite3';
SQLiteLibraryPath := '';
//LibHandle := dlopen('/usr/lib/libsqlite3.dylib', RTLD_LAZY);
LibHandle := dlopen('libsqlite3.dylib', RTLD_LAZY);
if LibHandle <> nil then
begin
Pdlinfo := LibHandle;
PtrSQLiteLibraryPath := Pdlinfo^.dli_fbase;
SQLiteLibraryPath := String(PtrSQLiteLibraryPath);
PtrSQLiteLibraryPath := nil;
dlclose(LibHandle);
end;
{$endif}
{$ifdef linux}
SQLDBLibraryLoaderLinux.ConnectionType := 'SQLite3';
SQLiteLibraryPath := '';
LibHandle := dlopen('libsqlite3.so.0', RTLD_LAZY);
if LibHandle <> nil then
begin
Pdlinfo := LibHandle;
PtrSQLiteLibraryPath := Pdlinfo^.dli_fbase;
SQLiteLibraryPath := String(PtrSQLiteLibraryPath);
PtrSQLiteLibraryPath := nil;
dlclose(LibHandle);
end;
{$endif}
if FileExists(SQLiteLibraryPath) then
begin
{$ifdef windows}
SQLDBLibraryLoaderWindows.LibraryName := SQLiteLibraryPath;
SQLDBLibraryLoaderWindows.Enabled := true;
SQLDBLibraryLoaderWindows.LoadLibrary;
{$endif}
{$ifdef darwin}
SQLDBLibraryLoaderOSX.LibraryName := SQLiteLibraryPath;
SQLDBLibraryLoaderOSX.Enabled := true;
SQLDBLibraryLoaderOSX.LoadLibrary;
{$endif}
{$ifdef linux}
SQLDBLibraryLoaderLinux.LibraryName := SQLiteLibraryPath;
SQLDBLibraryLoaderLinux.Enabled := true;
SQLDBLibraryLoaderLinux.LoadLibrary;
{$endif}
if CreateGUID(guid) = 0 then
begin
strFileNameRandomiser := GUIDToString(guid);
end
else
begin
strFileNameRandomiser := FormatDateTime('YYYY-MM-DD_HH-MM-SS.ZZZ', Now);
end;
// write the SQLite database file to system temp
SafePlaceForDB := GetTempDir;
if ForceDirectories(SafePlaceForDB) then
begin
SQLite3Connection1.DatabaseName := SafePlaceForDB + 'QuickHashDB_' + strFileNameRandomiser + '.sqlite';
// Create the database
CreateDatabase(SQLite3Connection1.DatabaseName);
if SQLIte3Connection1.Connected then
begin
lblConnectionStatus.Caption:= 'SQLite3 Database connection active';
end;
end
else
begin
Showmessage('Could not create folder ' + SafePlaceForDB + ' for ' + SQLite3Connection1.DatabaseName);
end;
end
else
begin
ShowMessage('Cannot create SQLite database. Probably SQLite is not installed on your system.');
MainForm.TabSheet3.Enabled := false; // disable FileS tab, because it needs SQLite
MainForm.TabSheet4.Enabled := false; // disable Copy tab, because it needs SQLite
end;
end;
// Create a fresh SQLite database for each instance of the program
procedure TfrmSQLiteDBases.CreateDatabase(DBaseName : string);
begin
SQLite3Connection1.Close; // Ensure the connection is closed when we start
try
// Since we're making this database for the first time,
// check whether the file already exists
if FileExists(SQLite3Connection1.DatabaseName) then
begin
DeleteFile(SQLite3Connection1.DatabaseName);
end;
// Make a new database and add the tables
try
SQLite3Connection1.Open;
SQLTransaction1.Active := true;
// Periodically sort the database out to ensure it stays in tip top shape
// during heavy usage
SQLite3Connection1.ExecuteDirect('PRAGMA auto_vacuum = FULL;');
// Per the SQLite Documentation (edited for clarity):
// The pragma user_version is used to set or get the value of the user-version.
// The user-version is a big-endian 32-bit signed integer stored in the database header at offset 60.
// The user-version is not used internally by SQLite. It may be used by applications for any purpose.
// http://www.sqlite.org/pragma.html#pragma_schema_version
SQLite3Connection1.ExecuteDirect('PRAGMA user_version = ' + IntToStr(user_version) + ';');
// Per the SQLite Documentation:
// The application_id PRAGMA is used to query or set the 32-bit unsigned big-endian
// "Application ID" integer located at offset 68 into the database header.
// Applications that use SQLite as their application file-format should set the
// Application ID integer to a unique integer so that utilities such as file(1) can
// determine the specific file type rather than just reporting "SQLite3 Database".
// A list of assigned application IDs can be seen by consulting the magic.txt file
// in the SQLite source repository.
// http://www.sqlite.org/pragma.html#pragma_application_id
SQLite3Connection1.ExecuteDirect('PRAGMA application_id = ' + IntToStr(application_id) + ';');
// Here we're setting up a table named "TBL_FILES" in the new database for FileS tab
// Note AUTOINCREMENT is NOT used! If it is, it causes problems with RowIDs etc after multiple selections
// Besides, SQLite advice is not to use it unless entirely necessary (http://sqlite.org/autoinc.html)
// VARCHAR is set as 32767 to ensure max length of NFTS based filename and paths can be utilised
SQLite3Connection1.ExecuteDirect('CREATE TABLE "TBL_FILES"('+
' "id" Integer NOT NULL PRIMARY KEY,'+
' "FileName" VARCHAR(32767) NOT NULL,'+
' "FilePath" VARCHAR(32767) NOT NULL,'+
' "HashValue" VARCHAR NOT NULL,'+
' "FileSize" VARCHAR NULL,'+
' "KnownHashFlag" VARCHAR NULL);');
// Creating an index based upon id in the TBL_FILES Table
SQLite3Connection1.ExecuteDirect('CREATE UNIQUE INDEX "FILES_id_idx" ON "TBL_FILES"( "id" );');
// Here we're setting up a table named "TBL_COPY" in the new database for Copy tab
// VARCHAR is set as 32767 to ensure max length of NFTS based filename and paths can be utilised
SQLite3Connection1.ExecuteDirect('CREATE TABLE "TBL_COPY"('+
' "id" Integer NOT NULL PRIMARY KEY,'+
' "SourceFilename" VARCHAR(32767) NOT NULL,'+
' "SourceHash" VARCHAR NULL,'+
' "DestinationFilename" VARCHAR(32767) NOT NULL,'+
' "DestinationHash" VARCHAR NULL,'+
' "DateAttributes" VARCHAR NULL);');
// Creating an index based upon id in the TBL_COPY Table
SQLite3Connection1.ExecuteDirect('CREATE UNIQUE INDEX "COPIED_FILES_id_idx" ON "TBL_COPY"( "id" );');
// New to v3.2.0 to enable a display grid for the comparison of two folders
// Here we're setting up a table named "TBL_COMPARE_TWO_FOLDERS" in the new database for Comapre Two Folders tab
// VARCHAR is set as 32767 to ensure max length of NFTS based filename and paths can be utilised
SQLite3Connection1.ExecuteDirect('CREATE TABLE "TBL_COMPARE_TWO_FOLDERS"('+
' "id" Integer NOT NULL PRIMARY KEY,'+
' "FolderAndFileNameA" VARCHAR(32767) NULL,'+
' "FolderAndFileNameAHash" VARCHAR NULL,'+
' "FolderAndFileNameB" VARCHAR(32767) NULL,'+
' "FolderAndFileNameBHash" VARCHAR NULL);');
// Creating an index based upon id in the TBL_COMPARE_TWO_FOLDERS Table
SQLite3Connection1.ExecuteDirect('CREATE UNIQUE INDEX "COMPARE_TWO_FOLDERS_id_idx" ON "TBL_COMPARE_TWO_FOLDERS"( "id" );');
// Now write to the new database
SQLTransaction1.CommitRetaining;
except
ShowMessage('SQLite detected but unable to create a new SQLite Database');
end;
except
ShowMessage('SQLite detected but could not check if a database file exists');
end;
end;
// I've spent what seems like half my life working out how to copy the entire selected
// row of a DBGrid component without success!! So I resorted to childhood logic.
// Anyone who knows of a better way, let me know!
procedure TfrmSQLiteDBases.CopySelectedRowFILESTAB(DBGrid : TDBGrid);
var
FileNameCell, FilePathCell, FileHashCell, AllRowCells : string;
begin
// Get the data from the filename cell that the user has selected
FileNameCell := DBGrid.DataSource.DataSet.Fields[1].Value;
// Get the data from the filepath cell that the user has selected
FilePathCell := DBGrid.DataSource.DataSet.Fields[2].Value;
// Get the data from the filehash cell that the user has selected
FileHashCell := DBGrid.DataSource.DataSet.Fields[3].Value;
// and just add them all together :-)
AllRowCells := FileNameCell + ',' + FilePathCell + ',' + FileHashCell;
Clipboard.AsText := AllRowCells;
end;
procedure TfrmSQLiteDBases.CopySelectedRowCOPYTAB(DBGrid : TDBGrid);
var
AllRowCells, SourceFileNameCell, SourceHash,
DestinationFilenameCell, DestinationHash, DateAttr : string;
begin
// Get the data from the source filename cell that the user has selected
SourceFileNameCell := DBGrid.DataSource.DataSet.Fields[1].Value;
// Get the source file hash cell that the user has selected
SourceHash := DBGrid.DataSource.DataSet.Fields[2].Value;
// Get the destination filename
DestinationFilenameCell := DBGrid.DataSource.DataSet.Fields[3].Value;
// Get the destination hash
DestinationHash := DBGrid.DataSource.DataSet.Fields[4].Value;
// Get the date attributes
DateAttr := DBGrid.DataSource.DataSet.Fields[5].Value;
// and just add them all together :-)
AllRowCells := SourceFileNameCell + ',' + SourceHash + ',' + DestinationFilenameCell + ',' + DestinationHash + ',' + DateAttr;
Clipboard.AsText := AllRowCells;
end;
// Copies selected row to clipboard of "Compare Two Folders" tab
procedure TfrmSQLiteDBases.CopySelectedRowC2FTAB(DBGrid : TDBGrid);
var
AllRowCells, FolderAFileNameCell, FolderAFileHash,
FolderBFileNameCell, FolderBFileHash : string;
begin
// Get the data from the source filename cell that the user has selected
FolderAFileNameCell := DBGrid.DataSource.DataSet.Fields[1].Value;
// Get the source file hash cell that the user has selected
FolderAFileHash := DBGrid.DataSource.DataSet.Fields[2].Value;
// Get the destination filename
FolderBFileNameCell := DBGrid.DataSource.DataSet.Fields[3].Value;
// Get the destination hash
FolderBFileHash := DBGrid.DataSource.DataSet.Fields[4].Value;
// and just add them all together :-)
AllRowCells := FolderAFileNameCell + ',' + FolderAFileHash + ',' + FolderBFileNameCell + ',' + FolderBFileHash;
Clipboard.AsText := AllRowCells;
end;
// Counts rows of current DBGrid. Returns positive integer if successfull and
// returns active display to top row
function TfrmSQLiteDBases.CountGridRows(DBGrid : TDBGrid) : integer;
var
NoOfRows : integer;
begin
result := -1;
NoOfRows := -1;
DBGrid.DataSource.DataSet.First;
while not DBGrid.DataSource.DataSet.EOF do
begin
inc(NoOfRows, 1);
DBGrid.DataSource.DataSet.Next;
end;
// Go to top of grid.
DBGrid.DataSource.DataSet.First;
// Return count
If NoOfRows > -1 then result := NoOfRows;
end;
// Saves the grid in FILES tab to HTML. If small volume of records, uses a stringlist.
// If big volume, uses file stream.
procedure TfrmSQLiteDBases.SaveFILESTabToHTML(DBGrid : TDBGrid; Filename : string);
var
strTitle, FileNameCell, FilePathCell, FileHashCell : string;
NoOfRowsInGrid : integer;
sl : TStringList;
fs : TFileStreamUTF8;
const
strHTMLHeader = '<HTML>' ;
strTITLEHeader = '<TITLE>QuickHash HTML Output' ;
strBODYHeader = '<BODY>' ;
strTABLEHeader = '<TABLE>' ;
strTABLEROWStart = '<TR>' ;
strTABLEDATAStart = '<TD>' ;
strTABLEDataEnd = '</TD>' ;
strTABLEROWEnd = '</TR>' ;
strTABLEFooter = '</TABLE>';
strBODYFooter = '</BODY>' ;
strTITLEFooter = '</TITLE>';
strHTMLFooter = '</HTML>' ;
begin
NoOfRowsInGrid := -1;
// If database volume not too big, use memory and stringlists. Otherwise, use file writes
if DBGrid.Name = 'RecursiveDisplayGrid1' then
begin
NoOfRowsInGrid := CountGridRows(DBGrid);// Count the rows first. If not too many, use memory. Otherwise, use filestreams
if (NoOfRowsInGrid < 10000) and (NoOfRowsInGrid > -1) then
try
MainForm.StatusBar2.Caption:= ' Saving grid to ' + Filename + '...please wait';
Application.ProcessMessages;
// Write the grid to a stringlist
sl := TStringList.Create;
sl.add('<HTML>');
sl.add('<TITLE>QuickHash HTML Output</TITLE>');
sl.add('<BODY>');
sl.add('<p>HTML Output generated ' + FormatDateTime('YYYY/MM/DD HH:MM:SS', Now) + ' using ' + MainForm.Caption + '</p>');
sl.add('<TABLE>');
DBGrid.DataSource.DataSet.DisableControls;
DBGrid.DataSource.DataSet.First;
while not DBGrid.DataSource.DataSet.EOF do
begin
sl.add('<tr>');
// Get the data from the filename cell that the user has selected
FileNameCell := DBGrid.DataSource.DataSet.Fields[1].Value;
sl.add('<td>'+FileNameCell+'</td>');
// Get the data from the filepath cell that the user has selected
FilePathCell := DBGrid.DataSource.DataSet.Fields[2].Value;
sl.add('<td>'+FilePathCell+'</td>');
// Get the data from the filehash cell that the user has selected
FileHashCell := DBGrid.DataSource.DataSet.Fields[3].Value;
sl.add('<td>'+FileHashCell+'</td>');
sl.add('</tr>');
DBGrid.DataSource.DataSet.Next;
end;
sl.add('</TABLE>');
sl.add('</BODY> ');
sl.add('</HTML> ');
DBGrid.DataSource.DataSet.EnableControls;
sl.SaveToFile(Filename);
finally
sl.free;
MainForm.StatusBar2.Caption:= ' Data saved to HTML file ' + Filename + '...OK';
Application.ProcessMessages;
end
else // Use filestream method because there's more than 10K rows. Too many to add HTML tags and store in memory
try
if not FileExists(filename) then
begin
fs := TFileStreamUTF8.Create(Filename, fmCreate);
end
else fs := TFileStreamUTF8.Create(Filename, fmOpenReadWrite);
MainForm.StatusBar2.Caption:= ' Saving grid to ' + Filename + '...please wait';
strTitle := '<p>HTML Output generated ' + FormatDateTime('YYYY/MM/DD HH:MM:SS', Now) + ' using ' + MainForm.Caption + '</p>';
Application.ProcessMessages;
fs.Write(strHTMLHeader[1], Length(strHTMLHeader));
fs.Write(#13#10, 2);
fs.Write(strTITLEHeader[1], Length(strTITLEHeader));
fs.Write(strTITLEFooter[1], Length(strTITLEFooter));
fs.Write(#13#10, 2);
fs.Write(strBODYHeader[1], Length(strBODYHeader));
fs.Write(strTitle[1], Length(strTitle));
fs.Write(#13#10, 2);
fs.Write(strTABLEHeader[1], Length(strTABLEHeader));
{ strTABLEROWStart = '<TR>' = 4 bytes
strTABLEDATAStart = '<TD>' = 4 bytes
strTABLEDataEnd = '</TD>' = 5 bytes
strTABLEROWEnd = '</TR>' = 5 bytes
strTABLEFooter = '</TABLE>' = 8 bytes
strBODYFooter = '</BODY>' = 7 bytes
strTITLEFooter = '</TITLE>' = 8 bytes
strHTMLFooter = '</HTML>' = 7 bytes}
DBGrid.DataSource.DataSet.DisableControls;
DBGrid.DataSource.DataSet.First;
while not DBGrid.DataSource.DataSet.EOF do
begin
// Start new row
fs.Write(strTABLEROWStart[1], 4);
// Get the data from the filename cell that the user has selected
FileNameCell := DBGrid.DataSource.DataSet.Fields[1].Value;
// Write filename to new row
fs.Write(strTABLEDATAStart[1], 4);
fs.Write(FileNameCell[1], Length(FileNameCell));
fs.Write(strTABLEDataEnd[1], 5);
// Get the data from the filepath cell that the user has selected
FilePathCell := DBGrid.DataSource.DataSet.Fields[2].Value;
// Write filepath to new row
fs.Write(strTABLEDATAStart[1], 4);
fs.Write(FilePathCell[1], Length(FilePathCell));
fs.Write(strTABLEDATAEnd[1], 5);
// Get the data from the filehash cell that the user has selected
FileHashCell := DBGrid.DataSource.DataSet.Fields[3].Value;
// Write hash to new row
fs.Write(strTABLEDATAStart[1], 4) ;
fs.Write(FileHashCell[1], Length(Trim(FileHashCell)));
fs.Write(strTABLEDATAEnd[1], 5);
// End the row
fs.Write(strTABLEROWEnd[1], 5);
fs.Write(#13#10, 2);
DBGrid.DataSource.DataSet.Next;
end;
fs.Write(strTABLEFooter, 8);
fs.Write(#13#10, 2);
fs.writeansistring(IntToStr(NoOfRowsInGrid) + ' grid entries saved.');
fs.Write(strBODYFooter, 7);
fs.Write(#13#10, 2);
fs.Write(strHTMLFooter, 7);
fs.Write(#13#10, 2);
DBGrid.DataSource.DataSet.EnableControls;
finally
fs.free;
MainForm.StatusBar2.Caption:= ' Data saved to HTML file ' + Filename + '...OK';
Application.ProcessMessages;
end;
end
else
if DBGrid.Name = 'frmDisplayGrid1' then
begin
// Same as above but use the 5 columns from COPY grid instead of the 3 of FILES
end;
end;
// Deletes a DB table from the SQLite DB
procedure TfrmSQLiteDBases.EmptyDBTable(TableName : string; DBGrid : TDBGrid);
var
DynamicSQLQuery: TSQLQuery;
begin
DynamicSQLQuery := TSQLQuery.Create(nil);
try
try
DynamicSQLQuery.DataBase := sqlFILES.Database;
DynamicSQLQuery.Transaction := sqlFILES.Transaction;
DynamicSQLQuery.SQL.Text := 'DELETE FROM ' + TableName;
if SQLite3Connection1.Connected then
begin
SQLTransaction1.Active := True;
DynamicSQLQuery.ExecSQL;
SQLTransaction1.CommitRetaining; // Retain transaction is important here
end;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
finally
DynamicSQLQuery.Free;
end;
end;
// Deletes a DB table from the COPY DB
procedure TfrmSQLiteDBases.EmptyDBTableCOPY(TableName : string; DBGrid : TDBGrid);
var
DynamicSQLQuery: TSQLQuery;
begin
DynamicSQLQuery := TSQLQuery.Create(nil);
try
try
DynamicSQLQuery.DataBase := sqlCOPY.Database;
DynamicSQLQuery.Transaction := sqlCOPY.Transaction;
DynamicSQLQuery.SQL.Text := 'DELETE FROM ' + TableName;
if SQLite3Connection1.Connected then
begin
SQLTransaction1.Active := True;
DynamicSQLQuery.ExecSQL;
SQLTransaction1.CommitRetaining; // Retain transaction is important here
end;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
finally
DynamicSQLQuery.Free;
end;
end;
// Empties table of Compare Two Folders
procedure TfrmSQLiteDBases.EmptyDBTableC2F(TableName : string; DBGrid : TDBGrid);
var
DynamicSQLQuery: TSQLQuery;
begin
DynamicSQLQuery := TSQLQuery.Create(nil);
try
try
DynamicSQLQuery.DataBase := sqlCOMPARETWOFOLDERS.Database;
DynamicSQLQuery.Transaction := sqlCOMPARETWOFOLDERS.Transaction;
DynamicSQLQuery.SQL.Text := 'DELETE FROM ' + TableName;
if SQLite3Connection1.Connected then
begin
SQLTransaction1.Active := True;
DynamicSQLQuery.ExecSQL;
SQLTransaction1.CommitRetaining; // Retain transaction is important here
end;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
finally
DynamicSQLQuery.Free;
end;
end;
// SaveDBToCSV exports the DBGrid (DBGridName) to a CSV file (filename) for the user
// Based on example in FPC\3.0.2\source\packages\fcl-db\tests\testdbexport.pas
// Requires the lazdbexport package be installed in Lazarus IDE
procedure TfrmSQLiteDBases.SaveDBToCSV(DBGrid : TDBGrid; Filename : string);
var
linetowrite : ansistring;
n : integer;
CSVFileToWrite : TFilestreamUTF8;
KnownHashFlagIsSet : boolean;
begin
Mainform.StatusBar2.SimpleText := 'Writing hash values to file...please wait';
Application.ProcessMessages;
linetowrite := '';
n := 0;
KnownHashFlagIsSet := false;
try
CSVFileToWrite := TFileStreamUTF8.Create(Filename, fmCreate);
// Now add all the hash strings
DBGrid.DataSource.DataSet.First;
// Write all columns, but dont try to include the Known Hash result if not computed to start with
// This boolean check should be quicker instead of checking for every row whether the field is empty or not
if MainForm.cbLoadHashList.checked then KnownHashFlagIsSet := true
else KnownHashFlagIsSet := false;
while not DBGrid.DataSource.DataSet.EOF do
begin
if KnownHashFlagIsSet then
begin
// Include all columns except the row count. That's not needed for a CSV output.
linetowrite := (DBGrid.DataSource.DataSet.Fields[1].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[2].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[3].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[4].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[5].Text) + #13#10;
end
else
begin
// Include all columns (except the row count) including the Known Hash Flag result.
linetowrite := (DBGrid.DataSource.DataSet.Fields[1].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[2].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[3].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[4].Text) + #13#10;
end;
n := 0;
n := Length(linetowrite);
try
CSVFileToWrite.Write(linetowrite[1], n);
finally
DBGrid.DataSource.DataSet.Next;
end;
end;
finally
CSVFileToWrite.Free;
end;
Mainform.StatusBar2.SimpleText := 'DONE';
ShowMessage('Grid data now in ' + Filename);
end;
procedure TfrmSQLiteDBases.SaveC2FDBToCSV(DBGrid : TDBGrid; Filename : string);
var
linetowrite : ansistring;
n : integer;
CSVFileToWrite : TFilestreamUTF8;
begin
Mainform.StatusBar2.SimpleText := 'Writing results to file...please wait';
Application.ProcessMessages;
linetowrite := '';
n := 0;
try
CSVFileToWrite := TFileStreamUTF8.Create(Filename, fmCreate);
// Now add all the hash strings
DBGrid.DataSource.DataSet.First;
while not DBGrid.DataSource.DataSet.EOF do
begin
// Include all columns
linetowrite := (DBGrid.DataSource.DataSet.Fields[1].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[2].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[3].Text) + ',' +
(DBGrid.DataSource.DataSet.Fields[4].Text) + #13#10;
n := 0;
n := Length(linetowrite);
try
CSVFileToWrite.Write(linetowrite[1], n);
finally
DBGrid.DataSource.DataSet.Next;
end;
end;
finally
CSVFileToWrite.Free;
end;
Mainform.StatusBar2.SimpleText := 'DONE';
ShowMessage('Grid data now in ' + Filename);
end;
{// Go to start of grid
DBGrid.DataSource.DataSet.First;
// And export it
try
Exporter := TCSVExporter.Create(nil);
ExportSettings := TCSVFormatSettings.Create(true);
Exporter.FormatSettings := ExportSettings;
Exporter.Dataset := DBGrid.DataSource.DataSet;
Exporter.FileName := FileName;
if Exporter.Execute > 0 then
begin
ShowMessage('CSV saved as ' + Filename);
end
else Showmessage('Could not save to CSV file ' + Filename);
finally
Exporter.Free;
ExportSettings.Free;
end; }
// Copies a DBGrid content to a temp text file then reads it into clipboard
procedure TfrmSQLiteDBases.DatasetToClipBoard(DBGrid : TDBGrid);
var
DeletedOK : boolean;
vStringList : TStringList;
Exporter : TCSVExporter;
ExportSettings: TCSVFormatSettings;
FileName : string;
begin
Filename := GetTempDir + 'QH_TmpFile.tmp';
DeletedOK := false;
// Go to start of grid
DBGrid.DataSource.DataSet.First;
// and export it...
try
Exporter := TCSVExporter.Create(nil);
try
ExportSettings := TCSVFormatSettings.Create(true);
Exporter.FormatSettings := ExportSettings;
Exporter.Dataset := DBGrid.DataSource.DataSet;
Exporter.FileName := FileName;
// if the temp outfile is written successfully with DBGrid content, load it to clipboard
if Exporter.Execute > 0 then
try
// we can free it now the file is written OK. If we dont free now, we
// cant use LoadFromFile next
if assigned(exporter) then freeandnil(exporter);
// Now load the text file into clipboard
vStringList := TStringList.Create;
vStringList.LoadFromFile(filename);
// Write file to clipboard
Clipboard.AsText := vStringList.Text;
finally
DeletedOK := DeleteFile(Filename);
if DeletedOK = false then Showmessage('Could not delete temporary file ' + filename);
if assigned(vStringList) then freeandnil(vStringList);
ShowMessage('Grid content now in clipboard.');
end;
finally
ExportSettings.Free;
end;
finally
Exporter.Free;
end;
end;
// ShowDuplicates lists entries with duplicate hash values from the FILES tab,
// by searching hash column for matches and then displays all rows fully
// for which duplicate hashes were found
procedure TfrmSQLiteDBases.ShowDuplicates(DBGrid : TDBGrid);
// Sourced from https://stackoverflow.com/questions/46345862/sql-how-to-return-all-column-fields-for-one-column-containing-duplicates
begin
try
DBGrid.DataSource.Dataset.Close; // <--- we don't use sqlFILES but the query connected to the grid
TSQLQuery(DBGrid.DataSource.Dataset).SQL.Text := 'SELECT Id, Filename, FilePath, HashValue, FileSize ' +
'FROM TBL_FILES WHERE HashValue IN ' +
'(SELECT HashValue FROM TBL_FILES ' +
'GROUP BY HashValue HAVING COUNT(*) > 1) ORDER BY hashvalue';
SQLite3Connection1.Connected := True;
SQLTransaction1.Active := True;
MainForm.RecursiveDisplayGrid1.Options:= MainForm.RecursiveDisplayGrid1.Options + [dgAutoSizeColumns];
DBGrid.DataSource.Dataset.Open;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
end;
// DeleteDuplicates remove duplicate files as found in the 'FILES' tab
procedure TfrmSQLiteDBases.DeleteDuplicates(DBGrid : TDBGrid);
var
FileName, FilePath, NameAndPath, FileHash : string;
i, FileDeletedCount : integer;
FilesDeletedOK : boolean;
slDuplicates, slDuplicatesDeleted : TStringList;
begin
FilesDeletedOK := false;
FileDeletedCount := 0;
try
slDuplicates := TStringList.Create;
slDuplicates.Sorted := true;
slDuplicatesDeleted := TStringList.Create;
slDuplicatesDeleted.Sorted := true;
while not DBGrid.DataSource.DataSet.EOF do
begin
for i := 0 to DBGrid.DataSource.DataSet.FieldCount -1 do
begin
FileName := DBGrid.DataSource.DataSet.Fields[1].Value;
FilePath := DBGrid.DataSource.DataSet.Fields[2].Value;
FileHash := DBGrid.DataSource.DataSet.Fields[3].Value;
NameAndPath := FilePath+FileName;
// Now, add the hash value, but only if it's not already in the stringlist
// If the currently examined hashvalue IS in the list, then it must be a duplicate
// and can therefore be deleted
if slDuplicates.IndexOf(FileHash) > -1 then
begin
FilesDeletedOK := DeleteFile(NameAndPath); // it's a duplicate
if FilesDeletedOK = true then
begin
inc(FileDeletedCount, 1);
slDuplicatesDeleted.Add(NameAndPath + ',' + FileHash + ', was deleted OK');
end;
// reset deletion flag
FilesDeletedOK := false;
end
else slDuplicates.add(FileHash);
// Go to next record
DBGrid.DataSource.DataSet.Next;
end;
end;
// Allow user the choice to save results of the duplicate file deletions
try
if MessageDlg(IntToStr(FileDeletedCount) + ' duplicate files deleted. Save details to text file?', mtConfirmation,
[mbCancel, mbNo, mbYes],0) = mrYes then
begin
MainForm.FilesDBGrid_SaveCSVDialog.Title := 'Save deleted file record as...';
MainForm.FilesDBGrid_SaveCSVDialog.InitialDir := GetCurrentDir;
MainForm.FilesDBGrid_SaveCSVDialog.Filter := 'Comma Sep|*.csv';
MainForm.FilesDBGrid_SaveCSVDialog.DefaultExt := 'csv';
if MainForm.FilesDBGrid_SaveCSVDialog.Execute then
begin
slDuplicatesDeleted.SaveToFile(MainForm.FilesDBGrid_SaveCSVDialog.Filename);
end;
end;
except
// do nothing
end;
finally
slDuplicates.free;
end;
end;
// *** Start of FILES tab related database routines ***
// Write computed values from the FILES tab to the database table TBL_FILES
procedure TfrmSQLiteDBases.WriteFILESValuesToDatabase(Filename, Filepath, HashValue, FileSize : string; KnownHash : boolean);
var
KnownHashFlag : string;
begin
try
sqlFILES.Close;
// Insert the values into the database. We're using ParamByName which prevents SQL Injection
// http://wiki.freepascal.org/Working_With_TSQLQuery#Parameters_in_TSQLQuery.SQL
if MainForm.cbLoadHashList.Checked then
begin
if KnownHash = false then
begin
KnownHashFlag := 'No';
sqlFILES.SQL.Text := 'INSERT into TBL_FILES (Filename, FilePath, HashValue, FileSize, KnownHashFlag) values (:Filename,:FilePath,:HashValue,:FileSize,:KnownHashFlag)';
end
else
begin
KnownHashFlag := 'Yes';
sqlFILES.SQL.Text := 'INSERT into TBL_FILES (Filename, FilePath, HashValue, FileSize, KnownHashFlag) values (:Filename,:FilePath,:HashValue,:FileSize,:KnownHashFlag)';
end;
end
else sqlFILES.SQL.Text := 'INSERT into TBL_FILES (Filename, FilePath, HashValue, FileSize) values (:Filename,:FilePath,:HashValue,:FileSize)';
SQLTransaction1.Active := True;
sqlFILES.Params.ParamByName('Filename').AsString := Filename;
sqlFILES.Params.ParamByName('FilePath').AsString := FilePath;
sqlFILES.Params.ParamByName('HashValue').AsString := hashvalue;
sqlFILES.Params.ParamByName('FileSize').AsString := FileSize;
if MainForm.cbLoadHashList.Checked then
begin
sqlFILES.Params.ParamByName('KnownHashFlag').AsString := KnownHashFlag;
end;
sqlFILES.ExecSQL;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
end;
// Used by the FILES tab to sort entries by ID in order
procedure TfrmSQLiteDBases.SortByID(DBGrid : TDBGrid);
begin
try
DBGrid.DataSource.Dataset.Close; // <--- we don't use sqlFILES but the query connected to the grid
TSQLQuery(DBGrid.DataSource.Dataset).SQL.Text := 'SELECT Id, Filename, FilePath, HashValue, FileSize, KnownHashFlag ' +
'FROM TBL_FILES ORDER BY Id';
SQLite3Connection1.Connected := True;
SQLTransaction1.Active := True;
MainForm.RecursiveDisplayGrid1.Options:= MainForm.RecursiveDisplayGrid1.Options + [dgAutoSizeColumns];
DBGrid.DataSource.Dataset.Open;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
end;
// Used by the FILES tab to sort entries by filename alphabetically
procedure TfrmSQLiteDBases.SortByFileName(DBGrid : TDBGrid);
begin
try
DBGrid.DataSource.Dataset.Close; // <--- we don't use sqlFILES but the query connected to the grid
TSQLQuery(DBGrid.DataSource.Dataset).SQL.Text := 'SELECT Id, Filename, FilePath, HashValue, FileSize, KnownHashFlag ' +
'FROM TBL_FILES ORDER BY FileName';
SQLite3Connection1.Connected := True;
SQLTransaction1.Active := True;
MainForm.RecursiveDisplayGrid1.Options:= MainForm.RecursiveDisplayGrid1.Options + [dgAutoSizeColumns];
DBGrid.DataSource.Dataset.Open;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
end;
// Used by FILES tab for sorting entries by file path alphabetically
procedure TfrmSQLiteDBases.SortByFilePath(DBGrid : TDBGrid);
begin
try
DBGrid.DataSource.Dataset.Close; // <--- we don't use sqlFILES but the query connected to the grid
TSQLQuery(DBGrid.DataSource.Dataset).SQL.Text := 'SELECT Id, Filename, FilePath, HashValue, FileSize, KnownHashFlag ' +
'FROM TBL_FILES ORDER BY FilePath';
SQLite3Connection1.Connected := True;
SQLTransaction1.Active := True;
MainForm.RecursiveDisplayGrid1.Options:= MainForm.RecursiveDisplayGrid1.Options + [dgAutoSizeColumns];
DBGrid.DataSource.Dataset.Open;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;
end;
end;
// Used by the FILES tab display grid to sort by hash
procedure TfrmSQLiteDBases.SortByHash(DBGrid : TDBGrid);
begin
try
DBGrid.DataSource.Dataset.Close; // <--- we don't use sqlFILES but the query connected to the grid
TSQLQuery(DBGrid.DataSource.Dataset).SQL.Text := 'SELECT Id, Filename, FilePath, HashValue, FileSize, KnownHashFlag ' +
'FROM TBL_FILES ORDER BY HashValue';
SQLite3Connection1.Connected := True;
SQLTransaction1.Active := True;
MainForm.RecursiveDisplayGrid1.Options:= MainForm.RecursiveDisplayGrid1.Options + [dgAutoSizeColumns];
DBGrid.DataSource.Dataset.Open;
except
on E: EDatabaseError do
begin
MessageDlg('Error','A database error has occurred. Technical error message: ' + E.Message,mtError,[mbOK],0);
end;