Esempio n. 1
0
// Takes care of query preparation and execution.
int prep_exec(FILE *f, sqlite3 *db, const char *q, const char *response_type) {
  sqlite3_stmt  *stmt;
  int result, prepare;
  if ((prepare = sqlite3_prepare_v2(db, q, -1, &stmt, 0)) == SQLITE_OK) {
    if (f) {
      result = file_prep_exec(f, stmt, response_type);
      fprintf(f, "\n");
    } else {
      /* Step only: queries with no resultset (check if 
       * table exists). For those queries preparation 
       * will always succeed.
       */ 
      result = sqlite3_step(stmt);
    }
  } else {
    if (f) {
      swill_fprintf(f, "Error in preparation of query: error no %i\n", prepare);
      swill_fprintf(f, "\nExtended error code %i.\n", sqlite3_extended_errcode(db));
      swill_fprintf(f, "\nExtended error message:\n%s\n\n", sqlite3_errmsg(db));
    }
    return prepare;
  }
  sqlite3_finalize(stmt);
  return result;
}
Esempio n. 2
0
bool SqlDatabase::openHelper(const QString &filename, int sqliteFlags)
{
    if (isOpen()) {
        return true;
    }

    sqliteFlags |= SQLITE_OPEN_NOMUTEX;

    SQLITE_DO(sqlite3_open_v2(filename.toUtf8().constData(), &_db, sqliteFlags, 0));

    if (_errId != SQLITE_OK) {
        qCWarning(lcSql) << "Error:" << _error << "for" << filename;
        if (_errId == SQLITE_CANTOPEN) {
            qCWarning(lcSql) << "CANTOPEN extended errcode: " << sqlite3_extended_errcode(_db);
#if SQLITE_VERSION_NUMBER >= 3012000
            qCWarning(lcSql) << "CANTOPEN system errno: " << sqlite3_system_errno(_db);
#endif
        }
        close();
        return false;
    }

    if (!_db) {
        qCWarning(lcSql) << "Error: no database for" << filename;
        return false;
    }

    sqlite3_busy_timeout(_db, 5000);

    return true;
}
Esempio n. 3
0
bool Handle::exec(const Statement &statement)
{
    int rc =
        sqlite3_exec((sqlite3 *) m_handle, statement.getDescription().c_str(),
                     nullptr, nullptr, nullptr);
    bool result = rc == SQLITE_OK;
    if (statement.getStatementType() == Statement::Type::Transaction) {
        const StatementTransaction &transaction =
            (const StatementTransaction &) statement;
        switch (transaction.getTransactionType()) {
            case StatementTransaction::Type::Begin:
                if (result) {
                    m_aggregation = true;
                }
                break;
            case StatementTransaction::Type::Commit:
                if (result) {
                    m_aggregation = false;
                }
                break;
            case StatementTransaction::Type::Rollback:
                m_aggregation = false;
                break;
        }
    }
    if (result) {
        m_error.reset();
        return true;
    }
    Error::ReportSQLite(m_tag, path, Error::HandleOperation::Exec, rc,
                        sqlite3_extended_errcode((sqlite3 *) m_handle),
                        sqlite3_errmsg((sqlite3 *) m_handle),
                        statement.getDescription(), &m_error);
    return false;
}
Esempio n. 4
0
int
duf_sqlite_prepare( const char *sql, duf_sqlite_stmt_t ** pstmt )
{
  int r3 = 0;
  const char *tail = NULL;

  assert( pDb );
  r3 = sqlite3_prepare_v2( pDb, sql, strlen( sql ), pstmt, &tail );
  DUF_TRACE( sqlite, 2, "  [%s]", sql );
  if ( r3 == SQLITE_ERROR )
  {
    const char *em = sqlite3_errmsg( pDb );

    DUF_SHOW_ERROR( "{%d:%d} can't prepare SQL:[%s] - %s", sqlite3_errcode( pDb ), sqlite3_extended_errcode( pDb ), sql, em );
    if ( sqlite3_strglob( "no such table: *", sqlite3_errmsg( pDb ) ) == 0 )
    {
/* changed DUF_ERROR_SQL_NO_TABLE => duf_r2sqlite_error_code(DUF_ERROR_SQL_NO_TABLE)
 * Not tested */
      r3 = duf_r2sqlite_error_code( DUF_ERROR_SQL_NO_TABLE ); /* FIXME : this is r3, not r; so DUF_ERROR_SQL_NO_TABLE is wrong */
      assert( duf_sqlite2r_error_code( r3 ) == DUF_ERROR_SQL_NO_TABLE );
      assert( 0 );
    }
    else
    {
      assert( 0 );
    }
  }
  /* assert( r3 == 0 ); */
  /* assert( r3 != SQLITE_MISUSE ); */
  DUF_TEST_R3S( r3, sql );
  return r3;
}
ikptr
ik_sqlite3_extended_errcode (ikptr s_conn, ikpcb * pcb)
{
#ifdef HAVE_SQLITE3_EXTENDED_ERRCODE
  sqlite3 *	conn = IK_SQLITE_CONNECTION(s_conn);
  int		rv;
  rv = sqlite3_extended_errcode(conn);
  return ika_integer_from_int(pcb, rv);
#else
  feature_failure(__func__);
#endif
}
Esempio n. 6
0
void Handle::close()
{
    int rc = sqlite3_close((sqlite3 *) m_handle);
    if (rc == SQLITE_OK) {
        m_handle = nullptr;
        m_error.reset();
        return;
    }
    Error::ReportSQLite(m_tag, path, Error::HandleOperation::Close, rc,
                        sqlite3_extended_errcode((sqlite3 *) m_handle),
                        sqlite3_errmsg((sqlite3 *) m_handle), &m_error);
}
Esempio n. 7
0
/**
 * Prints out an error message if an sqlite function just made one.
 * @param db is the concerned sqlite database
 * @param result is the result of the sqlite function
 * @param infos is a gchar * containing some context to help understanding
 *        the error.
 * @note sqlite3_errstr needs at least sqlite 3.7.15
 */
