Ejemplo n.º 1
0
void IDBFactoryBackendImpl::open(const String& name, PassRefPtr<IDBCallbacks> callbacks, PassRefPtr<SecurityOrigin> securityOrigin, Frame*, const String& dataDir, int64_t maximumSize)
{
    String fileIdentifier = securityOrigin->databaseIdentifier();
    String uniqueIdentifier = fileIdentifier + "@" + name;
    IDBDatabaseBackendMap::iterator it = m_databaseBackendMap.find(uniqueIdentifier);
    if (it != m_databaseBackendMap.end()) {
        callbacks->onSuccess(it->second);
        return;
    }

    // FIXME: Everything from now on should be done on another thread.

    RefPtr<IDBSQLiteDatabase> sqliteDatabase;
    SQLiteDatabaseMap::iterator it2 = m_sqliteDatabaseMap.find(fileIdentifier);
    if (it2 != m_sqliteDatabaseMap.end())
        sqliteDatabase = it2->second;
    else {
        sqliteDatabase = openSQLiteDatabase(securityOrigin.get(), dataDir, maximumSize, fileIdentifier, this);

        if (!sqliteDatabase || !createTables(sqliteDatabase->db()) || !migrateDatabase(sqliteDatabase->db())) {
            callbacks->onError(IDBDatabaseError::create(IDBDatabaseException::UNKNOWN_ERR, "Internal error."));
            m_sqliteDatabaseMap.set(fileIdentifier, 0);
            return;
        }
        m_sqliteDatabaseMap.set(fileIdentifier, sqliteDatabase.get());
    }

    RefPtr<IDBDatabaseBackendImpl> databaseBackend = IDBDatabaseBackendImpl::create(name, sqliteDatabase.get(), m_transactionCoordinator.get(), this, uniqueIdentifier);
    callbacks->onSuccess(databaseBackend.get());
    m_databaseBackendMap.set(uniqueIdentifier, databaseBackend.get());
}
Ejemplo n.º 2
0
Session::Session ( const std::string& sqliteDb )
  : connection_ ( sqliteDb )
{
  connection_.setProperty ( "show-queries", "true" );

  setConnection ( connection_ );

  mapClass<User> ( "user" );
  mapClass<AuthInfo> ( "auth_info" );
  mapClass<AuthInfo::AuthIdentityType> ( "auth_identity" );
  mapClass<AuthInfo::AuthTokenType> ( "auth_token" );

  try
    {
      createTables();
      std::cerr << "Created database." << std::endl;
    }
  catch ( std::exception& e )
    {
      std::cerr << e.what() << std::endl;
      std::cerr << "Using existing database";
    }

  users_ = new UserDatabase ( *this );
}
bool QHelpCollectionHandler::openCollectionFile()
{
    if (m_dbOpened)
        return m_dbOpened;

    m_connectionName = QHelpGlobal::uniquifyConnectionName(
                           QLatin1String("QHelpCollectionHandler"), this);
    bool openingOk = true;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), m_connectionName);
        db.setDatabaseName(collectionFile());
        openingOk = db.open();
        if (openingOk)
            m_query = QSqlQuery(db);
    }
    if (!openingOk) {
        QSqlDatabase::removeDatabase(m_connectionName);
        emit error(tr("Cannot open collection file: %1").arg(collectionFile()));
        return false;
    }

    m_query.exec(QLatin1String("SELECT COUNT(*) FROM sqlite_master WHERE TYPE=\'table\'"
                               "AND Name=\'NamespaceTable\'"));
    m_query.next();
    if (m_query.value(0).toInt() < 1) {
        if (!createTables(&m_query)) {
            emit error(tr("Cannot create tables in file %1!").arg(collectionFile()));
            return false;
        }
    }

    m_dbOpened = true;
    return m_dbOpened;
}
Ejemplo n.º 4
0
LevelOneDec::LevelOneDec(const QVector<QString> &vectorDate,
                         const QVector<QVector<double> > &vectorSensorReadings2D,
                         QWidget *parent) :
    QWidget(parent)
{
    vectorDateToLevelOne = vectorDate;
    vectorSensorReadings2DToLevelOne = vectorSensorReadings2D;

    row = vectorDateToLevelOne.size();
    col = vectorSensorReadings2DToLevelOne[0].size();

    retranslateUi();

    createTables();

    setVectorsToTables();

    createDoubleBoxes();

    createCharts();

    createToolBar();

    createWidgets();
}
Ejemplo n.º 5
0
//----------------------------------------------------------------------------
void ctkPluginStorageSQL::open()
{
  createDatabaseDirectory();

  QSqlDatabase database = getConnection();

  //Check if the sqlite version supports foreign key constraints
  QSqlQuery query(database);
  if (!query.exec("PRAGMA foreign_keys"))
  {
    close();
    throw ctkPluginDatabaseException(QString("Check for foreign key support failed."),
                                  ctkPluginDatabaseException::DB_SQL_ERROR);
  }

  if (!query.next())
  {
    close();
    throw ctkPluginDatabaseException(QString("SQLite db does not support foreign keys. It is either older than 3.6.19 or was compiled with SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER"),
                                  ctkPluginDatabaseException::DB_SQL_ERROR);
  }
  query.finish();
  query.clear();

  //Enable foreign key support
  if (!query.exec("PRAGMA foreign_keys = ON"))
  {
    close();
    throw ctkPluginDatabaseException(QString("Enabling foreign key support failed."),
                                  ctkPluginDatabaseException::DB_SQL_ERROR);
  }
  query.finish();


  //Check database structure (tables) and recreate tables if neccessary
  //If one of the tables is missing remove all tables and recreate them
  //This operation is required in order to avoid data coruption
  if (!checkTables())
  {
    if (dropTables())
    {
      createTables();
    }
    else
    {
      //dropTables() should've handled error message
      //and warning
      close();
    }
  }

  // silently remove any plugin marked as uninstalled
  cleanupDB();

  //Update database based on the recorded timestamps
  updateDB();

  initNextFreeIds();
}
Ejemplo n.º 6
0
int Solver::reset(const int& colors, const int& pegs, const bool& same_colors)
{
    mColors = colors;
    mPegs = pegs;
    mSameColors = same_colors;
    deleteTables();
    createTables();
    return mCodes.size;
}
Ejemplo n.º 7
0
/**
 * @brief Constructor.
 * Opens the Database. If empty, create the schema.
 */
