Example #1
0
  int SqliteDatabase::copyDatabaseContents(sqlite3 *srcHandle, sqlite3 *dstHandle)
  {
    // check parameters
    if ((srcHandle == nullptr) || (dstHandle == nullptr)) return SQLITE_ERROR;

    // initialize backup procedure
    auto bck = sqlite3_backup_init(dstHandle, "main", srcHandle, "main");
    if (bck == nullptr)
    {
      return SQLITE_ERROR;
    }

    // copy all data at once
    int err = sqlite3_backup_step(bck, -1);
    if (err != SQLITE_DONE)
    {
      // clean up and free ressources, but do not
      // overwrite the error code returned by
      // sqlite3_backup_step() above
      sqlite3_backup_finish(bck);

      return err;
    }

    // clean up and return
    err = sqlite3_backup_finish(bck);
    return err;
  }
int QueryDB::backup( QString from_db , QString to_db )
{
    sqlite3 *p_from , *p_dest ;
    sqlite3_backup *p_backup ;
    int rc = 0 ;

    rc = sqlite3_open( from_db.toAscii().data() , &p_from );
    if( rc != SQLITE_OK ){
        return rc ;
    }

    rc = sqlite3_open( to_db.toAscii().data() , &p_dest );
    if( rc != SQLITE_OK && rc != SQLITE_ERROR ){
        sqlite3_close( p_from ) ;
        return rc ;
    }

    p_backup = sqlite3_backup_init( p_dest , "main" , p_from , "main" );
    if( p_backup )
    {
        do {
            rc = sqlite3_backup_step( p_backup , 1 ) ;
        } while( rc==SQLITE_OK || rc==SQLITE_BUSY || rc==SQLITE_LOCKED );
        sqlite3_backup_finish( p_backup );
    }
    else
        return SQLITE_ERROR ;

    sqlite3_close( p_from ) ;
    sqlite3_close( p_dest ) ;

    return SQLITE_OK ;
}
Example #3
0
//------------------------------------------------------------------------------
BOOL BackupSQLITESession(char *src, char *dst)
{
  sqlite3 *dst_file, *src_file;
  if (sqlite3_open(dst, &dst_file) != SQLITE_OK)
  {
    return FALSE;
  }

  if (sqlite3_open(src, &src_file) != SQLITE_OK)
  {
    sqlite3_close(dst_file);
    return FALSE;
  }

  //backup
  BOOL ret = FALSE;
  sqlite3_backup *pBackup = sqlite3_backup_init(dst_file, "main", src_file, "main");
  if (pBackup)
  {
    sqlite3_backup_step(pBackup, -1);
    sqlite3_backup_finish(pBackup);
    ret = TRUE;
  }

  //close
  sqlite3_close(dst_file);
  sqlite3_close(src_file);

  return ret;
}
Example #4
0
// Release resource for SQLite database backup
Backup::~Backup() noexcept
{
    if (NULL != mpSQLiteBackup)
    {
        sqlite3_backup_finish(mpSQLiteBackup);
    }
}
Example #5
0
int sqlite3_backup_finish_idr(void *backup){
	
	DBbackup* dbi=(DBbackup*) backup;
	int res = sqlite3_backup_finish(dbi->backup);
	return res;
	
	
}
int bwl_backup_database(const char *szBackupDBFilePath)
{
#if SQLITE_VERSION_NUMBER >= 3006011
    if (NULL == db)
    {
        LOG("Blacklist Whitelist Database File Has Been Closed!");
        return BWLIST_ERROR;
    }

    sqlite3* pDBBake;
    sqlite3_backup* pBackup;
    int rc;
    rc = sqlite3_open(szBackupDBFilePath, &pDBBake);
    if (rc != SQLITE_OK)
    {
        LOG("Open Backup DB error:%s.", sqlite3_errmsg(pDBBake));
        sqlite3_close(pDBBake);
        return BWLIST_ERROR;
    }

    pBackup = sqlite3_backup_init(pDBBake, "main", db, "main");
    if (pBackup == 0)
    {
        LOG("Backup Init Error:%s.", sqlite3_errmsg(pDBBake));
        sqlite3_close(pDBBake);
        return BWLIST_ERROR;
    }

    do
    {
        rc = sqlite3_backup_step(pBackup, BACKUP_PAGECOUNT);
        if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED)
        {
          sqlite3_sleep(250);
        }
    }
    while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);

    sqlite3_backup_finish(pBackup);
    if (rc == SQLITE_DONE)
    {
        sqlite3_close(pDBBake);
        return BWLIST_OK;
    }
    else
    {
        LOG("Backup Step Error:%s.", sqlite3_errmsg(pDBBake));
        sqlite3_close(pDBBake);
        return BWLIST_ERROR;
    }

#else

    LOG("Backup not supported in this SQLite Version!");
    return BWLIST_ERROR;

