aboutsummaryrefslogtreecommitdiff
path: root/bpkg/database.cxx
blob: 65e3af81a858df9d2732d5fa6954bb49304f45f7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
// file      : bpkg/database.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <bpkg/database.hxx>

#include <sqlite3.h> // @@ TMP sqlite3_libversion_number()

#include <map>

#include <odb/schema-catalog.hxx>
#include <odb/sqlite/exceptions.hxx>

#include <bpkg/package.hxx>
#include <bpkg/package-odb.hxx>
#include <bpkg/diagnostics.hxx>

using namespace std;

namespace bpkg
{
  namespace sqlite = odb::sqlite;

  // Configuration types.
  //
  const string host_config_type   ("host");
  const string build2_config_type ("build2");

  const string&
  buildtime_dependency_type (const package_name& nm)
  {
    return build2_module (nm) ? build2_config_type : host_config_type;
  }

  // Configuration names.
  //
  void
  validate_configuration_name (const string& s, const char* what)
  {
    if (s.empty ())
      fail << "empty " << what;

    if (!(alpha (s[0]) || s[0] == '_'))
      fail << "invalid " << what << " '" << s << "': illegal first character "
           << "(must be alphabetic or underscore)";

    for (auto i (s.cbegin () + 1), e (s.cend ()); i != e; ++i)
    {
      char c (*i);

      if (!(alnum (c) || c == '_' || c == '-'))
        fail << "invalid " << what << " '" << s << "': illegal character "
             << "(must be alphabetic, digit, underscore, or dash)";
    }
  }

  // Register the data migration functions.
  //
  // NOTE: remember to qualify table/index names with \"main\". if using
  // native statements.
  //
  template <odb::schema_version v>
  using migration_entry = odb::data_migration_entry<v, DB_SCHEMA_VERSION_BASE>;

  // @@ Since there is no proper support for dropping table columns not in
  //    SQLite prior to 3.35.5 nor in ODB, we will drop the
  //    available_package_dependency_alternatives.dep_* columns manually. We,
  //    however, cannot do it here since ODB will try to set the dropped
  //    column values to NULL at the end of migration. Thus, we will do it
  //    ad hoc after the below schema_catalog::migrate() call.
  //
  //    NOTE: remove the mentioned ad hoc migration when removing this
  //    function.
  //
  static const migration_entry<13>
  migrate_v13 ([] (odb::database& db)
  {
    // Note that
    // available_package_dependency_alternative_dependencies.alternative_index
    // is copied from available_package_dependency_alternatives.index and
    // available_package_dependency_alternative_dependencies.index is set to 0.
    //
    db.execute (
      "INSERT INTO \"main\".\"available_package_dependency_alternative_dependencies\" "
      "(\"name\", "
      "\"version_epoch\", "
      "\"version_canonical_upstream\", "
      "\"version_canonical_release\", "
      "\"version_revision\", "
      "\"version_iteration\", "
      "\"dependency_index\", "
      "\"alternative_index\", "
      "\"index\", "
      "\"dep_name\", "
      "\"dep_min_version_epoch\", "
      "\"dep_min_version_canonical_upstream\", "
      "\"dep_min_version_canonical_release\", "
      "\"dep_min_version_revision\", "
      "\"dep_min_version_iteration\", "
      "\"dep_min_version_upstream\", "
      "\"dep_min_version_release\", "
      "\"dep_max_version_epoch\", "
      "\"dep_max_version_canonical_upstream\", "
      "\"dep_max_version_canonical_release\", "
      "\"dep_max_version_revision\", "
      "\"dep_max_version_iteration\", "
      "\"dep_max_version_upstream\", "
      "\"dep_max_version_release\", "
      "\"dep_min_open\", "
      "\"dep_max_open\") "
      "SELECT "
      "\"name\", "
      "\"version_epoch\", "
      "\"version_canonical_upstream\", "
      "\"version_canonical_release\", "
      "\"version_revision\", "
      "\"version_iteration\", "
      "\"dependency_index\", "
      "\"index\", "
      "0, "
      "\"dep_name\", "
      "\"dep_min_version_epoch\", "
      "\"dep_min_version_canonical_upstream\", "
      "\"dep_min_version_canonical_release\", "
      "\"dep_min_version_revision\", "
      "\"dep_min_version_iteration\", "
      "\"dep_min_version_upstream\", "
      "\"dep_min_version_release\", "
      "\"dep_max_version_epoch\", "
      "\"dep_max_version_canonical_upstream\", "
      "\"dep_max_version_canonical_release\", "
      "\"dep_max_version_revision\", "
      "\"dep_max_version_iteration\", "
      "\"dep_max_version_upstream\", "
      "\"dep_max_version_release\", "
      "\"dep_min_open\", "
      "\"dep_max_open\" "
      "FROM \"main\".\"available_package_dependency_alternatives\"");
  });

