Beispiel #1
0
Datei: db.c Projekt: Tilka/ncdc
// Executes a single query.
// If transaction = TRUE, the query is assumed to be executed in a transaction
//   (which has already been initiated)
// The return path (if any) and lastid (0 if not requested) are stored in *res
// and *lastid. The caller of this function is responsible for sending back the
// final response. If this function returns anything other than SQLITE_DONE,
// the query has failed.
// It is assumed that the first `flags' part of the queue item has already been
// fetched.
static int db_queue_process_one(sqlite3 *db, char *q, gboolean nocache, gboolean transaction, GAsyncQueue **res, gint64 *lastid) {
  char *query = darray_get_ptr(q);
  *res = NULL;
  *lastid = 0;

  // Would be nice to have the parameters logged
  g_debug("db: Executing \"%s\"", query);

  // Get statement handler
  int r = SQLITE_ROW;
  sqlite3_stmt *s;
  if(nocache ? sqlite3_prepare_v2(db, query, -1, &s, NULL) : db_queue_process_prepare(db, query, &s)) {
    g_critical("SQLite3 error preparing `%s': %s", query, sqlite3_errmsg(db));
    r = SQLITE_ERROR;
  }

  // Bind parameters
  int t, n;
  int i = 1;
  char *a;
  while((t = darray_get_int32(q)) != DBQ_END && t != DBQ_RES) {
    if(r == SQLITE_ERROR)
      continue;
    switch(t) {
    case DBQ_NULL:
      sqlite3_bind_null(s, i);
      break;
    case DBQ_INT:
      sqlite3_bind_int(s, i, darray_get_int32(q));
      break;
    case DBQ_INT64:
      sqlite3_bind_int64(s, i, darray_get_int64(q));
      break;
    case DBQ_TEXT:
      sqlite3_bind_text(s, i, darray_get_string(q), -1, SQLITE_STATIC);
      break;
    case DBQ_BLOB:
      a = darray_get_dat(q, &n);
      sqlite3_bind_blob(s, i, a, n, SQLITE_STATIC);
      break;
    }
    i++;
  }

  // Fetch information about what results we need to send back
  gboolean wantlastid = FALSE;
  char columns[20]; // 20 should be enough for everyone
  n = 0;
  if(t == DBQ_RES) {
    *res = darray_get_ptr(q);
    while((t = darray_get_int32(q)) != DBQ_END) {
      if(t == DBQ_LASTID)
        wantlastid = TRUE;
      else
        columns[n++] = t;
    }
  }

  // Execute query
  while(r == SQLITE_ROW) {
    // do the step()
    if(transaction)
      r = sqlite3_step(s);
    else
      while((r = sqlite3_step(s)) == SQLITE_BUSY)
        ;
    if(r != SQLITE_DONE && r != SQLITE_ROW)
      g_critical("SQLite3 error on step() of `%s': %s", query, sqlite3_errmsg(db));
    // continue with the next step() if we're not going to do anything with the results
    if(r != SQLITE_ROW || !*res || !n)
      continue;
    // send back a response
    GByteArray *rc = g_byte_array_new();
    darray_init(rc);
    darray_add_int32(rc, r);
    for(i=0; i<n; i++) {
      switch(columns[i]) {
      case DBQ_INT:   darray_add_int32( rc, sqlite3_column_int(  s, i)); break;
      case DBQ_INT64: darray_add_int64( rc, sqlite3_column_int64(s, i)); break;
      case DBQ_TEXT:  darray_add_string(rc, (char *)sqlite3_column_text( s, i)); break;
      case DBQ_BLOB:  darray_add_dat(   rc, sqlite3_column_blob( s, i), sqlite3_column_bytes(s, i)); break;
      default: g_warn_if_reached();
      }
    }
    g_async_queue_push(*res, g_byte_array_free(rc, FALSE));
  }

  // Fetch last id, if requested
  if(r == SQLITE_DONE && wantlastid)
    *lastid = sqlite3_last_insert_rowid(db);
  sqlite3_reset(s);
  if(nocache)
    sqlite3_finalize(s);

  return r;
}
Beispiel #2
0
/* call-seq: stmt.bind_param(key, value)
 *
 * Binds value to the named (or positional) placeholder. If +param+ is a
 * Fixnum, it is treated as an index for a positional placeholder.
 * Otherwise it is used as the name of the placeholder to bind to.
 *
 * See also #bind_params.
 */
