bool TSqlTransaction::begin(QSqlDatabase &database)
{
    if (!database.isValid()) {
        tSystemError("Can not begin transaction. Invalid database: %s", qPrintable(database.connectionName()));
        return false;
    }

    if (!enabled)
        return true;
    
    bool ok;
    int id = database.connectionName().left(2).toInt(&ok);
    
    if (!ok || id < 0 || id >= databases.count()) {
        tSystemError("Internal Error  [%s:%d]", __FILE__, __LINE__);
        return false;
    }
    
    if (databases[id].isValid()) {
        tSystemWarn("Has begun transaction already. database:%s", qPrintable(database.connectionName()));
        return true;
    }

    if (database.transaction()) {
        tQueryLog("[BEGIN] [databaseId:%d]", id);
    }

    databases[id] = database;
    return true;
}
예제 #2
1
    QSqlDatabaseWrapper(const DatabaseInfo &info)
        : m_open(false)
    {
        m_connectionName =
            "kactivities_db_resources_"
            // Adding the thread number to the database name
            + QString::number((quintptr)info.thread)
            // And whether it is read-only or read-write
            + (info.openMode == Database::ReadOnly ? "_readonly" : "_readwrite");

        m_database =
            QSqlDatabase::contains(m_connectionName)
            ? QSqlDatabase::database(m_connectionName)
            : QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), m_connectionName);

        if (info.openMode == Database::ReadOnly) {
            m_database.setConnectOptions(QStringLiteral("QSQLITE_OPEN_READONLY"));
        }

        // We are allowing the database file to be overridden mostly for testing purposes
        m_database.setDatabaseName(ResourcesDatabaseSchema::path());

        m_open = m_database.open();

        if (!m_open) {
            qWarning() << "KActivities: Database is not open: "
                       << m_database.connectionName()
                       << m_database.databaseName()
                       << m_database.lastError();

            if (info.openMode == Database::ReadWrite) {
                qFatal("KActivities: Opening the database in RW mode should always succeed");
            }
        }
    }
bool FrenchZipCodesStep::populateDatabase()
{
    Q_EMIT progressLabelChanged(tr("Reading raw sources..."));
    Q_EMIT progressRangeChanged(0, 1);
    Q_EMIT progress(0);

    // import the raw source in memory
    createDatabase();
    QSqlDatabase db = QSqlDatabase::database(DB_NAME);

    if (!db.tables().contains("ZIPS_IMPORT")) {
        Utils::Database::executeSqlFile(DB_NAME, sqlImportFileAbsPath());
    }

    if (!Utils::Database::importCsvToDatabase(DB_NAME, csvFileAbsPath(), "ZIPS_IMPORT", ";", true))
        return false;

    Q_EMIT progressLabelChanged(tr("Reading raw sources..."));
    Q_EMIT progress(1);

    // create the new database
    QString req;

    // remove alread recorded french codes
    req = "DELETE FROM `ZIPS` WHERE `ZIPS`.`COUNTRY`='fr';";
    Utils::Database::executeSQL(req, db);

    // OLD table: import new french codes
    // 4 chars
//    select * from zips where length(ZIP)>5;
//    select substr('00000' || ZIP, -5, 5) from ZIPS where zip like'14%';
    req = "INSERT INTO `ZIPS` (`ZIP`,`CITY`,`EXTRACODE`, `COUNTRY`) \n"
          "SELECT substr('00000' || ZIP, -5, 5), `COMMUNE`, `CODEINSEE`, 'fr' FROM `ZIPS_IMPORT` WHERE LENGTH(ZIP)=4 ORDER BY `ZIP`;";
    Utils::Database::executeSQL(req, db);
    // 5 chars
    req = "INSERT INTO `ZIPS` (`ZIP`,`CITY`,`EXTRACODE`, `COUNTRY`) \n"
          "SELECT substr(`ZIP`, 1, 5) , `COMMUNE`, `CODEINSEE`, 'fr' FROM `ZIPS_IMPORT` WHERE LENGTH(ZIP)>=5 ORDER BY `ZIP`;";
    Utils::Database::executeSQL(req, db);

    // clean database
    req = "DROP TABLE ZIPS_IMPORT;";
    Utils::Database::executeSQL(req, db);
    Utils::Database::vacuum(db.connectionName());

    // NEW table: import new french codes
    req = "DELETE FROM `IMPORT`";
    Utils::Database::executeSQL(req, db);
    req = "INSERT INTO `IMPORT` (`ZIP`,`CITY`,`ADMIN_CODE1`, `COUNTRY`) \n"
          "SELECT `ZIP`, `CITY`, `EXTRACODE`, 'FR' FROM `ZIPS`;";
    Utils::Database::executeSQL(req, db);

    // Add version
    setDatabaseVersion(db.connectionName(), QString(PACKAGE_VERSION), QDate::currentDate());

    LOG(QString("Database processed"));

    return true;
}
예제 #4
0
static v8::Handle<v8::Value> qmlsqldatabase_changeVersion(const v8::Arguments& args)
{
    if (args.Length() < 2)
        return v8::Undefined();

    QV8SqlDatabaseResource *r = v8_resource_cast<QV8SqlDatabaseResource>(args.This());
    if (!r || r->type != QV8SqlDatabaseResource::Database)
        V8THROW_REFERENCE("Not a SQLDatabase object");

    QV8Engine *engine = r->engine;

    QSqlDatabase db = r->database;
    QString from_version = engine->toString(args[0]);
    QString to_version = engine->toString(args[1]);
    v8::Handle<v8::Value> callback = args[2];

    if (from_version != r->version)
        V8THROW_SQL(SQLEXCEPTION_VERSION_ERR, QQmlEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(r->version));

    v8::Local<v8::Object> instance = databaseData(engine)->queryConstructor->NewInstance();
    QV8SqlDatabaseResource *r2 = new QV8SqlDatabaseResource(engine);
    r2->type = QV8SqlDatabaseResource::Query;
    r2->database = db;
    r2->version = r->version;
    r2->inTransaction = true;
    instance->SetExternalResource(r2);

    bool ok = true;
    if (callback->IsFunction()) {
        ok = false;
        db.transaction();

        v8::TryCatch tc;
        v8::Handle<v8::Value> callbackArgs[] = { instance };
        v8::Handle<v8::Function>::Cast(callback)->Call(engine->global(), 1, callbackArgs);

        if (tc.HasCaught()) {
            db.rollback();
            tc.ReThrow();
            return v8::Handle<v8::Value>();
        } else if (!db.commit()) {
            db.rollback();
            V8THROW_SQL(SQLEXCEPTION_UNKNOWN_ERR,QQmlEngine::tr("SQL transaction failed"));
        } else {
            ok = true;
        }
    }

    r2->inTransaction = false;

    if (ok) {
        r2->version = to_version;
#ifndef QT_NO_SETTINGS
        QSettings ini(qmlsqldatabase_databaseFile(db.connectionName(),engine) + QLatin1String(".ini"), QSettings::IniFormat);
        ini.setValue(QLatin1String("Version"), to_version);
#endif
    }

    return v8::Undefined();
}
예제 #5
0
QString QSqlDatabaseProto::connectionName()   const
{
  QSqlDatabase *item = qscriptvalue_cast<QSqlDatabase*>(thisObject());
  if (item)
    return item->connectionName();
  return QString();
}
예제 #6
0
RoomQueryModel::RoomQueryModel(const QVariantMap &columnLabels, QSqlDatabase db,
                               QObject *parent)
    : RefreshableSqlQueryModel(QUERY, db.connectionName(), parent) {
    const auto &rec = record();
    for (auto i = 0; i < rec.count(); i++) {
        setHeaderData(i, Qt::Horizontal, columnLabels[rec.fieldName(i)]);
    }
}
예제 #7
0
SqlQuery::SqlQuery(const QString &query /*= QString()*/, const QSqlDatabase& db /*= QSqlDatabase()*/ ) :
    QSqlQuery( db ), m_db( db )
{
    m_connectionName = db.connectionName();

    SqlQueryManager::instance()->registerQuery(this);
    if ( !query.isEmpty() )
        exec( query );
}
예제 #8
0
QString QSqlDatabaseProto::connectionName()   const
{
  QSqlDatabase *item = qscriptvalue_cast<QSqlDatabase*>(thisObject());
  if (item)
    return item->connectionName();
  else if (! thisObject().isNull())
    return thisObject().toVariant().value<QSqlDatabase>().connectionName();
  return QString();
}
/**
 * Inject icd10 downloaded files data into the SQLite database.
 * You must create the database first.
 * \sa createDatabase()
 */