DatabaseManager::DatabaseManager()
{
    openDB();

    createTables();

    m_moviesPathModel = new QStringListModel();

}
Ejemplo n.º 8
0
IDAImpl::IDAImpl()
{
    idaEncoder    = new IDAEncoderIdentity();
    idaDecoder    = new IDADecoderIdentity();    
//    idaEncoder    = new IDAEncoderRabin();
//    idaDecoder    = new IDADecoderRabin();    
    idaAuxVectors = new IDAAuxVectors();    
    
    createTables();
}
Ejemplo n.º 9
0
void U2SQLiteTripleStore::init(const QString &url, U2OpStatus &os) {
    if (db->handle != NULL) {
        os.setError(TripleStoreL10N::tr("Database is already opened!"));
        return;
    }
    if (state != U2DbiState_Void) {
        os.setError(TripleStoreL10N::tr("Illegal database state: %1").arg(state));
        return;
    }
    state = U2DbiState_Starting;
    if (url.isEmpty()) {
        os.setError(TripleStoreL10N::tr("URL is not specified"));
        state = U2DbiState_Void;
        return;
    }
    do {
        int flags = SQLITE_OPEN_READWRITE;
        flags |= SQLITE_OPEN_CREATE;
        QByteArray file = url.toUtf8();
        int rc = sqlite3_open_v2(file.constData(), &db->handle, flags, NULL);
        if (rc != SQLITE_OK) {
            QString err = db->handle == NULL ? QString(" error-code: %1").arg(rc) : QString(sqlite3_errmsg(db->handle));
            os.setError(TripleStoreL10N::tr("Error opening SQLite database: %1!").arg(err));
            break;
        }

        SQLiteQuery("PRAGMA synchronous = OFF", db, os).execute();
        SQLiteQuery("PRAGMA main.locking_mode = NORMAL", db, os).execute();
        SQLiteQuery("PRAGMA temp_store = MEMORY", db, os).execute();
        SQLiteQuery("PRAGMA journal_mode = MEMORY", db, os).execute();
        SQLiteQuery("PRAGMA cache_size = 10000", db, os).execute();

        // check if the opened database is valid sqlite dbi
        if (isEmpty(os)) {
            createTables(os);
            if (os.hasError()) {
                break;
            }
        }

        // OK, initialization complete
        if (!os.hasError()) {
            ioLog.trace(QString("SQLite: initialized: %1\n").arg(url));
        }
    } while (0);

    if (os.hasError()) {
        sqlite3_close(db->handle);
        db->handle = NULL;
        state = U2DbiState_Void;
        return;
    }
    state = U2DbiState_Ready;
}
Ejemplo n.º 10
0
void Database::init()
{
    qDebug() << "Initializing ...";
    if (isInitialized())
        return;

    qDebug() << "Not initialized";
    createTables();
    resetDefaults();
    setInitialized();
}
Ejemplo n.º 11
0
db::db(QObject *parent){
	if(openDB()){

		QSqlQuery query(database);
		bool a = query.exec("PRAGMA cache_size = 10000;");

		createTables();
		insertIntoPerson("Unknown");

		//	getUnlabeledPhotos();
	}

}
Ejemplo n.º 12
0
/**
 * @brief Constructor.
 * Opens the Database. If empty, create the schema.
 */