static void print_on_db_error(sqlite3 *db, int result, const gchar *infos)
{
    const char *message = NULL;
    int errcode = 0;

    if (result == SQLITE_ERROR)
        {
            errcode = sqlite3_extended_errcode(db);
            message = sqlite3_errstr(errcode);
            print_db_error(db, _("sqlite error (%d - %d) on %s: %s\n"), result, errcode, infos, message);
        }
}
SWIGEXPORT jint JNICALL Java_com_almworks_sqlite4java__1SQLiteSwiggedJNI_sqlite3_1extended_1errcode(JNIEnv *jenv, jclass jcls, jlong jarg1) {
  jint jresult = 0 ;
  sqlite3 *arg1 = (sqlite3 *) 0 ;
  int result;
  
  (void)jenv;
  (void)jcls;
  arg1 = *(sqlite3 **)&jarg1; 
  result = (int)sqlite3_extended_errcode(arg1);
  jresult = (jint)result; 
  return jresult;
}
Esempio n. 9
0
int
ctdb_update_sha(struct ctdb_state *state, uint8_t *sha, int32_t genid)
{
	sqlite3_stmt		*stmt;
	char			 shat[SHA_DIGEST_STRING_LENGTH];
	int			 rv = 0;

	rv = 0;

	if (state == NULL || state->ctdb_db == NULL)
		return rv;

	stmt = state->ctdb_stmt_update;
	ct_sha1_encode(sha, shat);

	if (state->ctdb_in_transaction == 0) {
		if (ctdb_begin_transaction(state) != 0)
			return (rv);
		state->ctdb_trans_commit_rem = OPS_PER_TRANSACTION;
	}

	if (clog_mask_is_set(CT_LOG_DB)) {
		ct_sha1_encode(sha, shat);
		CNDBG(CT_LOG_DB, "updating %s to genid %d ", shat, genid);
	}
	if (sqlite3_bind_int(stmt, 1, genid)) {
		CNDBG(CT_LOG_DB, "could not bind genid");
		return rv;
	}
	if (sqlite3_bind_blob(stmt, 2, sha, SHA_DIGEST_LENGTH,
	    SQLITE_STATIC)) {
		CNDBG(CT_LOG_DB, "could not bind sha");
		return rv;
	}

	if (sqlite3_step(stmt) == SQLITE_DONE) {
		CNDBG(CT_LOG_DB, "update completed");
		rv = 1;
	} else {
		CNDBG(CT_LOG_DB, "update failed %d [%s]",
		    sqlite3_extended_errcode(state->ctdb_db),
		    sqlite3_errmsg(state->ctdb_db));
	}

	sqlite3_reset(stmt);

	/* inserts are more 'costly' than reads */
	state->ctdb_trans_commit_rem -= 4;
	if (state->ctdb_trans_commit_rem <= 0)
		ctdb_end_transaction(state);

	return rv;
}
Esempio n. 10
0
void SQLiteError::log_error(size_t err, sqlite3_ptr& dbHandle)
{
    size_t errNumber = 0;
    //First, we check what kind of result code we have and output the appropriate message!
    switch(err)
    {
    case SQLITE_OK:
        std::cerr << "Notice: the connection to the database was successful or the operation ocurred without issues!" << std::endl;
        break;
    case SQLITE_IOERR:
    case SQLITE_CANTOPEN:
        std::cerr << "Error: Can't access database! An I/O error probably occurred or the file is missing!" << std::endl;
        std::cerr << "This error may have ocurred while attempting to read or write the database." << std::endl;
    case SQLITE_ERROR:
        std::cerr << "Error: An internal error ocurred in the SQlite engine!" << std::endl;
        std::cerr << "Hint: Something got really f'ed up if you are getting this error!" << std::endl;
    case SQLITE_PERM:
        std::cerr << "Error: Requested access mode for a newly created database could not be provided." << std::endl;
    case SQLITE_BUSY:
        std::cerr << "Error: the database file could not be written (or in some cases read) because of";
        std::cerr << " concurrent activity by some other database connection, usually a database ";
        std::cerr << "connection in a separate process." << std::endl;
    case SQLITE_ABORT:
    case SQLITE_INTERRUPT:
        std::cerr << "An operation was aborted prior to completion, usually by application request." << std::endl;
    case SQLITE_LOCKED:
        std::cerr << "a write operation could not continue because of a conflict within the same";
        std::cerr << " database connection or a conflict with a different database connection that uses a shared cache.";
        std::cerr << std::endl;
    case SQLITE_NOMEM:
        std::cerr << "SQLite was unable to allocate all the memory it needed to complete the operation." << std::endl;
    case SQLITE_READONLY:
        std::cerr << "An attempt is made to alter some data for which the current database connection ";
        std::cerr << "does not have write permission." << std::endl;
    case SQLITE_CORRUPT:
        std::cerr << "The database file has been corrupted." << std::endl;
    case SQLITE_FULL:
        std::cerr << "A write operation could not complete because the disk is full." << std::endl;
    default:
        std::cerr << "I did not write or copied error messages for all error codes from SQLite!";
        std::cerr << " As a result, all codes without explicit error messages will only output its value!";
        std::cerr << " You can read about the specific error from the SQLite documentation!";
        std::cerr << std::endl << std::endl << "The error code is: " << err << std::endl;
    }

    if(dbHandle)//Let's check if the caller wants to output a more specific error message.
    {
        errNumber = sqlite3_extended_errcode(dbHandle);
        std::cerr << std::endl << "Extended Error code is: " << errNumber << std::endl;
        std::cerr << sqlite3_errmsg(dbHandle) << std::endl;;
    }
}
Esempio n. 11
0
void StatementHandle::reset()
{
    int rc = sqlite3_reset((sqlite3_stmt *) m_stmt);
    if (rc == SQLITE_OK) {
        m_error.reset();
    } else {
        sqlite3 *handle = sqlite3_db_handle((sqlite3_stmt *) m_stmt);
        Error::ReportSQLite(m_handle.getTag(), m_handle.path,
                            Error::HandleOperation::Finalize, rc,
                            sqlite3_extended_errcode(handle),
                            sqlite3_errmsg(handle), &m_error);
    }
}
Esempio n. 12
0
/**
 * Prints out an error message if an sqlite function just made one.
 * @param db is the concerned sqlite database
 * @param result is the result of the sqlite function
 * @param infos is a gchar * containing some context to help understanding
 *        the error.
 * @note sqlite3_errstr needs at least sqlite 3.7.15
 */