bool Icd10Step::populateDatabaseWithRawSources()
{
    qWarning() << "populate ICD10 database";
    QStringList files;
    files
            << "CHAPTER"
            << "COMMON"
            << "DAGSTAR"
            << "DESCR"
            << "DESCRLIB"
            << "EXCLUDE"
            //            << "FIELDDEF"
            << "GLOSSAIRE"
            //            << "HTML"
            << "INCLUDE"
            << "INDIR"
            << "LIBELLE"
            << "MASTER"
            << "MEMO"
            << "NOTE"
            << "REFER"
            << "SYSTEM"
//            << "TABLE"
            << "VERSION"
            ;
//    if (!m_Progress) {
//        m_Progress = new QProgressDialog(tr("Populating database"), tkTr(Trans::Constants::CANCEL), 0, files.count() +1);
//    } else {
//        m_Progress->setRange(0, files.count() +1);
//    }
//    m_Progress->setValue(1);

    // Check database connection
    QSqlDatabase DB = QSqlDatabase::database(d->_connection);
    if (!DB.isOpen()) {
        if (!DB.open()) {
            LOG_ERROR(tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                 .arg(DB.connectionName()).arg(DB.lastError().text()));
            return false;
        }
    }

    // Convert downloaded files from ISO 8859-1 to UTF-8, then import them to the database
    QString path = d->_tmpPath + "/Exp_text/";
    foreach(const QString &file, files) {
        QString content;
        // Convert file
        content = Utils::readTextFile(path + file + ".txt", "ISO 8859-1", Utils::DontWarnUser);
        Utils::saveStringToFile(content, path + file + "-utf8.txt", Utils::Overwrite, Utils::DontWarnUser);
        // import files
        if (!Utils::Database::importCsvToDatabase(d->_connection, path + file + "-utf8.txt", file.toLower(), "¦", true)) {
            LOG_ERROR("Unable to import CSV data to database");
            continue;
        }
    }
예제 #10
0
파일: clientdb.cpp 프로젝트: abomb4/biye
bool createDB(const QString &path) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(path);
    if (!db.open()) {
        return false;
    }
    bool r;
    QSqlQuery query(db);
    r = query.exec("create table `fx_user` ("
        "`id` integer primary key,"
        "`name` varchar(32) not null unique,"
        "`email` varchar(32),"
        "`true_name` varchar(16),"
        "`department` integer not null,"
        "`icon` text,"
        "`status` int(1) not null default 1,"
        "`gmt_create` datetime not null,"
        "`gmt_modify` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_department` ("
        "`id` integer primary key,"
        "`parent_id` integer not null default 0,"
        "`name` varchar(32) not null,"
        "`gmt_create` datetime not null,"
        "`gmt_modify` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_chatlog` ("
        "`id` integer primary key,"
        "`sourceid` integer not null,"
        "`targetid` integer not null,"
        "`type` int(1) not null,"
        "`msg` text,"
        "`gmt_create` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_recent_contact` ("
        "`userid` integer not null,"
        "`contactid` integer not null,"
        "`last_time` datetime not null,"
        "constraint pk_recent primary key (userid, contactid)"
        ");");if (!r)return r;

    r = query.exec("create table `status` ("
        "`key` varchar(64) not null primary key,"
        "`value` varchar(255) not null default ''"
        ");");if (!r) return r;

    r = query.exec("insert into `status` values"
        "('last_user_update_time', ''),"
        "('last_department_update_time', ''),"
        "('last_user_name', '');");if (!r) return r;

    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
    return true;
}
예제 #11
0
static inline bool connectDatabase(QSqlDatabase DB, const int line)
{
    if (!DB.isOpen()) {
        if (!DB.open()) {
            Utils::Log::addError("GuardBase", tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                 .arg(DB.connectionName()).arg(DB.lastError().text()), __FILE__, line);
            return false;
        }
    }
    return true;
}
예제 #12
0
static QString qDBCaption(const QSqlDatabase &db)
{
//    QString nm = "DB:";
//    nm.append(db.connectionName());
//    nm.append(QLatin1Char(':'));
//    if (!db.userName().isEmpty())
//        nm.append(db.userName()).append(QLatin1Char('@'));
//    nm.append(db.databaseName());
    QString nm = db.connectionName();
    return nm;
}
예제 #13
0
파일: Utils.cpp 프로젝트: erikku/frosty
QStringList cache_columns(const QString& table, const QSqlDatabase& db)
{
	static QMap<QString, QMap<QString, QStringList> > master_cache;

	QMap<QString, QStringList> cache = master_cache.value(
		db.connectionName() );

	if( cache.contains(table) )
		return cache.value(table);

	QString sql;
	if(db.driverName() == "QMYSQL")
		sql = QString("DESCRIBE %1").arg(table);
	else // SQLite
		sql = QString("PRAGMA table_info(%1)").arg(table);

	QSqlQuery query(sql, db);
	if( !query.exec() )
		return QStringList();

	QStringList list;
	if(db.driverName() == "QMYSQL")
	{
		while( query.next() )
			list << query.record().value("Field").toString();
	}
	else // SQLite
	{
		while( query.next() )
			list << query.value(1).toString();
	}


	// Save the column info to the cache
	cache[table] = list;

	// Save the cache to the master cache (map of database connections)
	master_cache[db.connectionName()] = cache;

	return list;
}
static inline bool connectDatabase(QSqlDatabase &DB, const QString &file, const int line)
{
    if (!DB.isOpen()) {
        if (!DB.open()) {
            Utils::Log::addError("DrugBaseEssentials", tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                 .arg(DB.connectionName()).arg(DB.lastError().text()),
                                 file, line);
            return false;
        }
    }
    return true;
}
예제 #15
0
static QScriptValue qmlsqldatabase_change_version(QScriptContext *context, QScriptEngine *engine)
{
    if (context->argumentCount() < 2)
        return engine->undefinedValue();

    QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject());
    QString from_version = context->argument(0).toString();
    QString to_version = context->argument(1).toString();
    QScriptValue callback = context->argument(2);

    QScriptValue instance = engine->newObject();
    instance.setProperty(QLatin1String("executeSql"), engine->newFunction(qmlsqldatabase_executeSql,1));
    QScriptValue tx = engine->newVariant(instance,QVariant::fromValue(db));

    QString foundvers = context->thisObject().property(QLatin1String("version")).toString();
    if (from_version!=foundvers) {
        THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(foundvers));
        return engine->undefinedValue();
    }

    bool ok = true;
    if (callback.isFunction()) {
        ok = false;
        db.transaction();
        callback.call(QScriptValue(), QScriptValueList() << tx);
        if (engine->hasUncaughtException()) {
            db.rollback();
        } else {
            if (!db.commit()) {
                db.rollback();
                THROW_SQL(UNKNOWN_ERR,QDeclarativeEngine::tr("SQL transaction failed"));
            } else {
                ok = true;
            }
        }
    }

    if (ok) {
        context->thisObject().setProperty(QLatin1String("version"), to_version, QScriptValue::ReadOnly);
#ifndef QT_NO_SETTINGS
        QSettings ini(qmlsqldatabase_databaseFile(db.connectionName(),engine) + QLatin1String(".ini"), QSettings::IniFormat);
        ini.setValue(QLatin1String("Version"), to_version);
#endif
    }

    return engine->undefinedValue();
}
예제 #16
0
bool MusicUserWindow::disConnectDatabase()
{
    QString connectionName;
    {
        QSqlDatabase data = QSqlDatabase::database("user-data");
        connectionName = data.connectionName();
        if( data.isValid() )
        {
            data.close();
        }
        else
        {
            return false;
        }
    }
    QSqlDatabase::removeDatabase( connectionName );
    return true;
}
예제 #17
0
void DBConnector::ConnectToDB()
{
    if (!CanConnectToDB())
        return;

    ProgSettings sett;


    if (QSqlDatabase::database().isValid() && QSqlDatabase::database().isOpen())
    {
        QSqlDatabase::database().close();
        QSqlDatabase::removeDatabase(QSqlDatabase::database().connectionName());
    }

    QSqlDatabase db = QSqlDatabase::addDatabase(sett.DBType());

    db.setDatabaseName(sett.DBName());

    if (sett.DBType() != "QSQLITE")
    {
        db.setHostName(sett.DBHostName());
        db.setUserName(sett.DBUserName());
        db.setPassword(sett.DBPassword());
        db.setPort(sett.DBPort());
    }

    if (db.open())
        qDebug() << QString("Open connection '%1'").arg(db.connectionName());

        if (db.lastError().isValid())
        {
            qDebug() << db.lastError().text();

            QMessageBox::critical(0,tr(""),tr("ќшибка соединени¤ с базой данных: %1").arg(db.lastError().text()),QMessageBox::Ok);

        }
}
예제 #18
0
void podcast::xmlAddToDB() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("podcasts.db");

    if(db.open() == true)  {
        QSqlQuery query(db);
        QString queryString;

        //checking if podcast allready exists
        queryString = "select * from podcasts";
        query.exec(queryString);

        bool podcastExists = false;

        while(query.next() == true && podcastExists == false) {
            if(query.value(1).toString() == name)  {
                podcastExists = true;
                id = query.value(0).toInt();
            }
        }

        //if podcast allready exist; updates
        if(podcastExists == true)   {
            qDebug() << "podcast exists, updates";

            //loops through all episodes, compares with title variable
            for(int i = 0; i < episodes.size(); i++)    {
                queryString = "select * from episodes where title = :title and podcast_id = :podcast_id";
                query.prepare(queryString);
                query.bindValue(":title", episodes.at(i)->title);
                query.bindValue(":podcast_id", id);
                query.exec();

                //updates episode object with db data
                if(query.next() == true) {
                    if(query.value(5).toBool() == true)    {
                        episodes.at(i)->downloaded = true;
                    }
                }
                //creates new episode
                else    {
                    queryString = "insert into episodes (podcast_id, title, fileName, url, downloaded, dateAdded, datePublished) values (:podcast_id, :title, :fileName, :url, :downloaded, :dateAdded, :datePublished)";
                    query.prepare(queryString);
                    query.bindValue(":podcast_id", id);
                    query.bindValue(":title", episodes.at(i)->title);
                    query.bindValue(":fileName", episodes.at(i)->fileName);
                    query.bindValue(":url", episodes.at(i)->url.toString());
                    query.bindValue(":downloaded", false);
                    query.bindValue(":dateAdded", episodes.at(i)->dateAdded.toString("yyyy/MM/dd hh:mm:ss"));
                    query.bindValue(":datePublished", episodes.at(i)->datePublished.toString("yyyy/MM/dd hh:mm:ss"));
                    qDebug() << "UPDATES podcast with new episode: " << episodes.at(i)->title;
                    query.exec();
                }
            }
        }
        //else; creats new
        else    {
            qDebug() << "adding new podcast";
            //inserting podcast to db
            queryString = "insert into podcasts (name, rssUrl) values (:name, :rssUrl)";
            query.prepare(queryString);
            query.bindValue(":name", name);
            query.bindValue(":rssUrl", rssUrl.toString());
            query.exec();

            //getting podcast id
            queryString = "select id from podcasts where name = :name";
            query.prepare(queryString);
            query.bindValue(":name", name);
            query.exec();

            if(query.next() == true) {
                id = query.value(0).toInt();
            }

            //adds episodes to db
            int i = 0;
            while(i < episodes.size())    {
                queryString = "insert into episodes (podcast_id, title, fileName, url, downloaded, dateAdded, datePublished) values (:podcast_id, :title, :fileName, :url, :downloaded, :dateAdded, :datePublished)";
                query.prepare(queryString);
                query.bindValue(":podcast_id", id);
                query.bindValue(":title", episodes.at(i)->title);
                query.bindValue(":fileName", episodes.at(i)->fileName);
                query.bindValue(":url", episodes.at(i)->url.toString());
                query.bindValue(":downloaded", false);
                query.bindValue(":dateAdded", episodes.at(i)->dateAdded.toString("yyyy/MM/dd hh:mm:ss"));
                query.bindValue(":datePublished", episodes.at(i)->datePublished.toString("yyyy/MM/dd hh:mm:ss"));
                query.exec();
                i++;
            }
            qDebug() << "podcast added";
        }

        //rebuilds episode list with episode id from db
        episodes.clear();
        episode *tempEpisode;

        queryString = "select * from episodes where podcast_id = :podcast_id order by datePublished desc";
        query.prepare(queryString);
        query.bindValue(":podcast_id", id);
        query.exec();

        while(query.next() == true) {
            QDateTime episodeAdded = QDateTime::fromString(query.value(6).toString(), "yyyy/MM/dd hh:mm:ss");
            QDateTime episodePublished = QDateTime::fromString(query.value(7).toString(), "yyyy/MM/dd hh:mm:ss");
            tempEpisode = new episode(query.value(0).toInt(), id, query.value(2).toString(), query.value(3).toString(), query.value(4).toString(), query.value(5).toBool(), episodeAdded, episodePublished);
            episodes.append(tempEpisode);
        }

        db.close();
        qDebug() << "call podcastAdded();";
        emit podcastUpdated();
    }
    else    {
        qDebug() << db.lastError().text();
    }
    //flushes db
    QString connStr = db.connectionName();
    db = QSqlDatabase::QSqlDatabase();
    QSqlDatabase::removeDatabase(connStr);
}
bool InteractionStep::saveClassDrugInteractor(DrugInteractor *interactor, const QList<DrugInteractor *> &completeList, QSqlDatabase &db, DrugInteractor *parent)
{
    if (!db.isOpen()) {
        if (!db.open()) {
            LOG_ERROR_FOR("InteractionStep", tkTr(Trans::Constants::ERROR_1_FROM_DATABASE_2).arg(db.lastError().text()).arg(db.connectionName()));
            return false;
        }
    }

    // save interactor
    QSqlQuery query(db);
    int id = -1;
    // save using all associated ATC codes
    const QStringList &atcCodes = interactor->data(DrugInteractor::ATCCodeStringList).toStringList();
    if (atcCodes.isEmpty() && !interactor->isClass() && parent && parent->isClass()) {
        //        QString req = QString("INSERT INTO ATC_CLASS_TREE (ID_TREE, ID_CLASS, ID_ATC) VALUES "
        //                              "(NULL, %1,%2);")
        //                .arg(parent->data(CLASS_OR_MOL_ID).toString())
        //                .arg(interactor->data(CLASS_OR_MOL_ID).toString());
//        query.prepare(DrugsDB::Tools::drugBase()->prepareInsertQuery(DrugsDB::Constants::Table_ATC_CLASS_TREE));
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID, QVariant());
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_ATC, interactor->data(CLASS_OR_MOL_ID).toString());
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_CLASS, parent->data(CLASS_OR_MOL_ID).toString());
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_BIBMASTERID, QVariant());