  // @@ Since there is no proper support for dropping table columns not in
  //    SQLite prior to 3.35.5 nor in ODB, we will drop the
  //    available_package_dependencies.conditional column manually. We,
  //    however, cannot do it here since ODB will try to set the dropped
  //    column values to NULL at the end of migration. Thus, we will do it
  //    ad hoc after the below schema_catalog::migrate() call.
  //
  //    NOTE: remove the mentioned ad hoc migration when removing this
  //    function.
  //
  static const migration_entry<14>
  migrate_v14 ([] (odb::database&)
  {
  });

  static inline path
  cfg_path (const dir_path& d, bool create)
  {
    path f (d / bpkg_dir / "bpkg.sqlite3");

    if (!create && !exists (f))
      fail << d << " does not look like a bpkg configuration directory";

    return f;
  }

  // The BPKG_OPEN_CONFIGS environment variable.
  //
  // Automatically set it to the configuration directory path and clear in the
  // main database constructor and destructor, respectively. Also append the
  // attached database configuration paths in their constructors and clear
  // them in detach_all(). The paths are absolute, normalized, double-quoted,
  // and separated with spaces.
  //
  static const string open_name ("BPKG_OPEN_CONFIGS");

  struct database::impl
  {
    sqlite::connection_ptr conn; // Main connection.

    map<dir_path, database> attached_map;

    impl (sqlite::connection_ptr&& c): conn (move (c)) {}
  };

