<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of signon
 *
 * Copyright (C) 2011 Canonical Ltd.
 *
 * Contact: <NAME> <<EMAIL>>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "default-secrets-storage.h"
#include "signond-common.h"

#define RETURN_IF_NOT_OPEN(retval) \
    if (!isOpen()) { \
        TRACE() << "Secrets DB is not available"; \
        SignOn::CredentialsDBError error(QLatin1String("Not open"), \
                                         SignOn::CredentialsDBError::NotOpen); \
        setLastError(error); return retval; \
    }

#define S(s) QLatin1String(s)

using namespace SignonDaemonNS;

bool SecretsDB::createTables()
{
    QStringList createTableQuery = QStringList()
        <<  QString::fromLatin1(
            "CREATE TABLE CREDENTIALS"
            "(id INTEGER NOT NULL UNIQUE,"
            "username TEXT,"
            "password TEXT,"
            "PRIMARY KEY (id))")
        <<  QString::fromLatin1(
            "CREATE TABLE STORE"
            "(identity_id INTEGER,"
            "method_id INTEGER,"
            "key TEXT,"
            "value BLOB,"
            "PRIMARY KEY (identity_id, method_id, key))")

        << QString::fromLatin1(
            // Cascading Delete
            "CREATE TRIGGER tg_delete_credentials "
            "BEFORE DELETE ON CREDENTIALS "
            "FOR EACH ROW BEGIN "
            "    DELETE FROM STORE WHERE STORE.identity_id = OLD.id; "
            "END; "
        );

   foreach (QString createTable, createTableQuery) {
        QSqlQuery query = exec(createTable);
        if (lastError().isValid()) {
            TRACE() << "Error occurred while creating the database.";
            return false;
        }
        query.clear();
        commit();
    }
    return true;
}

bool SecretsDB::clear()
{
    TRACE();

    QStringList clearCommands = QStringList()
        << QLatin1String("DELETE FROM CREDENTIALS")
        << QLatin1String("DELETE FROM STORE");

    return transactionalExec(clearCommands);
}

bool SecretsDB::updateCredentials(const quint32 id,
                                  const QString &username,
                                  const QString &password)
{
    if (!startTransaction()) {
        TRACE() << "Could not start transaction. Error inserting credentials.";
        return false;
    }
    QSqlQuery query = newQuery();
    /* The identity might not be new and have no secret info stored at
     * the same time - e.g. if the secrets db has been deleted */
    bool hasSecretInfoStored = false;
    QString queryStr = QString::fromLatin1(
        "SELECT id FROM credentials WHERE id = %1").arg(id);

    QSqlQuery selectQuery = exec(queryStr);
    if (selectQuery.first())
        hasSecretInfoStored = true;

    if (hasSecretInfoStored) {
        TRACE() << "UPDATE:" << id;
        query.prepare(S("UPDATE CREDENTIALS SET username = :username, "
                        "password = :password "
                        "WHERE id = :id"));

     } else {
        TRACE() << "INSERT:" << id;
        query.prepare(S("INSERT OR REPLACE INTO CREDENTIALS "
                        "(id, username, password) "
                        "VALUES(:id, :username, :password)"));
    }

    query.bindValue(S(":id"), id);
    query.bindValue(S(":username"), username);
    query.bindValue(S(":password"), password);

    exec(query);

    if (errorOccurred()) {
        rollback();
        TRACE() << "Error occurred while storing crendentials";<commit_msg>Simplify updateCredentials()<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of signon
 *
 * Copyright (C) 2011 Canonical Ltd.
 *
 * Contact: <NAME> <<EMAIL>>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "default-secrets-storage.h"
#include "signond-common.h"

#define RETURN_IF_NOT_OPEN(retval) \
    if (!isOpen()) { \
        TRACE() << "Secrets DB is not available"; \
        SignOn::CredentialsDBError error(QLatin1String("Not open"), \
                                         SignOn::CredentialsDBError::NotOpen); \
        setLastError(error); return retval; \
    }

#define S(s) QLatin1String(s)

using namespace SignonDaemonNS;

bool SecretsDB::createTables()
{
    QStringList createTableQuery = QStringList()
        <<  QString::fromLatin1(
            "CREATE TABLE CREDENTIALS"
            "(id INTEGER NOT NULL UNIQUE,"
            "username TEXT,"
            "password TEXT,"
            "PRIMARY KEY (id))")
        <<  QString::fromLatin1(
            "CREATE TABLE STORE"
            "(identity_id INTEGER,"
            "method_id INTEGER,"
            "key TEXT,"
            "value BLOB,"
            "PRIMARY KEY (identity_id, method_id, key))")

        << QString::fromLatin1(
            // Cascading Delete
            "CREATE TRIGGER tg_delete_credentials "
            "BEFORE DELETE ON CREDENTIALS "
            "FOR EACH ROW BEGIN "
            "    DELETE FROM STORE WHERE STORE.identity_id = OLD.id; "
            "END; "
        );

   foreach (QString createTable, createTableQuery) {
        QSqlQuery query = exec(createTable);
        if (lastError().isValid()) {
            TRACE() << "Error occurred while creating the database.";
            return false;
        }
        query.clear();
        commit();
    }
    return true;
}

bool SecretsDB::clear()
{
    TRACE();

    QStringList clearCommands = QStringList()
        << QLatin1String("DELETE FROM CREDENTIALS")
        << QLatin1String("DELETE FROM STORE");

    return transactionalExec(clearCommands);
}

bool SecretsDB::updateCredentials(const quint32 id,
                                  const QString &username,
                                  const QString &password)
{
    if (!startTransaction()) {
        TRACE() << "Could not start transaction. Error inserting credentials.";
        return false;
    }
    QSqlQuery query = newQuery();

    TRACE() << "INSERT:" << id;
    query.prepare(S("INSERT OR REPLACE INTO CREDENTIALS "
                    "(id, username, password) "
                    "VALUES(:id, :username, :password)"));

    query.bindValue(S(":id"), id);
    query.bindValue(S(":username"), username);
    query.bindValue(S(":password"), password);

    exec(query);

    if (errorOccurred()) {
        rollback();
        TRACE() << "Error occurred while storing crendentials";
{'fraction_non_alphanumeric': 0.11096622766983961, 'fraction_numerical': 0.007302125440083453, 'mean_word_length': 2.291845493562232, 'pattern_counts': {'":': 6, '<': 57, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2543734', 'n_tokens_mistral': 2169, 'n_tokens_neox': 2067, 'n_words': 666}