//        if (!query.exec()) {
//            LOG_QUERY_ERROR_FOR("InteractionStep", query);
//        } else {
//            id = query.lastInsertId().toInt();
//        }
        query.finish();
    } else if (!atcCodes.isEmpty() && !interactor->isClass() && parent && parent->isClass()) {
        foreach(const QString &atc, atcCodes) {
            //            QString req = QString("INSERT INTO ATC_CLASS_TREE (ID_TREE, ID_CLASS, ID_ATC) VALUES "
            //                                  "(NULL, %1, (SELECT ATC_ID FROM ATC WHERE CODE=\"%2\"));")
            //                    .arg(parent->data(CLASS_OR_MOL_ID).toString()).arg(atc);

            QString atcId;
            QHash<int, QString> w;
            w.insert(DrugsDB::Constants::ATC_CODE, QString("='%1'").arg(atc));
//            QString req = DrugsDB::Tools::drugBase()->select(DrugsDB::Constants::Table_ATC, DrugsDB::Constants::ATC_ID, w);
//            if (query.exec(req)) {
//                if (query.next())
//                    atcId = query.value(0).toString();
//            } else {
//                LOG_QUERY_ERROR_FOR("InteractionStep", query);
//                db.rollback();
//                return false;
//            }
            query.finish();

//            query.prepare(DrugsDB::Tools::drugBase()->prepareInsertQuery(DrugsDB::Constants::Table_ATC_CLASS_TREE));
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID, QVariant());
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_ATC, atcId);
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_CLASS, parent->data(CLASS_OR_MOL_ID).toString());
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_BIBMASTERID, QVariant());

//            if (!query.exec()) {
//                LOG_QUERY_ERROR_FOR("InteractionStep", query);
//            } else {
//                id = query.lastInsertId().toInt();
//            }
            query.finish();
        }