static void print_on_db_error(sqlite3 *db, int result, const gchar *infos)
{
    const char *message = NULL;
    int errcode = 0;

    if (result == SQLITE_ERROR && db != NULL)
        {
            /** @note sqlite3_errstr needs at least sqlite 3.7.15 */
            errcode = sqlite3_extended_errcode(db);
            message = sqlite3_errstr(errcode);
            print_db_error(_("sqlite error (%d - %d) on %s: %s\n"), result, errcode, infos, message);
        }
}
Esempio n. 13
0
bool StatementHandle::step()
{
    int rc = sqlite3_step((sqlite3_stmt *) m_stmt);
    if (rc == SQLITE_ROW || rc == SQLITE_OK || rc == SQLITE_DONE) {
        m_error.reset();
        return rc == SQLITE_ROW;
    }
    sqlite3 *handle = sqlite3_db_handle((sqlite3_stmt *) m_stmt);
    Error::ReportSQLite(
        m_handle.getTag(), m_handle.path, Error::HandleOperation::Step, rc,
        sqlite3_extended_errcode(handle), sqlite3_errmsg(handle),
        sqlite3_sql((sqlite3_stmt *) m_stmt), &m_error);
    return false;
}
/* throw a SQLiteException with a message appropriate for the error in handle
   concatenated with the given message
 */
