Ejemplo n.º 1
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;
}
Ejemplo n.º 2
0
void Database::writePlayerData(const PlayerData& playerData)
{
    // Prepare statement.
    std::string statementString("UPDATE `players` SET worldId=:worldId, positionX=:positionX, positionY=:positionY, hp=:hp, maxhp=:maxhp, strength=:strength, agility=:agility, resistance=:resistance, xp=:xp, level=:level WHERE id=:dbid");

    sqlite3_stmt* statement;
    m_lastError = sqlite3_prepare(m_db, statementString.c_str(), statementString.size(), &statement, nullptr);

    if(m_lastError != SQLITE_OK)
        return;

    // Bind parameters.
    int parameterIndex = sqlite3_bind_parameter_index(statement, ":dbid");
    sqlite3_bind_int(statement, parameterIndex, playerData.dbid);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":worldId");
    sqlite3_bind_int(statement, parameterIndex, playerData.worldId);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":positionX");
    sqlite3_bind_double(statement, parameterIndex, playerData.positionX);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":positionY");
    sqlite3_bind_double(statement, parameterIndex, playerData.positionY);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":hp");
    sqlite3_bind_double(statement, parameterIndex, playerData.hp);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":maxhp");
    sqlite3_bind_double(statement, parameterIndex, playerData.maxhp);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":strength");
    sqlite3_bind_double(statement, parameterIndex, playerData.strength);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":agility");
    sqlite3_bind_double(statement, parameterIndex, playerData.agility);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":resistance");
    sqlite3_bind_double(statement, parameterIndex, playerData.resistance);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":xp");
    sqlite3_bind_double(statement, parameterIndex, playerData.xp);

    parameterIndex = sqlite3_bind_parameter_index(statement, ":level");
    sqlite3_bind_double(statement, parameterIndex, playerData.level);

    // Execute.
    while(true)
    {
        int status = sqlite3_step(statement);

        if(status == SQLITE_BUSY)
            continue;

        break;
    }

    // Free.
    sqlite3_finalize(statement);
}
Ejemplo n.º 3
0
// Bind a text value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bindNoCopy(const char* apName, const char* apValue)
{
    const int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    const int ret = sqlite3_bind_text(mStmtPtr, index, apValue, -1, SQLITE_STATIC);
    check(ret);
}
Ejemplo n.º 4
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);
}
Ejemplo n.º 5
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;
}
Ejemplo n.º 6
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 */
Ejemplo n.º 7
0
DLL_FUNCTION(int32_t) BU_SQLite_Bind_Parameter_Index(sqlite3_stmt* pStmt, const char* zName) {
#pragma comment(linker, "/EXPORT:BU_SQLite_Bind_Parameter_Index=_BU_SQLite_Bind_Parameter_Index@8")
	return sqlite3_bind_parameter_index(pStmt, zName);
}
Ejemplo n.º 8
0
 void SQLiteStatement::bind(string param, const void* value, int len, SQLiteStatement::ValueManagement valmgmt) const
 {
     int idx = sqlite3_bind_parameter_index(this->_stmt, param.c_str());
     this->bind(idx, value, len, valmgmt);
 }