bool InteractionStep::saveAtcClassification(const QList<DrugInteractor *> &interactors)
{
    QSqlDatabase db = QSqlDatabase::database(Core::Constants::MASTER_DATABASE_NAME);
    if (!db.isOpen()) {
        if (!db.open()) {
            LOG_ERROR_FOR("InteractionStep", tkTr(Trans::Constants::ERROR_1_FROM_DATABASE_2).arg(db.lastError().text()).arg(db.connectionName()));
            return false;
        }
    }
    Q_EMIT progressLabelChanged(tr("Creating interactions database (refresh ATC table)"));
    // Clean ATC table from old values
    QString req;
//    req = DrugsDB::Tools::drugBase()->prepareDeleteQuery(DrugsDB::Constants::Table_ATC);
//    DrugsDB::Tools::executeSqlQuery(req, Core::Constants::MASTER_DATABASE_NAME, __FILE__, __LINE__);
//    req = DrugsDB::Tools::drugBase()->prepareDeleteQuery(DrugsDB::Constants::Table_ATC_LABELS);
//    DrugsDB::Tools::executeSqlQuery(req, Core::Constants::MASTER_DATABASE_NAME, __FILE__, __LINE__);

    // Import ATC codes to database
    QFile file(atcCsvFile());
    if (!file.open(QFile::ReadOnly | QIODevice::Text)) {
        LOG_ERROR(QString("ERROR : can not open file %1, %2.").arg(file.fileName(), file.errorString()));
    } else {
        QString content = QString::fromUtf8(file.readAll());
        if (content.isEmpty())
            return false;
        const QStringList &list = content.split("\n", QString::SkipEmptyParts);
        foreach(const QString &s, list) {
            if (s.startsWith("--")) {
                qWarning() << s;
                continue;
            }
            QStringList values = s.split("\";\"");
            QMultiHash<QString, QVariant> labels;
            QString en = values[1].remove("\"").toUpper();
            labels.insert("en", en);
            QString fr = values[2].remove("\"").toUpper();
            if (fr.isEmpty())
                labels.insert("fr", en);
            else
                labels.insert("fr", fr);
            QString de = values[3].remove("\"").toUpper();
            if (de.isEmpty())
                labels.insert("de", en);
            else
                labels.insert("de", de);
//            if (!DrugsDB::Tools::createAtc(Core::Constants::MASTER_DATABASE_NAME, values[0].remove("\""), labels)) {
//                return false;
//            }
        }
    }
    Q_EMIT progress(1);

    // add FreeDiams ATC specific codes
    Q_EMIT progressLabelChanged(tr("Creating interactions database (add specific ATC codes)"));
    db.transaction();

    // 100 000 < ID < 199 999  == Interacting molecules without ATC code
    // 200 000 < ID < 299 999  == Interactings classes
    int molId = 100000;
    int classId = 200000;
    foreach(DrugInteractor *di, interactors) {
        if (!di->data(DrugInteractor::ATCCodeStringList).toStringList().count()) {
            // Create new ATC code for mols and/or interacting classes
            QMultiHash<QString, QVariant> labels;
            labels.insert("fr", di->data(DrugInteractor::FrLabel));
            if (!di->data(DrugInteractor::EnLabel).isNull())
                labels.insert("en", di->data(DrugInteractor::EnLabel));
            else
                labels.insert("en", di->data(DrugInteractor::FrLabel));
            if (!di->data(DrugInteractor::DeLabel).isNull())
                labels.insert("de", di->data(DrugInteractor::DeLabel));
            else
                labels.insert("de", di->data(DrugInteractor::FrLabel));

            if (di->isClass()) {
                ++classId;
                QString n = QString::number(classId-200000);
                n = n.rightJustified(4, '0');
//                if (!DrugsDB::Tools::createAtc(Core::Constants::MASTER_DATABASE_NAME, "ZXX" + n, labels, classId, !di->data(DrugInteractor::DoNotWarnDuplicated).toBool()))
//                    return false;
                di->setData(CLASS_OR_MOL_ID, classId);
                di->setData(FREEMEDFORMS_ATC_CODE, "ZXX" + n);
            } else {
                ++molId;
                QString n = QString::number(molId-100000);
                n = n.rightJustified(2, '0');
//                if (!DrugsDB::Tools::createAtc(Core::Constants::MASTER_DATABASE_NAME, "Z01AA" + n, labels, molId, !di->data(DrugInteractor::DoNotWarnDuplicated).toBool()))
//                    return false;
                di->setData(CLASS_OR_MOL_ID, molId);
                di->setData(FREEMEDFORMS_ATC_CODE, "Z01AA" + n);
            }
        }
    }
    db.commit();
    return true;
}
예제 #21
0
SqlQuery::SqlQuery(const QSqlDatabase& db) :
    QSqlQuery( db ), m_db(db)
{
    m_connectionName = db.connectionName();
    SqlQueryManager::instance()->registerQuery(this);
}
예제 #22
0
int main(int argc, char *argv[]) {
  if (CrashReporting::SendCrashReport(argc, argv)) {
    return 0;
  }

  CrashReporting crash_reporting;

#ifdef Q_OS_DARWIN
  // Do Mac specific startup to get media keys working.
  // This must go before QApplication initialisation.
  mac::MacMain();

  {
    // Bump the soft limit for the number of file descriptors from the default of 256 to
    // the maximum (usually 10240).
    struct rlimit limit;
    getrlimit(RLIMIT_NOFILE, &limit);

    // getrlimit() lies about the hard limit so we have to check sysctl.
    int max_fd = 0;
    size_t len = sizeof(max_fd);
    sysctlbyname("kern.maxfilesperproc", &max_fd, &len, NULL, 0);

    limit.rlim_cur = max_fd;
    int ret = setrlimit(RLIMIT_NOFILE, &limit);

    if (ret == 0) {
      qLog(Debug) << "Max fd:" << max_fd;
    }
  }
#endif

  QCoreApplication::setApplicationName("Clementine");
  QCoreApplication::setApplicationVersion(CLEMENTINE_VERSION_DISPLAY);
  QCoreApplication::setOrganizationName("Clementine");
  QCoreApplication::setOrganizationDomain("clementine-player.org");

#ifdef Q_OS_DARWIN
  // Must happen after QCoreApplication::setOrganizationName().
  setenv("XDG_CONFIG_HOME", Utilities::GetConfigPath(Utilities::Path_Root).toLocal8Bit().constData(), 1);
  if (mac::MigrateLegacyConfigFiles()) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(Utilities::GetConfigPath(
        Utilities::Path_Root) + "/" + Database::kDatabaseFilename);
    db.open();
    QSqlQuery query(
        "UPDATE songs SET art_manual = replace("
        "art_manual, '.config', 'Library/Application Support') "
        "WHERE art_manual LIKE '%.config%'", db);
    query.exec();
    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
  }
#endif

  // This makes us show up nicely in gnome-volume-control
  g_type_init();
  g_set_application_name(QCoreApplication::applicationName().toLocal8Bit());

  qRegisterMetaType<CoverSearchResult>("CoverSearchResult");
  qRegisterMetaType<QList<CoverSearchResult> >("QList<CoverSearchResult>");
  qRegisterMetaType<CoverSearchResults>("CoverSearchResults");
  qRegisterMetaType<Directory>("Directory");
  qRegisterMetaType<DirectoryList>("DirectoryList");
  qRegisterMetaType<Subdirectory>("Subdirectory");
  qRegisterMetaType<SubdirectoryList>("SubdirectoryList");
  qRegisterMetaType<Song>("Song");
  qRegisterMetaType<QList<Song> >("QList<Song>");
  qRegisterMetaType<SongList>("SongList");
  qRegisterMetaType<PlaylistItemPtr>("PlaylistItemPtr");
  qRegisterMetaType<QList<PlaylistItemPtr> >("QList<PlaylistItemPtr>");
  qRegisterMetaType<PlaylistItemList>("PlaylistItemList");
  qRegisterMetaType<Engine::State>("Engine::State");
  qRegisterMetaType<Engine::SimpleMetaBundle>("Engine::SimpleMetaBundle");
  qRegisterMetaType<Equalizer::Params>("Equalizer::Params");
  qRegisterMetaTypeStreamOperators<Equalizer::Params>("Equalizer::Params");
  qRegisterMetaType<const char*>("const char*");
  qRegisterMetaType<QNetworkReply*>("QNetworkReply*");
  qRegisterMetaType<QNetworkReply**>("QNetworkReply**");
  qRegisterMetaType<smart_playlists::GeneratorPtr>("smart_playlists::GeneratorPtr");
  qRegisterMetaType<ColumnAlignmentMap>("ColumnAlignmentMap");
  qRegisterMetaTypeStreamOperators<QMap<int, int> >("ColumnAlignmentMap");
  qRegisterMetaType<QNetworkCookie>("QNetworkCookie");
  qRegisterMetaType<QList<QNetworkCookie> >("QList<QNetworkCookie>");

  qRegisterMetaType<GstBuffer*>("GstBuffer*");
  qRegisterMetaType<GstElement*>("GstElement*");
  qRegisterMetaType<GstEnginePipeline*>("GstEnginePipeline*");