static VALUE bind_param(VALUE self, VALUE key, VALUE value)
{
  sqlite3StmtRubyPtr ctx;
  int status;
  int index;

  Data_Get_Struct(self, sqlite3StmtRuby, ctx);
  REQUIRE_OPEN_STMT(ctx);

  switch(TYPE(key)) {
    case T_SYMBOL:
      key = rb_funcall(key, rb_intern("to_s"), 0);
    case T_STRING:
      if(RSTRING_PTR(key)[0] != ':') key = rb_str_plus(rb_str_new2(":"), key);
      index = sqlite3_bind_parameter_index(ctx->st, StringValuePtr(key));
      break;
    default:
      index = (int)NUM2INT(key);
  }

  if(index == 0)
    rb_raise(rb_path2class("SQLite3::Exception"), "no such bind parameter");

  switch(TYPE(value)) {
    case T_STRING:
      if(CLASS_OF(value) == cSqlite3Blob
#ifdef HAVE_RUBY_ENCODING_H
              || rb_enc_get_index(value) == rb_ascii8bit_encindex()
#endif
        ) {
        status = sqlite3_bind_blob(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
      } else {
#ifdef HAVE_RUBY_ENCODING_H
        if(!UTF8_P(value)) {
              VALUE db          = rb_iv_get(self, "@connection");
              VALUE encoding    = rb_funcall(db, rb_intern("encoding"), 0);
              rb_encoding * enc = rb_to_encoding(encoding);
              value = rb_str_export_to_enc(value, enc);
          }
#endif

        status = sqlite3_bind_text(
            ctx->st,
            index,
            (const char *)StringValuePtr(value),
            (int)RSTRING_LEN(value),
            SQLITE_TRANSIENT
            );
      }
      break;
    case T_BIGNUM:
#if SIZEOF_LONG < 8
      if (RBIGNUM_LEN(value) * SIZEOF_BDIGITS <= 8) {
          status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)NUM2LL(value));
          break;
      }
#endif
    case T_FLOAT:
      status = sqlite3_bind_double(ctx->st, index, NUM2DBL(value));
      break;
    case T_FIXNUM:
      status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)FIX2LONG(value));
      break;
    case T_NIL:
      status = sqlite3_bind_null(ctx->st, index);
      break;
    default:
      rb_raise(rb_eRuntimeError, "can't prepare %s",
          rb_class2name(CLASS_OF(value)));
      break;
  }

  CHECK(sqlite3_db_handle(ctx->st), status);

  return self;
}
Beispiel #3
0
bool QSQLiteResult::exec()
{
    const QVector<QVariant> values = boundValues();

    d->skippedStatus = false;
    d->skipRow = false;
    d->rInf.clear();
    clearValues();
    setLastError(QSqlError());

    int res = sqlite3_reset(d->stmt);
    if (res != SQLITE_OK) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    int paramCount = sqlite3_bind_parameter_count(d->stmt);
    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = SQLITE_OK;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = sqlite3_bind_null(d->stmt, i + 1);
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
                                            ba->size(), SQLITE_STATIC);
                    break; }
                case QVariant::Int:
                    res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
                    break;
                case QVariant::Double:
                    res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
                    break;
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
                                              (str->size()) * sizeof(QChar), SQLITE_STATIC);
                    break; }
                default: {
                    QString str = value.toString();
                    // SQLITE_TRANSIENT makes sure that sqlite buffers the data
                    res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
                                              (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
                    break; }
                }
            }
            if (res != SQLITE_OK) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("QSQLiteResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}
int SqliteStatement::bindStatic (int position, const void* data, int length)
{
    return sqlite3_bind_blob (statement, position, data, length, SQLITE_STATIC);
}
Beispiel #5
0
 bool operator()(const sql_blob &value) const
 {
     return sqlite3_bind_blob(stmt_.get(), index_, value.data(), value.size(), SQLITE_TRANSIENT) ==
            SQLITE_OK;
 }
Beispiel #6
0
// Bind a binary blob value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const void* apValue, const int aSize)
{
    const int ret = sqlite3_bind_blob(mStmtPtr, aIndex, apValue, aSize, SQLITE_TRANSIENT);
    check(ret);
}
Beispiel #7
0
static krb5_error_code KRB5_CALLCONV
scc_store_cred(krb5_context context,
	       krb5_ccache id,
	       krb5_creds *creds)
{
    sqlite_uint64 credid;
    krb5_scache *s = SCACHE(id);
    krb5_error_code ret;
    krb5_data data;

    ret = make_database(context, s);
    if (ret)
	return ret;

    ret = encode_creds(context, creds, &data);
    if (ret)
	return ret;

    sqlite3_bind_int(s->icred, 1, s->cid);
    {
	krb5_enctype etype = 0;
	int kvno = 0;
	Ticket t;
	size_t len;

	ret = decode_Ticket(creds->ticket.data,
			    creds->ticket.length, &t, &len);
	if (ret == 0) {
	    if(t.enc_part.kvno)
		kvno = *t.enc_part.kvno;

	    etype = t.enc_part.etype;

	    free_Ticket(&t);
	}

	sqlite3_bind_int(s->icred, 2, kvno);
	sqlite3_bind_int(s->icred, 3, etype);

    }

    sqlite3_bind_blob(s->icred, 4, data.data, data.length, free_data);
    sqlite3_bind_int(s->icred, 5, time(NULL));

    ret = exec_stmt(context, s->db, "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO);
    if (ret) return ret;

    do {
	ret = sqlite3_step(s->icred);
    } while (ret == SQLITE_ROW);
    sqlite3_reset(s->icred);
    if (ret != SQLITE_DONE) {
	ret = KRB5_CC_IO;
	krb5_set_error_message(context, ret,
			       N_("Failed to add credential: %s", ""),
			       sqlite3_errmsg(s->db));
	goto rollback;
    }

    credid = sqlite3_last_insert_rowid(s->db);

    {
	bind_principal(context, s->db, s->iprincipal, 1, creds->server);
	sqlite3_bind_int(s->iprincipal, 2, 1);
	sqlite3_bind_int(s->iprincipal, 3, credid);
	
	do {
	    ret = sqlite3_step(s->iprincipal);
	} while (ret == SQLITE_ROW);
	sqlite3_reset(s->iprincipal);
	if (ret != SQLITE_DONE) {
	    ret = KRB5_CC_IO;
	    krb5_set_error_message(context, ret,
				   N_("Failed to add principal: %s", ""),
				   sqlite3_errmsg(s->db));
	    goto rollback;
	}
    }

    {
	bind_principal(context, s->db, s->iprincipal, 1, creds->client);
	sqlite3_bind_int(s->iprincipal, 2, 0);
	sqlite3_bind_int(s->iprincipal, 3, credid);
	
	do {
	    ret = sqlite3_step(s->iprincipal);
	} while (ret == SQLITE_ROW);
	sqlite3_reset(s->iprincipal);
	if (ret != SQLITE_DONE) {
	    ret = KRB5_CC_IO;
	    krb5_set_error_message(context, ret,
				   N_("Failed to add principal: %s", ""),
				   sqlite3_errmsg(s->db));
	    goto rollback;
	}
    }

    ret = exec_stmt(context, s->db, "COMMIT", KRB5_CC_IO);
    if (ret) return ret;

    return 0;

rollback:
    exec_stmt(context, s->db, "ROLLBACK", 0);

    return ret;
}
Beispiel #8
0
// Bind a binary blob value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bindNoCopy(const int aIndex, const void* apValue, const int aSize)
{
    const int ret = sqlite3_bind_blob(mStmtPtr, aIndex, apValue, aSize, SQLITE_STATIC);
    check(ret);
}
Beispiel #9
0
int
WfipsData::LoadFwas()
{
    //assert( poScenario->m_VDispLogic.size() > 0 );
    sqlite3_stmt *stmt;
    int rc, n, i;
    void *pGeom;

    /* Clear our lookup */
    FwaIndexMap.clear();

    poScenario->m_VFWA.clear();

    if( pszAnalysisAreaWkt )
    {
        n = CompileGeometry( pszAnalysisAreaWkt, &pGeom );
        if( n > 0 )
        {
            rc = sqlite3_prepare_v2( db, "SELECT * FROM fwa JOIN reload ON "
                                         "fwa.name=reload.fwa_name JOIN "
                                         "walk_in ON "
                                         "reload.fwa_name=walk_in.fwa_name "
                                         "WHERE ST_Intersects(@geom, geometry) "
                                         "AND name NOT LIKE '%unassigned%' "
                                         "AND substr(fwa.name, 0, 3) NOT IN "
                                         "('EA','SA','AK') "
                                         "AND fwa.ROWID IN "
                                         "(SELECT pkid FROM "
                                         "idx_fwa_geometry WHERE "
                                         "xmin <= MbrMaxX(@geom) AND "
                                         "xmax >= MbrMinX(@geom) AND "
                                         "ymin <= MbrMaxY(@geom) AND "
                                         "ymax >= MbrMinY(@geom))",
                                     -1, &stmt, NULL );

            rc = sqlite3_bind_blob( stmt,
                                    sqlite3_bind_parameter_index( stmt, "@geom" ),
                                    pGeom, n, sqlite3_free );
        }
        else
        {
            return SQLITE_ERROR;
        }
    }
    else
    {
        rc = sqlite3_prepare_v2( db, "SELECT * FROM fwa JOIN reload ON "
                                     "fwa.name=reload.fwa_name JOIN "
                                     "walk_in ON "
                                     "reload.fwa_name=walk_in.fwa_name "
                                     "WHERE fwa.name NOT LIKE '%unassigned%' "
                                     "AND substr(fwa.name, 0, 3) NOT IN "
                                     "('EA','SA','AK')",
                                 -1, &stmt, NULL );
    }
    const char *pszName, *pszFpu;
    int nWalkIn, nPumpRoll, nHead, nTail, nPara;
    double dfAttDist;
    int bWaterDrops, bExcluded;
    double dfDiscSize, dfEslSize, dfEslTime, dfAirGrnd;
    int nFirstDelay;
    const char *pszLogic;
    int anReload[5];
    int anWalkIn[6];
    int iFwa = 0;
    std::map<std::string, int>::iterator it;
    while( sqlite3_step( stmt ) == SQLITE_ROW )
    {
        pszName = (const char *)sqlite3_column_text( stmt, 1 );
        assert( pszName );
        pszFpu = (const char *)sqlite3_column_text( stmt, 2 );
        assert( pszFpu );
        // FMG 3
        nWalkIn = sqlite3_column_int( stmt, 4 );
        assert( nWalkIn >= 0 || nWalkIn <= 100 );
        nPumpRoll = sqlite3_column_int( stmt, 5 );
        assert( nPumpRoll >= 0 || nPumpRoll <= 100 );
        nHead = sqlite3_column_int( stmt, 6 );
        assert( nHead >= 0 || nHead <= 100 );
        nTail = sqlite3_column_int( stmt, 7 );
        assert( nTail >= 0 || nTail <= 100 );
        nPara = sqlite3_column_int( stmt, 8 );
        assert( nPara >= 0 || nPara <= 100 );
        assert( nPara + nTail + nHead < 101 );
        dfAttDist = sqlite3_column_double( stmt, 9 );
        assert( dfAttDist >= 0.0 );
        bWaterDrops = sqlite3_column_int( stmt, 10 );
        assert( bWaterDrops == 0 || bWaterDrops == 1 );
        bExcluded = sqlite3_column_int( stmt, 11 );
        assert( bExcluded == 0 || bExcluded == 1 );
        dfDiscSize = sqlite3_column_double( stmt, 12 );
        assert( dfDiscSize >= 0 );
        dfEslTime = sqlite3_column_double( stmt, 13 );
        assert( dfEslTime >= 0 );
        dfEslSize = sqlite3_column_double( stmt, 14 );
        assert( dfEslSize >= 0 );
        dfAirGrnd = sqlite3_column_double( stmt, 15 );
        assert( dfAirGrnd >= 0 );
        nFirstDelay = sqlite3_column_int( stmt, 16 );
        assert( nFirstDelay >= 0 );
        pszLogic = (const char *)sqlite3_column_text( stmt, 17 );
        assert( pszLogic );
        memset( anReload, 0, sizeof( int ) * 5 );
        for( i = 0; i < 5; i++ )
        {
            anReload[i] = sqlite3_column_int( stmt, 18+i );
            assert( anReload[i] >= 0 );
        }
        memset( anWalkIn, 0, sizeof( int ) * 6 );
        for( i = 0; i < 6; i++ )
        {
            anWalkIn[i] = sqlite3_column_int( stmt, 18+5+i );
            assert( anWalkIn[i] >= 0 );
        }
        /*
        ** We use defaults now for some delays: From FPA:
        **
        ** Post Escape Delay 20 minutes for all but smokejumpers, smokejumpers 
        ** 120 minutes.
        ** Post Unused Delay 10 minutes for all.
        ** Post Used Delay 30 minutes for all but boats and smokejumpers, boats
        ** and smokejumpers 120 minutes.
        **
        ** Columns:
        ** tracked,boat,crew,engine,helitack,smkjmp
        **/
        int anPostEscape[6] = {20,20, 20,20,20,120};
        int anPostUnused[6] = {10,10, 10,10,10,10};
        int anPostUsed[6]   = {30,120,30,30,30,120};
        /* Fixed, no assert */


        /*
        ** These values have also been defaulted.
        */
        std::string aoRos[10];
        double adfRosCoeff[10];
        double adfDiurn[24];
        for( i = 0; i < 10; i++ )
        {
            aoRos[i] = std::string( "NA" );
            adfRosCoeff[i] = 1.0;
        }
        /* Fixed, no assert */
        for( i = 0; i < 24; i++ )
        {
            adfDiurn[i] = 1.;
        }
        /* Fixed, no assert */

        /*
        ** The value of this is up for discussion...
        */
        it = DispLogIndexMap.find( pszLogic );
        if( it == DispLogIndexMap.end() )
        {
            i = 0;
            printf("Failed to load logic: %s for fwa: %s\n", pszLogic, pszName);
        }
        else
        {
            i = it->second;
        }
        poScenario->m_VFWA.push_back( CFWA( std::string( pszName ),
                                            std::string( "" ), nWalkIn,
                                            nPumpRoll, nHead, nTail, nPara,
                                            dfAttDist, bWaterDrops, bExcluded,
                                            dfDiscSize, dfEslTime, dfEslSize,
                                            dfAirGrnd, anWalkIn, anPostUsed,
                                            anPostUnused, anPostEscape, anReload,
                                            nFirstDelay, adfDiurn, aoRos,
                                            adfRosCoeff, iFwa,
                                            poScenario->m_VDispLogic[i],
                                            std::string( pszFpu ) ) );
        FwaIndexMap.insert( std::pair<std::string, int>( std::string( pszName ),
                                                         iFwa ) );
        iFwa++;
    }
    assert( FwaIndexMap.size() == poScenario->m_VFWA.size() );
    sqlite3_finalize( stmt );
    return 0;
}
Beispiel #10
0
ActionItemPtr
ActionLog::AddLocalActionDelete(const std::string& filename)
{
  _LOG_DEBUG("Adding local action DELETE");

  sqlite3_exec(m_db, "BEGIN TRANSACTION;", 0, 0, 0);

  const Block device_name = m_syncLog->GetLocalName().wireEncode();
  sqlite3_int64 version;
  BufferPtr parent_device_name;
  sqlite3_int64 parent_seq_no = -1;

  sqlite3_int64 action_time = std::time(0);

  tie(version, parent_device_name, parent_seq_no) = GetLatestActionForFile(filename);
  if (!parent_device_name) // no records exist or file was already deleted
  {
    _LOG_DEBUG("Nothing to delete... [" << filename << "]");

    // just in case, remove data from FileState
    sqlite3_stmt* stmt;
    sqlite3_prepare_v2(m_db, "DELETE FROM FileState WHERE filename = ? ", -1, &stmt, 0);
    sqlite3_bind_text(stmt, 1, filename.c_str(), filename.size(), SQLITE_STATIC); // file

    sqlite3_step(stmt);

    _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

    sqlite3_finalize(stmt);

    sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);
    return ActionItemPtr();
  }
  version++;

  sqlite3_int64 seq_no = m_syncLog->GetNextLocalSeqNo();

  sqlite3_stmt* stmt;
  sqlite3_prepare_v2(m_db, "INSERT INTO ActionLog "
                           "(device_name, seq_no, action, filename, version, action_timestamp, "
                           "parent_device_name, parent_seq_no, "
                           "action_name, action_content_object) "
                           "VALUES(?, ?, ?, ?, ?, datetime(?, 'unixepoch', 'localtime'),"
                           "        ?, ?,"
                           "        ?, ?)",
                     -1, &stmt, 0);

  sqlite3_bind_blob(stmt, 1, device_name.wire(), device_name.size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seq_no);
  sqlite3_bind_int(stmt, 3, 1);
  sqlite3_bind_text(stmt, 4, filename.c_str(), filename.size(), SQLITE_STATIC); // file

  sqlite3_bind_int64(stmt, 5, version);
  sqlite3_bind_int64(stmt, 6, action_time);

  sqlite3_bind_blob(stmt, 7, parent_device_name->buf(), parent_device_name->size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 8, parent_seq_no);

  ActionItemPtr item = make_shared<ActionItem>();
  item->set_action(ActionItem::DELETE);
  item->set_filename(filename);
  item->set_version(version);
  item->set_timestamp(action_time);
  item->set_parent_device_name(parent_device_name->buf(), parent_device_name->size());
  item->set_parent_seq_no(parent_seq_no);

  std::string item_msg;
  item->SerializeToString(&item_msg);

  // action name: /<device_name>/<appname>/action/<shared-folder>/<action-seq>
  Name actionName = Name("/");
  actionName.append(m_syncLog->GetLocalName()).append(m_appName).append("action");
  actionName.append(m_sharedFolderName).appendNumber(seq_no);
  _LOG_DEBUG("ActionName: " << actionName);

  shared_ptr<Data> actionData = make_shared<Data>();
  actionData->setName(actionName);
  actionData->setFreshnessPeriod(time::seconds(60));
  actionData->setContent(reinterpret_cast<const uint8_t*>(item_msg.c_str()), item_msg.size());
  m_keyChain.sign(*actionData);

  sqlite3_bind_blob(stmt, 9, actionName.wireEncode().wire(), actionName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_blob(stmt, 10, actionData->wireEncode().wire(), actionData->wireEncode().size(),
                    SQLITE_STATIC);

  sqlite3_step(stmt);

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  // cout << Name(parent_device_name) << endl;

  // assign name to the action, serialize action, and create content object

  sqlite3_finalize(stmt);

  // I had a problem including directory_name assignment as part of the initial insert.
  sqlite3_prepare_v2(m_db,
                     "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?",
                     -1, &stmt, 0);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_blob(stmt, 1, device_name.wire(), device_name.size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seq_no);
  sqlite3_step(stmt);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);

  return item;
}
Beispiel #11
0
ActionItemPtr
ActionLog::AddRemoteAction(const Name& deviceName, sqlite3_int64 seqno, shared_ptr<Data> actionData)
{
  if (!actionData) {
    _LOG_ERROR("actionData is not valid");
    return ActionItemPtr();
  }
  ActionItemPtr action = deserializeMsg<ActionItem>(
    Buffer(actionData->getContent().value(), actionData->getContent().value_size()));

  if (!action) {
    _LOG_ERROR("action cannot be decoded");
    return ActionItemPtr();
  }

  _LOG_DEBUG("AddRemoteAction: [" << deviceName.toUri() << "] seqno: " << seqno);

  sqlite3_stmt* stmt;
  sqlite3_prepare_v2(m_db,
                     "INSERT INTO ActionLog "
                     "(device_name, seq_no, action, filename, version, action_timestamp, "
                     "file_hash, file_atime, file_mtime, file_ctime, file_chmod, file_seg_num, "
                     "parent_device_name, parent_seq_no, "
                     "action_name, action_content_object) "
                     "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
                     "        ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?,?, "
                     "        ?, ?, "
                     "        ?, ?);",
                     -1, &stmt, 0);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_blob(stmt, 1, deviceName.wireEncode().wire(), deviceName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seqno);

  sqlite3_bind_int(stmt, 3, action->action());
  sqlite3_bind_text(stmt, 4, action->filename().c_str(), action->filename().size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 5, action->version());
  sqlite3_bind_int64(stmt, 6, action->timestamp());

  if (action->action() == ActionItem::UPDATE) {
    sqlite3_bind_blob(stmt, 7, action->file_hash().c_str(), action->file_hash().size(),
                      SQLITE_STATIC);

    // sqlite3_bind_int64(stmt, 8, atime); // NULL
    sqlite3_bind_int64(stmt, 9, action->mtime());
    // sqlite3_bind_int64(stmt, 10, ctime); // NULL

    sqlite3_bind_int(stmt, 11, action->mode());
    sqlite3_bind_int(stmt, 12, action->seg_num());
  }

  if (action->has_parent_device_name()) {
    sqlite3_bind_blob(stmt, 13, action->parent_device_name().c_str(),
                      action->parent_device_name().size(), SQLITE_STATIC);
    sqlite3_bind_int64(stmt, 14, action->parent_seq_no());
  }

  Name actionName = Name(deviceName);
  actionName.append("action").append(m_sharedFolderName).appendNumber(seqno);

  sqlite3_bind_blob(stmt, 15, actionName.wireEncode().wire(), actionName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_blob(stmt, 16, actionData->wireEncode().wire(), actionData->wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_step(stmt);

  // if action needs to be applied to file state, the trigger will take care of it

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  // I had a problem including directory_name assignment as part of the initial insert.
  sqlite3_prepare_v2(m_db,
                     "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?",
                     -1, &stmt, 0);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_blob(stmt, 1, deviceName.wireEncode().wire(), deviceName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seqno);
  sqlite3_step(stmt);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  return action;
}
Beispiel #12
0
	int Statement::Bind(int index, void const * data, int datalen)
	{
		return IsValid()
			? sqlite3_bind_blob(m_st, index+1, data, datalen, SQLITE_TRANSIENT)
			: SQLITE_ERROR;
	}
Beispiel #13
0
 void Statement::BindBlob(int col, const void* val, int val_len) 
 {
   CheckOk(sqlite3_bind_blob(GetStatement(), col + 1, val, val_len, SQLITE_TRANSIENT));
 }
Beispiel #14
0
/**
 * \brief apply appropriate tile properties to the sqlite statement */
static void _bind_sqlite_params(mapcache_context *ctx, void *vstmt, mapcache_cache_sqlite *cache, mapcache_tile *tile)
{
  sqlite3_stmt *stmt = vstmt;
  int paramidx;
  /* tile->x */
  paramidx = sqlite3_bind_parameter_index(stmt, ":x");
  if (paramidx) sqlite3_bind_int(stmt, paramidx, tile->x);

  /* tile->y */
  paramidx = sqlite3_bind_parameter_index(stmt, ":y");
  if (paramidx) sqlite3_bind_int(stmt, paramidx, tile->y);

  /* tile->y */
  paramidx = sqlite3_bind_parameter_index(stmt, ":z");
  if (paramidx) sqlite3_bind_int(stmt, paramidx, tile->z);

  /* eventual dimensions */
  paramidx = sqlite3_bind_parameter_index(stmt, ":dim");
  if (paramidx) {
    if (tile->dimensions) {
      char *dim = mapcache_util_get_tile_dimkey(ctx, tile, NULL, NULL);
      sqlite3_bind_text(stmt, paramidx, dim, -1, SQLITE_STATIC);
    } else {
      sqlite3_bind_text(stmt, paramidx, "", -1, SQLITE_STATIC);
    }
  }

  /* grid */
  paramidx = sqlite3_bind_parameter_index(stmt, ":grid");
  if (paramidx) sqlite3_bind_text(stmt, paramidx, tile->grid_link->grid->name, -1, SQLITE_STATIC);

  /* tileset */
  paramidx = sqlite3_bind_parameter_index(stmt, ":tileset");
  if (paramidx) sqlite3_bind_text(stmt, paramidx, tile->tileset->name, -1, SQLITE_STATIC);

  /* tile blob data */
  paramidx = sqlite3_bind_parameter_index(stmt, ":data");
  if (paramidx) {
    int written = 0;
    if(cache->detect_blank) {
      if(!tile->raw_image) {
        tile->raw_image = mapcache_imageio_decode(ctx, tile->encoded_data);
        GC_CHECK_ERROR(ctx);
      }
      if(mapcache_image_blank_color(tile->raw_image) != MAPCACHE_FALSE) {
        char *buf = apr_palloc(ctx->pool, 5* sizeof(char));
        buf[0] = '#';
        memcpy(buf+1,tile->raw_image->data,4);
        written = 1;
        sqlite3_bind_blob(stmt, paramidx, buf, 5, SQLITE_STATIC);
      }
    }
    if(!written) {
      if (!tile->encoded_data) {
        tile->encoded_data = tile->tileset->format->write(ctx, tile->raw_image, tile->tileset->format);
        GC_CHECK_ERROR(ctx);
      }
      if (tile->encoded_data && tile->encoded_data->size) {
        sqlite3_bind_blob(stmt, paramidx, tile->encoded_data->buf, tile->encoded_data->size, SQLITE_STATIC);
      } else {
        sqlite3_bind_text(stmt, paramidx, "", -1, SQLITE_STATIC);
      }
    }
  }
}
Beispiel #15
0
static int pdo_sqlite_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
		enum pdo_param_event event_type)
{
	pdo_sqlite_stmt *S = (pdo_sqlite_stmt*)stmt->driver_data;
	zval *parameter;

	switch (event_type) {
		case PDO_PARAM_EVT_EXEC_PRE:
			if (stmt->executed && !S->done) {
				sqlite3_reset(S->stmt);
				S->done = 1;
			}

			if (param->is_param) {

				if (param->paramno == -1) {
					param->paramno = sqlite3_bind_parameter_index(S->stmt, ZSTR_VAL(param->name)) - 1;
				}

				switch (PDO_PARAM_TYPE(param->param_type)) {
					case PDO_PARAM_STMT:
						return 0;

					case PDO_PARAM_NULL:
						if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
							return 1;
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;

					case PDO_PARAM_INT:
					case PDO_PARAM_BOOL:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
						} else {
							convert_to_long(parameter);
#if ZEND_LONG_MAX > 2147483647
							if (SQLITE_OK == sqlite3_bind_int64(S->stmt, param->paramno + 1, Z_LVAL_P(parameter))) {
								return 1;
							}
#else
							if (SQLITE_OK == sqlite3_bind_int(S->stmt, param->paramno + 1, Z_LVAL_P(parameter))) {
								return 1;
							}
#endif
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;

					case PDO_PARAM_LOB:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_RESOURCE) {
							php_stream *stm = NULL;
							php_stream_from_zval_no_verify(stm, parameter);
							if (stm) {
								zend_string *mem = php_stream_copy_to_mem(stm, PHP_STREAM_COPY_ALL, 0);
								zval_ptr_dtor(parameter);
								ZVAL_STR(parameter, mem ? mem : ZSTR_EMPTY_ALLOC());
							} else {
								pdo_raise_impl_error(stmt->dbh, stmt, "HY105", "Expected a stream resource");
								return 0;
							}
						} else if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
							pdo_sqlite_error_stmt(stmt);
							return 0;
						} else {
							convert_to_string(parameter);
						}

						if (SQLITE_OK == sqlite3_bind_blob(S->stmt, param->paramno + 1,
								Z_STRVAL_P(parameter),
								Z_STRLEN_P(parameter),
								SQLITE_STATIC)) {
							return 1;
						}
						return 0;

					case PDO_PARAM_STR:
					default:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
						} else {
							convert_to_string(parameter);
							if (SQLITE_OK == sqlite3_bind_text(S->stmt, param->paramno + 1,
									Z_STRVAL_P(parameter),
									Z_STRLEN_P(parameter),
									SQLITE_STATIC)) {
								return 1;
							}
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;
				}
			}
			break;

		default:
			;
	}
	return 1;
}
Beispiel #16
0
int
WfipsData::LoadDispatchLocations()
{
    sqlite3_stmt *stmt, *astmt, *estmt;
    int rc, n, i;
    void *pGeom = NULL;
    int nFwaCount;

    poScenario->m_VDispLoc.clear();

    if( pszAnalysisAreaWkt )
    {
        n = CompileGeometry( pszAnalysisAreaWkt, &pGeom );
        if( n > 0 )
        {
            rc = sqlite3_prepare_v2( db, "SELECT disploc.name,fpu_code,"
                                         "callback,X(disploc.geometry),"
                                         "Y(disploc.geometry) FROM "
                                         "disploc JOIN assoc ON "
                                         "name=disploc_name "
                                         "WHERE fwa_name NOT LIKE '%unassign%' "
                                         "AND substr(fwa_name, 0, 3) NOT IN "
                                         "('EA','SA','AK') "
                                         "AND fwa_name IN "
                                         "(SELECT name FROM fwa WHERE "
                                         "ST_Intersects(@geom, fwa.geometry) AND "
                                         "fwa.ROWID IN(SELECT pkid FROM "
                                         "idx_fwa_geometry WHERE "
                                         "xmin <= MbrMaxX(@geom) AND "
                                         "xmax >= MbrMinX(@geom) AND "
                                         "ymin <= MbrMaxY(@geom) AND "
                                         "ymax >= MbrMinY(@geom))) GROUP BY "
                                         "disploc.name",
                                     -1, &stmt, NULL );

            rc = sqlite3_bind_blob( stmt,
                                    sqlite3_bind_parameter_index( stmt, "@geom" ),
                                    pGeom, n, sqlite3_free );
        }
        else
        {
            return SQLITE_ERROR;
        }
    }
    else
    {
        rc = sqlite3_prepare_v2( db, "SELECT name,fpu_code,callback,"
                                     "X(geometry), Y(geometry) FROM disploc "
                                     "JOIN assoc ON name=disploc_name WHERE "
                                     "fwa_name NOT LIKE '%unassign%' "
                                     "AND substr(fwa_name, 0, 3) NOT IN "
                                     "('EA','SA','AK') "
                                     "GROUP BY disploc.name",
                                 -1, &stmt, NULL );
    }
    rc = sqlite3_prepare_v2( db, "SELECT fwa_name, distance FROM assoc WHERE "
                                 "disploc_name=?",
                             -1, &astmt, NULL );
    rc = sqlite3_prepare_v2( db, "SELECT COUNT(*) FROM resource WHERE disploc=?",
                             -1, &estmt, NULL );
    nFwaCount = poScenario->m_VFWA.size();

    const char *pszName, *pszFpu;
    const char *pszFwa;
    int nCallBack;
    double dfX, dfY;
    double dfDist;
    std::map<std::string, int>::iterator it;
    while( sqlite3_step( stmt ) == SQLITE_ROW )
    {
        pszName = (const char*)sqlite3_column_text( stmt, 0 );
        assert( pszName );
        rc = sqlite3_bind_text( estmt, 1, pszName, -1, NULL );
        if( sqlite3_step( estmt ) != SQLITE_ROW ||
            sqlite3_column_int( estmt, 0 ) < 1 )
        {
            sqlite3_reset( estmt );
            continue;
        }
        pszFpu = (const char*)sqlite3_column_text( stmt, 1 );
        assert( pszFpu );
        nCallBack = sqlite3_column_int( stmt, 2 );
        assert( nCallBack >= 0 );
        dfX = sqlite3_column_double( stmt, 3 );
        assert( dfX > -180 && dfX < 360 );
        dfY = sqlite3_column_double( stmt, 4 );
        assert( dfY > -180 && dfY < 360 );
        CDispLoc oDispLoc( std::string( pszName ), nCallBack,
                           std::string( pszFpu ), dfY, dfX );

        rc = sqlite3_bind_text( astmt, 1, pszName, -1, NULL );
        while( sqlite3_step( astmt ) == SQLITE_ROW )
        {
            pszFwa = (const char*)sqlite3_column_text( astmt, 0 );
            assert( pszFwa );
            dfDist = sqlite3_column_double( astmt, 1 );
            assert( dfDist >= 0 );
            it = FwaIndexMap.find( std::string( pszFwa ) );
            if( it != FwaIndexMap.end() )
            {
                i = it->second;
                poScenario->m_VFWA[i].AddAssociation( std::string( pszName ), dfDist );
                oDispLoc.AddAssocFWA( &(poScenario->m_VFWA[i]) );
            }
        }
        sqlite3_reset( astmt );
        sqlite3_reset( estmt );
        poScenario->m_VDispLoc.push_back( oDispLoc );
    }

    sqlite3_finalize( stmt );
    sqlite3_finalize( astmt );
    sqlite3_finalize( estmt );

	poScenario->CreateRescTypeVectors("C:/wfips/data/");

    return 0;
}
Beispiel #17
0
int db_share_files(const struct pub_file *files, size_t count, const struct client *owner)
{
    /* todo: do it in transaction */

    while (count-- > 0) {
        sqlite3_stmt *stmt;
        const char *ext;
        int ext_len;
        int i;
        uint64_t fid;

        if (!files->name_len) {
            files++;
            continue;
        }

        fid = MAKE_FID(files->hash);

        // find extension
        ext = file_extension(files->name, files->name_len);
        if (ext)
            ext_len = files->name + files->name_len - ext;
        else
            ext_len = 0;

        i = 1;
        stmt = s_stmt[SHARE_UPD];
        DB_CHECK(SQLITE_OK == sqlite3_reset(stmt));
        DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, files->name, files->name_len, SQLITE_STATIC));
        DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, ext, ext_len, SQLITE_STATIC));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, files->size));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->type));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->media_length));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->media_bitrate));
        DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, files->media_codec, files->media_codec_len, SQLITE_STATIC));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, fid));
        DB_CHECK(SQLITE_DONE == sqlite3_step(stmt));

        if (!sqlite3_changes(s_db)) {
            i = 1;
            stmt = s_stmt[SHARE_INS];
            DB_CHECK(SQLITE_OK == sqlite3_reset(stmt));
            DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, fid));
            DB_CHECK(SQLITE_OK == sqlite3_bind_blob(stmt, i++, files->hash, sizeof(files->hash), SQLITE_STATIC));
            DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, files->name, files->name_len, SQLITE_STATIC));
            DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, ext, ext_len, SQLITE_STATIC));
            DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, files->size));
            DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->type));
            DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->media_length));
            DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->media_bitrate));
            DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, files->media_codec, files->media_codec_len, SQLITE_STATIC));
            DB_CHECK(SQLITE_DONE == sqlite3_step(stmt));
        }

        i = 1;
        stmt = s_stmt[SHARE_SRC];
        DB_CHECK(SQLITE_OK == sqlite3_reset(stmt));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, fid));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, MAKE_SID(owner)));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->complete));
        DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, files->rating));
        DB_CHECK(SQLITE_DONE == sqlite3_step(stmt));

        files++;
    }

    return 1;

    failed:
    ED2KD_LOGERR("failed to add file to db (%s)", sqlite3_errmsg(s_db));
    return 0;
}
Beispiel #18
0
int
WfipsData::LoadDispatchLogic()
{
    sqlite3_stmt *stmt;
    sqlite3_stmt *rstmt;
    int rc, i, j, n, iLogic;
    void *pGeom;

    /* Clear our lookup */
    DispLogIndexMap.clear();

    poScenario->m_VDispLogic.clear();

    if( pszAnalysisAreaWkt )
    {
        n = CompileGeometry( pszAnalysisAreaWkt, &pGeom );
        if( n > 0 )
        {
            rc = sqlite3_prepare_v2( db, "SELECT displog.name,indice,num_lev,bp_1,"
                                         "bp_2,bp_3,bp_4 FROM fwa JOIN displog "
                                         "ON fwa.displogic_name=displog.name "
                                         "JOIN brk_point ON "
                                         "displog.name=brk_point.name "
                                         "WHERE ST_Intersects(@geom, geometry) "
                                         "AND fwa.name NOT LIKE '%unassign%' "
                                         "AND substr(fwa.name, 0, 3) NOT IN "
                                         "('EA','SA','AK') "
                                         "AND fwa.ROWID IN "
                                         "(SELECT pkid FROM "
                                         "idx_fwa_geometry WHERE "
                                         "xmin <= MbrMaxX(@geom) AND "
                                         "xmax >= MbrMinX(@geom) AND "
                                         "ymin <= MbrMaxY(@geom) AND "
                                         "ymax >= MbrMinY(@geom)) "
                                         "group by displog.name",
                                     -1, &stmt, NULL );

            rc = sqlite3_bind_blob( stmt,
                                    sqlite3_bind_parameter_index( stmt, "@geom" ),
                                    pGeom, n, sqlite3_free );
        }
        else
        {
            /* Geometry is bad */
            return SQLITE_ERROR;
        }
    }
    else
    {
        rc = sqlite3_prepare_v2( db, "SELECT displog.name,indice,"
                                     "num_lev,bp_1,bp_2,bp_3,bp_4 FROM "
                                     "fwa JOIN displog ON "
                                     "fwa.displogic_name=displog.name "
                                     "JOIN brk_point ON "
                                     "displog.name=brk_point.name "
                                     "WHERE fwa.name NOT LIKE '%unassign%' "
                                     "AND substr(fwa.name, 0, 3) NOT IN "
                                     "('EA','SA','AK') "
                                     "GROUP BY displog.name",
                                 -1, &stmt, NULL );
    }
    rc = sqlite3_prepare_v2( db, "SELECT * FROM  num_resc WHERE name=?", -1,
                             &rstmt, NULL );

    const char *pszName, *pszIndice;
    int nLevels, anBps[4];
    int nBp, anRescCount[13][5];
    iLogic = 0;

    /* Push a default displogic on so we avoid errors */
    poScenario->m_VDispLogic.push_back( CDispLogic() );
    DispLogIndexMap.insert( std::pair<std::string, int>( poScenario->m_VDispLogic[0].GetLogicID(), iLogic++ ) );

    while( sqlite3_step( stmt ) == SQLITE_ROW )
    {
        pszName = (const char*)sqlite3_column_text( stmt, 0 );
        assert( pszName );
        pszIndice = (const char*)sqlite3_column_text( stmt, 1 );
        /* No assert currently, but do we assume BI? */
        nLevels = sqlite3_column_int( stmt, 2 );
        assert( nLevels >= 3 && nLevels <= 5 );
        memset( anBps, 0, sizeof( int ) * 4 );
        for( i = 0; i < nLevels - 1; i++ )
        {
            anBps[i] = sqlite3_column_int( stmt, 3 + i );
        }
        sqlite3_bind_text( rstmt, 1, pszName, -1, NULL );
        i = 0;
        memset( anRescCount, 0, sizeof( int ) * 13 * 5 );
        while( sqlite3_step( rstmt ) == SQLITE_ROW )
        {
            for( j = 0; j < 13; j++ )
            {
                anRescCount[j][i] = sqlite3_column_int( rstmt, j+2 );
                assert( anRescCount[j][i] >= 0 );
                assert( i < 5 );
            }
            i++;
        }
        poScenario->m_VDispLogic.push_back( CDispLogic( std::string( pszName ),
                                            std::string( pszIndice ), nLevels,
                                            anBps, anRescCount ) );
        DispLogIndexMap.insert( std::pair<std::string, int>( pszName, iLogic++ ) );
        sqlite3_reset( rstmt );
    }
    assert( DispLogIndexMap.size() == poScenario->m_VDispLogic.size() );
    sqlite3_finalize( stmt );
    sqlite3_finalize( rstmt );
    return 0;
}
Beispiel #19
0
// Bind a binary blob value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const void* apValue, const int aSize)
{
    const int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    const int ret = sqlite3_bind_blob(mStmtPtr, index, apValue, aSize, SQLITE_TRANSIENT);
    check(ret);
}
void sqlite3_command::bind(int index, const void *data, int datalen, sqlite3_destructor_type p_destructor_type /*= SQLITE_STATIC  or SQLITE_TRANSIENT*/ ) {
	if(sqlite3_bind_blob(this->stmt, index, data, datalen, p_destructor_type)!=SQLITE_OK)
		throw database_error(&m_con);
}
int SqliteStatement::bind (int position, const void* data, int length)
{
    return sqlite3_bind_blob (statement, position, data, length, SQLITE_TRANSIENT);
}
Beispiel #22
0
/* --------------------------------------------------------------- */
void R_sqlbind( const int func )
{
	int col, i;
	double d;
	char type;

	if (!sqldb)   Lerror(ERR_DATABASE,1);
	if (!sqlstmt) Lerror(ERR_DATABASE,0);

	if (ARGN==0) {
		Licpy(ARGR, sqlite3_bind_parameter_count(sqlstmt));
		return;
	}

	if (ARGN!=3) Lerror(ERR_INCORRECT_CALL,0);

	if (Ldatatype(ARG1,'N'))
		col = Lrdint(ARG1);
	else {
		LASCIIZ(*ARG1);
		col = sqlite3_bind_parameter_index(sqlstmt, LSTR(*ARG1));
	}
	get_pad(2, type);

	switch (type) {
		case 'b': case 'B':	/* blob */
			Licpy(ARGR, sqlite3_bind_blob(sqlstmt, col,
				LSTR(*ARG3), LLEN(*ARG3), SQLITE_TRANSIENT));
			break;

		case 'i': case 'I':	/* integer */
			get_i(3, i);
			Licpy(ARGR, sqlite3_bind_int(sqlstmt, col, i));
			break;

		case 'd': case 'D':	/* double */
		case 'f': case 'F':
			L2REAL(ARG3);
			Licpy(ARGR, sqlite3_bind_double(sqlstmt, col, LREAL(*ARG3)));
			break;

		case 's': case 'S':	/* double */
		case 't': case 'T':
			L2STR(ARG3);
			Licpy(ARGR, sqlite3_bind_text(sqlstmt, col,
				LSTR(*ARG3), LLEN(*ARG3), SQLITE_TRANSIENT));
			break;

		case 'n': case 'N':	/* null */
			Licpy(ARGR, sqlite3_bind_null(sqlstmt, col));
			break;

		case 'z': case 'Z':	/* zero blob */
			get_i(3, i);
			Licpy(ARGR, sqlite3_bind_zeroblob(sqlstmt, col, i));
			break;

		default:
			Lerror(ERR_INCORRECT_CALL,0);
	}
} /* R_sqlbind */
int SqliteStatement::bindStatic (int position, Blob const& value)
{
    return sqlite3_bind_blob (statement, position, &value.front (), value.size (), SQLITE_STATIC);
}
Beispiel #24
0
void QgsOSMDatabase::exportSpatiaLiteNodes( const QString &tableName, const QStringList &tagKeys, const QStringList &notNullTagKeys )
{
  QString sqlInsertPoint = QStringLiteral( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) );
  for ( int i = 0; i < tagKeys.count(); ++i )
    sqlInsertPoint += QStringLiteral( ",?" );
  sqlInsertPoint += QLatin1String( ", GeomFromWKB(?, 4326))" );
  sqlite3_stmt *stmtInsert = nullptr;
  if ( sqlite3_prepare_v2( mDatabase, sqlInsertPoint.toUtf8().constData(), -1, &stmtInsert, nullptr ) != SQLITE_OK )
  {
    mError = QStringLiteral( "Prepare SELECT FROM nodes failed." );
    return;
  }

  QgsOSMNodeIterator nodes = listNodes();
  QgsOSMNode n;
  while ( ( n = nodes.next() ).isValid() )
  {
    QgsOSMTags t = tags( false, n.id() );

    // skip untagged nodes: probably they form a part of ways
    if ( t.count() == 0 )
      continue;

    //check not null tags
    bool skipNull = false;
    for ( int i = 0; i < notNullTagKeys.count() && !skipNull; ++i )
      if ( !t.contains( notNullTagKeys[i] ) )
        skipNull = true;

    if ( skipNull )
      continue;

    QgsGeometry geom = QgsGeometry::fromPoint( n.point() );
    int col = 0;
    sqlite3_bind_int64( stmtInsert, ++col, n.id() );

    // tags
    for ( int i = 0; i < tagKeys.count(); ++i )
    {
      if ( t.contains( tagKeys[i] ) )
        sqlite3_bind_text( stmtInsert, ++col, t.value( tagKeys[i] ).toUtf8().constData(), -1, SQLITE_TRANSIENT );
      else
        sqlite3_bind_null( stmtInsert, ++col );
    }

    QByteArray wkb( geom.exportToWkb() );
    sqlite3_bind_blob( stmtInsert, ++col, wkb.constData(), wkb.length(), SQLITE_STATIC );

    int insertRes = sqlite3_step( stmtInsert );
    if ( insertRes != SQLITE_DONE )
    {
      mError = QStringLiteral( "Error inserting node %1 [%2]" ).arg( n.id() ).arg( insertRes );
      break;
    }

    sqlite3_reset( stmtInsert );
    sqlite3_clear_bindings( stmtInsert );
  }

  sqlite3_finalize( stmtInsert );
}
Beispiel #25
0
static tb_bool_t tb_database_sqlite3_statement_bind(tb_database_sql_impl_t* database, tb_database_sql_statement_ref_t statement, tb_database_sql_value_t const* list, tb_size_t size)
{
    // check
    tb_database_sqlite3_t* sqlite = tb_database_sqlite3_cast(database);
    tb_assert_and_check_return_val(sqlite && sqlite->database && statement && list && size, tb_false);

    // the param count
    tb_size_t param_count = (tb_size_t)sqlite3_bind_parameter_count((sqlite3_stmt*)statement);
    tb_assert_and_check_return_val(size == param_count, tb_false);
   
    // walk
    tb_size_t i = 0;
    for (i = 0; i < size; i++)
    {
        // the value
        tb_database_sql_value_t const* value = &list[i];

        // done
        tb_int_t    ok = SQLITE_ERROR;
        tb_byte_t*  data = tb_null;
        switch (value->type)
        {
        case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
            tb_trace_i("sqlite3: test %lu %s", i, value->u.text.data);
            ok = sqlite3_bind_text((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.text.data, (tb_int_t)tb_database_sql_value_size(value), tb_null);
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
            ok = sqlite3_bind_int64((sqlite3_stmt*)statement, (tb_int_t)(i + 1), tb_database_sql_value_int64(value));
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
            ok = sqlite3_bind_int((sqlite3_stmt*)statement, (tb_int_t)(i + 1), (tb_int_t)tb_database_sql_value_int32(value));
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB16:
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB8:
            ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.blob.data, (tb_int_t)value->u.blob.size, tb_null);
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB32:
            {
                if (value->u.blob.stream)
                {
                    // done
                    do
                    {
                        // the stream size
                        tb_hong_t size = tb_stream_size(value->u.blob.stream);
                        tb_assert_and_check_break(size >= 0);

                        // make data
                        data = tb_malloc0_bytes((tb_size_t)size);
                        tb_assert_and_check_break(data);

                        // read data
                        if (!tb_stream_bread(value->u.blob.stream, data, (tb_size_t)size)) break;

                        // bind it
                        ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), data, (tb_int_t)size, tb_database_sqlite3_statement_bind_exit);

                    } while (0);
                }
                else ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.blob.data, (tb_int_t)value->u.blob.size, tb_null);
            }
            break;
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
        case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
            ok = sqlite3_bind_double((sqlite3_stmt*)statement, (tb_int_t)(i + 1), (tb_double_t)tb_database_sql_value_double(value));
            break;