  database::
  database (const dir_path& d,
            configuration* create,
            odb::tracer& tr,
            bool pre_attach,
            bool sys_rep,
            const dir_paths& pre_link,
            std::string str_repr)
      : sqlite::database (
          cfg_path (d, create != nullptr).string (),
          SQLITE_OPEN_READWRITE | (create != nullptr ? SQLITE_OPEN_CREATE : 0),
          true,                  // Enable FKs.
          "",                    // Default VFS.
          unique_ptr<sqlite::connection_factory> (
            new sqlite::serial_connection_factory)), // Single connection.
        config (normalize (d, "configuration")),
        config_orig (d),
        string (move (str_repr))
  {
    bpkg::tracer trace ("database");

    // Cache the (single) main connection we will be using.
    //
    unique_ptr<impl> ig ((impl_ = new impl (connection ())));

    try
    {
      tracer_guard tg (*this, trace);

      // Lock the database for as long as the connection is active. First we
      // set locking_mode to EXCLUSIVE which instructs SQLite not to release
      // any locks until the connection is closed. Then we force SQLite to
      // acquire the write lock by starting exclusive transaction. See the
      // locking_mode pragma documentation for details. This will also fail if
      // the database is inaccessible (e.g., file does not exist, already used
      // by another process, etc).
      //
      // Note that here we assume that any database that is ATTACHED within an
      // exclusive transaction gets the same treatment.
      //
      using odb::schema_catalog;

      impl_->conn->execute ("PRAGMA locking_mode = EXCLUSIVE");

      add_env (true /* reset */);
      auto g (make_exception_guard ([] () {unsetenv (open_name);}));

      {
        sqlite::transaction t (impl_->conn->begin_exclusive ());

        if (create != nullptr)
        {
          // Create the new schema and persist the self-link.
          //
          if (schema_version () != 0)
            fail << sqlite::database::name () << ": already has database "
                 << "schema";

          schema_catalog::create_schema (*this);

          // To speed up the query_dependents() function create the multi-
          // column index for the configuration and prerequisite columns of
          // the selected_package_prerequisites table.
          //
          // @@ Use ODB pragma if/when support for container indexes is added.
          //
          execute (
            "CREATE INDEX "
            "selected_package_prerequisites_configuration_prerequisite_i "
            "ON selected_package_prerequisites (configuration, "
            "prerequisite)");

          persist (*create); // Also assigns link id.

          // Cache the configuration information.
          //
          cache_config (create->uuid, create->name, create->type);
        }
        else
        {
          // Migrate the linked databases cluster.
          //
          migrate ();

          // Cache the configuration information.
          //
          shared_ptr<configuration> c (load<configuration> (0));
          cache_config (c->uuid, move (c->name), move (c->type));

          // Load the system repository, if requested.
          //
          if (sys_rep)
            load_system_repository ();
        }

        // Migrate the pre-linked databases and the database clusters they
        // belong to.
        //
        for (const dir_path& d: pre_link)
          attach (d).migrate ();

        t.commit ();
      }

      // Detach potentially attached during migration the (pre-)linked
      // databases.
      //
      detach_all ();

      if (pre_attach)
      {
        sqlite::transaction t (begin_exclusive ());
        attach_explicit (sys_rep);
        t.commit ();
      }
    }
    catch (odb::timeout&)
    {
      fail << "configuration " << d << " is already used by another process";
    }
    catch (const sqlite::database_exception& e)
    {
      fail << sqlite::database::name () << ": " << e.message ();
    }

    tracer (tr);

    // Note: will be leaked if anything further throws.
    //
    ig.release ();
  }

  // NOTE: if we ever load/persist any dynamically allocated objects in this
  // constructor, make sure such objects do not use the session or the session
  // is temporarily suspended in the attach() function (see its implementation
  // for the reasoning note) since the database will be moved.
  //
  database::
  database (impl* i,
            const dir_path& d,
            std::string schema,
            bool sys_rep)
      : sqlite::database (i->conn,
                          cfg_path (d, false /* create */).string (),
                          move (schema)),
        config (d),
        impl_ (i)
  {
    bpkg::tracer trace ("database");

    // Derive the configuration original directory path.
    //
    database& mdb (main_database ());

    if (mdb.config_orig.relative ())
    {
      // Fallback to absolute path if the configuration is on a different
      // drive on Windows.
      //
      if (optional<dir_path> c = config.try_relative (current_directory ()))
        config_orig = move (*c);
      else
        config_orig = config;
    }
    else
      config_orig = config;

    string = '[' + config_orig.representation () + ']';

    try
    {
      tracer_guard tg (*this, trace);

      // Cache the configuration information.
      //
      shared_ptr<configuration> c (load<configuration> (0));
      cache_config (c->uuid, move (c->name), move (c->type));

      // Load the system repository, if requested.
      //
      if (sys_rep)
        load_system_repository ();
    }
    catch (const sqlite::database_exception& e)
    {
      fail << sqlite::database::name () << ": " << e.message ();
    }

    add_env ();

    // Set the tracer used by the linked configurations cluster.
    //
    sqlite::database::tracer (mdb.tracer ());
  }

  database::
  ~database ()
  {
    if (impl_ != nullptr && // Not a moved-from database?
        main ())
    {
      delete impl_;

      unsetenv (open_name);
    }
  }

