File: Swdb.cpp

package info (click to toggle)
dnf5 5.4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 17,960 kB
  • sloc: cpp: 94,312; python: 3,370; xml: 1,073; ruby: 600; sql: 250; ansic: 232; sh: 104; perl: 62; makefile: 30
file content (473 lines) | stat: -rw-r--r-- 14,836 bytes parent folder | download
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
// Copyright Contributors to the DNF5 project.
// Copyright Contributors to the libdnf project.
// SPDX-License-Identifier: LGPL-2.1-or-later
//
// This file is part of libdnf: https://github.com/rpm-software-management/libdnf/
//
// Libdnf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Libdnf 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with libdnf.  If not, see <https://www.gnu.org/licenses/>.

// TODO(dmach): probably remove most of the functionality and/or merge it into TransactionSack
// the whole file is disabled via the SKIP macro because it doesn't compile with the new code
#ifdef SKIP

#include <cstdio>
#include <filesystem>

//#include "../hy-query-private.hpp"
//#include "../hy-subject.h"
#include "libdnf5/rpm/nevra.hpp"
#include "libdnf5/rpm/package_set.hpp"
#include "libdnf5/utils/bgettext/bgettext-lib.h"
//#include "../utils/filesystem.hpp"
#include "Swdb.hpp"
#include "Transformer.hpp"
#include "rpm_package.hpp"
#include "utils/sqlite3/sqlite3.hpp"

#include "libdnf5/rpm/package_sack_impl.hpp"

namespace libdnf5::transaction {

Swdb::Swdb(libdnf5::utils::SQLite3 & conn) : conn{&conn}, autoClose(true) {}

Swdb::Swdb(libdnf5::utils::SQLite3 & conn, bool autoClose) : conn{&conn}, autoClose(autoClose) {}

Swdb::Swdb(const std::string & path) : conn(nullptr), autoClose(true) {
    if (path == ":memory:") {
        // writing to an in-memory database
        conn = new libdnf5::utils::SQLite3(path);
        Transformer::createDatabase(*conn);
    } else if (!std::filesystem::exists(path.c_str())) {
        // writing to a file that doesn't exist and must be created

        // extract persistdir from path - "/var/lib/dnf/"
        auto found = path.find_last_of("/");

        Transformer transformer(path.substr(0, found), path);
        transformer.transform();

        conn = new libdnf5::utils::SQLite3(path);
    } else {
        // writing to an existing file
        conn = new libdnf5::utils::SQLite3(path);
    }
}

void Swdb::resetDatabase() {
    conn->close();
    if (std::filesystem::exists(getPath().c_str())) {
        remove(getPath().c_str());
    }
    conn->open();
    Transformer::createDatabase(get_connection());
}

void Swdb::closeDatabase() {
    conn->close();
}

Swdb::~Swdb() {
    if (autoClose) {
        try {
            closeDatabase();
        } catch (const std::exception &) {
        }
    }
}

void Swdb::initTransaction() {
    if (transactionInProgress) {
        throw std::logic_error(_("In progress"));
    }
    transactionInProgress = std::unique_ptr<Transaction>(new Transaction(get_connection()));
    itemsInProgress.clear();
}

int64_t Swdb::beginTransaction(int64_t dtStart, std::string rpmdbVersionBegin, std::string cmdline, uint32_t userId) {
    if (!transactionInProgress) {
        throw std::logic_error(_("Not in progress"));
    }

    // begin transaction
    transactionInProgress->set_dt_start(dtStart);
    transactionInProgress->set_rpmdb_version_begin(rpmdbVersionBegin);
    transactionInProgress->set_cmdline(cmdline);
    transactionInProgress->set_user_id(userId);
    transactionInProgress->begin();

    /*
    // save rpm items to map to resolve RPM callbacks
    for (auto item : transactionInProgress->getItems()) {
        auto transItem = item->getItem();
        if (transItem->getItemType() != TransactionItemType::RPM) {
            continue;
        }
        auto rpmItem = std::dynamic_pointer_cast< Package >(transItem);
        itemsInProgress[rpmItem->toStr()] = item;
    }
    */

    return transactionInProgress->get_id();
}

int64_t Swdb::endTransaction(int64_t dtEnd, std::string rpmdbVersionEnd, TransactionState state) {
    if (!transactionInProgress) {
        throw std::logic_error(_("Not in progress"));
    }
    transactionInProgress->set_dt_end(dtEnd);
    transactionInProgress->set_rpmdb_version_end(rpmdbVersionEnd);
    transactionInProgress->finish(state);
    return transactionInProgress->get_id();
}

int64_t Swdb::closeTransaction() {
    if (!transactionInProgress) {
        throw std::logic_error(_("Not in progress"));
    }
    int64_t result = transactionInProgress->get_id();
    transactionInProgress = std::unique_ptr<Transaction>(nullptr);
    itemsInProgress.clear();
    return result;
}


TransactionItemPtr Swdb::addItem(
    std::shared_ptr<Item> item, const std::string & repoid, TransactionItemAction action, TransactionItemReason reason)
//            std::shared_ptr<TransactionItem> replacedBy)
{
    if (!transactionInProgress) {
        throw std::logic_error(_("Not in progress"));
    }
    // auto replacedBy = std::make_shared<TransactionItem>(nullptr);
    return transactionInProgress->addItem(item, repoid, action, reason);
}

void Swdb::setItemDone(const std::string & nevra) {
    if (!transactionInProgress) {
        throw std::logic_error(_("No transaction in progress"));
    }
    auto item = itemsInProgress[nevra];
    item->set_state(TransactionItemState::DONE);
    //item->saveState();
}

TransactionItemReason Swdb::resolveRPMTransactionItemReason(
    const std::string & name, const std::string & arch, int64_t maxTransactionId) {
    // TODO:
    // -1: latest
    // -2: latest and lastTransaction data in memory
    /*
    if (maxTransactionId == -2 && transactionInProgress != nullptr) {
        for (auto i : transactionInProgress->getItems()) {
            auto rpm = std::dynamic_pointer_cast< Package >(i->getItem());
            if (!rpm) {
                continue;
            }
            if (rpm->get_name() == name && rpm->get_arch() == arch) {
                return i->get_reason();
            }
        }
    }
    */

    return Package::resolveTransactionItemReason(get_connection(), name, arch, maxTransactionId);
}

const std::string Swdb::getRPMRepo(const std::string & nevra) {
    libdnf5::rpm::Nevra nevraObject;
    if (!nevraObject.parse(nevra.c_str(), libdnf5::rpm::Nevra::Form::NEVRA)) {
        return "";
    }
    // TODO: hy_nevra_possibility should set epoch to 0 if epoch is not specified
    // and libdnf5::rpm::Nevra::Form::NEVRA is used
    if (nevraObject.get_epoch().empty()) {
        nevraObject.set_epoch(0);
    }

    const char * sql = R"**(
        SELECT
            repo.repoid as repoid
        FROM
            trans_item ti
        JOIN
            rpm USING (item_id)
        JOIN
            repo ON ti.repo_id == repo.id
        WHERE
            ti.action not in (3, 5, 7, 10)
            AND rpm.name = ?
            AND rpm.epoch = ?
            AND rpm.version = ?
            AND rpm.release = ?
            AND rpm.arch = ?
        ORDER BY
            ti.id DESC
        LIMIT 1;
    )**";
    // TODO: where trans.done != 0
    libdnf5::utils::SQLite3::Query query(*conn, sql);
    query.bindv(
        nevraObject.get_name(),
        nevraObject.get_epoch(),
        nevraObject.get_version(),
        nevraObject.get_release(),
        nevraObject.get_arch());
    if (query.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
        auto repoid = query.get<std::string>("repoid");
        return repoid;
    }
    return "";
}

