// Load an extension into the sqlite database. Only affects the current connection. // Parameter details can be found here: http://www.sqlite.org/c3ref/load_extension.html void Database::loadExtension(const char* apExtensionName, const char *apEntryPointName) { #ifdef SQLITE_OMIT_LOAD_EXTENSION // Unused (void)apExtensionName; (void)apEntryPointName; throw std::runtime_error("sqlite extensions are disabled"); #else #ifdef SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION // Since SQLite 3.13 (2016-05-18): // Security warning: // It is recommended that the SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION method be used to enable only this interface. // The use of the sqlite3_enable_load_extension() interface should be avoided to keep the SQL load_extension() // disabled and prevent SQL injections from giving attackers access to extension loading capabilities. // (NOTE: not using nullptr: cannot pass object of non-POD type 'std::__1::nullptr_t' through variadic function) int ret = sqlite3_db_config(mpSQLite, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, NULL); // NOTE: not using nullptr #else int ret = sqlite3_enable_load_extension(mpSQLite, 1); #endif check(ret); ret = sqlite3_load_extension(mpSQLite, apExtensionName, apEntryPointName, 0); check(ret); #endif }
VALUE do_sqlite3_cExtension_enable_load_extension(VALUE self, VALUE on) { #ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION VALUE id_connection = rb_intern("connection"); VALUE connection = rb_funcall(self, id_connection, 0); if (connection == Qnil) { return Qfalse; } // Retrieve the actual connection from the VALUE sqlite3_connection = rb_iv_get(connection, "@connection"); if (sqlite3_connection == Qnil) { return Qfalse; } sqlite3 *db; Data_Get_Struct(sqlite3_connection, sqlite3, db); if (!(db = DATA_PTR(connection))) { return Qfalse; } int status = sqlite3_enable_load_extension(db, on == Qtrue ? 1 : 0); if (status != SQLITE_OK) { rb_raise(eDO_ConnectionError, "Couldn't enable extension loading"); } return Qtrue; #else return Qfalse; #endif }
CAMLprim value caml_sqlite3_enable_load_extension(value v_db, value v_onoff) { int ret; db_wrap *dbw = Sqlite3_val(v_db); ret = sqlite3_enable_load_extension(dbw->db, Bool_val(v_onoff)); return Val_bool(ret); }
SWITCH_DECLARE(int) switch_core_db_load_extension(switch_core_db_t *db, const char *extension) { int ret = 0; char *err = NULL; sqlite3_enable_load_extension(db, 1); ret = sqlite3_load_extension(db, extension, 0, &err); sqlite3_enable_load_extension(db, 0); if (err) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "LOAD EXTENSION ERR [%s]\n", err); switch_core_db_free(err); err = NULL; } return ret; }
static char * GetFpuWkt( const char *pszFpu ) { int rc; sqlite3 *db; sqlite3_stmt *stmt; const char *pszFpuDb = WFIPS_DATA_TEST_PATH FPU_DB; char *pszWkt; rc = sqlite3_open_v2( pszFpuDb, &db, SQLITE_OPEN_READONLY, NULL ); BOOST_REQUIRE( rc == 0 ); rc = sqlite3_enable_load_extension( db, 1 ); rc = sqlite3_load_extension( db, SPATIALITE_EXT, NULL, NULL ); rc = sqlite3_prepare_v2( db, "SELECT AsText(geometry) FROM fpu WHERE " \ "fpu_code=?", -1, &stmt, NULL ); BOOST_REQUIRE( rc == 0 ); rc = sqlite3_bind_text( stmt, 1, pszFpu, -1, NULL ); BOOST_REQUIRE( rc == 0 ); rc = sqlite3_bind_text( stmt, 1, pszFpu, -1, NULL ); rc = sqlite3_step( stmt ); BOOST_REQUIRE( rc == 100 ); pszWkt = sqlite3_mprintf( "%s", (const char*)sqlite3_column_text( stmt, 0 ) ); sqlite3_finalize( stmt ); sqlite3_close( db ); return pszWkt; }
SEXP R_enable_load_extension(SEXP rdb, SEXP on) { int status; sqlite3 *db; db = GET_SQLITE_DB(rdb); status = sqlite3_enable_load_extension(db, LOGICAL(on)[0]); return(ScalarInteger(status)); }
/* call-seq: db.enable_load_extension(onoff) * * Enable or disable extension loading. */ static VALUE enable_load_extension(VALUE self, VALUE onoff) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, (int)NUM2INT(onoff))); return self; }
void SqliteWorkHorse::initDatabase(){ int rc = sqlite3_open_v2(this->plow->getDatabaseFile().c_str(), &db, SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READONLY,0); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return; } sqlite3_enable_load_extension(db,1); sqlite3_enable_load_extension(db,1); #ifdef WIN32 execute_query(db,"SELECT load_extension('mod_spatialite')"); #else execute_query(db,"SELECT load_extension('/usr/local/lib/mod_spatialite')"); #endif std::stringstream query_ss; query_ss << "SELECT load_extension('" << this->plow->getExtensionLocation() << "')"; std::cout << query_ss.str() << std::endl; execute_query(query_ss.str().c_str()); }
bool DBBrowserDB::open ( const QString & db) { bool ok=false; int err; if (isOpen()) close(); //try to verify the SQLite version 3 file header QFile dbfile(db); if ( dbfile.open( QIODevice::ReadOnly ) ) { char buffer[16+1]; dbfile.readLine(buffer, 16); QString contents = QString(buffer); dbfile.close(); if (!contents.startsWith("SQLite format 3")) { lastErrorMessage = QObject::tr("File is not a SQLite 3 database"); return false; } } else { lastErrorMessage = QObject::tr("File could not be read"); return false; } lastErrorMessage = QObject::tr("no error"); err = sqlite3_open_v2(db.toUtf8(), &_db, SQLITE_OPEN_READWRITE, NULL); if ( err ) { lastErrorMessage = QString::fromUtf8((const char*)sqlite3_errmsg(_db)); sqlite3_close(_db); _db = 0; return false; } if (_db){ // set preference defaults QSettings settings(QApplication::organizationName(), QApplication::organizationName()); settings.sync(); bool foreignkeys = settings.value( "/db/foreignkeys", false ).toBool(); setPragma("foreign_keys", foreignkeys ? "1" : "0"); if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA empty_result_callbacks = ON;", NULL,NULL,NULL)){ if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA show_datatypes = ON;", NULL,NULL,NULL)){ ok=true; } curDBFilename = db; } // Enable extension loading sqlite3_enable_load_extension(_db, 1); } return ok; }
SqliteConnection::SqliteConnection(const std::string& path, const bool allow_ext, const int flags, const std::string& vfs) : pConn_(NULL) { // Get the underlying database connection int rc = sqlite3_open_v2(path.c_str(), &pConn_, flags, vfs.size() ? vfs.c_str() : NULL); if (rc != SQLITE_OK) { stop("Could not connect to database:\n%s", getException()); } if (allow_ext) { sqlite3_enable_load_extension(pConn_, 1); } }
bool c_SQLite3::t_loadextension(const String& extension) { validate(); String translated = File::TranslatePath(extension); if (translated.empty()) { raise_warning("Unable to load extension at '%s'", extension.data()); return false; } char *errtext = NULL; sqlite3_enable_load_extension(m_raw_db, 1); if (sqlite3_load_extension(m_raw_db, translated.data(), 0, &errtext) != SQLITE_OK) { raise_warning("%s", errtext); sqlite3_free(errtext); sqlite3_enable_load_extension(m_raw_db, 0); return false; } sqlite3_enable_load_extension(m_raw_db, 0); return true; }
ikptr ik_sqlite3_enable_load_extension (ikptr s_conn, ikptr s_onoff, ikpcb * pcb) { #ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION sqlite3 * conn = IK_SQLITE_CONNECTION(s_conn);; int onoff = (IK_FALSE_OBJECT == s_onoff)? 0 : 1; int rv; rv = sqlite3_enable_load_extension(conn, onoff); return ika_integer_from_sqlite_errcode(pcb, rv); #else feature_failure(__func__); #endif }
void GDALGeometricAttributes::run_sql() { sqlite3 *db; int rc = sqlite3_open(vc.getDBID().c_str(), &db); sqlite3_enable_load_extension(db,1); if( rc ){ DM::Logger(DM::Error) << "Failed to open database"; return; } //Load spatialite sqlite3_enable_load_extension(db,1); #ifdef WIN32 execute_sql_statement(db,"SELECT load_extension('mod_spatialite')"); #else execute_sql_statement(db,"SELECT load_extension('/usr/local/lib/mod_spatialite')"); #endif std::stringstream query_stream; query_stream << "SELECT load_extension('" << this->getSimulation()->getSimulationConfig().getDefaultModulePath() << "/SqliteExtension/libdm_sqlite_plugin" << "')"; execute_sql_statement(db, query_stream.str().c_str()); query_stream.str(""); query_stream.clear(); query_stream << "UPDATE " << this->leadingViewName << " set "; if (isCalculateArea) query_stream << "area = area(geometry), "; if (isAspectRationBB) query_stream << "aspect_ratio_BB = dm_poly_aspect_ratio(ASWKT(geometry)), "; if (isPercentageFilled) query_stream << "percentage_filled = dm_poly_percentage_filled(ASWKT(geometry)) "; DM::Logger(DM::Standard) << query_stream.str(); execute_sql_statement(db, query_stream.str().c_str()); sqlite3_close(db); }
bool c_SQLite3::t_loadextension(CStrRef extension) { INSTANCE_METHOD_INJECTION_BUILTIN(SQLite3, SQLite3::loadextension); validate(); String translated = File::TranslatePath(extension); if (translated.empty()) { raise_warning("Unable to load extension at '%s'", extension.data()); return false; } char *errtext = NULL; sqlite3_enable_load_extension(m_raw_db, 1); if (sqlite3_load_extension(m_raw_db, translated.data(), 0, &errtext) != SQLITE_OK) { raise_warning("%s", errtext); sqlite3_free(errtext); sqlite3_enable_load_extension(m_raw_db, 0); return false; } sqlite3_enable_load_extension(m_raw_db, 0); return true; }
bool DBBrowserDB::create ( const QString & db) { bool ok=false; if (isOpen()) close(); lastErrorMessage = QObject::tr("no error"); // read encoding from settings and open with sqlite3_open for utf8 // and sqlite3_open16 for utf16 QSettings settings(QApplication::organizationName(), QApplication::organizationName()); QString sEncoding = settings.value("/db/defaultencoding", "UTF-8").toString(); int openresult = SQLITE_OK; if(sEncoding == "UTF-8" || sEncoding == "UTF8" || sEncoding == "Latin1") openresult = sqlite3_open(db.toUtf8(), &_db); else openresult = sqlite3_open16(db.utf16(), &_db); if( openresult != SQLITE_OK ){ lastErrorMessage = QString::fromUtf8((const char*)sqlite3_errmsg(_db)); sqlite3_close(_db); _db = 0; return false; } if (_db){ if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA empty_result_callbacks = ON;", NULL,NULL,NULL)){ if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA show_datatypes = ON;", NULL,NULL,NULL)){ ok=true; } curDBFilename = db; } // Enable extension loading sqlite3_enable_load_extension(_db, 1); // force sqlite3 do write proper file header // if we don't create and drop the table we might end up // with a 0 byte file, if the user cancels the create table dialog sqlite3_exec(_db, "CREATE TABLE notempty (id integer primary key);", NULL, NULL, NULL); sqlite3_exec(_db, "DROP TABLE notempty", NULL, NULL, NULL); sqlite3_exec(_db, "COMMIT;", NULL, NULL, NULL); } return ok; }
bool HHVM_METHOD(SQLite3, loadextension, const String& extension) { auto *data = Native::data<SQLite3>(this_); data->validate(); String translated = File::TranslatePath(extension); if (translated.empty()) { raise_warning("Unable to load extension at '%s'", extension.data()); return false; } char *errtext = nullptr; sqlite3_enable_load_extension(data->m_raw_db, 1); if (sqlite3_load_extension(data->m_raw_db, translated.data(), 0, &errtext) != SQLITE_OK) { raise_warning("%s", errtext); sqlite3_free(errtext); sqlite3_enable_load_extension(data->m_raw_db, 0); return false; } sqlite3_enable_load_extension(data->m_raw_db, 0); return true; }
SWIGEXPORT jint JNICALL Java_com_almworks_sqlite4java__1SQLiteSwiggedJNI_sqlite3_1enable_1load_1extension(JNIEnv *jenv, jclass jcls, jlong jarg1, jint jarg2) { jint jresult = 0 ; sqlite3 *arg1 = (sqlite3 *) 0 ; int arg2 ; int result; (void)jenv; (void)jcls; arg1 = *(sqlite3 **)&jarg1; arg2 = (int)jarg2; result = (int)sqlite3_enable_load_extension(arg1,arg2); jresult = (jint)result; return jresult; }
void CppSQLite3DB::open(const char* szFile) { int nRet = sqlite3_open(szFile, &mpDB); if (nRet != SQLITE_OK) { const char* szError = sqlite3_errmsg(mpDB); throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG); } //Load extension library. sqlite3_enable_load_extension(mpDB,1); sqlite3_load_extension(mpDB,getFullPath(extension_library_filename).c_str(),0,0); setBusyTimeout(mnBusyTimeoutMs); }
void Writer::CreateCloudTable(std::string const& name, boost::uint32_t srid) { std::ostringstream oss; ::soci::sqlite3_session_backend* backend = static_cast< ::soci::sqlite3_session_backend*>( m_session->get_backend()); try { int did_enable = sqlite3_enable_load_extension(static_cast<sqlite_api::sqlite3*>(backend->conn_), 1); if (did_enable == SQLITE_ERROR) throw sqlite_driver_error("Unable to enable extensions on sqlite backend -- can't enable spatialite"); oss << "SELECT load_extension('libspatialite.dylib')"; m_session->once << oss.str(); oss.str(""); } catch (std::runtime_error&) { throw; } oss << "SELECT InitSpatialMetadata()"; m_session->once << oss.str(); oss.str(""); std::string cloud_column = getOptions().getValueOrDefault<std::string>("cloud_column", "id"); oss << "CREATE TABLE " << boost::to_lower_copy(name) << " (" << boost::to_lower_copy(cloud_column) << " INTEGER PRIMARY KEY AUTOINCREMENT," << " schema TEXT," << " block_table varchar(64)" << ")"; m_session->once << oss.str(); oss.str(""); { bool is3d = getOptions().getValueOrDefault<bool>("is3d", false); boost::uint32_t nDim = 2 ;// is3d ? 3 : 2; oss << "SELECT AddGeometryColumn('" << boost::to_lower_copy(name) << "'," << "'extent'" << "," << srid << ", 'POLYGON', 'XY')"; m_session->once << oss.str(); oss.str(""); } }
static int load_dyn_extension (sqlite3 * db_handle) { int ret; char *err_msg = NULL; sqlite3_enable_load_extension (db_handle, 1); ret = sqlite3_exec (db_handle, "SELECT load_extension('mod_spatialite')", NULL, NULL, &err_msg); if (ret != SQLITE_OK) { fprintf (stderr, "load_extension() error: %s\n", err_msg); sqlite3_free (err_msg); return 0; } return 1; }
/* call-seq: db.enable_load_extension(onoff) * * Enable or disable extension loading. */ static VALUE enable_load_extension(VALUE self, VALUE onoff) { sqlite3RubyPtr ctx; int onoffparam; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); if (Qtrue == onoff) { onoffparam = 1; } else if (Qfalse == onoff) { onoffparam = 0; } else { onoffparam = (int)NUM2INT(onoff); } CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, onoffparam)); return self; }
bool DBBrowserDB::create ( const QString & db) { bool ok=false; if (isOpen()) close(); lastErrorMessage = QObject::tr("no error"); // read encoding from settings and open with sqlite3_open for utf8 // and sqlite3_open16 for utf16 QSettings settings(QApplication::organizationName(), QApplication::organizationName()); QString sEncoding = settings.value("/db/defaultencoding", "UTF-8").toString(); int openresult = SQLITE_OK; if(sEncoding == "UTF-8" || sEncoding == "UTF8" || sEncoding == "Latin1") openresult = sqlite3_open(db.toUtf8(), &_db); else openresult = sqlite3_open16(db.utf16(), &_db); if( openresult != SQLITE_OK ){ lastErrorMessage = QString::fromUtf8((const char*)sqlite3_errmsg(_db)); sqlite3_close(_db); _db = 0; return false; } if (_db){ if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA empty_result_callbacks = ON;", NULL,NULL,NULL)){ if (SQLITE_OK==sqlite3_exec(_db,"PRAGMA show_datatypes = ON;", NULL,NULL,NULL)){ ok=true; } curDBFilename = db; } // Enable extension loading sqlite3_enable_load_extension(_db, 1); } return ok; }
// Load an extension into the sqlite database. Only affects the current connection. // Parameter details can be found here: http://www.sqlite.org/c3ref/load_extension.html void Database::loadExtension(const char* apExtensionName, const char *apEntryPointName) { #ifdef SQLITE_OMIT_LOAD_EXTENSION # throw std::runtime_error("sqlite extensions are disabled"); # #else # int ret = sqlite3_enable_load_extension(mpSQLite, 1); check(ret); ret = sqlite3_load_extension(mpSQLite, apExtensionName, apEntryPointName, 0); check(ret); # #endif }
int main(int argc, char **argv) { sqlite3 *db; sqlite3_stmt *pStmt; int rc; rc = sqlite3_open("example.db", &db); if (rc != SQLITE_OK) { printf("db open error\n"); return -1; } sqlite3_enable_load_extension(db, 1); rc = sqlite3_load_extension(db, "libbfile_ext.so", NULL, NULL); if (rc != SQLITE_OK) { printf("load bfile extension error\n"); return -1; } /* clean the database */ cleandb(db); /* create table & directory, and insert data */ rc = prepare_db(db); if (rc) return -1; /* query bfile data */ rc = query_bfile(db); if (rc) return -1; /* replace directory alias */ rc = change_dir(db); if (rc) return -1; sqlite3_close(db); return 0; }
void sqlite3_connection::enable_load_extension(const bool enable) { if(!this->db) throw database_error("database is not open"); if (sqlite3_enable_load_extension(this->db, enable ? 1 : 0) != SQLITE_OK) throw database_error("unable to turn on extension support"); }
bool load_extension(std::string const& ext_path) { sqlite3_enable_load_extension(db_, 1); int result = sqlite3_load_extension(db_, ext_path.c_str(), 0 , 0); return (result == SQLITE_OK)? true : false; }
int db_sqlite_connect(struct my_con* ptr) { sqlite3* con; char* errmsg; struct db_sqlite_extension_list *iter; /* if connection already in use, close it first*/ if (ptr->init) sqlite3_close_v2(ptr->con); ptr->init = 1; memcpy(url_buf, ptr->id->url.s+sizeof(SQLITE_ID)-1, ptr->id->url.len - (sizeof(SQLITE_ID)-1)); url_buf[ptr->id->url.len - (sizeof(SQLITE_ID)-1)] = '\0'; if (sqlite3_open(url_buf, &con) != SQLITE_OK) { LM_ERR("Can't open database: %s\n", sqlite3_errmsg((sqlite3*)ptr->con)); return -1; } /* trying to load extensions */ if (extension_list) { if (sqlite3_enable_load_extension(con, 1)) { LM_ERR("failed to enable extension loading\n"); return -1; } iter=extension_list; for (iter=extension_list; iter; iter=iter->next) { if (sqlite3_load_extension(con, iter->ldpath, iter->entry_point, &errmsg)) { LM_ERR("failed to load!" "Extension [%s]! Entry point [%s]!" "Errmsg [%s]!\n", iter->ldpath, iter->entry_point, errmsg); goto out_free; } LM_DBG("Extension [%s] loaded!\n", iter->ldpath); } if (sqlite3_enable_load_extension(con, 0)) { LM_ERR("failed to enable extension loading\n"); return -1; } } ptr->con = con; return 0; out_free: while (extension_list) { iter=extension_list; extension_list=extension_list->next; pkg_free(iter); } return -1; }
/* public native void dbopen(String path, int flags, String locale); */ void dbopen(JNIEnv* env, jobject object, jstring pathString, jint flags) { int err; sqlite3 * handle = NULL; sqlite3_stmt * statement = NULL; char const * path8 = env->GetStringUTFChars(pathString, NULL); int sqliteFlags; // register the logging func on sqlite. needs to be done BEFORE any sqlite3 func is called. registerLoggingFunc(path8); // convert our flags into the sqlite flags if (flags & CREATE_IF_NECESSARY) { sqliteFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; } else if (flags & OPEN_READONLY) { sqliteFlags = SQLITE_OPEN_READONLY; } else { sqliteFlags = SQLITE_OPEN_READWRITE; } err = sqlite3_open_v2(path8, &handle, sqliteFlags, NULL); if (err != SQLITE_OK) { LOGE("sqlite3_open_v2(\"%s\", &handle, %d, NULL) failed\n", path8, sqliteFlags); throw_sqlite3_exception_errcode(env, err, "Could not open database"); goto done; } // Check that the database is really read/write when that is what we asked for. if ((sqliteFlags & SQLITE_OPEN_READWRITE) && sqlite3_db_readonly(handle, NULL)) { throw_sqlite3_exception(env, handle, "Could not open the database in read/write mode."); goto done; } // The soft heap limit prevents the page cache allocations from growing // beyond the given limit, no matter what the max page cache sizes are // set to. The limit does not, as of 3.5.0, affect any other allocations. sqlite3_soft_heap_limit(SQLITE_SOFT_HEAP_LIMIT); // Set the default busy handler to retry for 1000ms and then return SQLITE_BUSY err = sqlite3_busy_timeout(handle, 1000 /* ms */); if (err != SQLITE_OK) { LOGE("sqlite3_busy_timeout(handle, 1000) failed for \"%s\"\n", path8); throw_sqlite3_exception(env, handle, "Could not set busy timeout"); goto done; } #ifdef DB_INTEGRITY_CHECK static const char* integritySql = "pragma integrity_check(1);"; err = sqlite3_prepare_v2(handle, integritySql, -1, &statement, NULL); if (err != SQLITE_OK) { LOGE("sqlite_prepare_v2(handle, \"%s\") failed for \"%s\"\n", integritySql, path8); throw_sqlite3_exception(env, handle, "sqlite_prepare_v2(handle, \"pragma integrity_check(1);\") failed"); goto done; } // first is OK or error message err = sqlite3_step(statement); if (err != SQLITE_ROW) { LOGE("integrity check failed for \"%s\"\n", integritySql, path8); throw_sqlite3_exception(env, handle); goto done; } else { const char *text = (const char*)sqlite3_column_text(statement, 0); if (strcmp(text, "ok") != 0) { LOGE("integrity check failed for \"%s\": %s\n", integritySql, path8, text); jniThrowException(env, "net/sqlcipher/database/SQLiteDatabaseCorruptException", text); goto done; } } #endif sqlite3_enable_load_extension(handle, 1); LOGV("Opened '%s' - %p\n", path8, handle); env->SetLongField(object, offset_db_handle, (intptr_t)handle); handle = NULL; // The caller owns the handle now. done: // Release allocated resources if (path8 != NULL) env->ReleaseStringUTFChars(pathString, path8); if (statement != NULL) sqlite3_finalize(statement); if (handle != NULL) sqlite3_close(handle); }
/* What we need: specific condition, is walk in , tactic, distance elevation * minsteps, maxsteps, waterdrops, pump/roll, fwa id. */ int main( int argc, char *argv[] ) { GDALAllRegister(); OGRRegisterAll(); const char *pszInputfile = NULL; const char *pszOutputfile = NULL; const char *pszOutputFormat = "CSV"; char **papszCreateOptions = NULL; const char *pszDataPath = NULL; const char *pszFpuCode = NULL; int nLimit = 0; int bProgress = TRUE; double dfMaxX, dfMinX, dfMaxY, dfMinY; int bLimit = FALSE; double dfBuffer = 0.0; int i = 1; while( i < argc ) { if( EQUAL( argv[i], "-p" ) ) { bProgress = TRUE; } else if( EQUAL( argv[i], "-d" ) ) { pszDataPath = argv[++i]; } else if( EQUAL( argv[i], "-of" ) ) { pszOutputFormat = argv[++i]; } else if( EQUAL( argv[i], "-co" ) ) { papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] ); } else if( EQUAL( argv[i], "-sl" ) ) { dfMaxX = atof(argv[++i]); dfMinX = atof(argv[++i]); dfMaxY = atof(argv[++i]); dfMinY = atof(argv[++i]); bLimit = TRUE; } else if( EQUAL( argv[i], "-fpu" ) ) { pszFpuCode = argv[++i]; } else if( EQUAL( argv[i], "-b" ) ) { dfBuffer = atof( argv[++i] ); } else if( EQUAL( argv[i], "-l" ) ) { nLimit = atoi( argv[++i] ); } else if( EQUAL( argv[i], "-h" ) ) { Usage(); } else if( pszInputfile == NULL ) { pszInputfile = argv[i]; } else if( pszOutputfile == NULL ) { pszOutputfile = argv[i]; } else { Usage(); } i++; } if( pszInputfile == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "No input file provided\n"); Usage(); } if( pszOutputfile == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Invalid output selected, " "use database and table or output file\n" ); Usage(); } pszDataPath = CPLGetConfigOption( "OMFFR_DATA", NULL ); OGRDataSourceH hInputDS = OGROpen( pszInputfile, FALSE, NULL ); if( hInputDS == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Cannot open input file\n" ); Usage(); } int year, num, day; const char *dow, *disc_time; int bi; double ros; int fuel; const char *spec_cond; int slope, walkin; const char *tactic; double dist; int elev; double ltow; int minsteps = 250; int maxsteps = 10000; const char *sunrise, *sunset; int waterdrops, pumproll; char *abyFwa; const char *fwaid; double lon, lat; OGRLayerH hInputLayer; hInputLayer = OGR_DS_GetLayerByName( hInputDS, CPLGetBasename( pszInputfile ) ); OGRFeatureDefnH hInputFeatureDefn; OGRFeatureH hInputFeature; OGRGeometryH hGeometry; hInputFeatureDefn = OGR_L_GetLayerDefn( hInputLayer ); const char *pszTmpFilename =CPLFormFilename( pszDataPath, "irs/FWA", ".dat" ); std::vector<CFWA>fwas = LoadFwas( pszTmpFilename ); int nFeatures = OGR_L_GetFeatureCount( hInputLayer, TRUE ); FILE *fout = fopen( pszOutputfile, "w" ); //CFWA *fwa; Random random; char pszDb[8192]; sprintf( pszDb, "%s/omffr.sqlite", pszDataPath ); IRSDataAccess *poDA = IRSDataAccess::Create( 0, pszDb ); int rc; sqlite3 *db; rc = sqlite3_open_v2( pszDb, &db, SQLITE_OPEN_READONLY, NULL ); rc = sqlite3_enable_load_extension( db, 1 ); rc = sqlite3_load_extension( db, "/usr/local/lib/libspatialite.so", 0, NULL ); sqlite3_stmt *stmt; rc = sqlite3_prepare_v2( db, "SELECT * from fwa join fwa_bndry USING(fwa_gis_id) " \ "WHERE ST_Contains(fwa_bndry.geometry, MakePoint(?, ?, 4269))", -1, &stmt, NULL ); if(rc) { CPLError( CE_Failure, CPLE_AppDefined, "Could not open DB"); } GDALTermProgress( 0.0, NULL, NULL ); OGR_L_ResetReading( hInputLayer ); const char *pszFwaName; int nDone = 0; while( ( hInputFeature = OGR_L_GetNextFeature( hInputLayer ) ) != NULL ) { /* fwaid = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fwa_name" ) ); abyFwa = CPLStrdup( fwaid ); LaunderFwaName( abyFwa ); fwa = FindFwa( fwas, abyFwa ); if( fwa == NULL ) { CPLError( CE_Warning, CPLE_FileIO, "Could not load fwa (%s)from file, missing\n", abyFwa ); continue; } */ /* Get fwa by point */ hGeometry = OGR_F_GetGeometryRef( hInputFeature ); /* Try to handle non-geometry types (csv) */ if( hGeometry != NULL ) { lat = OGR_G_GetY( hGeometry, 0 ); lon = OGR_G_GetX( hGeometry, 0 ); } else { lat = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "Y") ); lon = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "X") ); } std::string oFwaName = poDA->PointQuery( "fwa_bndry", "fwa_lndr_name", lon, lat ); rc = sqlite3_bind_double( stmt, 1, lon ); rc = sqlite3_bind_double( stmt, 2, lat ); //sqlite3_bind_text( stmt, 1, oFwaName.c_str(), -1, SQLITE_TRANSIENT); rc = sqlite3_step( stmt ); if( rc != SQLITE_ROW && rc != SQLITE_DONE ) { CPLError( CE_Warning, CPLE_FileIO, "Could not load fwa (%s)from file, missing\n", oFwaName.c_str() ); sqlite3_reset(stmt); continue; } int nFwaWalkIn, nFwaHead, nFwaTail, nFwaPara, nFwaAttackD; int nFwaWaterDrop, nFwaPumpRoll; nFwaWalkIn = sqlite3_column_int( stmt, 4 ); nFwaHead = sqlite3_column_int( stmt, 6 ); nFwaTail = sqlite3_column_int( stmt, 7 ); nFwaPara = sqlite3_column_int( stmt, 8 ); nFwaAttackD = sqlite3_column_int( stmt, 9 ); nFwaWaterDrop = sqlite3_column_int( stmt, 10 ); nFwaPumpRoll = sqlite3_column_int( stmt, 5 ); year = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "year" ) ); num = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fire_num" ) ); day = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "day" ) ); dow = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "week_day" ) ); disc_time = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "disc_time" ) ); bi = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "bi" ) ); ros = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "ros" ) ); fuel = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "fuel" ) ); spec_cond = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "spec_cond" ) ); slope = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "slope_perc" ) ); //if( random.rand3() * 100 > fwa->GetWalkInPct() ) if( random.rand3() * 100 > nFwaWalkIn ) walkin = 0; else walkin = 1; //if( fwa->GetHead() == 100 ) if( nFwaHead == 100 ) tactic = "HEAD\0"; //else if( fwa->GetTail() == 100 ) else if( nFwaTail == 100 ) tactic = "TAIL\0"; //else if( fwa->GetParallel() == 100 ) else if( nFwaTail == 100 ) tactic = "PARALLEL\0"; else { int r = (int)(random.rand3() * 100 ); int total = 0; if( r < nFwaHead ) tactic = "HEAD\0"; else if( r < nFwaTail + nFwaTail ) tactic = "TAIL\0"; else tactic = "PARALLEL\0"; } //dist = fwa->GetAttackDist(); dist = nFwaAttackD; elev = OGR_F_GetFieldAsInteger( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "elev" ) ); ltow = OGR_F_GetFieldAsDouble( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "ratio" ) ); sunrise = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "sunrise" ) ); sunset = OGR_F_GetFieldAsString( hInputFeature, OGR_FD_GetFieldIndex( hInputFeatureDefn, "sunset" ) ); //if( fwa->GetWaterDrops() ) if( nFwaWaterDrop ) waterdrops = TRUE; else waterdrops = FALSE; //if( fwa->GetPumpnRoll() ) if( nFwaPumpRoll ) pumproll = TRUE; else pumproll = FALSE; fprintf( fout, "%d %d %d %s %s " "%d %lf %d %s %d " "%d %s %lf %d %lf " "%d %d %s %s %d " "%d %s %lf %lf\n", year, num, day, dow, disc_time, bi, ros, fuel, spec_cond, slope, walkin, tactic, dist, elev, ltow, minsteps, maxsteps, sunrise, sunset, waterdrops, pumproll, /* abyFwa */ oFwaName.c_str(), lat, lon ); sqlite3_reset(stmt); nDone++; GDALTermProgress( (float)nDone / (float)nFeatures, NULL, NULL ); } GDALTermProgress( 1.0, NULL, NULL ); fclose( fout ); OGR_DS_Destroy( hInputDS ); return 0; }
int main (int argc, char *argv[]) { sqlite3 *db_handle = NULL; char *sql_statement; int ret; char *err_msg = NULL; int i; char **results; int rows; int columns; ret = sqlite3_open_v2 (":memory:", &db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); if (ret != SQLITE_OK) { fprintf (stderr, "cannot open in-memory db: %s\n", sqlite3_errmsg (db_handle)); sqlite3_close (db_handle); db_handle = NULL; return -1; } sqlite3_enable_load_extension (db_handle, 1); asprintf(&sql_statement, "SELECT load_extension('libspatialite.so')"); ret = sqlite3_exec (db_handle, sql_statement, NULL, NULL, &err_msg); free(sql_statement); if (ret != SQLITE_OK) { fprintf (stderr, "load_extension() error: %s\n", err_msg); sqlite3_free (err_msg); return -2; } asprintf(&sql_statement, "SELECT spatialite_version()"); ret = sqlite3_get_table (db_handle, sql_statement, &results, &rows, &columns, &err_msg); free(sql_statement); if (ret != SQLITE_OK) { fprintf (stderr, "Error: %s\n", err_msg); sqlite3_free (err_msg); return -10; } if ((rows != 1) || (columns != 1)) { fprintf (stderr, "Unexpected error: spatialite_version() bad result: %i/%i.\n", rows, columns); return -11; } if (strcmp(results[1], VERSION) != 0) { fprintf (stderr, "Unexpected error: spatialite_version() bad result: %s.\n", results[1]); return -12; } sqlite3_free_table (results); asprintf(&sql_statement, "SELECT geos_version()"); ret = sqlite3_get_table (db_handle, sql_statement, &results, &rows, &columns, &err_msg); free(sql_statement); if (ret != SQLITE_OK) { fprintf (stderr, "Error2: %s\n", err_msg); sqlite3_free (err_msg); return -13; } if ((rows != 1) || (columns != 1)) { fprintf (stderr, "Unexpected error: geos_version() bad result: %i/%i.\n", rows, columns); return -14; } /* we tolerate any string here, because versions always change */ if (strlen(results[1]) == 0) { fprintf (stderr, "Unexpected error: geos_version() bad result.\n"); return -15; } sqlite3_free_table (results); asprintf(&sql_statement, "SELECT proj4_version()"); ret = sqlite3_get_table (db_handle, sql_statement, &results, &rows, &columns, &err_msg); free(sql_statement); if (ret != SQLITE_OK) { fprintf (stderr, "Error3: %s\n", err_msg); sqlite3_free (err_msg); return -14; } if ((rows != 1) || (columns != 1)) { fprintf (stderr, "Unexpected error: proj4_version() bad result: %i/%i.\n", rows, columns); return -14; } /* we tolerate any string here, because versions always change */ if (strlen(results[1]) == 0) { fprintf (stderr, "Unexpected error: proj4_version() bad result.\n"); return -15; } sqlite3_free_table (results); sqlite3_close (db_handle); sqlite3_reset_auto_extension(); return 0; }