#endif
}
Example #7
0
svn_error_t *
svn_sqlite__hotcopy(const char *src_path,
                    const char *dst_path,
                    apr_pool_t *scratch_pool)
{
  svn_sqlite__db_t *src_db;

  SVN_ERR(svn_sqlite__open(&src_db, src_path, svn_sqlite__mode_readonly,
                           NULL, 0, NULL, 0,
                           scratch_pool, scratch_pool));

  {
    svn_sqlite__db_t *dst_db;
    sqlite3_backup *backup;
    int rc1, rc2;

    SVN_ERR(svn_sqlite__open(&dst_db, dst_path, svn_sqlite__mode_rwcreate,
                             NULL, 0, NULL, 0, scratch_pool, scratch_pool));
    backup = sqlite3_backup_init(dst_db->db3, "main", src_db->db3, "main");
    if (!backup)
      return svn_error_createf(SVN_ERR_SQLITE_ERROR, NULL,
                               _("SQLite hotcopy failed for %s"), src_path);
    do
      {
        /* Pages are usually 1024 byte (SQLite docs). On my laptop
           copying gets faster as the number of pages is increased up
           to about 64, beyond that speed levels off.  Lets put the
           number of pages an order of magnitude higher, this is still
           likely to be a fraction of large databases. */
        rc1 = sqlite3_backup_step(backup, 1024);

        /* Should we sleep on SQLITE_OK?  That would make copying a
           large database take much longer.  When we do sleep how,
           long should we sleep?  Should the sleep get longer if we
           keep getting BUSY/LOCKED?  I have no real reason for
           choosing 25. */
        if (rc1 == SQLITE_BUSY || rc1 == SQLITE_LOCKED)
          sqlite3_sleep(25);
      }
    while (rc1 == SQLITE_OK || rc1 == SQLITE_BUSY || rc1 == SQLITE_LOCKED);
    rc2 = sqlite3_backup_finish(backup);
    if (rc1 != SQLITE_DONE)
      SQLITE_ERR(rc1, dst_db);
    SQLITE_ERR(rc2, dst_db);
    SVN_ERR(svn_sqlite__close(dst_db));
  }

  SVN_ERR(svn_sqlite__close(src_db));

  SVN_ERR(svn_io_copy_perms(src_path, dst_path, scratch_pool));

  return SVN_NO_ERROR;
}
Example #8
0
void SqliteConnection::copy_to(const SqliteConnectionPtr& pDest) {
    sqlite3_backup* backup =
        sqlite3_backup_init(pDest->conn(), "main", pConn_, "main");

    int rc = sqlite3_backup_step(backup, -1);
    if (rc != SQLITE_DONE) {
        stop("Failed to copy all data:\n%s", getException());
    }
    rc = sqlite3_backup_finish(backup);
    if (rc != SQLITE_OK) {
        stop("Could not finish copy:\n%s", getException());
    }
}
Example #9
0
/* perfexpert_database_connect */
int perfexpert_database_connect(sqlite3 **db, const char *file) {
    sqlite3_backup *pBackup;
    sqlite3 *disk_db;
    char *error = NULL;

    /* Check if file exists */
    if (-1 == access(file, F_OK)) {
        OUTPUT(("%s (%s)", _ERROR((char *)"file not found"), file));
        goto CLEAN_UP;
    }

    /* Open the DB on disk */
    if (SQLITE_OK != sqlite3_open(file, &disk_db)) {
        OUTPUT(("%s (%s), %s", _ERROR((char *)"openning database"), file,
                sqlite3_errmsg(disk_db)));
        goto CLEAN_UP;
    }

    /* Open the DB in memory */
    if (SQLITE_OK != sqlite3_open(":memory:", db)) {
        OUTPUT(("%s (%s)", _ERROR((char *)"openning in-memory database"),
                sqlite3_errmsg(*db)));
        goto CLEAN_UP;
    }

    /* Copy the data from disk DB to in-memory DB */
    pBackup = sqlite3_backup_init(*db, "main", disk_db, "main");
    if (pBackup) {
        (void)sqlite3_backup_step(pBackup, -1);
        (void)sqlite3_backup_finish(pBackup);
    }
    if (SQLITE_OK != sqlite3_errcode(*db)) {
        goto CLEAN_UP;
    }

    /* Enable foreign keys */
    if (SQLITE_OK != sqlite3_exec(*db, "PRAGMA foreign_keys = ON;", NULL, NULL, &error)) {
        OUTPUT(("%s %s", _ERROR("SQL error (enabling foreign keys)"), error));
        sqlite3_free(error);
        goto CLEAN_UP;
    }

    OUTPUT_VERBOSE((4, "      connected to %s", file));

    return PERFEXPERT_SUCCESS;

CLEAN_UP:
    sqlite3_close(*db);
    sqlite3_close(disk_db);
    return PERFEXPERT_ERROR;
}
Example #10
0
int loadDb(sqlite3 *pInMemory, sqlite3 *pfileDB){
  int rc;                   /* Function return code */
  sqlite3_backup *pBackup;  /* Backup object used to copy data */


    pBackup = sqlite3_backup_init(pInMemory, "main", pfileDB, "main");
    if( pBackup ){
      (void)sqlite3_backup_step(pBackup, -1);
      (void)sqlite3_backup_finish(pBackup);
    }
    rc = sqlite3_errcode(pInMemory);

  return rc;
}
Example #11
0
void Database::BackupFile(const QString& filename) {
    qLog(Debug) << "Starting database backup";
    QString dest_filename = QString("%1.bak").arg(filename);
    const int task_id =
        app_->task_manager()->StartTask(tr("Backing up database"));

    sqlite3* source_connection = nullptr;
    sqlite3* dest_connection = nullptr;

    BOOST_SCOPE_EXIT((source_connection)(dest_connection)(task_id)(app_)) {
        // Harmless to call sqlite3_close() with a nullptr pointer.
        sqlite3_close(source_connection);
        sqlite3_close(dest_connection);
        app_->task_manager()->SetTaskFinished(task_id);
    }
    BOOST_SCOPE_EXIT_END

    bool success = OpenDatabase(filename, &source_connection);
    if (!success) {
        return;
    }

    success = OpenDatabase(dest_filename, &dest_connection);
    if (!success) {
        return;
    }

    sqlite3_backup* backup =
        sqlite3_backup_init(dest_connection, "main", source_connection, "main");
    if (!backup) {
        const char* error_message = sqlite3_errmsg(dest_connection);
        qLog(Error) << "Failed to start database backup:" << error_message;
        return;
    }

    int ret = SQLITE_OK;
    do {
        ret = sqlite3_backup_step(backup, 16);
        const int page_count = sqlite3_backup_pagecount(backup);
        app_->task_manager()->SetTaskProgress(
            task_id, page_count - sqlite3_backup_remaining(backup), page_count);
    } while (ret == SQLITE_OK);

    if (ret != SQLITE_DONE) {
        qLog(Error) << "Database backup failed";
    }

    sqlite3_backup_finish(backup);
}
Example #12
0
/*
** This function is used to load the contents of a database file on disk
** into the "main" database of open database connection pInMemory, or
** to save the current contents of the database opened by pInMemory into
** a database file on disk. pInMemory is probably an in-memory database,
** but this function will also work fine if it is not.
**
** Parameter zFilename points to a nul-terminated string containing the
** name of the database file on disk to load from or save to. If parameter
** isSave is non-zero, then the contents of the file zFilename are
** overwritten with the contents of the database opened by pInMemory. If
** parameter isSave is zero, then the contents of the database opened by
** pInMemory are replaced by data loaded from the file zFilename.
**
** If the operation is successful, SQLITE_OK is returned. Otherwise, if
** an error occurs, an SQLite error code is returned.
*/
int loadOrSaveDb(sqlite3 *pInMemory, const char *zFilename, int isSave)
{
    int rc;                  /* Function return code */
    sqlite3 *pFile;          /* SqliteDatabase connection opened on zFilename */
    sqlite3_backup *pBackup; /* Backup object used to copy data */
    sqlite3 *pTo;            /* SqliteDatabase to copy to (pFile or pInMemory) */
    sqlite3 *pFrom;          /* SqliteDatabase to copy from (pFile or pInMemory) */

    /* Open the database file identified by zFilename. Exit early if this fails
                              ** for any reason. */
    rc = sqlite3_open(zFilename, &pFile);
    if (rc == SQLITE_OK)
    {

        /* If this is a 'load' operation (isSave==0), then data is copied
        ** from the database file just opened to database pInMemory.
        ** Otherwise, if this is a 'save' operation (isSave==1), then data
        ** is copied from pInMemory to pFile.  Set the variables pFrom and
        ** pTo accordingly. */
        pFrom = (isSave ? pInMemory : pFile);
        pTo = (isSave ? pFile : pInMemory);

        /* Set up the backup procedure to copy from the "main" database of
        ** connection pFile to the main database of connection pInMemory.
        ** If something goes wrong, pBackup will be set to NULL and an error
        ** code and  message left in connection pTo.
        **
        ** If the backup object is successfully created, call backup_step()
        ** to copy data from pFile to pInMemory. Then call backup_finish()
        ** to release resources associated with the pBackup object.  If an
        ** error occurred, then  an error code and message will be left in
        ** connection pTo. If no error occurred, then the error code belonging
        ** to pTo is set to SQLITE_OK.
        */
        pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
        if (pBackup)
        {
            (void)sqlite3_backup_step(pBackup, -1);
            (void)sqlite3_backup_finish(pBackup);
        }
        rc = sqlite3_errcode(pTo);
    }

    /* Close the database connection opened on database file zFilename
    ** and return the result of this function. */
    (void)sqlite3_close(pFile);
    return rc;
}
Example #13
0
static int load_or_save_memory(osux_database *db, bool is_save)
{
    sqlite3_backup *pBackup;  /* Backup object used to copy data */
    sqlite3 *pTo;             /* Database to copy to (pFile or pInMemory) */
    sqlite3 *pFrom;           /* Database to copy from (pFile or pInMemory) */

    pFrom = (is_save ? db->mem_handle  : db->file_handle);
    pTo   = (is_save ? db->file_handle : db->mem_handle);

    pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
    if (pBackup) {
        (void) sqlite3_backup_step(pBackup, -1);
        (void) sqlite3_backup_finish(pBackup);
    }
    return sqlite3_errcode(pTo);
}
Example #14
0
result_t SQLite::backup(exlib::string fileName, AsyncEvent *ac)
{
    if (!m_db)
        return CHECK_ERROR(CALL_E_INVALID_CALL);

    if (!ac)
        return CHECK_ERROR(CALL_E_NOSYNC);

    int32_t rc;
    struct sqlite3 *db2 = NULL;
    sqlite3_backup *pBackup;

    const char* c_str = fileName.c_str();

    if (!qstrcmp(c_str, "sqlite:", 7))
        c_str += 7;

    if (sqlite3_open_v2(c_str, &db2, SQLITE_OPEN_FLAGS, 0))
    {
        result_t hr = CHECK_ERROR(Runtime::setError(sqlite3_errmsg(db2)));
        return hr;
    }

    pBackup = sqlite3_backup_init(db2, "main", m_db, "main");
    if (pBackup)
    {
        do
        {
            rc = sqlite3_backup_step(pBackup, 5);
            if (rc == SQLITE_LOCKED)
                sqlite3_sleep(1);
        }
        while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);

        sqlite3_backup_finish(pBackup);
    }
    else
    {
        result_t hr = CHECK_ERROR(Runtime::setError(sqlite3_errmsg(m_db)));
        sqlite3_close(db2);
        return hr;
    }

    sqlite3_close(db2);

    return 0;
}
Example #15
0
  SNPdb::SNPdb(const string& SNP_db_filename) {
    int rc;
    sqlite3 *db1;

    rc = sqlite3_open(":memory:", &db);
    if(rc != SQLITE_OK) {
      sqlite3_close(db);
      throw runtime_error(string("Can't open database: ") + string(sqlite3_errmsg(db)));
    }

    rc = sqlite3_open(SNP_db_filename.c_str(), &db1);
    if(rc != SQLITE_OK) {
      sqlite3_close(db);
      sqlite3_close(db1);
      throw runtime_error(string("Can't open database: ") + string(sqlite3_errmsg(db)));
    }

    sqlite3_backup* bak = sqlite3_backup_init(db, "temp", db1, "main");
    if (bak == NULL) {
      sqlite3_close(db);
      sqlite3_close(db1);
      throw runtime_error(string("Can't init backup: ") + string(sqlite3_errmsg(db)));
    }

    rc = sqlite3_backup_step(bak, -1);
    if (rc != SQLITE_DONE) {
      sqlite3_close(db);
      sqlite3_close(db1);
      throw runtime_error(string("Can't step backup: ") + string(sqlite3_errmsg(db)));
    }

    rc = sqlite3_backup_finish(bak);
    if (rc != SQLITE_OK) {
      sqlite3_close(db);
      sqlite3_close(db1);
      throw runtime_error(string("Can't finish backup: ") + string(sqlite3_errmsg(db)));
    }

    sqlite3_close(db1);

    rc = sqlite3_prepare_v2(db, "select pos, ref, alt from snps where chrom=? and pos between ? and ?", -1, &intervalSearch, NULL);
    if (rc != SQLITE_OK) {
      sqlite3_close(db);
      throw runtime_error(string("Can't prepare statement: ") + string(sqlite3_errmsg(db)));
    }
  }