TransactionPtr Swdb::getLastTransaction() {
    const char * sql = R"**(
        SELECT
            id
        FROM
            trans
        ORDER BY
            id DESC
        LIMIT 1
    )**";
    libdnf5::utils::SQLite3::Statement query(get_connection(), sql);
    if (query.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
        auto transId = query.get<int64_t>(0);
        auto transaction = std::make_shared<Transaction>(get_connection(), transId);
        return transaction;
    }
    return nullptr;
}

std::vector<TransactionPtr> Swdb::listTransactions() {
    const char * sql = R"**(
        SELECT
            id
        FROM
            trans
        ORDER BY
            id
    )**";
    libdnf5::utils::SQLite3::Statement query(get_connection(), sql);
    std::vector<TransactionPtr> result;
    while (query.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
        auto transId = query.get<int64_t>(0);
        auto transaction = std::make_shared<Transaction>(get_connection(), transId);
        result.push_back(transaction);
    }
    return result;
}

void Swdb::setReleasever(std::string value) {
    if (!transactionInProgress) {
        throw std::logic_error(_("Not in progress"));
    }
    transactionInProgress->set_releasever(value);
}


void Swdb::add_console_output_line(int file_descriptor, const std::string & line) {
    if (!transactionInProgress) {
        throw std::logic_error(_("Not in progress"));
    }
    transactionInProgress->add_console_output_line(file_descriptor, line);
}

/*
std::vector< TransactionItemPtr >
Swdb::getCompsGroupItemsByPattern(const std::string &pattern)
{
    return CompsGroupItem::getTransactionItemsByPattern(conn, pattern);
}
*/