#ifdef HAVE_REMOTE
  qRegisterMetaType<xrme::SIPInfo>("xrme::SIPInfo");
#endif

#ifdef HAVE_LIBLASTFM
  lastfm::ws::ApiKey = LastFMService::kApiKey;
  lastfm::ws::SharedSecret = LastFMService::kSecret;
#endif

  CommandlineOptions options(argc, argv);

  {
    // Only start a core application now so we can check if there's another
    // Clementine running without needing an X server.
    // This MUST be done before parsing the commandline options so QTextCodec
    // gets the right system locale for filenames.
    QtSingleCoreApplication a(argc, argv);
    crash_reporting.SetApplicationPath(a.applicationFilePath());

    // Parse commandline options - need to do this before starting the
    // full QApplication so it works without an X server
    if (!options.Parse())
      return 1;

    if (a.isRunning()) {
      if (options.is_empty()) {
        qLog(Info) << "Clementine is already running - activating existing window";
      }
      if (a.sendMessage(options.Serialize(), 5000)) {
        return 0;
      }
      // Couldn't send the message so start anyway
    }
  }

  // Detect technically invalid usage of non-ASCII in ID3v1 tags.
  UniversalEncodingHandler handler;
  TagLib::ID3v1::Tag::setStringHandler(&handler);

#ifdef HAVE_REMOTE
  if (options.stun_test() != CommandlineOptions::StunTestNone) {
    QCoreApplication app(argc, argv);

    ICESession::StaticInit();
    ICESession ice;
    ice.Init(options.stun_test() == CommandlineOptions::StunTestOffer
             ? ICESession::DirectionControlling
             : ICESession::DirectionControlled);

    QEventLoop loop;
    QObject::connect(&ice,
        SIGNAL(CandidatesAvailable(const xrme::SIPInfo&)),
        &loop, SLOT(quit()));
    loop.exec();

    const xrme::SIPInfo& candidates = ice.candidates();
    qDebug() << candidates;

    QString sip_info;
    {
      QFile file;
      file.open(stdin, QIODevice::ReadOnly);
      QTextStream in(&file);
      in >> sip_info;
    }
    QStringList sip_components = sip_info.split(':');

    xrme::SIPInfo remote_session;
    remote_session.user_fragment = sip_components[0];
    remote_session.password = sip_components[1];

    xrme::SIPInfo::Candidate cand;
    cand.address = sip_components[2];
    cand.port = sip_components[3].toUShort();
    cand.type = sip_components[4];
    cand.component = sip_components[5].toInt();
    cand.priority = sip_components[6].toInt();
    cand.foundation = sip_components[7];

    remote_session.candidates << cand;

    qDebug() << "Remote:" << remote_session;

    ice.StartNegotiation(remote_session);
    loop.exec();

    return 0;
  }
예제 #23
0
파일: main.cpp 프로젝트: joilar/CivAdvisor
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QTextStream out(stdout);
    out << "Hello world!" << endl;

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("basic.sqlite");
    bool ok = db.open();

    out << "What is the database name? " << db.databaseName() << endl;
    out << "Did I connect to " << db.databaseName() << "? " << ok << endl;
    out << "Is the connection valid? " << db.isValid() << endl;
    out << "Is the connection open? " << db.isOpen() << endl;
    out << "What is the driver name? " << db.driverName() << endl;
    out << "What is the host name? " << db.hostName() << endl;
    out << "What is the connection name? " << db.connectionName() << endl;
    out << "What are the connection options? " << db.connectOptions() << endl;

    bool hasQuerySize = db.driver()->hasFeature(QSqlDriver::QuerySize);
    out << "Does sqlite support querying the result set size? " << hasQuerySize << endl;

    out << "Tables:";
    QStringList tables = db.tables();
    foreach (QString table, tables) {
        out << " " << table;
    }
    out << endl;

    QSqlQuery query;
    query.setForwardOnly(true);
    query.exec("SELECT * from advances");

    if (hasQuerySize) {
        out << "Querying advances (" << query.size() << " results):" << endl;
    } else {
        out << "Querying advances:" << endl;
    }

    QStringList columns;

    QSqlRecord record = query.record();
    out << "Number of columns: " << record.count() << endl;
    for (int i = 0; i < record.count(); i++) {
        out << "column " << i << ": " << record.fieldName(i) << endl;
        columns.append(record.fieldName(i));
    }

    QList<QObject*> advances;

    while(query.next()) {
        Civilization::Advance *advance = new Civilization::Advance();

        out << "advance " << advances.size() << ":";

        for (int i = 0; i < columns.size(); i++) {
            out << " " << columns[i] << ": " << query.value(i).toString();
            QVariant v(query.value(i).toString());
            advance->setProperty(columns[i].toLatin1().data(), v);
        }

        out << endl;

        advances.append(advance);
    }

    out << advances.size() << " results." << endl;

    db.close();

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("advanceListModel", QVariant::fromValue(advances));
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
예제 #24
0
bool GuardBase::createDatabase(const QString &connectionName,
                                 const QString &dbName,
                                 const QString &pathOrHostName,
                                 TypeOfAccess access,
                                 AvailableDrivers driver,
                                 const QString &login,
                                 const QString &pass,
                                 const int port,
                                 CreationOption createOption
                                 )
{
    // TODO: manage createOption
    // TODO: manage access
    Q_UNUSED(createOption);
    Q_UNUSED(access);

    if (connectionName != Constants::DB_GUARD)
        return false;

    LOG(tkTr(Trans::Constants::TRYING_TO_CREATE_1_PLACE_2)
        .arg(dbName).arg(pathOrHostName));

    // create an empty database and connect
    QSqlDatabase DB;
    if (driver == SQLite) {
        DB = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        if (!QDir(pathOrHostName).exists())
            if (!QDir().mkpath(pathOrHostName))
                LOG(tkTr(Trans::Constants::_1_ISNOT_AVAILABLE_CANNOTBE_CREATED).arg(pathOrHostName));
        DB.setDatabaseName(QDir::cleanPath(pathOrHostName + QDir::separator() + dbName));
        DB.open();
        setDriver(Utils::Database::SQLite);
    }
    else if (driver == MySQL) {
        DB = QSqlDatabase::database(connectionName);
        if (!DB.open()) {
            QSqlDatabase d = QSqlDatabase::addDatabase("QMYSQL", "__GUARD_CREATOR");
            d.setHostName(pathOrHostName);
            d.setUserName(login);
            d.setPassword(pass);
            d.setPort(port);
            if (!d.open()) {
                Utils::warningMessageBox(tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                         .arg(DB.connectionName()).arg(DB.lastError().text()),
                                         tkTr(Trans::Constants::CONTACT_DEV_TEAM));
                return false;
            }
            QSqlQuery q(QString("CREATE DATABASE `%1`").arg(dbName), d);
            if (!q.isActive()) {
                LOG_QUERY_ERROR(q);
                Utils::warningMessageBox(tkTr(Trans::Constants::DATABASE_1_CANNOT_BE_CREATED_ERROR_2)
                                         .arg(DB.connectionName()).arg(DB.lastError().text()),
                                         tkTr(Trans::Constants::CONTACT_DEV_TEAM));
                return false;
            }
            if (!DB.open()) {
                Utils::warningMessageBox(tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                         .arg(DB.connectionName()).arg(DB.lastError().text()),
                                         tkTr(Trans::Constants::CONTACT_DEV_TEAM));
                return false;
            }
            DB.setDatabaseName(dbName);
        }
        if (QSqlDatabase::connectionNames().contains("__GUARD_CREATOR"))
            QSqlDatabase::removeDatabase("__GUARD_CREATOR");
        DB.open();
        setDriver(Utils::Database::MySQL);
    }

    // create db structure
    // before we need to inform Utils::Database of the connectionName to use
    setConnectionName(connectionName);

    if (createTables()) {
        LOG(tkTr(Trans::Constants::DATABASE_1_CORRECTLY_CREATED).arg(dbName));
    } else {
        LOG_ERROR(tkTr(Trans::Constants::DATABASE_1_CANNOT_BE_CREATED_ERROR_2)
                         .arg(dbName, DB.lastError().text()));
        return false;
    }

    // Add version number
    if (!setVersion(Utils::Field(Constants::Table_VERSION, Constants::VERSION_TEXT), Constants::DB_ACTUALVERSION)) {
        LOG_ERROR_FOR("GuardBase", "Unable to set version");
    }
    return true;
}
예제 #25
0
int main(int argc, char *argv[]) {
  if (CrashReporting::SendCrashReport(argc, argv)) {
    return 0;
  }

  CrashReporting crash_reporting;

#ifdef Q_OS_DARWIN
  // Do Mac specific startup to get media keys working.
  // This must go before QApplication initialisation.
  mac::MacMain();
#endif

  QCoreApplication::setApplicationName("Clementine");
  QCoreApplication::setApplicationVersion(CLEMENTINE_VERSION_DISPLAY);
  QCoreApplication::setOrganizationName("Clementine");
  QCoreApplication::setOrganizationDomain("clementine-player.org");

#ifdef Q_OS_DARWIN
  // Must happen after QCoreApplication::setOrganizationName().
  setenv("XDG_CONFIG_HOME", Utilities::GetConfigPath(Utilities::Path_Root).toLocal8Bit().constData(), 1);
  if (mac::MigrateLegacyConfigFiles()) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(Utilities::GetConfigPath(
        Utilities::Path_Root) + "/" + Database::kDatabaseFilename);
    db.open();
    QSqlQuery query(
        "UPDATE songs SET art_manual = replace("
        "art_manual, '.config', 'Library/Application Support') "
        "WHERE art_manual LIKE '%.config%'", db);
    query.exec();
    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
  }