  database::
  database (database&& db)
      : sqlite::database (move (db)),
        uuid (db.uuid),
        name (move (db.name)),
        type (move (db.type)),
        config (move (db.config)),
        config_orig (move (db.config_orig)),
        string (move (db.string)),
        system_repository (move (db.system_repository)),
        impl_ (db.impl_),
        explicit_links_ (move (db.explicit_links_)),
        implicit_links_ (move (db.implicit_links_))
  {
    db.impl_ = nullptr; // See ~database().
  }

  void database::
  add_env (bool reset) const
  {
    using std::string;

    string v;

    if (!reset)
    {
      if (optional<string> e = getenv (open_name))
        v = move (*e);
    }

    v += (v.empty () ? "\"" : " \"") + config.string () + '"';

    setenv (open_name, v);
  }

  void database::
  tracer (tracer_type* t)
  {
    main_database ().sqlite::database::tracer (t);

    for (auto& db: impl_->attached_map)
      db.second.sqlite::database::tracer (t);
  }

  void database::
  migrate ()
  {
    using odb::schema_catalog;

    odb::schema_version sv  (schema_version ());
    odb::schema_version scv (schema_catalog::current_version (*this));

    if (sv != scv)
    {
      if (sv < schema_catalog::base_version (*this))
        fail << "configuration " << config_orig << " is too old";

      if (sv > scv)
        fail << "configuration " << config_orig << " is too new";

      // Note that we need to migrate the current database before the linked
      // ones to properly handle link cycles.
      //
      schema_catalog::migrate (*this);

      // Note that the potential data corruption with `DROP COLUMN` is fixed
      // in 3.35.5.
      //
      // @@ TMP Get rid of manual column dropping when ODB starts supporting
      //    that properly. Not doing so will result in failure of the below
      //    queries.
      //
      if (sqlite3_libversion_number () >= 3035005)
      {
        auto drop = [this] (const char* table, const char* column)
        {
          execute (std::string ("ALTER TABLE \"main\".") + table +
                   " DROP COLUMN \"" + column + '"');
        };

        // @@ TMP See migrate_v13() for details.
        //
        if (sv < 13)
        {
          const char* cs[] = {"dep_name",
                              "dep_min_version_epoch",
                              "dep_min_version_canonical_upstream",
                              "dep_min_version_canonical_release",
                              "dep_min_version_revision",
                              "dep_min_version_iteration",
                              "dep_min_version_upstream",
                              "dep_min_version_release",
                              "dep_max_version_epoch",
                              "dep_max_version_canonical_upstream",
                              "dep_max_version_canonical_release",
                              "dep_max_version_revision",
                              "dep_max_version_iteration",
                              "dep_max_version_upstream",
                              "dep_max_version_release",
                              "dep_min_open",
                              "dep_max_open",
                              nullptr};

          for (const char** c (cs); *c != nullptr; ++c)
            drop ("available_package_dependency_alternatives", *c);
        }

        // @@ TMP See migrate_v14() for details.
        //
        if (sv < 14)
          drop ("available_package_dependencies", "conditional");
      }

      for (auto& c: query<configuration> (odb::query<configuration>::id != 0))
      {
        dir_path d (c.effective_path (config));

        // Remove the dangling implicit link.
        //
        if (!c.expl && !exists (d))
        {
          warn << "implicit link " << c.path << " of configuration "
               << config_orig << " no longer exists, removing";

          erase (c);
          continue;
        }

        attach (d).migrate ();
      }
    }
  }

  void database::
  cache_config (const uuid_type& u, optional<std::string> n, std::string t)
  {
    // NOTE: remember to update database(database&&) if changing anything
    // here.
    //
    uuid = u;
    name = move (n);
    type = move (t);
  }