DatabaseManager::DatabaseManager(MoviesDebug *moviesDebug)
{
    m_debug = moviesDebug;
    openDB();

    createTables();
    m_movieFields = "m.id, m.title, m.original_title, m.release_date, m.country, m.duration, m.synopsis, m.file_path, m.colored, m.format, m.suffix, m.rank";
    m_peopleFields = "p.id, p.firstname, p.lastname, p.realname, p.birthday, p.biography";
    m_tagFields = "t.id, t.name";
    m_moviesPathModel = new QStringListModel();
    m_tagListModel = new QStringListModel();
    debug("[DatabaseManager] object created");
}
Ejemplo n.º 13
0
void Replacements::unitTest() {
    BOOST_CHECKPOINT("begin");

    sqlite3* db;

//    using namespace boost::filesystem;
//    path dbFileName = initial_path<path>()/"unitTest_Replacements.db3";
//    if (exists(dbFileName))
//        boost::filesystem::remove(dbFileName);
//
//    if(sqlite3_open(dbFileName.file_string().c_str(), &db)) {
    if(sqlite3_open(":memory:", &db)) {
        sqlite3_close(db);
        throw std::runtime_error("could not open database file");
    }
    BOOST_REQUIRE(db!=NULL);
    Replacement::createTables(db);
    createTables(db);

    BOOST_CHECKPOINT("create objects");
    Replacements rpAlpha(db, "Replacements::unitTest", 1);
    Replacements rpBeta(db, "Replacements::unitTest", 100);
    //BOOST_CHECK_THROW(Replacements rpGamma(db, "Replacements::unitTest"), runtime_error);
    rpAlpha.addReplacement("test", "TEST");
    BOOST_REQUIRE(int(rpAlpha.getReplacements().size()) == 1);

    BOOST_CHECKPOINT("getReplacements()");
    rpBeta.addReplacement("\\d", "Zahl");
    rpAlpha.addReplacement("\\d", "Zahl");
    BOOST_REQUIRE(rpAlpha.getReplacements().size() == 2);

    BOOST_REQUIRE_EQUAL(int(rpAlpha.getReplacements().size()) , 2);
    BOOST_CHECK(rpAlpha.getReplacements()[0]->getRegex().str() == "test");
    BOOST_CHECK(rpAlpha.getReplacements()[0]->getReplacement() == "TEST");
    BOOST_CHECK(rpAlpha.getReplacements()[1]->getRegex().str() == "\\d");
    BOOST_CHECK(rpAlpha.getReplacements()[1]->getReplacement() == "Zahl");


    BOOST_CHECKPOINT("replace()");
    BOOST_CHECK(rpAlpha.replace("testing") == "TESTing");
    BOOST_CHECK(rpAlpha.replace("te3sting") == "teZahlsting");


    BOOST_CHECKPOINT("Gamma");
    Replacements rpGamma(db, "Replacements::unitTest", 1);
    BOOST_REQUIRE_EQUAL(int(rpGamma.getReplacements().size()) , 2);
    BOOST_CHECK(rpGamma.getReplacements()[0]->getRegex().str() == "test");
    BOOST_CHECK(rpGamma.getReplacements()[0]->getReplacement() == "TEST");
    BOOST_CHECK(rpGamma.getReplacements()[1]->getRegex().str() == "\\d");
    BOOST_CHECK(rpGamma.getReplacements()[1]->getReplacement() == "Zahl");
}
Ejemplo n.º 14
0
/*!
  Creates a new SQLITE database in the user's home/.configwizard directory,
  named according to the username input in the previous page.
*/
void NewPage::CreateDatabase()
{
     QDir d( QDir::home() );
     d.cd(".configwizard");
     QString dbPath = d.path();
     dbPath.append("/");
     QString userName = nameLineEdit->text();
     userName.replace(" ", "");
     QString userEmail = emailLineEdit->text();
     userEmail.replace(" ", "");
     QString userPass = passLineEdit->text();
     userPass.replace(" ", "");
     dbPath.append(userName);
     dbPath.append(".db");
     databasePath = dbPath;

     configdb = QSqlDatabase::addDatabase("QSQLITE");
     configdb.setDatabaseName(dbPath);
     if( configdb.open() )
     {
        qWarning("Database created");
     }
     else
     {
        qWarning("Database not created");
     }

     qWarning() << "Path to database is " << databasePath;

     QString userFileName = d.absolutePath();
     userFileName.append("/userFileName");
     QFile userFile(userFileName);
     userFile.open(QIODevice::WriteOnly);
     userFile.write(databasePath.toLatin1());
     userFile.close();


     // Create the database structure
     QSqlQuery createTables(configdb);
     QString createTablesSQL = "CREATE TABLE \"tuser\" (\"userid\", \"username\", \"useremail\", \"password\")";
     createTables.exec(createTablesSQL);
     QString insertUserSQL = "INSERT INTO tuser (userid, username, useremail, password) VALUES (1, \'";
     insertUserSQL.append(userName);
     insertUserSQL.append("\',\'");
     insertUserSQL.append(userEmail);
     insertUserSQL.append("\',\'");
     insertUserSQL.append(userPass);
     insertUserSQL.append("\')");
     createTables.exec(insertUserSQL);
     qWarning() << insertUserSQL;
}
Ejemplo n.º 15
0
bool QgsStyle::createDb( const QString& filename )
{
  mErrorString.clear();
  if ( !openDB( filename ) )
  {
    mErrorString = QStringLiteral( "Unable to create database" );
    QgsDebugMsg( mErrorString );
    return false;
  }

  createTables();

  return true;
}
Ejemplo n.º 16
0
bool QgsStyle::createMemoryDb()
{
  mErrorString.clear();
  if ( !openDB( QStringLiteral( ":memory:" ) ) )
  {
    mErrorString = QStringLiteral( "Unable to create temporary memory database" );
    QgsDebugMsg( mErrorString );
    return false;
  }

  createTables();

  return true;
}
Ejemplo n.º 17
0
BlogSession::BlogSession(dbo::SqlConnectionPool& connectionPool)
  : connectionPool_(connectionPool),
    users_(*this)
{
  setConnectionPool(connectionPool_);

  mapClass<Comment>("comment");
  mapClass<Post>("post");
  mapClass<Tag>("tag");
  mapClass<Token>("token");
  mapClass<User>("user");

  try {
    dbo::Transaction t(*this);
    createTables();

    dbo::ptr<User> admin = add(Wt::cpp14::make_unique<User>());
    User *a = admin.modify();
    a->name = ADMIN_USERNAME;
    a->role = User::Admin;

    Wt::Auth::User authAdmin
      = users_.findWithIdentity(Wt::Auth::Identity::LoginName, a->name);
    blogPasswords.updatePassword(authAdmin, ADMIN_PASSWORD);

    dbo::ptr<Post> post = add(Wt::cpp14::make_unique<Post>());
    Post *p = post.modify();

    p->state = Post::Published;
    p->author = admin;
    p->title = "Welcome!";
    p->briefSrc = "Welcome to your own blog.";
    p->bodySrc = "We have created for you an " + ADMIN_USERNAME +
      " user with password " + ADMIN_PASSWORD;
    p->briefHtml = asciidoc(p->briefSrc);
    p->bodyHtml = asciidoc(p->bodySrc);
    p->date = Wt::WDateTime::currentDateTime();

    dbo::ptr<Comment> rootComment = add(Wt::cpp14::make_unique<Comment>());
    rootComment.modify()->post = post;

    t.commit();

    std::cerr << "Created database, and user " << ADMIN_USERNAME
	      << " / " << ADMIN_PASSWORD << std::endl;
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    std::cerr << "Using existing database";
  }
}
Ejemplo n.º 18
0
/*!
 * Performs default startup
 */