Example #16
0
int SqliteDatabase::copy(const char *backup_name) {
  if (active == false)
    throw DbErrors("Can't copy database: no active connection...");

  CLog::Log(LOGDEBUG, "Copying from %s to %s at %s", db.c_str(), backup_name, host.c_str());

  int rc;
  std::string backup_db = backup_name;

  sqlite3 *pFile;           /* Database connection opened on zFilename */
  sqlite3_backup *pBackup;  /* Backup object used to copy data */

  //
  if (backup_name[0] == '/' || backup_name[0] == '\\')
    backup_db = backup_db.substr(1);

  // ensure the ".db" extension is appended to the end
  if ( backup_db.find(".db") != (backup_db.length()-3) )
    backup_db += ".db";

  std::string backup_path = host + backup_db;

  /* Open the database file identified by zFilename. Exit early if this fails
  ** for any reason. */
  rc = sqlite3_open(backup_path.c_str(), &pFile);
  if( rc==SQLITE_OK )
  {
    pBackup = sqlite3_backup_init(pFile, "main", getHandle(), "main");

    if( pBackup )
    {
      (void)sqlite3_backup_step(pBackup, -1);
      (void)sqlite3_backup_finish(pBackup);
    }

    rc = sqlite3_errcode(pFile);
  }

  (void)sqlite3_close(pFile);

  if( rc != SQLITE_OK )
    throw DbErrors("Can't copy database. (%d)", rc);

  return rc;
}
Example #17
0
/* perfexpert_database_disconnect */
int perfexpert_database_disconnect(sqlite3 *db) {
    char *my_file = NULL;
    sqlite3_backup *pBackup;
    sqlite3 *disk_db;

    /* Sanity check: only disconnect from a DB which is connected */
    if (NULL == db) {
        return PERFEXPERT_SUCCESS;
    }

    /* Open the DB on disk */
    PERFEXPERT_ALLOC(char, my_file,
                     (strlen(PERFEXPERT_DB) + strlen(globals.workdir) + 2));
    sprintf(my_file, "%s/%s", globals.workdir, PERFEXPERT_DB);

    if (SQLITE_OK != sqlite3_open(my_file, &disk_db)) {
        OUTPUT(("%s (%s), %s", _ERROR((char *)"openning output database"),
                my_file, sqlite3_errmsg(disk_db)));
        return PERFEXPERT_ERROR;
    }

    /* Copy the data from disk DB to in-memory DB */
    pBackup = sqlite3_backup_init(disk_db, "main", db, "main");
    if (pBackup) {
        (void)sqlite3_backup_step(pBackup, -1);
        (void)sqlite3_backup_finish(pBackup);
    }
    if (SQLITE_OK != sqlite3_errcode(db)) {
        OUTPUT(("%s (%s), %s", _ERROR((char *)"writing output database"),
                my_file, sqlite3_errmsg(disk_db)));
        PERFEXPERT_DEALLOC(my_file);
        return PERFEXPERT_ERROR;
    }
    PERFEXPERT_DEALLOC(my_file);

    sqlite3_close(db);
    sqlite3_close(disk_db);

    OUTPUT_VERBOSE((4, "disconnected from database (saved in %s/%s)",
                    globals.workdir, PERFEXPERT_DB));

    return PERFEXPERT_SUCCESS;
}
int loadOrSaveDB(sqlite3* pInMemory, const QString& sFilename, bool bSave)
{
    int rc = 0;                   //函数返回值
    sqlite3* pFile = nullptr;           //打开的硬盘数据库指针
    sqlite3_backup* pBackup = nullptr;  //拷贝数据临时对象句柄
    sqlite3* pTo = nullptr;             //目标数据库
    sqlite3* pFrom = nullptr;           //源数据库

    /************************************************************************/
    /*
    SQLite提供了以下3个APIs函数用于完成此操作,这里仅仅给出它们的基本用法,
    至于使用细节可以参考SQLite官方网站"APIs Reference"(http://www.sqlite.org/c3ref/backup_finish.html)。
    1). 函数sqlite3_backup_init()用于创建sqlite3_backup对象,该对象将作为本次拷贝操作的句柄传给其余两个函数。
    2). 函数sqlite3_backup_step()用于数据拷贝,如果该函数的第二个参数为-1,那么整个拷贝过程都将在该函数的一次调用中完成。
    3). 函数sqlite3_backup_finish()用于释放sqlite3_backup_init()函数申请的资源,以避免资源泄露。
    在整个拷贝过程中如果出现任何错误,我们都可以通过调用目的数据库连接的sqlite3_errcode()函数来获取具体的错误码。
    此外,如果sqlite3_backup_step()调用失败,由于sqlite3_backup_finish()函数并不会修改当前连接的错误码,因
    此我们可以在调用sqlite3_backup_finish()之后再获取错误码,从而在代码中减少了一次错误处理。
    */
    /************************************************************************/
    //打开本地文件
    std::string sStdFilename = sFilename.toStdString();
    const char* pFilename = sStdFilename.c_str();
    rc = sqlite3_open(pFilename, &pFile);
    if (rc == SQLITE_OK)
    {
        //如果是保存,则是将内存数据库写入硬盘。
        //反之则是将硬盘数据库写入内存
        pFrom = (bSave ? pInMemory : pFile);
        pTo = (bSave ? pFile : pInMemory);

        pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
        if (pBackup){
            (void)sqlite3_backup_step(pBackup, -1);
            (void)sqlite3_backup_finish(pBackup);
        }
        rc = sqlite3_errcode(pTo);
    }

    (void)sqlite3_close(pFile);
    return rc;
}
void CEvaluationEngine::terminateEngine()
{
    SSMRESULT           res = SSM_E_FAIL;
    sqlite3             *pBackupFile = NULL;
    sqlite3_backup      *pBackup = NULL;
    std::stringstream   sstream;

    //Remove all triggers on db side
    m_mtxTriggerId.lock();
    for (std::map<int, IEvaluationEngineEvent *>::iterator itor = m_mapTriggers.begin();
         itor != m_mapTriggers.end(); ++itor)
    {
        sstream << "drop trigger WatchInsertModel" << itor->first << ";" << std::ends;
        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));
        sstream.str("");

        sstream << "drop trigger WatchUpdateModel" << itor->first << ";" << std::ends;
        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));
        sstream.str("");
    }
    m_mtxTriggerId.unlock();

    if (strlen(LOCATION_SSM_DB_DUMP) > 0)
    {
        CHK_SQLITE(sqlite3_open(LOCATION_SSM_DB_DUMP, &pBackupFile), SQLITE_OK);
        pBackup = sqlite3_backup_init(pBackupFile, "main", m_pSQLite3, "main");
        CHK_SQLITE(sqlite3_errcode(pBackupFile), SQLITE_OK);
        SSM_CLEANUP_NULL_ASSERT(pBackup);
        CHK_SQLITE(sqlite3_backup_step(pBackup, -1), SQLITE_DONE);
        CHK_SQLITE(sqlite3_backup_finish(pBackup), SQLITE_OK);
        CHK_SQLITE(sqlite3_close(pBackupFile), SQLITE_OK);
    }

    CHK_SQLITE(sqlite3_close(m_pSQLite3), SQLITE_OK);

    m_pSQLite3 = NULL;

    res = SSM_S_OK;