  void database::
  load_system_repository ()
  {
    assert (!system_repository); // Must only be loaded once.

    system_repository = bpkg::system_repository ();

    // Query for all the packages with the system substate and enter their
    // versions into system_repository as non-authoritative. This way an
    // available_package (e.g., a stub) will automatically "see" system
    // version, if one is known.
    //
    assert (transaction::has_current ());

    for (const auto& p: query<selected_package> (
           odb::query<selected_package>::substate == "system"))
      system_repository->insert (p.name,
                                 p.version,
                                 false /* authoritative */);
  }

  database& database::
  attach (const dir_path& d, bool sys_rep)
  {
    assert (d.absolute () && d.normalized ());

    // Check if we are trying to attach the main database.
    //
    database& md (main_database ());
    if (d == md.config)
      return md;

    auto& am (impl_->attached_map);

    auto i (am.find (d));

    if (i == am.end ())
    {
      // We know from the implementation that 4-character schema names are
      // optimal. So try to come up with a unique abbreviated hash that is 4
      // or more characters long.
      //
      std::string schema;
      {
        sha256 h (d.string ());

        for (size_t n (4);; ++n)
        {
          schema = h.abbreviated_string (n);

          if (find_if (am.begin (), am.end (),
                       [&schema] (const map<dir_path, database>::value_type& v)
                       {
                         return v.second.schema () == schema;
                       }) == am.end ())
            break;
        }
      }

      // If attaching out of an exclusive transaction (all our transactions
      // are exclusive), start one to force database locking (see the above
      // locking_mode discussion for details).
      //
      sqlite::transaction t;
      if (!sqlite::transaction::has_current ())
        t.reset (begin_exclusive ());

      try
      {
        // NOTE: we need to be careful here not to bind any persistent objects
        // the database constructor may load/persist to the temporary database
        // object in the session cache.
        //
        i = am.insert (
          make_pair (d, database (impl_, d, move (schema), sys_rep))).first;
      }
      catch (odb::timeout&)
      {
        fail << "configuration " << d << " is already used by another process";
      }

      if (!t.finalized ())
        t.commit ();
    }

    return i->second;
  }

  void database::
  detach_all ()
  {
    assert (main ());

    explicit_links_.clear ();
    implicit_links_.clear ();

    for (auto i (impl_->attached_map.begin ());
         i != impl_->attached_map.end (); )
    {
      i->second.detach ();
      i = impl_->attached_map.erase (i);
    }

    // Remove the detached databases from the environment.
    //
    add_env (true /* reset */);
  }

  void database::
  verify_link (const configuration& lc, database& ldb)
  {
    const dir_path& c (ldb.config_orig);

    if (lc.uuid != ldb.uuid)
      fail << "configuration " << c << " uuid mismatch" <<
        info << "uuid " << ldb.uuid <<
        info << (!lc.expl ? "implicitly " : "") << "linked with "
           << config_orig << " as " << lc.uuid;

    if (lc.type != ldb.type)
      fail << "configuration " << c << " type mismatch" <<
        info << "type " << ldb.type <<
        info << (!lc.expl ? "implicitly " : "") << "linked with "
           << config_orig << " as " << lc.type;

    if (lc.effective_path (config) != ldb.config)
      fail << "configuration " << c << " path mismatch" <<
        info << (!lc.expl ? "implicitly " : "") << "linked with "
           << config_orig << " as " << lc.path;
  }

  void database::
  attach_explicit (bool sys_rep)
  {
    assert (transaction::has_current ());

    if (explicit_links_.empty ())
    {
      // Note that the self-link is implicit.
      //
      explicit_links_.push_back (linked_config {0, name, *this});

      for (auto& lc: query<configuration> (odb::query<configuration>::expl))
      {
        database& db (attach (lc.effective_path (config), sys_rep));
        verify_link (lc, db);

        explicit_links_.push_back (linked_config {*lc.id, move (lc.name), db});
        db.attach_explicit (sys_rep);
      }
    }
  }