SingleshotManager::SingleshotManager(QString project_path, QSqlDatabase db, MediaManager *media, QObject *parent) :
    SoundManager(project_path, QString("singleshot"), db, media, parent)
{
    this->path = QString("%1/%2").arg(this->project_path, "sfx");
    this->library_identifier = QString("sfx_library");
    createTables();
    library_model = new LibraryModel(library_identifier);
    objects_model = new ObjectsModel(objects_identifier);
    objects_tracks_model = new ObjectsTracksModel(objects_tracks_identifier, library_identifier);

    rescanLibrary();
    createObjectsList();
    connect(objects_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(createObjectsList()));
}
Ejemplo n.º 19
0
bool ThumbnailSchemaUpdater::createDatabase()
{
    if ( createTables()
         && createIndices()
         && createTriggers())
    {
        m_currentVersion = schemaVersion();
        m_currentRequiredVersion = 1;
        return true;
    }
    else
    {
        return false;
    }
}
Ejemplo n.º 20
0
//========CONSTRUCTORS==========
DbManager::DbManager()
{
    QFileInfo checkFile(QCoreApplication::applicationDirPath() + "\\data.db");
    bool db_exists = checkFile.exists();

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(QCoreApplication::applicationDirPath() + "\\data.db");

    if(!db_exists)
    {
        createTables();
    }

    execQuery("SELECT * FROM *"); //for some reason you have to display the list twice unless you do this

}
Ejemplo n.º 21
0
void DatabaseSQLite::open(const QString& path)
{
    if (_db.isOpen())
        return;

    _dbPath = QDir::toNativeSeparators(path);
    bool exists = QFile::exists(_dbPath);

    _db.setDatabaseName(_dbPath);

    // Open database
    if(!_db.open())
        throw Exception("Couldn't open SQLite database.");

    if (!exists)
        createTables();
}
Ejemplo n.º 22
0
void ShopperDatabase::connectDatabase()
{
    if(!db.isOpen())
        if(!db.isValid()) {
            qWarning("using SQLite");
            db = QSqlDatabase::addDatabase("QSQLITE");
              // db = QSqlDatabase::addDatabase("QMYSQLDriver");
#ifdef Q_WS_QWS
            db.setDatabaseName(Qtopia::applicationFileName(QLatin1String("Shopper"),
                                                           QLatin1String("shopper.sqlite")));
#else
            db.setDatabaseName(QLatin1String("shopper.sqlite"));
#endif
            db.setUserName("shopper");
            db.setPassword("1234");

            if(!db.open()) {
                QMessageBox::critical(0, qApp->tr("Cannot open database"),
                                      qApp->tr("Unable to establish a database connection.\n"
                                               "Click Cancel to exit."),
                                      QMessageBox::Cancel,
                                      QMessageBox::NoButton);
                return;
            }

            if(!db.isValid()) {
                QMessageBox::critical(0, qApp->tr("Cannot open database"),
                                      qApp->tr("Unable to establish a database connection.\n"
                                               "Click Cancel to exit."),
                                      QMessageBox::Cancel,
                                      QMessageBox::NoButton);
                return;
            }

        }
    qWarning("%d table entry",(db.tables(QSql::Tables).count()));
    QSqlQuery xsql;
    xsql.exec(QLatin1String("PRAGMA synchronous = OFF"));
    xsql.exec(QLatin1String("PRAGMA temp_store = memory"));
    xsql.exec(QLatin1String("PRAGMA temp_store_directory = '/tmp';"));

    if(db.tables(QSql::Tables).count() < 1) {
        createTables();
    }
}
Ejemplo n.º 23
0
/*!
 * Default startup + randomizer seed
 * Available containers:
 * objects: List of all objects.
 * objects_status: Status of objects in "objects", id == objects.id
 * objects_tracks: All available tracks
 * objects_range_start: Start of tracks for object in objects_tracks, id == objects.id
 * objects_range_stop: Stop of tracks for object in objects_tracks, id == objects.id
 * media_container: id == objects.id
 */