#endif
        case TB_DATABASE_SQL_VALUE_TYPE_NULL:
            ok = sqlite3_bind_null((sqlite3_stmt*)statement, (tb_int_t)(i + 1));
            break;
        default:
            tb_trace_e("statement: bind: unknown value type: %lu", value->type);
            break;
        }

        // failed?
        if (SQLITE_OK != ok)
        {
            // exit data
            if (data) tb_free(data);
            data = tb_null;

            // save state
            sqlite->base.state = tb_database_sqlite3_state_from_errno(sqlite3_errcode(sqlite->database));

            // trace
            tb_trace_e("statement: bind value[%lu] failed, error[%d]: %s", i, sqlite3_errcode(sqlite->database), sqlite3_errmsg(sqlite->database));
            break;
        }
    }

    // ok?
    return (i == size)? tb_true : tb_false;
}
Beispiel #26
0
void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString &tableName,
    const QStringList &tagKeys,
    const QStringList &notNullTagKeys )
{
  Q_UNUSED( tagKeys );

  QString sqlInsertLine = QStringLiteral( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) );
  for ( int i = 0; i < tagKeys.count(); ++i )
    sqlInsertLine += QStringLiteral( ",?" );
  sqlInsertLine += QLatin1String( ", GeomFromWKB(?, 4326))" );
  sqlite3_stmt *stmtInsert = nullptr;
  if ( sqlite3_prepare_v2( mDatabase, sqlInsertLine.toUtf8().constData(), -1, &stmtInsert, nullptr ) != SQLITE_OK )
  {
    mError = QStringLiteral( "Prepare SELECT FROM ways failed." );
    return;
  }

  QgsOSMWayIterator ways = listWays();
  QgsOSMWay w;
  while ( ( w = ways.next() ).isValid() )
  {
    QgsOSMTags t = tags( true, w.id() );

    QgsPolyline polyline = wayPoints( w.id() );

    if ( polyline.count() < 2 )
      continue; // invalid way

    bool isArea = ( polyline.first() == polyline.last() ); // closed way?
    // filter out closed way that are not areas through tags
    if ( isArea && ( t.contains( QStringLiteral( "highway" ) ) || t.contains( QStringLiteral( "barrier" ) ) ) )
    {
      // make sure tags that indicate areas are taken into consideration when deciding on a closed way is or isn't an area
      // and allow for a closed way to be exported both as a polygon and a line in case both area and non-area tags are present
      if ( ( t.value( QStringLiteral( "area" ) ) != QLatin1String( "yes" ) && !t.contains( QStringLiteral( "amenity" ) ) && !t.contains( QStringLiteral( "landuse" ) ) && !t.contains( QStringLiteral( "building" ) ) && !t.contains( QStringLiteral( "natural" ) ) && !t.contains( QStringLiteral( "leisure" ) ) && !t.contains( QStringLiteral( "aeroway" ) ) ) || !closed )
        isArea = false;
    }

    if ( closed != isArea )
      continue; // skip if it's not what we're looking for

    //check not null tags
    bool skipNull = false;
    for ( int i = 0; i < notNullTagKeys.count() && !skipNull; ++i )
      if ( !t.contains( notNullTagKeys[i] ) )
        skipNull = true;

    if ( skipNull )
      continue;

    QgsGeometry geom = closed ? QgsGeometry::fromPolygon( QgsPolygon() << polyline ) : QgsGeometry::fromPolyline( polyline );
    int col = 0;
    sqlite3_bind_int64( stmtInsert, ++col, w.id() );

    // tags
    for ( int i = 0; i < tagKeys.count(); ++i )
    {
      if ( t.contains( tagKeys[i] ) )
        sqlite3_bind_text( stmtInsert, ++col, t.value( tagKeys[i] ).toUtf8().constData(), -1, SQLITE_TRANSIENT );
      else
        sqlite3_bind_null( stmtInsert, ++col );
    }

    if ( !geom.isNull() )
    {
      QByteArray wkb( geom.exportToWkb() );
      sqlite3_bind_blob( stmtInsert, ++col, wkb.constData(), wkb.length(), SQLITE_STATIC );
    }
    else
      sqlite3_bind_null( stmtInsert, ++col );

    int insertRes = sqlite3_step( stmtInsert );
    if ( insertRes != SQLITE_DONE )
    {
      mError = QStringLiteral( "Error inserting way %1 [%2]" ).arg( w.id() ).arg( insertRes );
      break;
    }

    sqlite3_reset( stmtInsert );
    sqlite3_clear_bindings( stmtInsert );
  }

  sqlite3_finalize( stmtInsert );
}
Beispiel #27
0
/*
 * Send an SQL query to the server
 */