  linked_databases& database::
  implicit_links (bool attach_, bool sys_rep)
  {
    assert (transaction::has_current ());

    // Note that cached implicit links must at least contain the self-link,
    // if the databases are already attached and cached.
    //
    if (implicit_links_.empty () && attach_)
    {
      implicit_links_.push_back (*this);

      using q = odb::query<configuration>;

      for (const auto& lc: query<configuration> (q::id != 0))
      {
        dir_path d (lc.effective_path (config));

        // Skip the dangling implicit link.
        //
        if (!lc.expl && !exists (d))
        {
          if (verb > 1)
            info << "skipping dangling implicit backlink " << lc.path <<
              info << "use 'cfg-unlink --dangling' to clean up";

          continue;
        }

        database& db (attach (d, sys_rep));

        // Verify the link integrity.
        //
        verify_link (lc, db);

        // If the link is explicit, also check if it is also implicit (see
        // cfg_link() for details) and skip if it is not.
        //
        if (lc.expl)
        {
          shared_ptr<configuration> cf (backlink (db));

          if (!cf->expl)
            continue;
        }

        // If the explicitly linked databases are pre-attached, normally to
        // make the selected packages loadable, then we also pre-attach
        // explicit links of the database being attached implicitly, by the
        // same reason. Indeed, think of loading the package dependent from
        // the implicitly linked database as a selected package.
        //
        if (!explicit_links_.empty ())
          db.attach_explicit (sys_rep);

        implicit_links_.push_back (db);
      }
    }

    return implicit_links_;
  }

  shared_ptr<configuration> database::
  backlink (database& db)
  {
    using q = odb::query<configuration>;

    shared_ptr<configuration> cf (
      db.query_one<configuration> (q::uuid == uuid.string ()));

    if (cf == nullptr)
      fail << "configuration " << db.config_orig << " is linked with "
           << config_orig << " but latter is not implicitly linked "
           << "with former";

    // While at it, verify the integrity of the other end of the link.
    //
    db.verify_link (*cf, *this);
    return cf;
  }

  linked_databases database::
  dependent_configs (bool sys_rep)
  {
    linked_databases r;

    // Note that if this configuration is of a build-time dependency type
    // (host or build2) we need to be carefull during recursion and do not
    // cross the build-time dependency type boundary. So for example, for the
    // following implicit links only cfg1, cfg2, and cfg3 configurations are
    // included.
    //
    // cfg1 (this, host) -> cfg2 (host) -> cfg3 (build2) -> cfg4 (target)
    //
    // Add the linked database to the resulting list if it is of the linking
    // database type (t) or this type (t) is of the expected build-time
    // dependency type (bt).
    //
    auto add = [&r, sys_rep] (database& db,
                              const std::string& t,
                              const std::string& bt,
                              const auto& add)
    {
      if (!(db.type == t || t == bt) ||
          std::find (r.begin (), r.end (), db) != r.end ())
        return;

      r.push_back (db);

      const linked_databases& lds (db.implicit_links (true /* attach */,
                                                      sys_rep));

      // New boundary type.
      //
      const std::string& nbt (db.type == bt ? bt : empty_string);

      for (auto i (lds.begin_linked ()); i != lds.end (); ++i)
      {
        database& ldb (*i);
        add (ldb, db.type, nbt, add);

        // If this configuration is of the build2 type, then also add the
        // private host configurations of its implicitly linked
        // configurations.
        //
        if (db.type == build2_config_type)
        {
          if (database* hdb = ldb.private_config (host_config_type))
            add (*hdb, db.type, nbt, add);
        }
      }
    };

    add (*this,
         type,
         (type == host_config_type || type == build2_config_type
          ? type
          : empty_string),
         add);

    return r;
  }