SfxManager::SfxManager(QString project_path, QSqlDatabase db, MediaManager *media, QObject *parent): SoundManager(project_path, QString("sfx"), db, media, parent)
{
    qsrand(QTime::currentTime().msec());

    createTables();

    library_model = new LibraryModel(library_identifier);
    objects_model = new ObjectsModel(objects_identifier);
    objects_tracks_model = new ObjectsTracksModel(objects_tracks_identifier, library_identifier);
    objects_tracks_model->setHeaderData(2, Qt::Horizontal, tr("Track"), Qt::DisplayRole);
    objects_tracks_model->setHeaderData(3, Qt::Horizontal, tr("Pause"), Qt::DisplayRole);
    objects_tracks_model->setHeaderData(4, Qt::Horizontal, tr("Maximum offset before"), Qt::DisplayRole);
    objects_tracks_model->setHeaderData(5, Qt::Horizontal, tr("Maximum offset after"), Qt::DisplayRole);

    rescanLibrary();
    createObjectsList();
    connect(objects_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(createObjectsList()));
}
Ejemplo n.º 24
0
ParsingTable::ParsingTable(vector<NonTerminal*> nonterminals, vector<Terminal*> terminals) {
    nt = nonterminals;
    t = terminals;

    t.push_back(new Terminal("$"));

    //dynamically allocate 2D table
    table = new Rule **[nt.size()];
    for(int i=0; i<nt.size(); i++)
        table[i] = new Rule *[t.size()];

    //initalize to empty
    for(int i=0; i<nt.size(); i++)
        for(int j=0; j<t.size(); j++)
            table[i][j] = NULL;

    createTables();
}
Ejemplo n.º 25
0
/**
 * @brief Constructor.
 * Opens the Database. If empty, create the schema.
 */
