-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathdatabase.cpp
More file actions
1561 lines (1371 loc) · 45.2 KB
/
Copy pathdatabase.cpp
File metadata and controls
1561 lines (1371 loc) · 45.2 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
/*
* Copyright (C) 2016-2017, Egor Pugin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "database.h"
#include "directories.h"
#include "exceptions.h"
#include "enums.h"
#include "hash.h"
#include "http.h"
#include "lock.h"
#include "settings.h"
#include "sqlite_database.h"
#include "stamp.h"
#include "printers/cmake.h"
#include <primitives/command.h>
#include <primitives/lock.h>
#include <primitives/pack.h>
#include <primitives/templates.h>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <sqlite3.h>
#include <shared_mutex>
#include <primitives/log.h>
//DECLARE_STATIC_LOGGER(logger, "db");
#define PACKAGES_DB_REFRESH_TIME_MINUTES 15
#define PACKAGES_DB_SCHEMA_VERSION 1
#define PACKAGES_DB_SCHEMA_VERSION_FILE "schema.version"
#define PACKAGES_DB_VERSION_FILE "db.version"
#define PACKAGES_DB_DOWNLOAD_TIME_FILE "packages.time"
const String db_repo_url = "https://github.com/cppan/database";
const String db_master_url = db_repo_url + "/archive/master.zip";
const String db_version_url = "https://raw.githubusercontent.com/cppan/database/master/" PACKAGES_DB_VERSION_FILE;
const path db_dir_name = "database";
const path db_repo_dir_name = "repository";
const String packages_db_name = "packages.db";
const String service_db_name = "service.db";
TYPED_EXCEPTION(NoSuchVersion);
std::vector<StartupAction> startup_actions{
{ 1, StartupAction::ClearCache },
{ 2, StartupAction::ServiceDbClearConfigHashes },
{ 4, StartupAction::CheckSchema },
{ 5, StartupAction::ClearStorageDirExp },
{ 6, StartupAction::ClearSourceGroups },
{ 7, StartupAction::ClearStorageDirExp | StartupAction::ClearStorageDirBin | StartupAction::ClearStorageDirLib },
{ 8, StartupAction::ClearCfgDirs },
{ 9, StartupAction::ClearStorageDirExp },
{ 10, StartupAction::ClearPackagesDatabase },
{ 11, StartupAction::ServiceDbClearConfigHashes },
{ 12, StartupAction::ClearStorageDirExp | StartupAction::ClearStorageDirObj },
{ 13, StartupAction::ClearStorageDirExp },
// full cleanup, we changed api name encoding to hashes :(
{ 14, StartupAction::ClearStorageDirExp | StartupAction::ClearStorageDirObj | StartupAction::ClearStorageDirSrc | StartupAction::ClearStorageDirBin | StartupAction::ClearStorageDirLib },
};
const TableDescriptors &get_service_tables()
{
// to prevent side effects as with global variable
// ! append new tables to the end only !
static const TableDescriptors service_tables{
{ "ClientStamp",
R"(
CREATE TABLE "ClientStamp" (
"stamp" INTEGER NOT NULL
);
)" },
{"ConfigHashes",
R"(
CREATE TABLE "ConfigHashes" (
"hash" TEXT NOT NULL, -- program (settings) hash
"config" TEXT NOT NULL, -- config
"config_hash" TEXT NOT NULL, -- config hash
PRIMARY KEY ("hash")
);
)"},
{ "FileStamps",
R"(
CREATE TABLE "FileStamps" (
"file" TEXT NOT NULL,
"stamp" INTEGER NOT NULL,
PRIMARY KEY ("file")
);
)" },
{"InstalledPackages",
R"(
CREATE TABLE "InstalledPackages" (
"id" INTEGER NOT NULL,
"package" TEXT NOT NULL,
"version" TEXT NOT NULL,
"hash" TEXT NOT NULL,
PRIMARY KEY ("id"),
UNIQUE ("package", "version")
);
)"},
{"NextClientVersionCheck",
R"(
CREATE TABLE "NextClientVersionCheck" (
"timestamp" INTEGER NOT NULL
);
insert into NextClientVersionCheck values (0);
)"},
{"NRuns", // unneeded?
R"(
CREATE TABLE "NRuns" (
"n_runs" INTEGER NOT NULL
);
insert into NRuns values (0);
)"},
{"PackagesDbSchemaVersion",
R"(
CREATE TABLE "PackagesDbSchemaVersion" (
"version" INTEGER NOT NULL
);
insert into PackagesDbSchemaVersion values ()" +
std::to_string(PACKAGES_DB_SCHEMA_VERSION) + R"();
)"},
{"PackageDependenciesHashes",
R"(
CREATE TABLE "PackageDependenciesHashes" (
"package" TEXT NOT NULL,
"dependencies" TEXT NOT NULL,
PRIMARY KEY ("package")
);
)"},
{ "SourceGroups",
R"(
CREATE TABLE "SourceGroups" (
"id" INTEGER NOT NULL,
"package_id" INTEGER NOT NULL,
"path" TEXT NOT NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("package_id") REFERENCES "InstalledPackages" ("id") ON DELETE CASCADE
);
)" },
{ "SourceGroupFiles",
R"(
CREATE TABLE "SourceGroupFiles" (
"source_group_id" INTEGER NOT NULL,
"path" TEXT NOT NULL,
FOREIGN KEY ("source_group_id") REFERENCES "SourceGroups" ("id") ON DELETE CASCADE
);
)" },
{"StartupActions",
R"(
CREATE TABLE "StartupActions" (
"id" INTEGER NOT NULL,
"action" INTEGER NOT NULL,
PRIMARY KEY ("id", "action")
);
)"},
{"TableHashes",
R"(
CREATE TABLE "TableHashes" (
"tbl" TEXT NOT NULL,
"hash" TEXT NOT NULL,
PRIMARY KEY ("tbl")
);
)"},
};
return service_tables;
}
const TableDescriptors data_tables{
{
"Projects",
R"(
CREATE TABLE "Projects" (
"id" INTEGER NOT NULL,
"path" TEXT(2048) NOT NULL,
"type_id" INTEGER NOT NULL,
"flags" INTEGER NOT NULL,
PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "ProjectPath" ON "Projects" ("path" ASC);
)"
},
{
"ProjectVersions",
R"(
CREATE TABLE "ProjectVersions" (
"id" INTEGER NOT NULL,
"project_id" INTEGER NOT NULL,
"major" INTEGER,
"minor" INTEGER,
"patch" INTEGER,
"branch" TEXT,
"flags" INTEGER NOT NULL,
"created" DATE NOT NULL,
"hash" TEXT NOT NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("project_id") REFERENCES "Projects" ("id")
);
)"
},
{
"ProjectVersionDependencies",
R"(
CREATE TABLE "ProjectVersionDependencies" (
"project_version_id" INTEGER NOT NULL,
"project_dependency_id" INTEGER NOT NULL,
"version" TEXT NOT NULL,
"flags" INTEGER NOT NULL,
PRIMARY KEY ("project_version_id", "project_dependency_id"),
FOREIGN KEY ("project_version_id") REFERENCES "ProjectVersions" ("id"),
FOREIGN KEY ("project_dependency_id") REFERENCES "Projects" ("id")
);
)"
},
};
path getDbDirectory()
{
// db per storage
return directories.storage_dir_etc / db_dir_name;
}
int readPackagesDbSchemaVersion(const path &dir)
{
auto p = dir / PACKAGES_DB_SCHEMA_VERSION_FILE;
if (!fs::exists(p))
return 0;
return std::stoi(read_file(p));
}
void writePackagesDbSchemaVersion(const path &dir)
{
write_file(dir / PACKAGES_DB_SCHEMA_VERSION_FILE, std::to_string(PACKAGES_DB_SCHEMA_VERSION));
}
int readPackagesDbVersion(const path &dir)
{
auto p = dir / PACKAGES_DB_VERSION_FILE;
if (!fs::exists(p))
return 0;
return std::stoi(read_file(p));
}
void writePackagesDbVersion(const path &dir, int version)
{
write_file(dir / PACKAGES_DB_VERSION_FILE, std::to_string(version));
}
ServiceDatabase &getServiceDatabase(bool init)
{
// this holder will init on-disk sdb once
// later thread local calls will just open it
static ServiceDatabase run_once_db;
if (init)
run_once_db.init();
thread_local
ServiceDatabase db;
return db;
}
ServiceDatabase &getServiceDatabaseReadOnly()
{
return getServiceDatabase();
RUN_ONCE
{
getServiceDatabase();
};
static ServiceDatabase db;
RUN_ONCE
{
db.open(true);
};
return db;
}
PackagesDatabase &getPackagesDatabase()
{
// this holder will init on-disk pkgdb once
// later thread local calls will just open it
static PackagesDatabase run_once_db;
thread_local
PackagesDatabase db;
return db;
}
Database::Database(const String &name, const TableDescriptors &tds)
: tds(tds)
{
db_dir = getDbDirectory();
fn = db_dir / name;
if (!fs::exists(fn))
{
ScopedFileLock lock(fn);
if (!fs::exists(fn))
{
open();
for (auto &td : tds)
db->execute(td.query);
created = true;
}
}
if (!db)
open();
}
void Database::open(bool read_only)
{
db = std::make_unique<SqliteDatabase>(fn.string(), read_only);
// prevent SQLITE_BUSY rc
// hope 1 min is enough to wait for write operation
// in multithreaded environment
sqlite3_busy_timeout(db->getDb(), 60000);
}
void Database::recreate()
{
db.reset();
ScopedFileLock lock(fn);
fs::remove(fn);
open();
for (auto &td : tds)
db->execute(td.query);
created = true;
}
ServiceDatabase::ServiceDatabase()
: Database(service_db_name, get_service_tables())
{
}
void ServiceDatabase::init()
{
RUN_ONCE
{
createTables();
checkStamp();
increaseNumberOfRuns();
checkForUpdates();
};
// move out of RUN_ONCE because it may try to init sdb again
performStartupActions();
}
void ServiceDatabase::createTables() const
{
// add table hashes
if (created)
{
for (auto &td : tds)
setTableHash(td.name, sha256(td.query));
}
auto create_table = [this](const auto &td)
{
db->execute(td.query);
setTableHash(td.name, sha256(td.query));
};
// TableHashes first, out of order
auto th = std::find_if(tds.begin(), tds.end(), [](const auto &td)
{
return td.name == "TableHashes";
});
if (!db->getNumberOfColumns(th->name))
create_table(*th);
// create only new tables
for (auto &td : tds)
{
if (db->getNumberOfColumns(td.name))
continue;
create_table(td);
}
}
void ServiceDatabase::recreateTable(const TableDescriptor &td) const
{
db->dropTable(td.name);
db->execute(td.query);
setTableHash(td.name, sha256(td.query));
}
void ServiceDatabase::checkStamp() const
{
String s;
db->execute("select * from ClientStamp",
[&s](SQLITE_CALLBACK_ARGS)
{
s = cols[0];
return 0;
});
if (s == cppan_stamp)
return;
if (s.empty())
db->execute("replace into ClientStamp values ('" + cppan_stamp + "')");
else
db->execute("update ClientStamp set stamp = '" + cppan_stamp + "'");
// if stamp is changed, we do some usual stuff between versions
clearFileStamps();
}
void ServiceDatabase::performStartupActions() const
{
registerCmakePackage();
// perform startup actions on client update
try
{
static bool once = false;
if (once)
return;
std::set<int> actions_performed; // prevent multiple execution of the same actions
for (auto &a : startup_actions)
{
if (isActionPerformed(a))
continue;
if (actions_performed.find(a.action) != actions_performed.end())
{
setActionPerformed(a);
continue;
}
if (!once)
LOG_INFO(logger, "Initializing storage");
once = true;
actions_performed.insert(a.action);
setActionPerformed(a);
// do actions
if (a.action & StartupAction::ClearCache)
{
CMakePrinter().clear_cache();
}
if (a.action & StartupAction::ServiceDbClearConfigHashes)
{
clearConfigHashes();
// also cleanup temp build dir
error_code ec;
fs::remove_all(temp_directory_path(), ec);
}
if (a.action & StartupAction::CheckSchema)
{
// create new tables
createTables();
// re-create changed tables
for (auto &td : tds)
{
auto h = sha256(td.query);
if (getTableHash(td.name) == h)
continue;
db->dropTable(td.name);
db->execute(td.query);
setTableHash(td.name, h);
}
}
if (a.action & StartupAction::ClearPackagesDatabase)
{
fs::remove(getDbDirectory() / packages_db_name);
}
if (a.action & StartupAction::ClearStorageDirExp)
{
remove_all_from_dir(directories.storage_dir_exp);
}
if (a.action & StartupAction::ClearStorageDirTmp)
{
remove_all_from_dir(directories.storage_dir_tmp);
}
if (a.action & StartupAction::ClearStorageDirObj)
{
remove_all_from_dir(directories.storage_dir_obj);
}
if (a.action & StartupAction::ClearStorageDirSrc)
{
remove_all_from_dir(directories.storage_dir_src);
}
if (a.action & StartupAction::ClearStorageDirBin)
{
// also remove exp to trigger cmake
remove_all_from_dir(directories.storage_dir_exp);
remove_all_from_dir(directories.storage_dir_bin);
}
if (a.action & StartupAction::ClearStorageDirLib)
{
// also remove exp to trigger cmake
remove_all_from_dir(directories.storage_dir_exp);
remove_all_from_dir(directories.storage_dir_lib);
}
if (a.action & StartupAction::ClearSourceGroups)
{
clearSourceGroups();
}
if (a.action & StartupAction::ClearCfgDirs)
{
for (auto &i : boost::make_iterator_range(fs::directory_iterator(directories.storage_dir_cfg), {}))
{
if (fs::is_directory(i))
fs::remove_all(i);
}
}
}
}
catch (std::exception &e)
{
// do not fail
LOG_WARN(logger, "Warning: " << e.what());
}
}
void ServiceDatabase::checkForUpdates() const
{
using namespace std::literals;
auto last_check = getLastClientUpdateCheck();
auto d = Clock::now() - last_check;
if (d < 3h)
return;
try
{
// if there are updates, set next check (and notification) in 20 mins
// to issue a message every run
if (Settings::get_user_settings().checkForUpdates())
setLastClientUpdateCheck(last_check + 20min);
else
setLastClientUpdateCheck();
}
catch (...)
{
}
}
TimePoint ServiceDatabase::getLastClientUpdateCheck() const
{
TimePoint tp;
db->execute("select * from NextClientVersionCheck",
[&tp](SQLITE_CALLBACK_ARGS)
{
tp = Clock::from_time_t(std::stoll(cols[0]));
return 0;
});
return tp;
}
void ServiceDatabase::setLastClientUpdateCheck(const TimePoint &p) const
{
db->execute("update NextClientVersionCheck set timestamp = '" +
std::to_string(Clock::to_time_t(p)) + "'");
}
String ServiceDatabase::getTableHash(const String &table) const
{
String h;
db->execute("select hash from TableHashes where tbl = '" + table + "'",
[&h](SQLITE_CALLBACK_ARGS)
{
h = cols[0];
return 0;
});
return h;
}
void ServiceDatabase::setTableHash(const String &table, const String &hash) const
{
db->execute("replace into TableHashes values ('" + table + "', '" + hash + "')");
}
Stamps ServiceDatabase::getFileStamps() const
{
Stamps st;
db->execute("select * from FileStamps",
[&st](SQLITE_CALLBACK_ARGS)
{
st[cols[0]] = fs::file_time_type(fs::file_time_type::duration(std::stoll(cols[1])));
return 0;
});
return st;
}
void ServiceDatabase::setFileStamps(const Stamps &stamps) const
{
if (stamps.empty())
{
clearFileStamps();
return;
}
String q = "replace into FileStamps values ";
for (auto &s : stamps)
q += "('" + to_printable_string(normalize_path(s.first)) + "', '" + std::to_string((int64_t)s.second.time_since_epoch().count()) + "'),";
q.resize(q.size() - 1);
q += ";";
db->execute(q);
}
void ServiceDatabase::clearFileStamps() const
{
db->execute("delete from FileStamps");
}
bool ServiceDatabase::isActionPerformed(const StartupAction &action) const
{
int n = 0;
try
{
db->execute("select count(*) from StartupActions where id = '" +
std::to_string(action.id) + "' and action = '" + std::to_string(action.action) + "'",
[&n](SQLITE_CALLBACK_ARGS)
{
n = std::stoi(cols[0]);
return 0;
});
}
catch (const std::exception&)
{
// if error is in StartupActions, recreate it
auto th = std::find_if(tds.begin(), tds.end(), [](const auto &td)
{
return td.name == "StartupActions";
});
recreateTable(*th);
}
return n == 1;
}
void ServiceDatabase::setActionPerformed(const StartupAction &action) const
{
db->execute("insert into StartupActions values ('" +
std::to_string(action.id) + "', '" + std::to_string(action.action) + "')");
}
int ServiceDatabase::getNumberOfRuns() const
{
int n_runs = 0;
db->execute("select n_runs from NRuns;", [&n_runs](SQLITE_CALLBACK_ARGS)
{
n_runs = std::stoi(cols[0]);
return 0;
});
return n_runs;
}
int ServiceDatabase::increaseNumberOfRuns() const
{
auto prev = getNumberOfRuns();
db->execute("update NRuns set n_runs = n_runs + 1;");
return prev;
}
int ServiceDatabase::getPackagesDbSchemaVersion() const
{
int version = 0;
db->execute("select version from PackagesDbSchemaVersion;", [&version](SQLITE_CALLBACK_ARGS)
{
version = std::stoi(cols[0]);
return 0;
});
return version;
}
void ServiceDatabase::setPackagesDbSchemaVersion(int version) const
{
db->execute("update PackagesDbSchemaVersion set version = " + std::to_string(version));
}
void ServiceDatabase::clearConfigHashes() const
{
db->execute("delete from ConfigHashes");
}
String ServiceDatabase::getConfigByHash(const String &settings_hash) const
{
String c;
db->execute("select config from ConfigHashes where hash = '" + settings_hash + "'",
[&c](SQLITE_CALLBACK_ARGS)
{
c = cols[0];
return 0;
});
return c;
}
void ServiceDatabase::addConfigHash(const String &settings_hash, const String &config, const String &config_hash) const
{
if (config.empty())
return;
db->execute("replace into ConfigHashes values ('" + settings_hash + "', '" + config + "', '" + config_hash + "'" + ")");
}
void ServiceDatabase::removeConfigHashes(const String &h) const
{
db->execute("delete from ConfigHashes where config_hash = '" + h + "'");
}
void ServiceDatabase::setPackageDependenciesHash(const Package &p, const String &hash) const
{
db->execute("replace into PackageDependenciesHashes values ('" + p.target_name + "', '" + hash + "')");
}
bool ServiceDatabase::hasPackageDependenciesHash(const Package &p, const String &hash) const
{
bool has = false;
db->execute("select * from PackageDependenciesHashes where package = '" + p.target_name + "' "
"and dependencies = '" + hash + "'",
[&has](SQLITE_CALLBACK_ARGS)
{
has = true;
return 0;
});
return has;
}
void ServiceDatabase::setSourceGroups(const Package &p, const SourceGroups &sgs) const
{
auto id = getInstalledPackageId(p);
if (id == 0)
return;
removeSourceGroups(id);
for (auto &sg : sgs)
{
db->execute("insert into SourceGroups (package_id, path) values ('" + std::to_string(id) + "', '" + sg.first + "');");
if (!sg.second.empty())
{
auto sg_id = db->getLastRowId();
String q = "insert into SourceGroupFiles values ";
for (auto &f : sg.second)
q += "('" + std::to_string(sg_id) + "', '" + f + "'),";
q.resize(q.size() - 1);
q += ";";
db->execute(q);
}
}
}
SourceGroups ServiceDatabase::getSourceGroups(const Package &p) const
{
SourceGroups sgs;
auto id = getInstalledPackageId(p);
if (id == 0)
return sgs;
std::map<int, String> ids;
db->execute("select id, path from SourceGroups where package_id = '" + std::to_string(id) + "';",
[&ids](SQLITE_CALLBACK_ARGS)
{
ids[std::stoi(cols[0])] = cols[1];
return 0;
});
for (auto &i : ids)
{
auto &sg = sgs[i.second];
db->execute("select path from SourceGroupFiles where source_group_id = '" + std::to_string(i.first) + "';",
[&sg](SQLITE_CALLBACK_ARGS)
{
sg.insert(cols[0]);
return 0;
});
}
return sgs;
}
void ServiceDatabase::removeSourceGroups(const Package &p) const
{
auto id = getInstalledPackageId(p);
if (id == 0)
return;
removeSourceGroups(id);
}
void ServiceDatabase::removeSourceGroups(int id) const
{
db->execute("delete from SourceGroups where package_id = '" + std::to_string(id) + "';");
}
void ServiceDatabase::clearSourceGroups() const
{
db->execute("delete from SourceGroupFiles;");
db->execute("delete from SourceGroups;");
}
void ServiceDatabase::addInstalledPackage(const Package &p) const
{
auto h = p.getFilesystemHash();
if (getInstalledPackageHash(p) == h)
return;
db->execute("replace into InstalledPackages (package, version, hash) values ('" + p.ppath.toString() + "', '" + p.version.toString() + "', '" + p.getFilesystemHash() + "')");
}
void ServiceDatabase::removeInstalledPackage(const Package &p) const
{
db->execute("delete from InstalledPackages where package = '" + p.ppath.toString() + "' and version = '" + p.version.toString() + "'");
}
String ServiceDatabase::getInstalledPackageHash(const Package &p) const
{
String hash;
db->execute("select hash from InstalledPackages where package = '" + p.ppath.toString() + "' and version = '" + p.version.toString() + "'",
[&hash](SQLITE_CALLBACK_ARGS)
{
hash = cols[0];
return 0;
});
return hash;
}
int ServiceDatabase::getInstalledPackageId(const Package &p) const
{
int id = 0;
db->execute("select id from InstalledPackages where package = '" + p.ppath.toString() + "' and version = '" + p.version.toString() + "'",
[&id](SQLITE_CALLBACK_ARGS)
{
id = std::stoi(cols[0]);
return 0;
});
return id;
}
PackagesSet ServiceDatabase::getInstalledPackages() const
{
std::set<std::pair<String, String>> pkgs_s;
db->execute("select package, version from InstalledPackages",
[&pkgs_s](SQLITE_CALLBACK_ARGS)
{
pkgs_s.insert({ cols[0], cols[1] });
return 0;
});
PackagesSet pkgs;
for (auto &p : pkgs_s)
{
Package pkg;
pkg.ppath = p.first;
pkg.version = p.second;
pkg.createNames();
pkgs.insert(pkg);
}
return pkgs;
}
PackagesDatabase::PackagesDatabase()
: Database(packages_db_name, data_tables)
{
db_repo_dir = db_dir / db_repo_dir_name;
RUN_ONCE
{
init();
};
// at the end we always reopen packages db as read only
open(true);
}
void PackagesDatabase::init()
{
if (created)
{
LOG_INFO(logger, "Packages database was not found");
download();
load();
}
else if (Settings::get_system_settings().can_update_packages_db && isCurrentDbOld())
{
LOG_DEBUG(logger, "Checking remote version");
int version_remote = 0;
try
{
version_remote = std::stoi(download_file(db_version_url));
}
catch (std::exception &e)
{
LOG_DEBUG(logger, "Couldn't download db version file: " << e.what());
}
if (version_remote > readPackagesDbVersion(db_repo_dir))
{
// multiprocess aware
single_process_job(get_lock("db_update"), [this]
{
download();
load(true);
});
}
}
}
void PackagesDatabase::download()
{
LOG_INFO(logger, "Downloading database");
auto download_archive = [this]()
{
fs::create_directories(db_repo_dir);
auto fn = get_temp_filename();
download_file(db_master_url, fn, 1_GB);
auto unpack_dir = get_temp_filename();
auto files = unpack_file(fn, unpack_dir);
for (auto &f : files)
fs::copy_file(f, db_repo_dir / f.filename(), fs::copy_options::overwrite_existing);
fs::remove_all(unpack_dir);
fs::remove(fn);
};
const String git = "git";
if (!primitives::resolve_executable(git).empty())
{
auto git_init = [this, &git]()
{
fs::create_directories(db_repo_dir);
primitives::Command::execute({ git,"-C",db_repo_dir.string(),"init","." });
primitives::Command::execute({ git,"-C",db_repo_dir.string(),"remote","add","github",db_repo_url });
primitives::Command::execute({ git,"-C",db_repo_dir.string(),"pull","github","master" });
};
try
{
if (!fs::exists(db_repo_dir / ".git"))
{
git_init();
}
else
{
std::error_code ec1, ec2;
primitives::Command::execute({ git,"-C",db_repo_dir.string(),"pull","github","master" }, ec1);
primitives::Command::execute({ git,"-C",db_repo_dir.string(),"reset","--hard" }, ec2);
if (ec1 || ec2)
{
// can throw
fs::remove_all(db_repo_dir);
git_init();
}
}
}
catch (const std::exception &)
{
// cannot throw
error_code ec;
fs::remove_all(db_repo_dir, ec);
download_archive();
}
}
else
{
download_archive();
}
writeDownloadTime();
}