  linked_databases database::
  dependency_configs (optional<bool> buildtime, const std::string& tp)
  {
    // The type only makes sense if build-time dependency configurations are
    // requested.
    //
    if (buildtime)
      assert (!*buildtime            ||
              tp == host_config_type ||
              tp == build2_config_type);
    else
      assert (tp.empty ());

    linked_databases r;

    // Allow dependency configurations of the dependent configuration own type
    // if all or runtime dependency configurations are requested.
    //
    bool allow_own_type  (!buildtime || !*buildtime);

    // Allow dependency configurations of the host type if all or regular
    // build-time dependency configurations are requested.
    //
    bool allow_host_type (!buildtime ||
                          (*buildtime && tp == host_config_type));

    // Allow dependency configurations of the build2 type if all or build2
    // module dependency configurations are requested.
    //
    bool allow_build2_type (!buildtime ||
                            (*buildtime && tp == build2_config_type));

    // Add the linked database to the resulting list if it is of the linking
    // database type and allow_own_type is true, or it is of the host type and
    // allow_host_type is true, or it is of the build2 type and
    // allow_build2_type is true. Call itself recursively for the explicitly
    // linked configurations.
    //
    // Note that the linked database of the linking database type is not added
    // if allow_own_type is false, however its own linked databases of the
    // host/build2 type are added, if allow_host_type/allow_build2_type is
    // true.
    //
    linked_databases chain; // Note: we may not add but still descend.
    auto add = [&r,
                allow_own_type,
                allow_host_type,
                allow_build2_type,
                &chain]
               (database& db,
                const std::string& t,
                const auto& add)
    {
      if (std::find (r.begin (),     r.end (),     db) != r.end () ||
          std::find (chain.begin (), chain.end (), db) != chain.end ())
        return;

      bool own    (db.type == t);
      bool host   (db.type == host_config_type);
      bool build2 (db.type == build2_config_type);

      // Bail out if we are not allowed to descend.
      //
      if (!own && !(allow_host_type && host) && !(allow_build2_type && build2))
        return;

      // Add the database to the list, if allowed, and descend afterwards.
      //
      if ((allow_own_type    && own)  ||
          (allow_host_type   && host) ||
          (allow_build2_type && build2))
        r.push_back (db);

      chain.push_back (db);

      {
        const linked_configs& lcs (db.explicit_links ());
        for (auto i (lcs.begin_linked ()); i != lcs.end (); ++i)
          add (i->db, db.type, add);
      }

      // If this is a private host configuration, then also add the parent's
      // explicitly linked configurations of the build2 type.
      //
      if (db.private_ () && db.type == host_config_type)
      {
        const linked_configs& lcs (db.parent_config ().explicit_links ());

        for (auto i (lcs.begin_linked ()); i != lcs.end (); ++i)
        {
          database& ldb (i->db);
          if (ldb.type == build2_config_type)
            add (ldb, db.type, add);
        }
      }

      chain.pop_back ();
    };

    add (*this, type, add);
    return r;
  }

  linked_databases database::
  dependency_configs (const package_name& n, bool buildtime)
  {
    return dependency_configs (buildtime,
                               (buildtime
                                ? buildtime_dependency_type (n)
                                : empty_string));
  }

  linked_databases database::
  dependency_configs ()
  {
    return dependency_configs (nullopt      /* buildtime */,
                               empty_string /* type */);
  }

  linked_databases database::
  cluster_configs (bool sys_rep)
  {
    linked_databases r;

    // If the database is not in the resulting list, then add it and its
    // dependent and dependency configurations, recursively.
    //
    auto add = [&r, sys_rep] (database& db, const auto& add)
    {
      if (std::find (r.begin (), r.end (), db) != r.end ())
        return;

      r.push_back (db);

      {
        linked_databases cs (db.dependency_configs ());
        for (auto i (cs.begin_linked ()); i != cs.end (); ++i)
          add (*i, add);
      }

      {
        linked_databases cs (db.dependent_configs (sys_rep));
        for (auto i (cs.begin_linked ()); i != cs.end (); ++i)
          add (*i, add);
      }
    };

    add (*this, add);

    return r;
  }