CLEANUP:
    return;
}
Example #20
0
bool Utility::fileToMemory(sqlite3* pInMemory, const std::string& fileName)
{
	int rc;
	sqlite3* pFile;
	sqlite3_backup* pBackup;

	rc = sqlite3_open_v2(fileName.c_str(), &pFile, SQLITE_OPEN_READONLY | SQLITE_OPEN_URI, NULL);
	if(rc == SQLITE_OK )
	{
		pBackup = sqlite3_backup_init(pInMemory, "main", pFile, "main");
		if( pBackup )
		{
			sqlite3_backup_step(pBackup, -1);
			sqlite3_backup_finish(pBackup);
		}
		rc = sqlite3_errcode(pFile);
	}

	sqlite3_close(pFile);
	return SQLITE_OK == rc;
}
Example #21
0
bool Utility::memoryToFile(const std::string& fileName, sqlite3* pInMemory)
{
	int rc;
	sqlite3* pFile;
	sqlite3_backup* pBackup;

	rc = sqlite3_open(fileName.c_str(), &pFile);
	if(rc == SQLITE_OK )
	{
		pBackup = sqlite3_backup_init(pFile, "main", pInMemory, "main");
		if( pBackup )
		{
			sqlite3_backup_step(pBackup, -1);
			sqlite3_backup_finish(pBackup);
		}
		rc = sqlite3_errcode(pFile);
	}

	sqlite3_close(pFile);
	return SQLITE_OK == rc;
}
Example #22
0
bool CSqliteBase::loadOrSaveDb(sqlite3 * & pInMemeory, const char *zFilename, bool isSave)  