#endif

  // This makes us show up nicely in gnome-volume-control
  g_type_init();
  g_set_application_name(QCoreApplication::applicationName().toLocal8Bit());

  qRegisterMetaType<CoverSearchResult>("CoverSearchResult");
  qRegisterMetaType<QList<CoverSearchResult> >("QList<CoverSearchResult>");
  qRegisterMetaType<CoverSearchResults>("CoverSearchResults");
  qRegisterMetaType<Directory>("Directory");
  qRegisterMetaType<DirectoryList>("DirectoryList");
  qRegisterMetaType<Subdirectory>("Subdirectory");
  qRegisterMetaType<SubdirectoryList>("SubdirectoryList");
  qRegisterMetaType<Song>("Song");
  qRegisterMetaType<QList<Song> >("QList<Song>");
  qRegisterMetaType<SongList>("SongList");
  qRegisterMetaType<PlaylistItemPtr>("PlaylistItemPtr");
  qRegisterMetaType<QList<PlaylistItemPtr> >("QList<PlaylistItemPtr>");
  qRegisterMetaType<PlaylistItemList>("PlaylistItemList");
  qRegisterMetaType<Engine::State>("Engine::State");
  qRegisterMetaType<Engine::SimpleMetaBundle>("Engine::SimpleMetaBundle");
  qRegisterMetaType<Equalizer::Params>("Equalizer::Params");
  qRegisterMetaTypeStreamOperators<Equalizer::Params>("Equalizer::Params");
  qRegisterMetaType<const char*>("const char*");
  qRegisterMetaType<QNetworkReply*>("QNetworkReply*");
  qRegisterMetaType<QNetworkReply**>("QNetworkReply**");
  qRegisterMetaType<smart_playlists::GeneratorPtr>("smart_playlists::GeneratorPtr");
  qRegisterMetaType<ColumnAlignmentMap>("ColumnAlignmentMap");
  qRegisterMetaTypeStreamOperators<QMap<int, int> >("ColumnAlignmentMap");
  qRegisterMetaType<QNetworkCookie>("QNetworkCookie");
  qRegisterMetaType<QList<QNetworkCookie> >("QList<QNetworkCookie>");
  qRegisterMetaType<SearchProvider::Result>("SearchProvider::Result");
  qRegisterMetaType<SearchProvider::ResultList>("SearchProvider::ResultList");
  qRegisterMetaType<DigitallyImportedClient::Channel>("DigitallyImportedClient::Channel");
  qRegisterMetaType<SomaFMService::Stream>("SomaFMService::Stream");
  qRegisterMetaTypeStreamOperators<DigitallyImportedClient::Channel>("DigitallyImportedClient::Channel");
  qRegisterMetaTypeStreamOperators<SomaFMService::Stream>("SomaFMService::Stream");

  qRegisterMetaType<GstBuffer*>("GstBuffer*");
  qRegisterMetaType<GstElement*>("GstElement*");
  qRegisterMetaType<GstEnginePipeline*>("GstEnginePipeline*");

#ifdef HAVE_REMOTE
  qRegisterMetaType<xrme::SIPInfo>("xrme::SIPInfo");
#endif

#ifdef HAVE_LIBLASTFM
  lastfm::ws::ApiKey = LastFMService::kApiKey;
  lastfm::ws::SharedSecret = LastFMService::kSecret;
  lastfm::setNetworkAccessManager(new NetworkAccessManager);
#endif

  CommandlineOptions options(argc, argv);

  {
    // Only start a core application now so we can check if there's another
    // Clementine running without needing an X server.
    // This MUST be done before parsing the commandline options so QTextCodec
    // gets the right system locale for filenames.
    QtSingleCoreApplication a(argc, argv);
    crash_reporting.SetApplicationPath(a.applicationFilePath());

    // Parse commandline options - need to do this before starting the
    // full QApplication so it works without an X server
    if (!options.Parse())
      return 1;

    if (a.isRunning()) {
      if (options.is_empty()) {
        qLog(Info) << "Clementine is already running - activating existing window";
      }
      if (a.sendMessage(options.Serialize(), 5000)) {
        return 0;
      }
      // Couldn't send the message so start anyway
    }
  }

#ifdef Q_OS_LINUX
  // Force Clementine's menu to be shown in the Clementine window and not in
  // the Unity global menubar thing.  See:
  // https://bugs.launchpad.net/unity/+bug/775278
  setenv("QT_X11_NO_NATIVE_MENUBAR", "1", true);
#endif

  // Initialise logging
  logging::Init();
  logging::SetLevels(options.log_levels());
  g_log_set_default_handler(reinterpret_cast<GLogFunc>(&logging::GLog), NULL);

  IncreaseFDLimit();

  QtSingleApplication a(argc, argv);
#ifdef Q_OS_DARWIN
  QCoreApplication::setLibraryPaths(
      QStringList() << QCoreApplication::applicationDirPath() + "/../PlugIns");
#endif

  a.setQuitOnLastWindowClosed(false);

  // Do this check again because another instance might have started by now
  if (a.isRunning() && a.sendMessage(options.Serialize(), 5000)) {
    return 0;
  }

#ifndef Q_OS_DARWIN
  // Gnome on Ubuntu has menu icons disabled by default.  I think that's a bad
  // idea, and makes some menus in Clementine look confusing.
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, false);
#else
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, true);
#endif

  // Set the permissions on the config file on Unix - it can contain passwords
  // for internet services so it's important that other users can't read it.
  // On Windows these are stored in the registry instead.
#ifdef Q_OS_UNIX
  {
    QSettings s;

    // Create the file if it doesn't exist already
    if (!QFile::exists(s.fileName())) {
      QFile file(s.fileName());
      file.open(QIODevice::WriteOnly);
    }

    // Set -rw-------
    QFile::setPermissions(s.fileName(), QFile::ReadOwner | QFile::WriteOwner);
  }
#endif

#ifdef HAVE_QCA
  QCA::Initializer qca_initializer;
#endif

  // Resources
  Q_INIT_RESOURCE(data);
  Q_INIT_RESOURCE(translations);

  // Grooveshark uses GoDaddy to sign its SSL certificates, which are in turn
  // signed by a ValiCert CA.  This CA certificate isn't installed by default
  // in Windows, it's only added by windows update, or manually browsing to a
  // website with a certificate signed by ValiCert.  Here we explicitly add
  // that CA to the default list used by QSslSocket, so it always works in
  // Clementine.
  QSslSocket::addDefaultCaCertificates(
        QSslCertificate::fromPath(":/grooveshark-valicert-ca.pem", QSsl::Pem));

  // Has the user forced a different language?
  QString language = options.language();
  if (language.isEmpty()) {
    QSettings s;
    s.beginGroup("General");
    language = s.value("language").toString();
  }

  // Translations
  LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language);
  LoadTranslation("clementine", ":/translations", language);
  LoadTranslation("clementine", a.applicationDirPath(), language);
  LoadTranslation("clementine", QDir::currentPath(), language);

  // Icons
  IconLoader::Init();

  // Appearance (UI costumization)
  Appearance appearance;

  Echonest::Config::instance()->setAPIKey("DFLFLJBUF4EGTXHIG");
  Echonest::Config::instance()->setNetworkAccessManager(new NetworkAccessManager);

  // Network proxy
  QNetworkProxyFactory::setApplicationProxyFactory(
      NetworkProxyFactory::Instance());

  // Seed the random number generator
  srand(time(NULL));

  // Initialize the repository of cover providers.  Last.fm registers itself
  // when its service is created.
  CoverProviders cover_providers;
  cover_providers.AddProvider(new AmazonCoverProvider);
  cover_providers.AddProvider(new DiscogsCoverProvider);

  // Create the tag loader on another thread.
  TagReaderClient* tag_reader_client = new TagReaderClient;

  QThread tag_reader_thread;
  tag_reader_thread.start();
  tag_reader_client->moveToThread(&tag_reader_thread);
  tag_reader_client->Start();

  // Create some key objects
  scoped_ptr<BackgroundThread<Database> > database(
      new BackgroundThreadImplementation<Database, Database>(NULL));
  database->Start(true);
  TaskManager task_manager;
  PlaylistManager playlists(&task_manager, NULL);
  Player player(&playlists, &task_manager);
  GlobalSearch global_search;
  InternetModel internet_model(database.get(), &task_manager, &player,
                               &cover_providers, &global_search, NULL);