std::vector<std::string> Swdb::getPackageCompsGroups(const std::string & packageName) {
    const char * sql_all_groups = R"**(
        SELECT DISTINCT
            g.groupid
        FROM
            comps_group g
        JOIN
            comps_group_package p ON p.group_id = g.item_id
        WHERE
            p.name = ?
            AND p.installed = 1
        ORDER BY
            g.groupid
    )**";

    const char * sql_trans_items = R"**(
        SELECT
            ti.action as action,
            ti.reason as reason,
            i.item_id as group_id
        FROM
            trans_item ti
        JOIN
            comps_group i USING (item_id)
        JOIN
            trans t ON ti.trans_id = t.id
        WHERE
            t.state = 1
            AND ti.action not in (3, 5, 7)
            AND i.groupid = ?
        ORDER BY
            ti.trans_id DESC
        LIMIT 1
    )**";

    const char * sql_group_package = R"**(
        SELECT
            p.name
        FROM
            comps_group_package p
        WHERE
            p.group_id = ?
            AND p.installed = 1
    )**";

    std::vector<std::string> result;

    // list all relevant groups
    libdnf5::utils::SQLite3::Query query_all_groups(*conn, sql_all_groups);
    query_all_groups.bindv(packageName);

    while (query_all_groups.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
        auto groupid = query_all_groups.get<std::string>("groupid");
        libdnf5::utils::SQLite3::Query query_trans_items(*conn, sql_trans_items);
        query_trans_items.bindv(groupid);
        if (query_trans_items.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
            auto action = static_cast<TransactionItemAction>(query_trans_items.get<int64_t>("action"));
            // if the last record is group removal, skip
            if (action == TransactionItemAction::REMOVE) {
                continue;
            }
            auto groupId = query_trans_items.get<int64_t>("group_id");
            libdnf5::utils::SQLite3::Query query_group_package(*conn, sql_group_package);
            query_group_package.bindv(groupId);
            if (query_group_package.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
                result.push_back(groupid);
            }
        }
    }
    return result;
}

std::vector<std::string> Swdb::getCompsGroupEnvironments(const std::string & groupId) {
    const char * sql_all_environments = R"**(
        SELECT DISTINCT
            e.environmentid
        FROM
            comps_environment e
        JOIN
            comps_environment_group g ON g.environment_id = e.item_id
        WHERE
            g.groupid = ?
            AND g.installed = 1
        ORDER BY
            e.environmentid
    )**";

    const char * sql_trans_items = R"**(
        SELECT
            ti.action as action,
            ti.reason as reason,
            i.item_id as environment_id
        FROM
            trans_item ti
        JOIN
            comps_environment i USING (item_id)
        JOIN
            trans t ON ti.trans_id = t.id
        WHERE
            t.state = 1
            AND ti.action not in (3, 5, 7)
            AND i.environmentid = ?
        ORDER BY
            ti.trans_id DESC
        LIMIT 1
    )**";

    const char * sql_environment_group = R"**(
        SELECT
            g.groupid
        FROM
            comps_environment_group g
        WHERE
            g.environment_id = ?
            AND g.installed = 1
    )**";

    std::vector<std::string> result;

    // list all relevant groups
    libdnf5::utils::SQLite3::Query query_all_environments(*conn, sql_all_environments);
    query_all_environments.bindv(groupId);

    while (query_all_environments.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
        auto envid = query_all_environments.get<std::string>("environmentid");
        libdnf5::utils::SQLite3::Query query_trans_items(*conn, sql_trans_items);
        query_trans_items.bindv(envid);
        if (query_trans_items.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
            auto action = static_cast<TransactionItemAction>(query_trans_items.get<int64_t>("action"));
            // if the last record is group removal, skip
            if (action == TransactionItemAction::REMOVE) {
                continue;
            }
            auto envId = query_trans_items.get<int64_t>("environment_id");
            libdnf5::utils::SQLite3::Query query_environment_group(*conn, sql_environment_group);
            query_environment_group.bindv(envId);
            if (query_environment_group.step() == libdnf5::utils::SQLite3::Statement::StepResult::ROW) {
                result.push_back(envid);
            }
        }
    }
    return result;
}


/*
std::vector< TransactionItemPtr >
Swdb::getCompsEnvironmentItemsByPattern(const std::string &pattern)
{
    return CompsEnvironmentItem::getTransactionItemsByPattern(conn, pattern);
}
*/

/*
PackagePtr
Swdb::createPackage()
{
    return std::make_shared< Package >(conn);
}

CompsEnvironmentItemPtr
Swdb::createCompsEnvironmentItem()
{
    return std::make_shared< CompsEnvironmentItem >(conn);
}

CompsGroupItemPtr
Swdb::createCompsGroupItem()
{
    return std::make_shared< CompsGroupItem >(conn);
}
*/

std::vector<int64_t> Swdb::searchTransactionsByRPM(const std::vector<std::string> & patterns) {
    return Package::searchTransactions(get_connection(), patterns);
}

}  // namespace libdnf5::transaction

#endif