DatabaseManager::DatabaseManager()
{
    m_movieFields = "m.id, "
                    "m.title, "
                    "m.original_title, "
                    "m.release_date, "
                    "m.country, "
                    "m.duration, "
                    "m.synopsis, "
                    "m.id_path, "
                    "m.file_path, "
                    "m.poster_path, "
                    "m.colored, "
                    "m.format, "
                    "m.suffix, "
                    "m.rank, "
                    "m.imported, "
                    "m.id_tmdb, "
                    "m.show ";

    m_episodeFields = "e.id, "
                      "e.number, "
                      "e.season, "
                      "e.id_show, "
                      "e.id_movie ";

    m_showFields =  "s.id, "
                    "s.name, "
                    "s.finished ";

    m_peopleFields = "p.id, "
                     "p.name, "
                     "p.birthday, "
                     "p.biography, "
                     "p.imported, "
                     "p.id_tmdb ";

    m_tagFields = "t.id, "
                  "t.name ";

    openDB();
    createTables();
    Macaw::DEBUG("[DatabaseManager] object created");
}
void SQLiteDatabaseConnection::open(QString dbConnectionString)
{
    int rc; //return-Wert speichern
    QFile file(dbConnectionString);
    bool dbExisted = file.exists();
    
    rc = sqlite3_open_v2(dbConnectionString.toStdString().c_str(), &_db, 
		SQLITE_OPEN_READWRITE |
		SQLITE_OPEN_CREATE |
		SQLITE_OPEN_FULLMUTEX,
		NULL);
    
    if (rc != SQLITE_OK)
    {   //Es gab einen Fehler beim Öffnen der Datenbank.
        _dbOpen = false;
        sqlite3_close(_db);
        std::cerr << "Failed to open database file \"" << dbConnectionString.toStdString()
            << "\"" << std::endl;
        return;
    }
    
    //Erstelle Tabellen nur, wenn die Datei vorher nicht existierte.
    if (!dbExisted)
        _dbOpen = createTables();
    else
    {
        _dbOpen = true;
        
        //Geschwindigkeit der DB erhöhen
        QStringList statements;
        statements << "PRAGMA page_size = 4096;";
        statements << "PRAGMA max_page_count = 2147483646;";
        statements << "PRAGMA cache_size=50000;";
        statements << "PRAGMA synchronous=OFF;";
        statements << "PRAGMA journal_mode=MEMORY;";
        statements << "PRAGMA temp_store = MEMORY;";
        QStringList::const_iterator it;
        for (it = statements.constBegin(); it != statements.constEnd(); it++)
        {
            execCreateTableStatement(it->toStdString());
        }
    }
}
Ejemplo n.º 27
0
int ccDBOpen(char *name)
{
    int rv = FALSE;
    if (sqlite3_open_v2(name, &dbPointer,SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK && checkDb())
    {
#ifdef TEST
        printf("checkdb...");
#endif
        char *zErrMsg  = 0;
        int rc = sqlite3_exec(dbPointer, "PRAGMA journal_mode = OFF; PRAGMA synchronous = OFF;PRAGMA temp_store = MEMORY;", 
                              verscallback, 0, &zErrMsg);
        if( rc!=SQLITE_OK )
        {
          fprintf(stderr, "SQL error: %s\n", zErrMsg);
          sqlite3_free(zErrMsg);
        }
        rv = TRUE;
    }
    else 
    {
        if (dbPointer)
            sqlite3_close(dbPointer);
        dbPointer = NULL;
        remove(name);
        if (sqlite3_open_v2(name, &dbPointer, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) == SQLITE_OK)
        {
#ifdef TEST
            printf("createdb...");
#endif
            rv = createTables();
        }
        else
        {
#ifdef TEST
            printf("open...");
#endif
        }
    }
    if (rv)
        sqlite3_busy_timeout(dbPointer, 800);
    atexit(unregister);
    return rv;
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{
  FILE *input;

  parseArgs(argc, argv);
  if (!logFileName) {
    input = stdin;
    logFileName = "<stdin>";
  } else {
    input = fopen(logFileName, "r");
    if (input == NULL)
      everror("unable to open %s", logFileName);
  }

  createTables();
  readLog(input);
  (void)fclose(input);
  return 0;
}
Ejemplo n.º 29
0
Database::Database(const char *file)
  : m_db(NULL),
    m_result_table(NULL),
    m_curr_row(0)
{
  bool newDB = true;
  FILE *f;

  if ((f = fopen(file, "r"))) {
    fclose(f);
    newDB = false;
  }
  
  if (sqlite3_open_v2(file, &m_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, 0) != SQLITE_OK) {
    sqlite3_close(m_db);
    m_db = NULL;
  }
  
  if (newDB) createTables();
}
Ejemplo n.º 30
0
void MainWindow::openFile()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open file"),
                       tr(""), tr("Excel Files (*.xlsx)"));
    if (database.isOpen() && fileName.length() > 0 &&
       fileName.endsWith(".xlsx", Qt::CaseInsensitive))
    {
        if (check_box_open->isChecked())
        {
            for (int table_id = 0; table_id < number_of_tables; ++table_id)
            {
                dropTable(table_names.at(table_id));
            }
        }
        createTables();
        readExcelFile(fileName);
        table_models.at(table_list->currentRow())->select();
        QMessageBox::information(this,tr(""),tr("Load file ok"));
    }
}