#ifdef Q_OS_LINUX
  // In 11.04 Ubuntu decided that the system tray should be reserved for certain
  // whitelisted applications.  Clementine will override this setting and insert
  // itself into the list of whitelisted apps.
  UbuntuUnityHack hack;
#endif // Q_OS_LINUX

  // Create the tray icon and OSD
  scoped_ptr<SystemTrayIcon> tray_icon(SystemTrayIcon::CreateSystemTrayIcon());
  OSD osd(tray_icon.get());

  ArtLoader art_loader;

#ifdef HAVE_DBUS
  qDBusRegisterMetaType<QImage>();
  qDBusRegisterMetaType<TrackMetadata>();
  qDBusRegisterMetaType<TrackIds>();
  qDBusRegisterMetaType<QList<QByteArray> >();

  mpris::Mpris mpris(&player, &art_loader);

  QObject::connect(&playlists, SIGNAL(CurrentSongChanged(Song)), &art_loader, SLOT(LoadArt(Song)));
  QObject::connect(&art_loader, SIGNAL(ThumbnailLoaded(Song, QString, QImage)),
                   &osd, SLOT(CoverArtPathReady(Song, QString)));

  GlobalSearchService global_search_service(&global_search);
#endif

  // Window
  MainWindow w(
      database.get(),
      &task_manager,
      &playlists,
      &internet_model,
      &player,
      tray_icon.get(),
      &osd,
      &art_loader,
      &cover_providers,
      &global_search);
#ifdef HAVE_GIO
  ScanGIOModulePath();
#endif
#ifdef HAVE_DBUS
  QObject::connect(&mpris, SIGNAL(RaiseMainWindow()), &w, SLOT(Raise()));
#endif
  QObject::connect(&a, SIGNAL(messageReceived(QByteArray)), &w, SLOT(CommandlineOptionsReceived(QByteArray)));
  w.CommandlineOptionsReceived(options);

  int ret = a.exec();

  tag_reader_client->deleteLater();
  tag_reader_thread.quit();
  tag_reader_thread.wait();

#ifdef Q_OS_LINUX
  // The nvidia driver would cause Clementine (or any application that used
  // opengl) to use 100% cpu on shutdown.  See:
  //   http://code.google.com/p/clementine-player/issues/detail?id=2088
  //   https://bugs.gentoo.org/show_bug.cgi?id=375615
  // Work around this problem by exiting immediately (and not running the buggy
  // nvidia atexit shutdown handler) if we're using one of the affected versions
  // of the nvidia driver.

  QFile self_maps("/proc/self/maps");
  if (self_maps.open(QIODevice::ReadOnly)) {
    QByteArray data = self_maps.readAll();
    if (data.contains("libnvidia-tls.so.285.03") ||
        data.contains("libnvidia-tls.so.280.13") ||
        data.contains("libnvidia-tls.so.275.28") ||
        data.contains("libnvidia-tls.so.275.19")) {
      qLog(Warning) << "Exiting immediately to work around NVIDIA driver bug";
      _exit(ret);
    }
    self_maps.close();
  }
#endif

  return ret;
}
예제 #26
0
bool TemplateBase::createDatabase(const QString &connectionName , const QString &dbName,
                    const QString &pathOrHostName,
                    TypeOfAccess access, AvailableDrivers driver,
                    const QString & login, const QString & pass,
                    const int port,
                    CreationOption /*createOption*/
                   )
{
    Q_UNUSED(access);
    if (connectionName != Templates::Constants::DB_TEMPLATES_NAME)
        return false;

    LOG(tkTr(Trans::Constants::TRYING_TO_CREATE_1_PLACE_2)
        .arg(dbName).arg(pathOrHostName));

    setConnectionName(connectionName);
    setDriver(driver);

    // create an empty database and connect
    QSqlDatabase DB;
    if (driver == SQLite) {
        DB = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        if (!QDir(pathOrHostName).exists())
            if (!QDir().mkpath(pathOrHostName))
                LOG(tkTr(Trans::Constants::_1_ISNOT_AVAILABLE_CANNOTBE_CREATED).arg(pathOrHostName));
        DB.setDatabaseName(QDir::cleanPath(pathOrHostName + QDir::separator() + dbName));
        if (!DB.open())
            LOG(tkTr(Trans::Constants::DATABASE_1_CANNOT_BE_CREATED_ERROR_2).arg(dbName).arg(DB.lastError().text()));
    }
    else if (driver == MySQL) {
        DB = QSqlDatabase::database(connectionName);
        if (!DB.open()) {
            QSqlDatabase d = QSqlDatabase::addDatabase("QMYSQL", "__TEMPLATES_CREATOR");
            d.setHostName(pathOrHostName);
            d.setUserName(login);
            d.setPassword(pass);
            d.setPort(port);
            if (!d.open()) {
                Utils::warningMessageBox(tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                         .arg(DB.connectionName()).arg(DB.lastError().text()),
                                         tkTr(Trans::Constants::CONTACT_DEV_TEAM));
                return false;
            }
            QSqlQuery q(QString("CREATE DATABASE `%1`").arg(dbName), d);
            if (!q.isActive()) {
                LOG_QUERY_ERROR(q);
                Utils::warningMessageBox(tkTr(Trans::Constants::DATABASE_1_CANNOT_BE_CREATED_ERROR_2)
                                         .arg(DB.connectionName()).arg(DB.lastError().text()),
                                         tkTr(Trans::Constants::CONTACT_DEV_TEAM));
                return false;
            }
            if (!DB.open()) {
                Utils::warningMessageBox(tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                         .arg(DB.connectionName()).arg(DB.lastError().text()),
                                         tkTr(Trans::Constants::CONTACT_DEV_TEAM));
                return false;
            }
            DB.setDatabaseName(dbName);
        }
        if (QSqlDatabase::connectionNames().contains("__TEMPLATES_CREATOR"))
            QSqlDatabase::removeDatabase("__TEMPLATES_CREATOR");
        if (!DB.open()) {
            Utils::warningMessageBox(tkTr(Trans::Constants::UNABLE_TO_OPEN_DATABASE_1_ERROR_2)
                                     .arg(DB.connectionName()).arg(DB.lastError().text()),
                                     tkTr(Trans::Constants::CONTACT_DEV_TEAM));
            return false;
        }
    }


    if (createTables()) {
        LOG(tkTr(Trans::Constants::DATABASE_1_CORRECTLY_CREATED).arg(dbName));
    } else {
        LOG_ERROR(tkTr(Trans::Constants::DATABASE_1_CANNOT_BE_CREATED_ERROR_2)
                  .arg(dbName, DB.lastError().text()));
        return false;
    }

    QString req = "CREATE TRIGGER delete_all_category_children AFTER "
                  "DELETE ON `CATEGORIES` "
                  "FOR EACH ROW "
                  "  BEGIN"
                  "    DELETE FROM `CATEGORIES` WHERE `CATEGORIES`.`PARENT_CATEGORY`=old.`CATEGORY_ID`;"
                  "    DELETE FROM `TEMPLATES` WHERE `TEMPLATES`.`ID_CATEGORY`=old.`CATEGORY_ID`;"
                  "  END;";
    if (!executeSQL(req, DB)) {
        return false;
    }

    // Add version number
    if (!setVersion(Utils::Field(Constants::Table_Version, Constants::VERSION_ACTUAL), Constants::DB_ACTUAL_VERSION)) {
        LOG_ERROR_FOR("TemplateBase", "Unable to set version");
    }
    return true;
}
예제 #27
0
void removeDatabase(
        const QSqlDatabase& database) {
    DEBUG_ASSERT(!database.isOpen());
    QSqlDatabase::removeDatabase(database.connectionName());
}
예제 #28
0
int main(int argc, char *argv[]) {
  if (CrashReporting::SendCrashReport(argc, argv)) {
    return 0;
  }

  CrashReporting crash_reporting;

#ifdef Q_OS_DARWIN
  // Do Mac specific startup to get media keys working.
  // This must go before QApplication initialisation.
  mac::MacMain();
#endif

  QCoreApplication::setApplicationName("Clementine");
  QCoreApplication::setApplicationVersion(CLEMENTINE_VERSION_DISPLAY);
  QCoreApplication::setOrganizationName("Clementine");
  QCoreApplication::setOrganizationDomain("clementine-player.org");

#ifdef Q_OS_DARWIN
  // Must happen after QCoreApplication::setOrganizationName().
  setenv("XDG_CONFIG_HOME", Utilities::GetConfigPath(Utilities::Path_Root).toLocal8Bit().constData(), 1);
  if (mac::MigrateLegacyConfigFiles()) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(Utilities::GetConfigPath(
        Utilities::Path_Root) + "/" + Database::kDatabaseFilename);
    db.open();
    QSqlQuery query(
        "UPDATE songs SET art_manual = replace("
        "art_manual, '.config', 'Library/Application Support') "
        "WHERE art_manual LIKE '%.config%'", db);
    query.exec();
    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
  }