  database& database::
  find_attached (uint64_t id, bool s)
  {
    assert (!explicit_links_.empty ());

    // Note that there shouldn't be too many databases, so the linear search
    // is OK.
    //
    auto r (find_if (explicit_links_.begin (), explicit_links_.end (),
                     [&id] (const linked_config& lc)
                     {
                       return lc.id == id;
                     }));

    if (r == explicit_links_.end () || (!s && r == explicit_links_.begin ()))
      fail << "no configuration with id " << id << " is linked with "
           << config_orig;

    return r->db;
  }

  database& database::
  find_attached (const std::string& name, bool s)
  {
    assert (!explicit_links_.empty ());

    auto r (find_if (explicit_links_.begin (), explicit_links_.end (),
                     [&name] (const linked_config& lc)
                     {
                       return lc.name && *lc.name == name;
                     }));

    if (r == explicit_links_.end () || (!s && r == explicit_links_.begin ()))
      fail << "no configuration with name '" << name << "' is linked with "
           << config_orig;

    return r->db;
  }

  database& database::
  find_attached (const uuid_type& uid, bool s)
  {
    assert (!explicit_links_.empty ());

    auto r (find_if (explicit_links_.begin (), explicit_links_.end (),
                     [&uid] (const linked_config& lc)
                     {
                       return lc.db.get ().uuid == uid;
                     }));

    if (r == explicit_links_.end () || (!s && r == explicit_links_.begin ()))
      fail << "no configuration with uuid " << uid << " is linked with "
           << config_orig;

    return r->db;
  }

  database& database::
  find_attached (const dir_path& d, bool s)
  {
    assert (!explicit_links_.empty ());

    auto r (find_if (explicit_links_.begin (), explicit_links_.end (),
                     [&d] (const linked_config& lc)
                     {
                       return lc.db.get ().config == d;
                     }));

    if (r == explicit_links_.end () || (!s && r == explicit_links_.begin ()))
      fail << "no configuration with path " << d << " is linked with "
           << config_orig;

    return r->db;
  }

  database* database::
  try_find_dependency_config (const uuid_type& uid)
  {
    for (database& ldb: dependency_configs ())
    {
      if (uid == ldb.uuid)
        return &ldb;
    }

    return nullptr;
  }

  database& database::
  find_dependency_config (const uuid_type& uid)
  {
    if (database* db = try_find_dependency_config (uid))
      return *db;

    fail << "no configuration with uuid " << uid << " is linked with "
         << config_orig << endf;
  }

  database& database::
  parent_config (bool sys_rep)
  {
    assert (private_ ());

    dir_path pd (config.directory ().directory ()); // Parent configuration.
    const linked_databases& lds (implicit_links (true /* attach */, sys_rep));

    for (auto i (lds.begin_linked ()); i != lds.end (); ++i)
    {
      if (i->get ().config == pd)
        return *i;
    }

    // This should not happen normally and is likely to be the result of some
    // bpkg misuse.
    //
    fail << "configuration " << pd << " is not linked to its private "
         << "configuration " << config << endf;
  }

  database* database::
  private_config (const std::string& type)
  {
    assert (!explicit_links_.empty ());

    auto r (find_if (explicit_links_.begin_linked (), explicit_links_.end (),
                     [&type] (const linked_config& lc)
                     {
                       database& db (lc.db);
                       return db.private_ () && db.type == type;
                     }));

    return r != explicit_links_.end () ? &r->db.get () : nullptr;
  }

  bool database::
  main ()
  {
    return *this == main_database ();
  }

  // compare_lazy_ptr
  //
  bool compare_lazy_ptr::
  less (const odb::database& x, const odb::database& y) const
  {
    return static_cast<const database&> (x) < static_cast<const database&> (y);
  }
}