void throw_sqlite3_exception(JNIEnv* env, sqlite3* handle, const char* message) {
    if (handle) {
        // get the error code and message from the SQLite connection
        // the error message may contain more information than the error code
        // because it is based on the extended error code rather than the simplified
        // error code that SQLite normally returns.
        throw_sqlite3_exception(env, sqlite3_extended_errcode(handle),
                sqlite3_errmsg(handle), message);
    } else {
        // we use SQLITE_OK so that a generic SQLiteException is thrown;
        // any code not specified in the switch statement below would do.
        throw_sqlite3_exception(env, SQLITE_OK, "unknown error", message);
    }
}
Esempio n. 15
0
void wi_error_set_sqlite3_error_with_description(void *db, wi_string_t *description) {
	wi_string_t		*string;
	
	string = wi_string_with_cstring(sqlite3_errmsg(db));
	
	if(description)
		string = wi_string_by_appending_format(string, WI_STR(" : %@"), description);
	
	wi_error_set_error_with_string(WI_ERROR_DOMAIN_SQLITE3,
#ifdef HAVE_SQLITE3_EXTENDED_ERRCODE
								   sqlite3_extended_errcode(db),
#else
								   sqlite3_errcode(db),
#endif
								   string);
}
Esempio n. 16
0
static void log_sqlite_error (sqlite_ctx_t *ctx, const char *fmt, ...)
{
    const char *sq_errmsg = sqlite3_errmsg (ctx->db);
    int sq_errcode = sqlite3_extended_errcode (ctx->db);
    char buf[64];
    va_list ap;

    va_start (ap, fmt);
    (void)vsnprintf (buf, sizeof (buf), fmt, ap);
    va_end (ap);

    if (!sq_errmsg)
        sq_errmsg = "unknown error code";

    flux_log (ctx->h, LOG_ERR, "%s: %s(%d)", buf, sq_errmsg, sq_errcode);
}
Esempio n. 17
0
/**
 * Executes the SQL command onto the database without any callback
 * @param database : the db_t * structure that contains the database connexion
 * @param sql_cmd : a gchar * SQL command to be executed onto the database
 * @param format_message : a gchar * format message to be used in case of an error
 */