{
	int rc;  

	sqlite3 *pFile;  

	sqlite3_backup *pBackup;  

	sqlite3 *pTo;  

	sqlite3 *pFrom;  

	rc = sqlite3_open(zFilename, &pFile);  

	if(rc == SQLITE_OK)  

	{  

		pFrom = (isSave?pInMemeory:pFile);  
		pTo = (isSave?pFile:pInMemeory);  

		pBackup = sqlite3_backup_init(pTo,"main",pFrom,"main");  

		if(pBackup)  
		{  
			(void)sqlite3_backup_step(pBackup,-1);  
			(void)sqlite3_backup_finish(pBackup);  
		}  

		rc = sqlite3_errcode(pTo);  

	}  

	(void)sqlite3_close(pFile);  
	if(rc ==SQLITE_OK)
		return true;

	return false;  
}  
Example #23
0
/**
 * @brief Perform an online backup of our database db to the database file named
 * by zFilename. Used to store our memory table in between map changes to disk
 *
 * This function copies 5 database pages from pDb to
 * zFilename, then unlocks pDb and sleeps for 250 ms, then repeats the
 * process until the entire database is backed up.
 *
 * The third argument passed to this function must be a pointer to a progress
 * function. After each set of 5 pages is backed up, the progress function
 * is invoked with two integer parameters: the number of pages left to
 * copy, and the total number of pages in the source file. This information
 * may be used, for example, to update a GUI progress bar.
 *
 * While this function is running, another thread may use the database pDb, or
 * another process may access the underlying database file via a separate
 * connection.
 *
 * If the backup process is successfully completed, SQLITE_OK is returned.
 * Otherwise, if an error occurs, an SQLite error code is returned.
 *
 * @param zFilename
 *
 * @return
 *
 */