static int db_sqlite_submit_query(const db1_con_t* _h, const str* _s)
{
	struct sqlite_connection *conn = CON_SQLITE(_h);
	sqlite3_stmt *stmt;
	const db_val_t *val;
	int rc, i;

	LM_DBG("submit_query: %.*s\n", _s->len, _s->s);

	rc = sqlite3_prepare_v2(conn->conn, _s->s, _s->len, &stmt, NULL);
	if (rc != SQLITE_OK) {
		LM_ERR("failed to prepare statement: %s\n",
			sqlite3_errmsg(conn->conn));
		return -1;
	}
	conn->stmt = stmt;

	for (i = 1; i <= conn->bindpos; i++) {
		val = conn->bindarg[i-1];
		if (VAL_NULL(val)) {
			rc = sqlite3_bind_null(stmt, i);
		} else switch (VAL_TYPE(val)) {
		case DB1_INT:
			rc = sqlite3_bind_int(stmt, i, VAL_INT(val));
			break;
		case DB1_BIGINT:
			rc = sqlite3_bind_int64(stmt, i, VAL_BIGINT(val));
			break;
		case DB1_DOUBLE:
			rc = sqlite3_bind_double(stmt, i, VAL_DOUBLE(val));
			break;
		case DB1_STRING:
			rc = sqlite3_bind_text(stmt, i,
				VAL_STRING(val), -1, NULL);
			break;
		case DB1_STR:
			rc = sqlite3_bind_text(stmt, i,
				VAL_STR(val).s, VAL_STR(val).len, NULL);
			break;
		case DB1_DATETIME:
			rc = sqlite3_bind_double(stmt, i, timet_to_sqlite(VAL_TIME(val)));
			break;
		case DB1_BLOB:
			rc = sqlite3_bind_blob(stmt, i,
				VAL_BLOB(val).s, VAL_BLOB(val).len,
				NULL);
			break;
		case DB1_BITMAP:
			rc = sqlite3_bind_int(stmt, i, VAL_BITMAP(val));
			break;
		default:
			LM_ERR("unknown bind value type %d\n", VAL_TYPE(val));
			return -1;
		}
		if (rc != SQLITE_OK) {
			LM_ERR("Parameter bind failed: %s\n",
				sqlite3_errmsg(conn->conn));
			return -1;
		}
	}

	return 0;
}
Beispiel #28
0
DLL_FUNCTION(int32_t) BU_SQLite_Bind_Blob(sqlite3_stmt* pStmt, int32_t index, void* zData, int32_t nData) {
#pragma comment(linker, "/EXPORT:BU_SQLite_Bind_Blob=_BU_SQLite_Bind_Blob@16")
	return sqlite3_bind_blob(pStmt, index, zData, nData, nullptr);
}
Beispiel #29
0
int machine_bind_blob(Code stmt,int index,void * blob,int size){
return msg_id( sqlite3_bind_blob((sqlite3_stmt*)stmt, index ,blob, size, 0));
}
Beispiel #30
0
int
gpgsql_stepx (sqlite3 *db,
              sqlite3_stmt **stmtp,
              gpgsql_stepx_callback callback,
              void *cookie,
              char **errmsg,
              const char *sql, ...)
{
  int rc;
  int err = 0;
  sqlite3_stmt *stmt = NULL;

  va_list va;
  int args;
  enum gpgsql_arg_type t;
  int i;

  int cols;
  /* Names of the columns.  We initialize this lazily to avoid the
     overhead in case the query doesn't return any results.  */
  const char **azColName = 0;
  int callback_initialized = 0;

  const char **azVals = 0;

  callback_initialized = 0;

  if (stmtp && *stmtp)
    {
      stmt = *stmtp;

      /* Make sure this statement is associated with the supplied db.  */
      log_assert (db == sqlite3_db_handle (stmt));

#if DEBUG_TOFU_CACHE
      prepares_saved ++;
#endif
    }
  else
    {
      const char *tail = NULL;

      rc = sqlite3_prepare_v2 (db, sql, -1, &stmt, &tail);
      if (rc)
        log_fatal ("failed to prepare SQL: %s", sql);

      /* We can only process a single statement.  */
      if (tail)
        {
          while (*tail == ' ' || *tail == ';' || *tail == '\n')
            tail ++;

          if (*tail)
            log_fatal
              ("sqlite3_stepx can only process a single SQL statement."
               "  Second statement starts with: '%s'\n",
               tail);
        }

      if (stmtp)
        *stmtp = stmt;
    }

#if DEBUG_TOFU_CACHE
  queries ++;
#endif

  args = sqlite3_bind_parameter_count (stmt);
  va_start (va, sql);
  if (args)
    {
      for (i = 1; i <= args; i ++)
        {
          t = va_arg (va, enum gpgsql_arg_type);
          switch (t)
            {
            case SQLITE_ARG_INT:
              {
                int value = va_arg (va, int);
                err = sqlite3_bind_int (stmt, i, value);
                break;
              }
            case SQLITE_ARG_LONG_LONG:
              {
                long long value = va_arg (va, long long);
                err = sqlite3_bind_int64 (stmt, i, value);
                break;
              }
            case SQLITE_ARG_STRING:
              {
                char *text = va_arg (va, char *);
                err = sqlite3_bind_text (stmt, i, text, -1, SQLITE_STATIC);
                break;
              }
            case SQLITE_ARG_BLOB:
              {
                char *blob = va_arg (va, void *);
                long long length = va_arg (va, long long);
                err = sqlite3_bind_blob (stmt, i, blob, length, SQLITE_STATIC);
                break;
              }
            default:
              /* Internal error.  Likely corruption.  */
              log_fatal ("Bad value for parameter type %d.\n", t);
            }

          if (err)
            {
              log_fatal ("Error binding parameter %d\n", i);
              goto out;
            }
        }

    }
  t = va_arg (va, enum gpgsql_arg_type);
  log_assert (t == SQLITE_ARG_END);
  va_end (va);

  for (;;)
    {
      rc = sqlite3_step (stmt);

      if (rc != SQLITE_ROW)
        /* No more data (SQLITE_DONE) or an error occurred.  */
        break;

      if (! callback)
        continue;

      if (! callback_initialized)
        {
          cols = sqlite3_column_count (stmt);
          azColName = xmalloc (2 * cols * sizeof (const char *) + 1);

          for (i = 0; i < cols; i ++)
            azColName[i] = sqlite3_column_name (stmt, i);

          callback_initialized = 1;
        }

      azVals = &azColName[cols];
      for (i = 0; i < cols; i ++)
        {
          azVals[i] = sqlite3_column_text (stmt, i);
          if (! azVals[i] && sqlite3_column_type (stmt, i) != SQLITE_NULL)
            /* Out of memory.  */
            {
              err = SQLITE_NOMEM;
              break;
            }
        }

      if (callback (cookie, cols, (char **) azVals, (char **) azColName, stmt))
        /* A non-zero result means to abort.  */
        {
          err = SQLITE_ABORT;
          break;
        }
    }

 out:
  xfree (azColName);

  if (stmtp)
    rc = sqlite3_reset (stmt);
  else
    rc = sqlite3_finalize (stmt);
  if (rc == SQLITE_OK && err)
    /* Local error.  */
    {
      rc = err;
      if (errmsg)
        {
          const char *e = sqlite3_errstr (err);
          size_t l = strlen (e) + 1;
          *errmsg = sqlite3_malloc (l);
          if (! *errmsg)
            log_fatal ("Out of memory.\n");
          memcpy (*errmsg, e, l);
        }
    }
  else if (rc != SQLITE_OK && errmsg)
    /* Error reported by sqlite.  */
    {
      const char * e = sqlite3_errmsg (db);
      size_t l = strlen (e) + 1;
      *errmsg = sqlite3_malloc (l);
      if (! *errmsg)
        log_fatal ("Out of memory.\n");
      memcpy (*errmsg, e, l);
    }

  return rc;
}