static void exec_sql_cmd(db_t *database, gchar *sql_cmd, gchar *format_message)
{
    char *error_message = NULL;
    const char *message = NULL;
    int result = 0;

    result = sqlite3_exec(database->db, sql_cmd, NULL, 0, &error_message);

    if (result != SQLITE_OK)
        {
            result = sqlite3_extended_errcode(database->db);
            /* sqlite3_errstr needs at least sqlite 3.7.15 */
            message = sqlite3_errstr(result);
            print_db_error(database->db, format_message, result, message);
        }
}
Esempio n. 18
0
void StatementHandle::finalize()
{
    if (m_stmt) {
        sqlite3 *handle = sqlite3_db_handle((sqlite3_stmt *) m_stmt);
        int rc = sqlite3_finalize((sqlite3_stmt *) m_stmt);
        m_stmt = nullptr;
        if (rc == SQLITE_OK) {
            m_error.reset();
            return;
        }
        Error::ReportSQLite(m_handle.getTag(), m_handle.path,
                            Error::HandleOperation::Finalize, rc,
                            sqlite3_extended_errcode(handle),
                            sqlite3_errmsg(handle), &m_error);
    }
}
Esempio n. 19
0
const int DB::GetLastExtendedError(std::string &errormessage)
{
    if(IsOpen())
    {
        int errcode=sqlite3_extended_errcode(m_db);
        const char *errmsg=sqlite3_errmsg(m_db);
        if(errmsg)
        {
            errormessage=errmsg;
        }
        return errcode;
    }
    else
    {
        return SQLITE_OK;
    }
}
Esempio n. 20
0
bool Handle::isTableExists(const std::string &tableName)
{
    int rc = sqlite3_table_column_metadata((sqlite3 *) m_handle, nullptr,
                                           tableName.c_str(), nullptr, nullptr,
                                           nullptr, nullptr, nullptr, nullptr);
    if (rc == SQLITE_OK) {
        m_error.reset();
        return true;
    }
    if (rc == SQLITE_ERROR) {
        m_error.reset();
        return false;
    }
    Error::ReportSQLite(m_tag, path, Error::HandleOperation::IsTableExists, rc,
                        sqlite3_extended_errcode((sqlite3 *) m_handle),
                        sqlite3_errmsg((sqlite3 *) m_handle), &m_error);
    return false;
}
Esempio n. 21
0
SqlException::SqlException(sqlite3* database, const std::string& query, const std::string& message) {
    std::stringstream what;

    const auto errorCode = sqlite3_extended_errcode(database);
    const auto errorString = sqlite3_errstr(errorCode);
    const auto errorMessage = sqlite3_errmsg(database);

    what << errorString << " (" << errorCode << "): " << errorMessage;

    if (!message.empty()) {
        what << " (" << message << ")";
    }

    if (!query.empty()) {
        what << " for query \"" << query << "\"";
    }

    m_what = what.str();
}
Esempio n. 22
0
bool SqlQuery::exec()
{
    qCDebug(lcSql) << "SQL exec" << _sql;

    if (!_stmt) {
        qCWarning(lcSql) << "Can't exec query, statement unprepared.";
        return false;
    }

    // Don't do anything for selects, that is how we use the lib :-|
    if (!isSelect() && !isPragma()) {
        int rc, n = 0;
        do {
            rc = sqlite3_step(_stmt);
            if (rc == SQLITE_LOCKED) {
                rc = sqlite3_reset(_stmt); /* This will also return SQLITE_LOCKED */
                n++;
                OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC);
            } else if (rc == SQLITE_BUSY) {
                OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC);
                n++;
            }
        } while ((n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)));
        _errId = rc;

        if (_errId != SQLITE_DONE && _errId != SQLITE_ROW) {
            _error = QString::fromUtf8(sqlite3_errmsg(_db));
            qCWarning(lcSql) << "Sqlite exec statement error:" << _errId << _error << "in" << _sql;
            if (_errId == SQLITE_IOERR) {
                qCWarning(lcSql) << "IOERR extended errcode: " << sqlite3_extended_errcode(_db);
#if SQLITE_VERSION_NUMBER >= 3012000
                qCWarning(lcSql) << "IOERR system errno: " << sqlite3_system_errno(_db);
#endif
            }
        } else {
            qCDebug(lcSql) << "Last exec affected" << numRowsAffected() << "rows.";
        }
        return (_errId == SQLITE_DONE); // either SQLITE_ROW or SQLITE_DONE
    }

    return true;
}
Esempio n. 23
0
bool Handle::setCipherKey(const void *data, int size)
{
#ifdef SQLITE_HAS_CODEC
    int rc = sqlite3_key((sqlite3 *) m_handle, data, size);
    if (rc == SQLITE_OK) {
        m_error.reset();
        return true;
    }
    Error::ReportSQLite(m_tag, path, Error::HandleOperation::SetCipherKey, rc,
                        sqlite3_extended_errcode((sqlite3 *) m_handle),
                        sqlite3_errmsg((sqlite3 *) m_handle), &m_error);
    return false;
#else  //SQLITE_HAS_CODEC
    Error::ReportSQLite(m_tag, path, Error::HandleOperation::SetCipherKey,
                        SQLITE_MISUSE, SQLITE_MISUSE,
                        "[sqlite3_key] is not supported for current config",
                        &m_error);
    return false;
#endif //SQLITE_HAS_CODEC
}
Esempio n. 24
0
/**
 * Executes the SQL command onto the database without any callback
 * @param database : the db_t * structure that contains the database connexion
 * @param sql_cmd : a gchar * SQL command to be executed onto the database
 * @param format_message : a gchar * format message to be used in case of an error
 */