int DB_BackupDB(const char *zFilename, void (*xProgress)(int, int)) // Progress function to invoke
{
	int            rc;        // Function return code
	sqlite3        *pFile;    // Database connection opened on zFilename
	sqlite3_backup *pBackup;  // Backup handle used to copy data

	// Open the database file identified by zFilename.
	rc = sqlite3_open(zFilename, &pFile);
	if (rc == SQLITE_OK)
	{
		// Open the sqlite3_backup object used to accomplish the transfer
		pBackup = sqlite3_backup_init(pFile, "main", db, "main");
		if (pBackup)
		{
			// Each iteration of this loop copies 5 database pages from database
			// pDb to the backup database. If the return value of backup_step()
			// indicates that there are still further pages to copy, sleep for
			// 250 ms before repeating.
			do
			{
				rc = sqlite3_backup_step(pBackup, 5);
				xProgress(sqlite3_backup_remaining(pBackup), sqlite3_backup_pagecount(pBackup));
				if (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED)
				{
					sqlite3_sleep(250);
				}
			}
			while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);

			// Release resources allocated by backup_init().
			(void) sqlite3_backup_finish(pBackup);
		}
		rc = sqlite3_errcode(pFile);
	}

	// Close the database connection opened on database file zFilename and return the result of this function.
	(void) sqlite3_close(pFile);
	return rc;
}
Example #24
0
ECode CBackup::NativeFinalize()
{
#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
    hbk *bk = mHandle;
    Int32 ret = SQLITE_OK;
    char *err = 0;

    if (bk) {
    if (bk->h) {
        handle *h = bk->h;
        hbk *bkc, **bkp;

        bkp = &h->backups;
        bkc = *bkp;
        while (bkc) {
        if (bkc == bk) {
            *bkp = bkc->next;
            break;
        }
        bkp = &bkc->next;
        bkc = *bkp;
        }
    }
    if (bk->bkup) {
        ret = sqlite3_backup_finish(bk->bkup);
        if (ret != SQLITE_OK && bk->h) {
        err = (char *) sqlite3_errmsg((sqlite3 *) bk->h->sqlite);
        }
    }
    bk->bkup = 0;
    free(bk);
    mHandle = 0;
    if (ret != SQLITE_OK) {
        return E_SQL_SQLITE_THROWEX_EXCEPTION;
    }
    }
#endif
    return NOERROR;
}
Example #25
0
static int backupTestCmd(
  ClientData clientData, 
  Tcl_Interp *interp, 
  int objc,
  Tcl_Obj *const*objv
){
  enum BackupSubCommandEnum {
    BACKUP_STEP, BACKUP_FINISH, BACKUP_REMAINING, BACKUP_PAGECOUNT
  };
  struct BackupSubCommand {
    const char *zCmd;
    enum BackupSubCommandEnum eCmd;
    int nArg;
    const char *zArg;
  } aSub[] = {
    {"step",      BACKUP_STEP      , 1, "npage" },
    {"finish",    BACKUP_FINISH    , 0, ""      },
    {"remaining", BACKUP_REMAINING , 0, ""      },
    {"pagecount", BACKUP_PAGECOUNT , 0, ""      },
    {0, 0, 0, 0}
  };

  sqlite3_backup *p = (sqlite3_backup *)clientData;
  int iCmd;
  int rc;

  rc = Tcl_GetIndexFromObjStruct(
      interp, objv[1], aSub, sizeof(aSub[0]), "option", 0, &iCmd
  );
  if( rc!=TCL_OK ){
    return rc;
  }
  if( objc!=(2 + aSub[iCmd].nArg) ){
    Tcl_WrongNumArgs(interp, 2, objv, aSub[iCmd].zArg);
    return TCL_ERROR;
  }

  switch( aSub[iCmd].eCmd ){

    case BACKUP_FINISH: {
      const char *zCmdName;
      Tcl_CmdInfo cmdInfo;
      zCmdName = Tcl_GetString(objv[0]);
      Tcl_GetCommandInfo(interp, zCmdName, &cmdInfo);
      cmdInfo.deleteProc = 0;
      Tcl_SetCommandInfo(interp, zCmdName, &cmdInfo);
      Tcl_DeleteCommand(interp, zCmdName);

      rc = sqlite3_backup_finish(p);
      Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC);
      break;
    }

    case BACKUP_STEP: {
      int nPage;
      if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &nPage) ){
        return TCL_ERROR;
      }
      rc = sqlite3_backup_step(p, nPage);
      Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC);
      break;
    }

    case BACKUP_REMAINING:
      Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_remaining(p)));
      break;

    case BACKUP_PAGECOUNT:
      Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_backup_pagecount(p)));
      break;
  }

  return TCL_OK;
}
Example #26
0
backup::~backup() {
	if (handle) {
		sqlite3_backup_finish(handle);
	}
}
Example #27
0
SQLiteBkp::~SQLiteBkp()
{
    sqlite3_backup_finish(m_bkp);
}
Example #28
0
static int
copy_database(sqlite3 *src, sqlite3 *dst, const char *name)
{
	sqlite3_backup	*b;
	char		*errmsg;
	off_t		 total;
	off_t		 done;
	off_t		 page_size;
	time_t		 start;
	time_t		 elapsed;
	int		 ret;

	assert(src != NULL);
	assert(dst != NULL);

	/* Do not remove until gcc has gone from FreeBSD base */
	done = total = 0;

	ret = sqlite3_exec(dst, "PRAGMA main.locking_mode=EXCLUSIVE;"
			   "BEGIN IMMEDIATE;COMMIT;", NULL, NULL, &errmsg);
	if (ret != SQLITE_OK) {
		pkg_emit_error("sqlite error -- %s", errmsg);
		sqlite3_free(errmsg);
		return (EPKG_FATAL);
	}

	ret = sqlite3_exec(dst, "PRAGMA page_size", ps_cb, &page_size, &errmsg);
	if (ret != SQLITE_OK) {
		pkg_emit_error("sqlite error -- %s", errmsg);
		sqlite3_free(errmsg);
		return (EPKG_FATAL);
	}

	b = sqlite3_backup_init(dst, "main", src, "main");

	elapsed = -1;
	done = total = 0;
	start = time(NULL);

	do {
		ret = sqlite3_backup_step(b, NPAGES);

		if (ret != SQLITE_OK && ret != SQLITE_DONE ) {
			if (ret == SQLITE_BUSY) {
				sqlite3_sleep(250);
			} else {
				ERROR_SQLITE(dst);
				break;
			}
		}

		total = sqlite3_backup_pagecount(b) * page_size;
		done = total - sqlite3_backup_remaining(b) * page_size; 

		/* Callout no more than once a second */
		if (elapsed < time(NULL) - start) {
			elapsed = time(NULL) - start;
			pkg_emit_fetching(name, total, done, elapsed);
		}
	} while(done < total);

	ret = sqlite3_backup_finish(b);
	pkg_emit_fetching(name, total, done, time(NULL) - start); 

	sqlite3_exec(dst, "PRAGMA main.locking_mode=NORMAL;"
			   "BEGIN IMMEDIATE;COMMIT;", NULL, NULL, &errmsg);

	if (ret != SQLITE_OK) {
		pkg_emit_error("sqlite error -- %s", errmsg);
		sqlite3_free(errmsg);
		return (EPKG_FATAL);
	}

	return ret;
}
SSMRESULT CEvaluationEngine::initializeEngine()
{
    SSMRESULT           res = SSM_E_FAIL;
    sqlite3             *pBackupFile = NULL;
    sqlite3_backup      *pBackup = NULL;

    const char *strCreate_ModelRelationTable =
        "create table [ModelRelation]\
		(\
		modelId integer primary key autoincrement,\
		modelName text NOT NULL,\
		lPos int NOT NULL,\
		rPos int NOT NULL\
		);";

    const char *strCreate_DataRelationTable =
        "create table [DataRelation]\
		(\
		id integer primary key autoincrement,\
		modelId int NOT NULL,\
		lPos int NOT NULL,\
		rPos int NOT NULL,\
		dataId int NOT NULL\
		);";

    //Create rootModel
    const char *strRootModel = "insert into [ModelRelation] values (null, 'root', 1, 2);";

    const char *tblRoot =
        "create table [ModelData1](dataId integer primary key autoincrement, name text);";

    const char *rootData = "insert into [ModelData1] values (null, 'root');";

    const char *rootRelation = "insert into [DataRelation] values (null, 1, 1, 2, 1);";

    CHK_SQLITE(sqlite3_open_v2(LOCATION_SSM_DB, &m_pSQLite3,
                               SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL), SQLITE_OK);

    CHK_SQLITE(sqlite3_create_function_v2(m_pSQLite3, "OnSQLTrigger", 3, SQLITE_UTF8, NULL,
                                          onSQLTrigger, NULL, NULL, NULL),
               SQLITE_OK);

    if (strlen(LOCATION_SSM_DB_DUMP) > 0 &&
        sqlite3_open_v2(LOCATION_SSM_DB_DUMP, &pBackupFile, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
    {
        pBackup = sqlite3_backup_init(m_pSQLite3, "main", pBackupFile, "main");
        CHK_SQLITE(sqlite3_errcode(pBackupFile), SQLITE_OK);
        SSM_CLEANUP_NULL_ASSERT(pBackup);
        CHK_SQLITE(sqlite3_backup_step(pBackup, -1), SQLITE_DONE);
        CHK_SQLITE(sqlite3_backup_finish(pBackup), SQLITE_OK);
        CHK_SQLITE(sqlite3_close(pBackupFile), SQLITE_OK);
        res = SSM_S_OK;
    }
    else
    {
        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(strCreate_ModelRelationTable));
        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(strCreate_DataRelationTable));

        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(strRootModel));
        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(tblRoot));
        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(rootData));
        SSM_CLEANUP_ASSERT(executeSQL_NoReturn(rootRelation));
    }