Ejemplo n.º 9
0
void
makedb(int compress)
{
	ssize_t nchars;
	char *line = 0;
	size_t len = 0;
	sqlite3 *db = NULL;
	sqlite3_stmt *stmt = NULL;
	char *query;
	int rc = 0;
	int i = 0;
	int idx = 0;
	char *errmsg = NULL;

	FILE *file = fopen("./sample.txt", "r");
	if (file == NULL)
		err(EXIT_FAILURE, "fopen failed");

	remove(DBPATH);
	db = init_db();
	if (compress)
		query = "CREATE VIRTUAL TABLE fts USING FTS4(data, i, tokenize=porter, "
			"compress=zip, uncompress=unzip)";
	else
		query = "CREATE VIRTUAL TABLE fts USING FTS4(data, i, tokenize=porter)";

	rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
	if (rc != SQLITE_OK) {
		warnx("sqlite3_prepare failed while creating db");
		sqlite3_close(db);
		fclose(file);
		sqlite3_free(query);
		exit(EXIT_FAILURE);
	}
	sqlite3_step(stmt);
	sqlite3_finalize(stmt);
	
	sqlite3_exec(db, "BEGIN", NULL, NULL, &errmsg);
	if (errmsg) {
		warnx("%s", errmsg);
		fclose(file);
		sqlite3_close(db);
		free(errmsg);
		exit(EXIT_FAILURE);
	}
	
	
	while ((nchars = getline(&line, &len, file)) != -1) {
		query = "INSERT INTO fts VALUES(:line, :i)";
		rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
		if (rc != SQLITE_OK) {
			warnx("sqlite3_prepare failed while inserting data");
			warnx("%s", sqlite3_errmsg(db));
			sqlite3_close(db);
			fclose(file);
			exit(EXIT_FAILURE);
		}
	
		idx = sqlite3_bind_parameter_index(stmt, ":line");
		rc = sqlite3_bind_text(stmt, idx, line, -1, NULL);
		if (rc != SQLITE_OK) {
			warnx("%s", sqlite3_errmsg(db));
			sqlite3_finalize(stmt);
			sqlite3_close(db);
			fclose(file);
			exit(EXIT_FAILURE);
		}
		idx = sqlite3_bind_parameter_index(stmt, ":i");
		rc = sqlite3_bind_int(stmt, idx, i);
		if (rc != SQLITE_OK) {
			warnx("%s", sqlite3_errmsg(db));
			sqlite3_finalize(stmt);
			sqlite3_close(db);
			fclose(file);
			exit(EXIT_FAILURE);
		}
		
		sqlite3_step(stmt);
		sqlite3_finalize(stmt);
	}
	
	sqlite3_exec(db, "END", NULL, NULL, &errmsg);
	if (errmsg) {
		warnx("%s", errmsg);
		free(errmsg);
	}
	fclose(file);
	sqlite3_close(db);
}
Ejemplo n.º 10
0
bool PDOSqliteStatement::paramHook(PDOBoundParam *param,
                                   PDOParamEvent event_type) {
  switch (event_type) {
  case PDO_PARAM_EVT_EXEC_PRE:
    if (executed && !m_done) {
      sqlite3_reset(m_stmt);
      m_done = 1;
    }

    if (param->is_param) {
      if (param->paramno == -1) {
        param->paramno = sqlite3_bind_parameter_index(m_stmt,
                                                      param->name.c_str()) - 1;
      }

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

      case PDO_PARAM_NULL:
        if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
          return true;
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_INT:
      case PDO_PARAM_BOOL:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          if (SQLITE_OK == sqlite3_bind_int(m_stmt, param->paramno + 1,
                                            param->parameter.toInt64())) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_LOB:
        if (param->parameter.isResource()) {
          Variant buf = f_stream_get_contents(param->parameter);
          if (!same(buf, false)) {
            param->parameter = buf;
          } else {
            pdo_raise_impl_error(dbh, this, "HY105",
                                 "Expected a stream resource");
            return false;
          }
        } else if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
          handleError(__FILE__, __LINE__);
          return false;
        }

        {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_blob(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_STR:
      default:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_text(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;
      }
    }
    break;

  default:;
  }
  return true;
}
Ejemplo n.º 11
0
		bool exec(const std::string& sql, 
			const bindings_type& bindings, 
			rows_type* rows)
		{
			boost::mutex::scoped_lock lock(guard_);
			auto it = stmt_ptr_map_.find(sql);
			sqlite3_stmt* stmt;
			if(it == stmt_ptr_map_.end()) {
				sqlite3_stmt* new_stmt;
				int ret = sqlite3_prepare_v2(db_ptr_.get(), sql.c_str(), sql.size(), &new_stmt, NULL);
				if(new_stmt == NULL ) {
					std::cerr << "Failed to execute statement: " << sql << std::endl;
					return false;
				}
				if(ret != SQLITE_OK) {
					std::cerr << "Failed to execute statement: " << sql << ", " << ret << std::endl;
					sqlite3_finalize(new_stmt);
					return false;
				}
				stmt_ptr_map_[sql] = boost::shared_ptr<sqlite3_stmt>(new_stmt, statement_finalise());
				stmt = new_stmt;
			} else {
				stmt = it->second.get();
				// Reset the prepared statement, which is more efficient than re-creating
				// as preparing a statement is expensive.
				sqlite3_reset(stmt);
				sqlite3_clear_bindings(stmt);
			}
#ifdef BOOST_NO_CXX11_RANGE_BASED_FOR
			BOOST_FOREACH(auto bit, bindings) {
#else
			for(auto bit : bindings) {
#endif
				int ndx = 0;
				if(bit.first.type() == json_spirit::int_type) {
					ndx = bit.first.get_int();
				} else if(bit.first.type() == json_spirit::str_type) {
					ndx = sqlite3_bind_parameter_index(stmt, bit.first.get_str().c_str());
				} else {
					ASSERT_LOG(false, "parameter for binding index must be int or string: " << bit.first.type());
				}
				ASSERT_LOG(ndx != 0, "Bad index value: 0");
				switch(bit.second.type()) {
					case json_spirit::obj_type: {
						json_spirit::mObject& obj = bit.second.get_obj();
						std::string s = json_spirit::write(obj);
						sqlite3_bind_blob(stmt, ndx, static_cast<const void*>(s.c_str()), s.size(), SQLITE_TRANSIENT);
						break;
					}
					case json_spirit::array_type: {
						json_spirit::mArray& ary = bit.second.get_array();
						std::string s = json_spirit::write(ary);
						sqlite3_bind_blob(stmt, ndx, static_cast<const void*>(s.c_str()), s.size(), SQLITE_TRANSIENT);
						break;
					}
					case json_spirit::str_type: {
						std::string s = bit.second.get_str();
						sqlite3_bind_text(stmt, ndx, s.c_str(), s.size(), SQLITE_TRANSIENT);
						break;
					}
					case json_spirit::bool_type: {
						sqlite3_bind_int(stmt, ndx, bit.second.get_bool());
						break;
					}
					case json_spirit::int_type: {
						sqlite3_bind_int(stmt, ndx, bit.second.get_int());
						break;
					}
					case json_spirit::real_type: {
						sqlite3_bind_double(stmt, ndx, bit.second.get_real());
						break;
					}
					case json_spirit::null_type: {
						sqlite3_bind_null(stmt, ndx);
						break;
					}
				}
			}
			
			std::vector<json_spirit::mValue> ret_rows;
			// Step through the statement
			bool stepping = true;
			while(stepping) {
				int ret = sqlite3_step(stmt);
				if(ret == SQLITE_ROW) {
					int col_count = sqlite3_column_count(stmt);
					for(int n = 0; n != col_count; ++n) {
						int type = sqlite3_column_type(stmt, n);
						switch(type) {
							case SQLITE_INTEGER: {
								int val = sqlite3_column_int(stmt, n);
								ret_rows.push_back(json_spirit::mValue(val));
								break;
							}
							case SQLITE_FLOAT: {
								double val = sqlite3_column_double(stmt, n);
								ret_rows.push_back(json_spirit::mValue(val));
								break;
							}
							case SQLITE_BLOB: {
								const char* blob = reinterpret_cast<const char *>(sqlite3_column_blob(stmt, n));
								int len = sqlite3_column_bytes(stmt, n);
								json_spirit::mValue value;
								json_spirit::read(std::string(blob, blob + len), value);
								ret_rows.push_back(value);
								break;
							}
							case SQLITE_NULL: {
								ret_rows.push_back(json_spirit::mValue());
								break;
							}
							case SQLITE_TEXT: {
								const uint8_t* us = sqlite3_column_text(stmt, n);
								int len = sqlite3_column_bytes(stmt, n);
								std::string s(us, us + len);
								ret_rows.push_back(json_spirit::mValue(s));
								break;
							}
						}						
					}
				} else if(ret == SQLITE_DONE) {
					stepping = false;
				} else {
					std::cerr << "Error stepping through statement: " << sql << ", " << ret << " : " << sqlite3_errmsg(db_ptr_.get()) << std::endl;
					return false;
				}
			}

			ASSERT_LOG(rows != NULL || ret_rows.empty() != false, "There was data to return but no place to put it.");
			rows->swap(ret_rows);
			return true;
		}
	private:
Ejemplo n.º 12
0
 int Query::BindingIndex(std::string name) {
     return sqlite3_bind_parameter_index(statement, name.c_str());
 }
Ejemplo n.º 13
0
int Statement::index(const char* arg_name) {
   int i = sqlite3_bind_parameter_index(stmt, arg_name);
   if(i <= 0) 
      throw ValueError("The key '%s' is invalid (doesn't match with any argument.", arg_name);
   return i;
}
Ejemplo n.º 14
0
static int bind_parameters(
    sqlite3_drv_t *drv, char *buffer, int buffer_size, int *p_index,
    sqlite3_stmt *statement, int *p_type, int *p_size) {
  // decoding parameters
  int i, cur_list_size = -1, param_index = 1, param_indices_are_explicit = 0, result = 0;
  long param_index_long;
  char param_name[MAXATOMLEN + 1]; // parameter names shouldn't be longer than 256!
  char *acc_string;
  result = ei_decode_list_header(buffer, p_index, &cur_list_size);
  if (result) {
    // probably all parameters are integers between 0 and 255
    // and the list was encoded as string (see ei documentation)
    ei_get_type(buffer, p_index, p_type, p_size);
    if (*p_type != ERL_STRING_EXT) {
      return output_error(drv, SQLITE_ERROR,
                          "error while binding parameters");
    }
    acc_string = driver_alloc(sizeof(char*) * (*p_size + 1));
    ei_decode_string(buffer, p_index, acc_string);
    for (param_index = 1; param_index <= *p_size; param_index++) {
      sqlite3_bind_int(statement, param_index, (int) acc_string[param_index - 1]);
    }
    driver_free(acc_string);
    return 0;
  }
  for (i = 0; i < cur_list_size; i++) {
    if (*p_index >= buffer_size) {
      return output_error(drv, SQLITE_ERROR,
                          "error while binding parameters");
    }
    ei_get_type(buffer, p_index, p_type, p_size);
    if (*p_type == ERL_SMALL_TUPLE_EXT) {
      int old_index = *p_index;
      // param with name or explicit index
      param_indices_are_explicit = 1;
      if (*p_size != 2) {
        return output_error(drv, SQLITE_MISUSE,
                            "tuple should contain index or name, and value");
      }
      ei_decode_tuple_header(buffer, p_index, p_size);
      ei_get_type(buffer, p_index, p_type, p_size);
      // first element of tuple is int (index), atom, or string (name)
      switch (*p_type) {
      case ERL_SMALL_INTEGER_EXT:
      case ERL_INTEGER_EXT:
        ei_decode_long(buffer, p_index, &param_index_long);
        param_index = param_index_long;
        break;
      case ERL_ATOM_EXT:
        ei_decode_atom(buffer, p_index, param_name);
        // insert zero terminator
        param_name[*p_size] = '\0';
        if (strncmp(param_name, "blob", 5) == 0) {
          // this isn't really a parameter name!
          *p_index = old_index;
          param_indices_are_explicit = 0;
          goto IMPLICIT_INDEX; // yuck
        }
        else {
          param_index = sqlite3_bind_parameter_index(statement, param_name);
        }
        break;
      case ERL_STRING_EXT:
        if (*p_size >= MAXATOMLEN) {
          return output_error(drv, SQLITE_TOOBIG, "parameter name too long");
        }
        ei_decode_string(buffer, p_index, param_name);
        // insert zero terminator
        param_name[*p_size] = '\0';
        param_index = sqlite3_bind_parameter_index(statement, param_name);
        break;
      default:
        return output_error(
            drv, SQLITE_MISMATCH,
            "parameter index must be given as integer, atom, or string");
      }
      result = decode_and_bind_param(
          drv, buffer, p_index, statement, param_index, p_type, p_size);
      if (result != SQLITE_OK) {
        return result; // error has already been output
      }
    }
    else {
      IMPLICIT_INDEX:
      if (param_indices_are_explicit) {
        return output_error(
            drv, SQLITE_MISUSE,
            "parameters without indices shouldn't follow indexed or named parameters");
      }

      result = decode_and_bind_param(
          drv, buffer, p_index, statement, param_index, p_type, p_size);
      if (result != SQLITE_OK) {
        return result; // error has already been output
      }
      ++param_index;
    }
  }
  return result;
}
Ejemplo n.º 15
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;
}
Ejemplo n.º 16
0
// Bind a string value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const std::string& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, aValue.c_str(), static_cast<int>(aValue.size()), SQLITE_TRANSIENT);
    check(ret);
}
Ejemplo n.º 17
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;
}
Ejemplo n.º 18
0
// Bind a text value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const char* apValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, apValue, -1, SQLITE_TRANSIENT);
    check(ret);
}
Ejemplo n.º 19
0
static void _bindConstraints(sqlite3_stmt* statement, const struct mLibraryEntry* constraints) {
	if (!constraints) {
		return;
	}

	int useIndex, index;
	if (constraints->crc32) {
		useIndex = sqlite3_bind_parameter_index(statement, ":useCrc32");
		index = sqlite3_bind_parameter_index(statement, ":crc32");
		sqlite3_bind_int(statement, useIndex, 1);
		sqlite3_bind_int(statement, index, constraints->crc32);
	}

	if (constraints->filesize) {
		useIndex = sqlite3_bind_parameter_index(statement, ":useSize");
		index = sqlite3_bind_parameter_index(statement, ":size");
		sqlite3_bind_int(statement, useIndex, 1);
		sqlite3_bind_int64(statement, index, constraints->filesize);
	}

	if (constraints->filename) {
		useIndex = sqlite3_bind_parameter_index(statement, ":useFilename");
		index = sqlite3_bind_parameter_index(statement, ":path");
		sqlite3_bind_int(statement, useIndex, 1);
		sqlite3_bind_text(statement, index, constraints->filename, -1, SQLITE_TRANSIENT);
	}

	if (constraints->base) {
		useIndex = sqlite3_bind_parameter_index(statement, ":useRoot");
		index = sqlite3_bind_parameter_index(statement, ":root");
		sqlite3_bind_int(statement, useIndex, 1);
		sqlite3_bind_text(statement, index, constraints->base, -1, SQLITE_TRANSIENT);
	}

	if (constraints->internalCode[0]) {
		useIndex = sqlite3_bind_parameter_index(statement, ":useInternalCode");
		index = sqlite3_bind_parameter_index(statement, ":internalCode");
		sqlite3_bind_int(statement, useIndex, 1);
		sqlite3_bind_text(statement, index, constraints->internalCode, -1, SQLITE_TRANSIENT);
	}

	if (constraints->platform != PLATFORM_NONE) {
		useIndex = sqlite3_bind_parameter_index(statement, ":usePlatform");
		index = sqlite3_bind_parameter_index(statement, ":platform");
		sqlite3_bind_int(statement, useIndex, 1);
		sqlite3_bind_int(statement, index, constraints->platform);
	}
}
Ejemplo n.º 20
0
int Statement::getParameterPos(const char *name)
{
    int pos = sqlite3_bind_parameter_index(impl->stmt, name);
    if (!pos) throw ParameterUnknown(name);
    return pos - 1;
}
Ejemplo n.º 21
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;
}
Ejemplo n.º 22
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);
      }
    }
  }
}
Ejemplo n.º 23
0
// Bind a NULL value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName)
{
    const int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    const int ret = sqlite3_bind_null(mStmtPtr, index);
    check(ret);
}
Ejemplo n.º 24
0
static void _mapcache_cache_mbtiles_delete(mapcache_context *ctx, mapcache_cache *pcache, mapcache_tile *tile)
{
  mapcache_cache_sqlite *cache = (mapcache_cache_sqlite*) pcache;
  mapcache_pooled_connection *pc;
  struct sqlite_conn *conn;
  sqlite3_stmt *stmt1,*stmt2,*stmt3;
  int ret;
  const char *tile_id;
  size_t tile_id_size;
  pc = mapcache_sqlite_get_conn(ctx,cache,tile,0);
  if (GC_HAS_ERROR(ctx)) {
    mapcache_sqlite_release_conn(ctx, pc);
    return;
  }
  conn = SQLITE_CONN(pc);
  stmt1 = conn->prepared_statements[MBTILES_DEL_TILE_SELECT_STMT_IDX];
  stmt2 = conn->prepared_statements[MBTILES_DEL_TILE_STMT1_IDX];
  stmt3 = conn->prepared_statements[MBTILES_DEL_TILE_STMT2_IDX];
  if(!stmt1) {
    sqlite3_prepare(conn->handle, "select tile_id from map where tile_col=:x and tile_row=:y and zoom_level=:z",-1,&conn->prepared_statements[MBTILES_DEL_TILE_SELECT_STMT_IDX], NULL);
    sqlite3_prepare(conn->handle, "delete from map where tile_col=:x and tile_row=:y and zoom_level=:z", -1, &conn->prepared_statements[MBTILES_DEL_TILE_STMT1_IDX], NULL);
    sqlite3_prepare(conn->handle, "delete from images where tile_id=:foobar", -1, &conn->prepared_statements[MBTILES_DEL_TILE_STMT2_IDX], NULL);
    stmt1 = conn->prepared_statements[MBTILES_DEL_TILE_SELECT_STMT_IDX];
    stmt2 = conn->prepared_statements[MBTILES_DEL_TILE_STMT1_IDX];
    stmt3 = conn->prepared_statements[MBTILES_DEL_TILE_STMT2_IDX];
  }

  /* first extract tile_id from the tile we will delete. We need this because we do not know
   * if the tile is empty or not.
   * If it is empty, we will not delete the image blob data from the images table */
  cache->bind_stmt(ctx, stmt1, cache, tile);
  do {
    ret = sqlite3_step(stmt1);
    if (ret != SQLITE_DONE && ret != SQLITE_ROW && ret != SQLITE_BUSY && ret != SQLITE_LOCKED) {
      ctx->set_error(ctx, 500, "sqlite backend failed on mbtile del 1: %s", sqlite3_errmsg(conn->handle));
      sqlite3_reset(stmt1);
      mapcache_sqlite_release_conn(ctx, pc);
      return;
    }
  } while (ret == SQLITE_BUSY || ret == SQLITE_LOCKED);
  if (ret == SQLITE_DONE) { /* tile does not exist, ignore */
    sqlite3_reset(stmt1);
    mapcache_sqlite_release_conn(ctx, pc);
    return;
  } else {
    tile_id = (const char*) sqlite3_column_text(stmt1, 0);
    tile_id_size = sqlite3_column_bytes(stmt1, 0);
  }


  /* delete the tile from the "map" table */
  cache->bind_stmt(ctx,stmt2, cache, tile);
  ret = sqlite3_step(stmt2);
  if (ret != SQLITE_DONE && ret != SQLITE_ROW) {
    ctx->set_error(ctx, 500, "sqlite backend failed on mbtile del 2: %s", sqlite3_errmsg(conn->handle));
    sqlite3_reset(stmt1);
    sqlite3_reset(stmt2);
    mapcache_sqlite_release_conn(ctx, pc);
    return;
  }

  if(tile_id[0] != '#') {
    /* the tile isn't empty, we must also delete from the images table */
    int paramidx = sqlite3_bind_parameter_index(stmt3, ":foobar");
    if (paramidx) {
      sqlite3_bind_text(stmt3, paramidx, tile_id, tile_id_size, SQLITE_STATIC);
    }
    ret = sqlite3_step(stmt3);
    if (ret != SQLITE_DONE && ret != SQLITE_ROW) {
      ctx->set_error(ctx, 500, "sqlite backend failed on mbtile del 3: %s", sqlite3_errmsg(conn->handle));
      sqlite3_reset(stmt1);
      sqlite3_reset(stmt2);
      sqlite3_reset(stmt3);
      mapcache_sqlite_release_conn(ctx, pc);
      return;
    }
  }

  sqlite3_reset(stmt1);
  sqlite3_reset(stmt2);
  sqlite3_reset(stmt3);
  mapcache_sqlite_release_conn(ctx, pc);
}
Ejemplo n.º 25
0
// Bind an int value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const int& aValue)
{
    const int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    const int ret = sqlite3_bind_int(mStmtPtr, index, aValue);
    check(ret);
}
Ejemplo n.º 26
0
PlayerData Database::getPlayerData(const std::string& username)
{
    // Prepare statement.
    std::string statementString("SELECT * FROM `players` WHERE username=:username");

    sqlite3_stmt* statement;
    m_lastError = sqlite3_prepare(m_db, statementString.c_str(), statementString.size(), &statement, nullptr);

    if(m_lastError != SQLITE_OK)
        return PlayerData();

    // Bind parameters.
    int usernameParameterIndex = sqlite3_bind_parameter_index(statement, ":username");
    sqlite3_bind_text(statement, usernameParameterIndex, username.c_str(), username.size(), nullptr);

    // Execute.
    while(true)
    {
        int status = sqlite3_step(statement);

        if(status == SQLITE_BUSY)
            continue;

        break;
    }

    PlayerData playerData;

    playerData.dbid = sqlite3_column_int(statement, 0);

    const unsigned char* cuc_string_username = sqlite3_column_text(statement, 1);
    const char* cc_string_username = reinterpret_cast<const char*>(cuc_string_username);

    try
    {
        playerData.username = std::string(cc_string_username);
    }
    catch(std::exception& e)
    {
        playerData.username = "";
    }

    const unsigned char* cuc_string_hashedPassword = sqlite3_column_text(statement, 2);
    const char* cc_string_hashedPassword = reinterpret_cast<const char*>(cuc_string_hashedPassword);

    try
    {
        playerData.hashedPassword = std::string(cc_string_hashedPassword);
    }
    catch(std::exception& e)
    {
        playerData.hashedPassword = "";
    }


    playerData.worldId = sqlite3_column_int(statement, 3);
    playerData.positionX = sqlite3_column_double(statement, 4);
    playerData.positionY = sqlite3_column_double(statement, 5);

    playerData.hp = sqlite3_column_double(statement, 6);
    playerData.maxhp = sqlite3_column_double(statement, 7);
    playerData.strength = sqlite3_column_double(statement, 8);
    playerData.agility = sqlite3_column_double(statement, 9);
    playerData.resistance = sqlite3_column_double(statement, 10);

    playerData.xp = sqlite3_column_double(statement, 11);
    playerData.level = sqlite3_column_double(statement, 12);

    // Free.
    sqlite3_finalize(statement);

    return playerData;
}