static int exec_sql_cmd(db_t *database, gchar *sql_cmd, gchar *format_message)
{
    char *error_message = NULL;
    const char *message = NULL;
    int result = 0;
    int errcode = 0;

    if (database != NULL && database->db != NULL)
        {
            result = sqlite3_exec(database->db, sql_cmd, NULL, 0, &error_message);

            if (result != SQLITE_OK)
                {
                    /** @note sqlite3_errstr needs at least sqlite 3.7.15 */
                    errcode = sqlite3_extended_errcode(database->db);
                    message = sqlite3_errstr(result);
                    print_db_error(format_message, result, errcode, message);
                }
        }

    return result;
}
Esempio n. 25
0
std::shared_ptr<StatementHandle> Handle::prepare(const Statement &statement)
{
    if (statement.getStatementType() == Statement::Type::Transaction) {
        Error::Abort(
            "[prepare] a transaction is not allowed, use [exec] instead",
            &m_error);
        return nullptr;
    }
    sqlite3_stmt *stmt = nullptr;
    int rc = sqlite3_prepare_v2((sqlite3 *) m_handle,
                                statement.getDescription().c_str(), -1, &stmt,
                                nullptr);
    if (rc == SQLITE_OK) {
        m_error.reset();
        return std::shared_ptr<StatementHandle>(
            new StatementHandle(stmt, *this));
    }
    Error::ReportSQLite(m_tag, path, Error::HandleOperation::Prepare, rc,
                        sqlite3_extended_errcode((sqlite3 *) m_handle),
                        sqlite3_errmsg((sqlite3 *) m_handle),
                        statement.getDescription(), &m_error);
    return nullptr;
}
    StatementReference::StatementReference(sqlite3* database,
                                           const char* sql)
    {
      if (database == NULL || sql == NULL)
      {
        throw OrthancSQLiteException(ErrorCode_ParameterOutOfRange);
      }

      root_ = NULL;
      refCount_ = 0;

      int error = sqlite3_prepare_v2(database, sql, -1, &statement_, NULL);
      if (error != SQLITE_OK)
      {
#if ORTHANC_SQLITE_STANDALONE != 1
        LOG(ERROR) << "SQLite: " << sqlite3_errmsg(database)
                   << " (" << sqlite3_extended_errcode(database) << ")";
#endif

        throw OrthancSQLiteException(ErrorCode_SQLitePrepareStatement);
      }

      assert(IsRoot());
    }
Esempio n. 27
0
 int
 Database::getMostRecentErrCode ()
 {
   return sqlite3_extended_errcode (_connection->db ());
 }