CLEANUP:
    return res;
}
Example #30
0
static gboolean
backup_job (GIOSchedulerJob *job,
            GCancellable    *cancellable,
            gpointer         user_data)
{
	BackupInfo *info = user_data;

	const gchar *src_path;
	GFile *parent_file, *temp_file;
	gchar *temp_path;

	sqlite3 *src_db = NULL;
	sqlite3 *temp_db = NULL;
	sqlite3_backup *backup = NULL;

	src_path = tracker_db_manager_get_file (TRACKER_DB_METADATA);
	parent_file = g_file_get_parent (info->destination);
	temp_file = g_file_get_child (parent_file, TRACKER_DB_BACKUP_META_FILENAME_T);
	g_file_delete (temp_file, NULL, NULL);
	temp_path = g_file_get_path (temp_file);

	if (sqlite3_open_v2 (src_path, &src_db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Could not open sqlite3 database:'%s'", src_path);
	}

	if (!info->error && sqlite3_open (temp_path, &temp_db) != SQLITE_OK) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Could not open sqlite3 database:'%s'", temp_path);
	}

	if (!info->error) {
		backup = sqlite3_backup_init (temp_db, "main", src_db, "main");

		if (!backup) {
			g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
				     "Unable to initialize sqlite3 backup from '%s' to '%s'", src_path, temp_path);
		}
	}

	if (!info->error && sqlite3_backup_step (backup, -1) != SQLITE_DONE) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Unable to complete sqlite3 backup");
	}

	if (backup) {
		if (sqlite3_backup_finish (backup) != SQLITE_OK) {
			if (info->error) {
				/* sqlite3_backup_finish can provide more detailed error message */
				g_clear_error (&info->error);
			}
			g_set_error (&info->error,
			             TRACKER_DB_BACKUP_ERROR,
			             TRACKER_DB_BACKUP_ERROR_UNKNOWN,
				     "Unable to finish sqlite3 backup: %s",
				     sqlite3_errmsg (temp_db));
		}
		backup = NULL;
	}

	if (temp_db) {
		sqlite3_close (temp_db);
		temp_db = NULL;
	}

	if (src_db) {
		sqlite3_close (src_db);
		src_db = NULL;
	}

	if (!info->error) {
		g_file_move (temp_file, info->destination,
		             G_FILE_COPY_OVERWRITE,
		             NULL, NULL, NULL,
		             &info->error);
	}

	g_free (temp_path);
	g_object_unref (temp_file);
	g_object_unref (parent_file);

	g_idle_add_full (G_PRIORITY_DEFAULT, perform_callback, info,
	                 backup_info_free);

	return FALSE;
}