#endif

  // This makes us show up nicely in gnome-volume-control
  g_type_init();
  g_set_application_name(QCoreApplication::applicationName().toLocal8Bit());

  RegisterMetaTypes();

#ifdef HAVE_LIBLASTFM
  lastfm::ws::ApiKey = LastFMService::kApiKey;
  lastfm::ws::SharedSecret = LastFMService::kSecret;
  lastfm::setNetworkAccessManager(new NetworkAccessManager);
#endif

  CommandlineOptions options(argc, argv);

  {
    // Only start a core application now so we can check if there's another
    // Clementine running without needing an X server.
    // This MUST be done before parsing the commandline options so QTextCodec
    // gets the right system locale for filenames.
    QtSingleCoreApplication a(argc, argv);
    crash_reporting.SetApplicationPath(a.applicationFilePath());

    // Parse commandline options - need to do this before starting the
    // full QApplication so it works without an X server
    if (!options.Parse())
      return 1;

    if (a.isRunning()) {
      if (options.is_empty()) {
        qLog(Info) << "Clementine is already running - activating existing window";
      }
      if (a.sendMessage(options.Serialize(), 5000)) {
        return 0;
      }
      // Couldn't send the message so start anyway
    }
  }

  // Initialise logging
  logging::Init();
  logging::SetLevels(options.log_levels());
  g_log_set_default_handler(reinterpret_cast<GLogFunc>(&logging::GLog), NULL);

  // Seed the random number generators.
  time_t t = time(NULL);
  srand(t);
  qsrand(t);

  IncreaseFDLimit();

  QtSingleApplication a(argc, argv);

  // A bug in Qt means the wheel_scroll_lines setting gets ignored and replaced
  // with the default value of 3 in QApplicationPrivate::initialize.
  {
    QSettings qt_settings(QSettings::UserScope, "Trolltech");
    qt_settings.beginGroup("Qt");
    QApplication::setWheelScrollLines(
          qt_settings.value("wheelScrollLines",
                            QApplication::wheelScrollLines()).toInt());
  }

#ifdef Q_OS_DARWIN
  QCoreApplication::setLibraryPaths(
      QStringList() << QCoreApplication::applicationDirPath() + "/../PlugIns");
#endif

  a.setQuitOnLastWindowClosed(false);

  // Do this check again because another instance might have started by now
  if (a.isRunning() && a.sendMessage(options.Serialize(), 5000)) {
    return 0;
  }

#ifndef Q_OS_DARWIN
  // Gnome on Ubuntu has menu icons disabled by default.  I think that's a bad
  // idea, and makes some menus in Clementine look confusing.
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, false);
#else
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, true);
  // Fixes focus issue with NSSearchField, see QTBUG-11401
  QCoreApplication::setAttribute(Qt::AA_NativeWindows, true);
#endif

  SetGstreamerEnvironment();

  // Set the permissions on the config file on Unix - it can contain passwords
  // for internet services so it's important that other users can't read it.
  // On Windows these are stored in the registry instead.
#ifdef Q_OS_UNIX
  {
    QSettings s;

    // Create the file if it doesn't exist already
    if (!QFile::exists(s.fileName())) {
      QFile file(s.fileName());
      file.open(QIODevice::WriteOnly);
    }

    // Set -rw-------
    QFile::setPermissions(s.fileName(), QFile::ReadOwner | QFile::WriteOwner);
  }
#endif

#ifdef HAVE_QCA
  QCA::Initializer qca_initializer;
#endif

  // Resources
  Q_INIT_RESOURCE(data);
  Q_INIT_RESOURCE(translations);

  // Grooveshark uses GoDaddy to sign its SSL certificates, which are in turn
  // signed by a ValiCert CA.  This CA certificate isn't installed by default
  // in Windows, it's only added by windows update, or manually browsing to a
  // website with a certificate signed by ValiCert.  Here we explicitly add
  // that CA to the default list used by QSslSocket, so it always works in
  // Clementine.
  QSslSocket::addDefaultCaCertificates(
        QSslCertificate::fromPath(":/grooveshark-valicert-ca.pem", QSsl::Pem));

  // Has the user forced a different language?
  QString language = options.language();
  if (language.isEmpty()) {
    QSettings s;
    s.beginGroup("General");
    language = s.value("language").toString();
  }

  // Translations
  LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language);
  LoadTranslation("clementine", ":/translations", language);
  LoadTranslation("clementine", a.applicationDirPath(), language);
  LoadTranslation("clementine", QDir::currentPath(), language);

  // Icons
  IconLoader::Init();

  Application app;

  Echonest::Config::instance()->setAPIKey("DFLFLJBUF4EGTXHIG");
  Echonest::Config::instance()->setNetworkAccessManager(new NetworkAccessManager);

  // Network proxy
  QNetworkProxyFactory::setApplicationProxyFactory(
      NetworkProxyFactory::Instance());

  // Initialize the repository of cover providers.  Last.fm registers itself
  // when its service is created.
  app.cover_providers()->AddProvider(new AmazonCoverProvider);
  app.cover_providers()->AddProvider(new DiscogsCoverProvider);

#ifdef Q_OS_LINUX
  // In 11.04 Ubuntu decided that the system tray should be reserved for certain
  // whitelisted applications.  Clementine will override this setting and insert
  // itself into the list of whitelisted apps.
  UbuntuUnityHack hack;
#endif // Q_OS_LINUX

  // Create the tray icon and OSD
  scoped_ptr<SystemTrayIcon> tray_icon(SystemTrayIcon::CreateSystemTrayIcon());
  OSD osd(tray_icon.get(), &app);

#ifdef HAVE_DBUS
  mpris::Mpris mpris(&app);
#endif

  // Window
  MainWindow w(&app, tray_icon.get(), &osd);
#ifdef HAVE_GIO
  ScanGIOModulePath();
#endif
#ifdef HAVE_DBUS
  QObject::connect(&mpris, SIGNAL(RaiseMainWindow()), &w, SLOT(Raise()));
#endif
  QObject::connect(&a, SIGNAL(messageReceived(QByteArray)), &w, SLOT(CommandlineOptionsReceived(QByteArray)));
  w.CommandlineOptionsReceived(options);

  int ret = a.exec();

#ifdef Q_OS_LINUX
  // The nvidia driver would cause Clementine (or any application that used
  // opengl) to use 100% cpu on shutdown.  See:
  //   http://code.google.com/p/clementine-player/issues/detail?id=2088
  //   https://bugs.gentoo.org/show_bug.cgi?id=375615
  // Work around this problem by exiting immediately (and not running the buggy
  // nvidia atexit shutdown handler) if we're using one of the affected versions
  // of the nvidia driver.

  QFile self_maps("/proc/self/maps");
  if (self_maps.open(QIODevice::ReadOnly)) {
    QByteArray data = self_maps.readAll();
    if (data.contains("libnvidia-tls.so.285.03") ||
        data.contains("libnvidia-tls.so.280.13") ||
        data.contains("libnvidia-tls.so.275.28") ||
        data.contains("libnvidia-tls.so.275.19")) {
      qLog(Warning) << "Exiting immediately to work around NVIDIA driver bug";
      _exit(ret);
    }
    self_maps.close();
  }
#endif

  return ret;
}
예제 #29
0
	QString Database::connectionName() {
		QSqlDatabase db = QSqlDatabase::database();
		return db.connectionName();
	}