Esempio n. 28
0
static JSVAL sqlite_extended_errcode(JSARGS args) {
    HandleScope scope;
    Local<External>wrap = Local<External>::Cast(args[0]);
    sqlite3 *db = (sqlite3 *)wrap->Value();
    return scope.Close(Integer::New(sqlite3_extended_errcode(db)));
}
Esempio n. 29
0
int
ctdb_insert_sha(struct ctdb_state *state, uint8_t *sha_k, uint8_t *sha_v,
    uint8_t *iv, int32_t genid)
{
	char			shatk[SHA_DIGEST_STRING_LENGTH];
	char			shatv[SHA_DIGEST_STRING_LENGTH];
	int			rv, rc;
	sqlite3_stmt		*stmt;

	rv = 0;

	if (state == NULL || state->ctdb_db == NULL)
		return rv;

	stmt = state->ctdb_stmt_insert;

	if (state->ctdb_in_transaction == 0) {
		if (ctdb_begin_transaction(state) != 0)
			return (rv);
		state->ctdb_trans_commit_rem = OPS_PER_TRANSACTION;
	}

	if (clog_mask_is_set(CT_LOG_DB)) {
		ct_sha1_encode(sha_k, shatk);
		if (sha_v == NULL)
			shatv[0] = '\0';
		else
			ct_sha1_encode(sha_v, shatv);
		CNDBG(CT_LOG_DB, "inserting for bin %s, %s", shatk, shatv);
	}
	if (sqlite3_bind_blob(stmt, 1, sha_k, SHA_DIGEST_LENGTH,
	    SQLITE_STATIC)) {
		CNDBG(CT_LOG_DB, "could not bind sha_k");
		return rv;
	}
	if (state->ctdb_crypt) {
		if (sha_v == NULL || iv == NULL)
			CABORTX("crypt mode, but no sha_v/iv");
		if (sqlite3_bind_blob(stmt, 2, sha_v,
		    SHA_DIGEST_LENGTH, SQLITE_STATIC)) {
			CNDBG(CT_LOG_DB, "could not bind sha_v");
			sqlite3_reset(stmt);
			return rv;
		}

		if (sqlite3_bind_blob(stmt, 3, iv,
		    CT_IV_LEN, SQLITE_STATIC)) {
			CNDBG(CT_LOG_DB, "could not bind iv ");
			sqlite3_reset(stmt);
			return rv;
		}
		if (sqlite3_bind_int(stmt, 4, genid) != 0) {
			CNDBG(CT_LOG_DB, "could not bind genid");
			sqlite3_reset(stmt);
			return rv;
		}
	} else {
		if (sqlite3_bind_int(stmt, 2, genid) != 0) {
			CNDBG(CT_LOG_DB, "could not bind genid");
			sqlite3_reset(stmt);
			return rv;
		}

	}

	rc = sqlite3_step(stmt);
	if (rc == SQLITE_DONE) {
		CNDBG(CT_LOG_DB, "insert completed");
		rv = 1;
	} else if (rc != SQLITE_CONSTRAINT) {
		CNDBG(CT_LOG_DB, "insert failed %d %d [%s]", rc,
		    sqlite3_extended_errcode(state->ctdb_db),
		    sqlite3_errmsg(state->ctdb_db));
	} else  {
		CNDBG(CT_LOG_DB, "sha already exists");
	}

	sqlite3_reset(stmt);

	/* inserts are more 'costly' than reads */
	state->ctdb_trans_commit_rem -= 4;
	if (state->ctdb_trans_commit_rem <= 0)
		ctdb_end_transaction(state);

	return rv;
}
Esempio n. 30
0
/* Takes care of query preparation and execution. 
 * Writes results to file.
 */
int test_prep_exec(FILE *f, sqlite3 *db, const char *q) {
  sqlite3_stmt  *stmt;
  int result, col, prepare;
  if ((prepare = sqlite3_prepare_v2(db, q, -1, &stmt, 0)) == SQLITE_OK) {
    fprintf(f,"Statement prepared.\n");
    for (col = 0; col < sqlite3_column_count(stmt); col++) {
      fprintf(f, "%s ", sqlite3_column_name(stmt, col));
    }
    fprintf(f, "\n");
    while ((result = sqlite3_step(stmt)) == SQLITE_ROW) {
      fprintf(f, "\n");
      for (col = 0; col < sqlite3_column_count(stmt); col++) {
	switch (sqlite3_column_type(stmt, col)) {
	case 1:
	  fprintf(f, "%i ", sqlite3_column_int(stmt, col));
	  break;
	case 2:
	  fprintf(f, "%f ", 
		  sqlite3_column_double(stmt, col));
	  break;
	case 3:
	  fprintf(f, "%s ", 
		  sqlite3_column_text(stmt, col));
	  break;
	case 4:
	  fprintf(f, "%s ", 
		  (char *)sqlite3_column_blob(stmt, col));
	  break;
	case 5:
	  fprintf(f, "(null) ");
	  break;
	}
      }
    }
    switch (result) {
    case SQLITE_DONE:
      fprintf(f, "\n\nDone\n");
      break;
    case SQLITE_OK:
      fprintf(f, "\n\nOK\n");
      break;
    case SQLITE_ERROR:
      fprintf(f, "\n\nSQL error or missing database\n");
      break;
    case SQLITE_MISUSE:
      fprintf(f, "\n\nLibrary used incorrectly\n");
      break;
    default:
      fprintf(f, "\n\nError code: %i.\nPlease advise Sqlite error codes (http://www.sqlite.org/c3ref/c_abort.html)", result);
    }
    fprintf(f, "\n");
  } else {
    fprintf(f, "Error in preparation of query: error no %i\n", prepare);
    fprintf(f, "\nExtended error code %i.\n", sqlite3_extended_errcode(db));
    fprintf(f, "\nExtended error message:\n%s\n\n", sqlite3_errmsg(db));
    return prepare;
  }
  deinit_temp_structs();
  sqlite3_finalize(stmt);
  return result;
}