1 // NavDataCache.cxx - defines a unified binary cache for navigation
2 // data, parsed from various text / XML sources.
4 // Written by James Turner, started 2012.
6 // Copyright (C) 2012 James Turner
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 #include "NavDataCache.hxx"
31 #include <stdint.h> // for int64_t
32 #include <sstream> // for std::ostringstream
34 #include <boost/foreach.hpp>
38 // the standard sqlite3.h doesn't give a way to set SQLITE_UINT64_TYPE,
39 // so we have to hope sizeof(int64_t) matches sizeof(sqlite3_int64).
40 // otherwise things will go bad quickly.
43 // to ensure compatability between sqlite3_int64 and PositionedID,
44 // force the type used by sqlite to match PositionedID explicitly
45 #define SQLITE_INT64_TYPE int64_t
46 #define SQLITE_UINT64_TYPE uint64_t
48 #include "fg_sqlite3.h"
52 #include <simgear/sg_inlines.h>
53 #include <simgear/structure/exception.hxx>
54 #include <simgear/debug/logstream.hxx>
55 #include <simgear/bucket/newbucket.hxx>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/misc/strutils.hxx>
58 #include <simgear/threads/SGThread.hxx>
59 #include <simgear/threads/SGGuard.hxx>
61 #include <Main/globals.hxx>
62 #include <Main/fg_props.hxx>
63 #include <Main/options.hxx>
64 #include "markerbeacon.hxx"
65 #include "navrecord.hxx"
66 #include <Airports/airport.hxx>
67 #include <Airports/runways.hxx>
68 #include <ATC/CommStation.hxx>
70 #include <Navaids/fixlist.hxx>
71 #include <Navaids/navdb.hxx>
72 #include "PositionedOctree.hxx"
73 #include <Airports/apt_loader.hxx>
74 #include <Navaids/airways.hxx>
76 #include <Airports/parking.hxx>
77 #include <Airports/gnnode.hxx>
78 #include "CacheSchema.h"
82 #define SG_NAVCACHE SG_NAVAID
83 //#define LAZY_OCTREE_UPDATES 1
87 const int MAX_RETRIES = 10;
89 const int CACHE_SIZE_KBYTES= 32 * 1024;
91 // bind a std::string to a sqlite statement. The std::string must live the
92 // entire duration of the statement execution - do not pass a temporary
93 // std::string, or the compiler may delete it, freeing the C-string storage,
94 // and causing subtle memory corruption bugs!
95 void sqlite_bind_stdstring(sqlite3_stmt* stmt, int value, const std::string& s)
97 sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_STATIC);
100 // variant of the above, which does not care about the lifetime of the
101 // passed std::string
102 void sqlite_bind_temp_stdstring(sqlite3_stmt* stmt, int value, const std::string& s)
104 sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_TRANSIENT);
107 typedef sqlite3_stmt* sqlite3_stmt_ptr;
109 void f_distanceCartSqrFunction(sqlite3_context* ctx, int argc, sqlite3_value* argv[])
115 SGVec3d posA(sqlite3_value_double(argv[0]),
116 sqlite3_value_double(argv[1]),
117 sqlite3_value_double(argv[2]));
119 SGVec3d posB(sqlite3_value_double(argv[3]),
120 sqlite3_value_double(argv[4]),
121 sqlite3_value_double(argv[5]));
122 sqlite3_result_double(ctx, distSqr(posA, posB));
126 static string cleanRunwayNo(const string& aRwyNo)
128 if (aRwyNo[0] == 'x') {
129 return string(); // no ident for taxiways
132 string result(aRwyNo);
133 // canonicalise runway ident
134 if ((aRwyNo.size() == 1) || !isdigit(aRwyNo[1])) {
135 result = "0" + aRwyNo;
138 // trim off trailing garbage
139 if (result.size() > 2) {
140 char suffix = toupper(result[2]);
142 result = result.substr(0, 2);
149 } // anonymous namespace
155 * Thread encapsulating a cache rebuild. This is not used to parallelise
156 * the rebuild - we must still wait until completion before doing other
157 * startup, since many things rely on a complete cache. The thread is used
158 * so we don't block the main event loop for an unacceptable duration,
159 * which causes 'not responding' / spinning beachballs on Windows & Mac
161 class RebuildThread : public SGThread
164 RebuildThread(NavDataCache* cache) :
166 _phase(NavDataCache::REBUILD_UNKNOWN),
167 _completionPercent(0),
173 bool isFinished() const
175 SGGuard<SGMutex> g(_lock);
184 SG_LOG(SG_NAVCACHE, SG_INFO, "cache rebuild took:" << st.elapsedMSec() << "msec");
186 SGGuard<SGMutex> g(_lock);
188 _phase = NavDataCache::REBUILD_DONE;
191 NavDataCache::RebuildPhase currentPhase() const
193 NavDataCache::RebuildPhase ph;
194 SGGuard<SGMutex> g(_lock);
199 unsigned int completionPercent() const
201 unsigned int perc = 0;
202 SGGuard<SGMutex> g(_lock);
203 perc = _completionPercent;
207 void setProgress(NavDataCache::RebuildPhase ph, unsigned int percent)
209 SGGuard<SGMutex> g(_lock);
211 _completionPercent = percent;
215 NavDataCache* _cache;
216 NavDataCache::RebuildPhase _phase;
217 unsigned int _completionPercent;
218 mutable SGMutex _lock;
222 ////////////////////////////////////////////////////////////////////////////
224 typedef std::map<PositionedID, FGPositionedRef> PositionedCache;
226 class AirportTower : public FGPositioned
229 AirportTower(PositionedID& guid, PositionedID airport,
230 const string& ident, const SGGeod& pos) :
231 FGPositioned(guid, FGPositioned::TOWER, ident, pos)
236 class NavDataCache::NavDataCachePrivate
239 NavDataCachePrivate(const SGPath& p, NavDataCache* o) :
247 transactionAborted(false)
251 ~NavDataCachePrivate()
258 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache at:" << path);
260 readOnly = fgGetBool("/sim/fghome-readonly", false);
262 int openFlags = readOnly ? SQLITE_OPEN_READONLY :
263 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
264 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=1055
265 // for the UTF8 / path logic here
266 std::string pathUtf8 = path.utf8Str();
267 sqlite3_open_v2(pathUtf8.c_str(), &db, openFlags, NULL);
269 sqlite3_stmt_ptr checkTables =
270 prepare("SELECT count(*) FROM sqlite_master WHERE name='properties'");
272 sqlite3_create_function(db, "distanceCartSqr", 6, SQLITE_ANY, NULL,
273 f_distanceCartSqrFunction, NULL, NULL);
275 execSelect(checkTables);
276 bool didCreate = false;
277 if (!readOnly && (sqlite3_column_int(checkTables, 0) == 0)) {
278 SG_LOG(SG_NAVCACHE, SG_INFO, "will create tables");
283 readPropertyQuery = prepare("SELECT value FROM properties WHERE key=?");
284 writePropertyQuery = prepare("INSERT INTO properties (key, value) VALUES (?,?)");
285 clearProperty = prepare("DELETE FROM properties WHERE key=?1");
288 writeIntProperty("schema-version", SCHEMA_VERSION);
290 int schemaVersion = outer->readIntProperty("schema-version");
291 if (schemaVersion != SCHEMA_VERSION) {
292 SG_LOG(SG_NAVCACHE, SG_INFO, "Navcache schema mismatch, will rebuild");
293 throw sg_exception("Navcache schema has changed");
297 // see http://www.sqlite.org/pragma.html#pragma_cache_size
298 // for the details, small cache would cause thrashing.
299 std::ostringstream q;
300 q << "PRAGMA cache_size=-" << CACHE_SIZE_KBYTES << ";";
307 BOOST_FOREACH(sqlite3_stmt_ptr stmt, prepared) {
308 sqlite3_finalize(stmt);
314 void checkCacheFile()
316 SG_LOG(SG_NAVCACHE, SG_INFO, "running DB integrity check");
320 sqlite3_stmt_ptr stmt = prepare("PRAGMA quick_check(1)");
321 if (!execSelect(stmt)) {
322 throw sg_exception("DB integrity check failed to run");
325 string v = (char*) sqlite3_column_text(stmt, 0);
327 throw sg_exception("DB integrity check returned:" + v);
330 SG_LOG(SG_NAVCACHE, SG_INFO, "NavDataCache integrity check took:" << st.elapsedMSec());
334 bool isCachedFileModified(const SGPath& path, bool verbose);
336 void callSqlite(int result, const string& sql)
338 if (result == SQLITE_OK)
342 if (result == SQLITE_MISUSE) {
343 errMsg = "Sqlite API abuse";
344 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
346 errMsg = sqlite3_errmsg(db);
347 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running:\n\t" << sql);
350 throw sg_exception("Sqlite error:" + errMsg, sql);
353 void runSQL(const string& sql)
355 sqlite3_stmt_ptr stmt;
356 callSqlite(sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL), sql);
360 } catch (sg_exception&) {
361 sqlite3_finalize(stmt);
365 sqlite3_finalize(stmt);
368 sqlite3_stmt_ptr prepare(const string& sql)
370 sqlite3_stmt_ptr stmt;
371 callSqlite(sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL), sql);
372 prepared.push_back(stmt);
376 void finalize(sqlite3_stmt_ptr s)
378 StmtVec::iterator it = std::find(prepared.begin(), prepared.end(), s);
379 if (it == prepared.end()) {
380 throw sg_exception("Finalising statement that was not prepared");
387 void reset(sqlite3_stmt_ptr stmt)
390 if (sqlite3_reset(stmt) != SQLITE_OK) {
391 string errMsg = sqlite3_errmsg(db);
392 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error resetting:" << errMsg);
393 throw sg_exception("Sqlite error resetting:" + errMsg, sqlite3_sql(stmt));
397 bool execSelect(sqlite3_stmt_ptr stmt)
399 return stepSelect(stmt);
402 bool stepSelect(sqlite3_stmt_ptr stmt)
406 while (retries < MAX_RETRIES) {
407 result = sqlite3_step(stmt);
408 if (result == SQLITE_ROW) {
409 return true; // at least one result row
412 if (result == SQLITE_DONE) {
413 return false; // no result rows
416 if (result != SQLITE_BUSY) {
420 SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache contention on select, will retry:" << retries);
421 SGTimeStamp::sleepForMSec(++retries * 10);
422 } // of retry loop for DB locked
424 if (retries >= MAX_RETRIES) {
425 SG_LOG(SG_NAVCACHE, SG_ALERT, "exceeded maximum number of SQLITE_BUSY retries");
430 if (result == SQLITE_MISUSE) {
431 errMsg = "Sqlite API abuse";
432 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
434 errMsg = sqlite3_errmsg(db);
435 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " (" << result
436 << ") while running:\n\t" << sqlite3_sql(stmt));
439 throw sg_exception("Sqlite error:" + errMsg, sqlite3_sql(stmt));
442 void execSelect1(sqlite3_stmt_ptr stmt)
444 if (!execSelect(stmt)) {
445 SG_LOG(SG_NAVCACHE, SG_WARN, "empty SELECT running:\n\t" << sqlite3_sql(stmt));
446 throw sg_exception("no results returned for select", sqlite3_sql(stmt));
450 sqlite3_int64 execInsert(sqlite3_stmt_ptr stmt)
453 sqlite3_int64 rowid = sqlite3_last_insert_rowid(db);
458 void execUpdate(sqlite3_stmt_ptr stmt)
466 string_list commands = simgear::strutils::split(SCHEMA_SQL, ";");
467 BOOST_FOREACH(std::string sql, commands) {
473 } // of commands in scheme loop
476 void prepareQueries()
478 writePropertyMulti = prepare("INSERT INTO properties (key, value) VALUES(?1,?2)");
480 beginTransactionStmt = prepare("BEGIN");
481 commitTransactionStmt = prepare("COMMIT");
482 rollbackTransactionStmt = prepare("ROLLBACK");
485 #define POSITIONED_COLS "rowid, type, ident, name, airport, lon, lat, elev_m, octree_node"
486 #define AND_TYPED "AND type>=?2 AND type <=?3"
487 statCacheCheck = prepare("SELECT stamp FROM stat_cache WHERE path=?");
488 stampFileCache = prepare("INSERT OR REPLACE INTO stat_cache "
489 "(path, stamp) VALUES (?,?)");
491 loadPositioned = prepare("SELECT " POSITIONED_COLS " FROM positioned WHERE rowid=?");
492 loadAirportStmt = prepare("SELECT has_metar FROM airport WHERE rowid=?");
493 loadNavaid = prepare("SELECT range_nm, freq, multiuse, runway, colocated FROM navaid WHERE rowid=?");
494 loadCommStation = prepare("SELECT freq_khz, range_nm FROM comm WHERE rowid=?");
495 loadRunwayStmt = prepare("SELECT heading, length_ft, width_m, surface, displaced_threshold,"
496 "stopway, reciprocal, ils FROM runway WHERE rowid=?1");
498 getAirportItems = prepare("SELECT rowid FROM positioned WHERE airport=?1 " AND_TYPED);
501 setAirportMetar = prepare("UPDATE airport SET has_metar=?2 WHERE rowid="
502 "(SELECT rowid FROM positioned WHERE ident=?1 AND type>=?3 AND type <=?4)");
503 sqlite3_bind_int(setAirportMetar, 3, FGPositioned::AIRPORT);
504 sqlite3_bind_int(setAirportMetar, 4, FGPositioned::SEAPORT);
506 setRunwayReciprocal = prepare("UPDATE runway SET reciprocal=?2 WHERE rowid=?1");
507 setRunwayILS = prepare("UPDATE runway SET ils=?2 WHERE rowid=?1");
508 setNavaidColocated = prepare("UPDATE navaid SET colocated=?2 WHERE rowid=?1");
510 insertPositionedQuery = prepare("INSERT INTO positioned "
511 "(type, ident, name, airport, lon, lat, elev_m, octree_node, "
512 "cart_x, cart_y, cart_z)"
513 " VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)");
515 setAirportPos = prepare("UPDATE positioned SET lon=?2, lat=?3, elev_m=?4, octree_node=?5, "
516 "cart_x=?6, cart_y=?7, cart_z=?8 WHERE rowid=?1");
517 insertAirport = prepare("INSERT INTO airport (rowid, has_metar) VALUES (?, ?)");
518 insertNavaid = prepare("INSERT INTO navaid (rowid, freq, range_nm, multiuse, runway, colocated)"
519 " VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
521 insertCommStation = prepare("INSERT INTO comm (rowid, freq_khz, range_nm)"
522 " VALUES (?, ?, ?)");
523 insertRunway = prepare("INSERT INTO runway "
524 "(rowid, heading, length_ft, width_m, surface, displaced_threshold, stopway, reciprocal)"
525 " VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)");
526 runwayLengthFtQuery = prepare("SELECT length_ft FROM runway WHERE rowid=?1");
528 removePOIQuery = prepare("DELETE FROM positioned WHERE type=?1 AND ident=?2");
531 findClosestWithIdent = prepare("SELECT rowid FROM positioned WHERE ident=?1 "
532 AND_TYPED " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
534 findCommByFreq = prepare("SELECT positioned.rowid FROM positioned, comm WHERE "
535 "positioned.rowid=comm.rowid AND freq_khz=?1 "
536 AND_TYPED " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
538 findNavsByFreq = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
539 "positioned.rowid=navaid.rowid "
540 "AND navaid.freq=?1 " AND_TYPED
541 " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
543 findNavsByFreqNoPos = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
544 "positioned.rowid=navaid.rowid AND freq=?1 " AND_TYPED);
546 findNavaidForRunway = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
547 "positioned.rowid=navaid.rowid AND runway=?1 AND type=?2");
549 // for an octree branch, return the child octree nodes which exist,
550 // described as a bit-mask
551 getOctreeChildren = prepare("SELECT children FROM octree WHERE rowid=?1");
553 #ifdef LAZY_OCTREE_UPDATES
554 updateOctreeChildren = prepare("UPDATE octree SET children=?2 WHERE rowid=?1");
556 // mask the new child value into the existing one
557 updateOctreeChildren = prepare("UPDATE octree SET children=(?2 | children) WHERE rowid=?1");
560 // define a new octree node (with no children)
561 insertOctree = prepare("INSERT INTO octree (rowid, children) VALUES (?1, 0)");
563 getOctreeLeafChildren = prepare("SELECT rowid, type FROM positioned WHERE octree_node=?1");
565 searchAirports = prepare("SELECT ident, name FROM positioned WHERE (name LIKE ?1 OR ident LIKE ?1) " AND_TYPED);
566 sqlite3_bind_int(searchAirports, 2, FGPositioned::AIRPORT);
567 sqlite3_bind_int(searchAirports, 3, FGPositioned::SEAPORT);
569 getAllAirports = prepare("SELECT ident, name FROM positioned WHERE type>=?1 AND type <=?2");
570 sqlite3_bind_int(getAllAirports, 1, FGPositioned::AIRPORT);
571 sqlite3_bind_int(getAllAirports, 2, FGPositioned::SEAPORT);
574 getAirportItemByIdent = prepare("SELECT rowid FROM positioned WHERE airport=?1 AND ident=?2 AND type=?3");
576 findAirportRunway = prepare("SELECT airport, rowid FROM positioned WHERE ident=?2 AND type=?3 AND airport="
577 "(SELECT rowid FROM positioned WHERE type=?4 AND ident=?1)");
578 sqlite3_bind_int(findAirportRunway, 3, FGPositioned::RUNWAY);
579 sqlite3_bind_int(findAirportRunway, 4, FGPositioned::AIRPORT);
581 // three-way join to get the navaid ident and runway ident in a single select.
582 // we're joining positioned to itself by the navaid runway, with the complication
583 // that we need to join the navaids table to get the runway ID.
584 // we also need to filter by type to excluse glideslope (GS) matches
585 findILS = prepare("SELECT nav.rowid FROM positioned AS nav, positioned AS rwy, navaid WHERE "
586 "nav.ident=?1 AND nav.airport=?2 AND rwy.ident=?3 "
587 "AND rwy.rowid = navaid.runway AND navaid.rowid=nav.rowid "
588 "AND (nav.type=?4 OR nav.type=?5)");
590 sqlite3_bind_int(findILS, 4, FGPositioned::ILS);
591 sqlite3_bind_int(findILS, 5, FGPositioned::LOC);
594 findAirway = prepare("SELECT rowid FROM airway WHERE network=?1 AND ident=?2");
595 insertAirway = prepare("INSERT INTO airway (ident, network) "
598 insertAirwayEdge = prepare("INSERT INTO airway_edge (network, airway, a, b) "
599 "VALUES (?1, ?2, ?3, ?4)");
601 isPosInAirway = prepare("SELECT rowid FROM airway_edge WHERE network=?1 AND a=?2");
603 airwayEdgesFrom = prepare("SELECT airway, b FROM airway_edge WHERE network=?1 AND a=?2");
605 airwayEdges = prepare("SELECT a, b FROM airway_edge WHERE airway=?1");
608 void writeIntProperty(const string& key, int value)
610 sqlite_bind_stdstring(clearProperty, 1, key);
611 execUpdate(clearProperty);
613 sqlite_bind_stdstring(writePropertyQuery, 1, key);
614 sqlite3_bind_int(writePropertyQuery, 2, value);
615 execUpdate(writePropertyQuery);
619 FGPositioned* loadById(sqlite_int64 rowId, sqlite3_int64& aptId);
621 FGAirport* loadAirport(sqlite_int64 rowId,
622 FGPositioned::Type ty,
623 const string& id, const string& name, const SGGeod& pos)
625 sqlite3_bind_int64(loadAirportStmt, 1, rowId);
626 execSelect1(loadAirportStmt);
627 bool hasMetar = (sqlite3_column_int(loadAirportStmt, 0) > 0);
628 reset(loadAirportStmt);
630 return new FGAirport(rowId, id, pos, name, hasMetar, ty);
633 FGRunwayBase* loadRunway(sqlite3_int64 rowId, FGPositioned::Type ty,
634 const string& id, const SGGeod& pos, PositionedID apt)
636 sqlite3_bind_int(loadRunwayStmt, 1, rowId);
637 execSelect1(loadRunwayStmt);
639 double heading = sqlite3_column_double(loadRunwayStmt, 0);
640 double lengthM = sqlite3_column_int(loadRunwayStmt, 1);
641 double widthM = sqlite3_column_double(loadRunwayStmt, 2);
642 int surface = sqlite3_column_int(loadRunwayStmt, 3);
644 if (ty == FGPositioned::TAXIWAY) {
645 reset(loadRunwayStmt);
646 return new FGTaxiway(rowId, id, pos, heading, lengthM, widthM, surface);
647 } else if (ty == FGPositioned::HELIPAD) {
648 reset(loadRunwayStmt);
649 return new FGHelipad(rowId, apt, id, pos, heading, lengthM, widthM, surface);
651 double displacedThreshold = sqlite3_column_double(loadRunwayStmt, 4);
652 double stopway = sqlite3_column_double(loadRunwayStmt, 5);
653 PositionedID reciprocal = sqlite3_column_int64(loadRunwayStmt, 6);
654 PositionedID ils = sqlite3_column_int64(loadRunwayStmt, 7);
655 FGRunway* r = new FGRunway(rowId, apt, id, pos, heading, lengthM, widthM,
656 displacedThreshold, stopway, surface);
658 if (reciprocal > 0) {
659 r->setReciprocalRunway(reciprocal);
666 reset(loadRunwayStmt);
671 CommStation* loadComm(sqlite3_int64 rowId, FGPositioned::Type ty,
672 const string& id, const string& name,
674 PositionedID airport)
676 sqlite3_bind_int64(loadCommStation, 1, rowId);
677 execSelect1(loadCommStation);
679 int range = sqlite3_column_int(loadCommStation, 0);
680 int freqKhz = sqlite3_column_int(loadCommStation, 1);
681 reset(loadCommStation);
683 CommStation* c = new CommStation(rowId, name, ty, pos, freqKhz, range);
684 c->setAirport(airport);
688 FGPositioned* loadNav(sqlite3_int64 rowId,
689 FGPositioned::Type ty, const string& id,
690 const string& name, const SGGeod& pos)
692 sqlite3_bind_int64(loadNavaid, 1, rowId);
693 execSelect1(loadNavaid);
695 PositionedID runway = sqlite3_column_int64(loadNavaid, 3);
696 // marker beacons are light-weight
697 if ((ty == FGPositioned::OM) || (ty == FGPositioned::IM) ||
698 (ty == FGPositioned::MM))
701 return new FGMarkerBeaconRecord(rowId, ty, runway, pos);
704 int rangeNm = sqlite3_column_int(loadNavaid, 0),
705 freq = sqlite3_column_int(loadNavaid, 1);
706 double mulituse = sqlite3_column_double(loadNavaid, 2);
707 PositionedID colocated = sqlite3_column_int64(loadNavaid, 4);
711 (ty == FGPositioned::MOBILE_TACAN)
712 ? new FGMobileNavRecord
713 (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway)
715 (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway);
718 n->setColocatedDME(colocated);
723 PositionedID insertPositioned(FGPositioned::Type ty, const string& ident,
724 const string& name, const SGGeod& pos, PositionedID apt,
727 SGVec3d cartPos(SGVec3d::fromGeod(pos));
729 sqlite3_bind_int(insertPositionedQuery, 1, ty);
730 sqlite_bind_stdstring(insertPositionedQuery, 2, ident);
731 sqlite_bind_stdstring(insertPositionedQuery, 3, name);
732 sqlite3_bind_int64(insertPositionedQuery, 4, apt);
733 sqlite3_bind_double(insertPositionedQuery, 5, pos.getLongitudeDeg());
734 sqlite3_bind_double(insertPositionedQuery, 6, pos.getLatitudeDeg());
735 sqlite3_bind_double(insertPositionedQuery, 7, pos.getElevationM());
738 Octree::Leaf* octreeLeaf = Octree::global_spatialOctree->findLeafForPos(cartPos);
739 assert(intersects(octreeLeaf->bbox(), cartPos));
740 sqlite3_bind_int64(insertPositionedQuery, 8, octreeLeaf->guid());
742 sqlite3_bind_null(insertPositionedQuery, 8);
745 sqlite3_bind_double(insertPositionedQuery, 9, cartPos.x());
746 sqlite3_bind_double(insertPositionedQuery, 10, cartPos.y());
747 sqlite3_bind_double(insertPositionedQuery, 11, cartPos.z());
749 PositionedID r = execInsert(insertPositionedQuery);
753 FGPositionedList findAllByString(const string& s, const string& column,
754 FGPositioned::Filter* filter, bool exact)
757 if (!exact) query += "%";
759 // build up SQL query text
760 string matchTerm = exact ? "=?1" : " LIKE ?1";
761 string sql = "SELECT rowid FROM positioned WHERE " + column + matchTerm;
763 sql += " " AND_TYPED;
766 // find or prepare a suitable statement frrm the SQL
767 sqlite3_stmt_ptr stmt = findByStringDict[sql];
770 findByStringDict[sql] = stmt;
773 sqlite_bind_stdstring(stmt, 1, query);
775 sqlite3_bind_int(stmt, 2, filter->minType());
776 sqlite3_bind_int(stmt, 3, filter->maxType());
779 FGPositionedList result;
780 // run the prepared SQL
781 while (stepSelect(stmt))
783 FGPositioned* pos = outer->loadById(sqlite3_column_int64(stmt, 0));
784 if (filter && !filter->pass(pos)) {
788 result.push_back(pos);
795 PositionedIDVec selectIds(sqlite3_stmt_ptr query)
797 PositionedIDVec result;
798 while (stepSelect(query)) {
799 result.push_back(sqlite3_column_int64(query, 0));
805 double runwayLengthFt(PositionedID rwy)
807 sqlite3_bind_int64(runwayLengthFtQuery, 1, rwy);
808 execSelect1(runwayLengthFtQuery);
809 double length = sqlite3_column_double(runwayLengthFtQuery, 0);
810 reset(runwayLengthFtQuery);
814 void flushDeferredOctreeUpdates()
816 BOOST_FOREACH(Octree::Branch* nd, deferredOctreeUpdates) {
817 sqlite3_bind_int64(updateOctreeChildren, 1, nd->guid());
818 sqlite3_bind_int(updateOctreeChildren, 2, nd->childMask());
819 execUpdate(updateOctreeChildren);
822 deferredOctreeUpdates.clear();
825 void removePositionedWithIdent(FGPositioned::Type ty, const std::string& aIdent)
827 sqlite3_bind_int(removePOIQuery, 1, ty);
828 sqlite_bind_stdstring(removePOIQuery, 2, aIdent);
829 execUpdate(removePOIQuery);
830 reset(removePOIQuery);
838 /// the actual cache of ID -> instances. This holds an owning reference,
839 /// so once items are in the cache they will never be deleted until
840 /// the cache drops its reference
841 PositionedCache cache;
842 unsigned int cacheHits, cacheMisses;
845 * record the levels of open transaction objects we have
847 unsigned int transactionLevel;
848 bool transactionAborted;
849 sqlite3_stmt_ptr beginTransactionStmt, commitTransactionStmt, rollbackTransactionStmt;
851 SGPath aptDatPath, metarDatPath, navDatPath, fixDatPath, poiDatPath,
852 carrierDatPath, airwayDatPath;
854 sqlite3_stmt_ptr readPropertyQuery, writePropertyQuery,
855 stampFileCache, statCacheCheck,
856 loadAirportStmt, loadCommStation, loadPositioned, loadNavaid,
858 sqlite3_stmt_ptr writePropertyMulti, clearProperty;
860 sqlite3_stmt_ptr insertPositionedQuery, insertAirport, insertTower, insertRunway,
861 insertCommStation, insertNavaid;
862 sqlite3_stmt_ptr setAirportMetar, setRunwayReciprocal, setRunwayILS, setNavaidColocated,
864 sqlite3_stmt_ptr removePOIQuery;
866 sqlite3_stmt_ptr findClosestWithIdent;
867 // octree (spatial index) related queries
868 sqlite3_stmt_ptr getOctreeChildren, insertOctree, updateOctreeChildren,
869 getOctreeLeafChildren;
871 sqlite3_stmt_ptr searchAirports, getAllAirports;
872 sqlite3_stmt_ptr findCommByFreq, findNavsByFreq,
873 findNavsByFreqNoPos, findNavaidForRunway;
874 sqlite3_stmt_ptr getAirportItems, getAirportItemByIdent;
875 sqlite3_stmt_ptr findAirportRunway,
878 sqlite3_stmt_ptr runwayLengthFtQuery;
881 sqlite3_stmt_ptr findAirway, insertAirwayEdge,
882 isPosInAirway, airwayEdgesFrom,
883 insertAirway, airwayEdges;
885 // since there's many permutations of ident/name queries, we create
886 // them programtically, but cache the exact query by its raw SQL once
888 std::map<string, sqlite3_stmt_ptr> findByStringDict;
890 typedef std::vector<sqlite3_stmt_ptr> StmtVec;
893 std::set<Octree::Branch*> deferredOctreeUpdates;
895 // if we're performing a rebuild, the thread that is doing the work.
897 std::auto_ptr<RebuildThread> rebuilder;
900 //////////////////////////////////////////////////////////////////////
902 FGPositioned* NavDataCache::NavDataCachePrivate::loadById(sqlite3_int64 rowid,
903 sqlite3_int64& aptId)
906 sqlite3_bind_int64(loadPositioned, 1, rowid);
907 execSelect1(loadPositioned);
909 assert(rowid == sqlite3_column_int64(loadPositioned, 0));
910 FGPositioned::Type ty = (FGPositioned::Type) sqlite3_column_int(loadPositioned, 1);
912 PositionedID prowid = static_cast<PositionedID>(rowid);
913 string ident = (char*) sqlite3_column_text(loadPositioned, 2);
914 string name = (char*) sqlite3_column_text(loadPositioned, 3);
915 aptId = sqlite3_column_int64(loadPositioned, 4);
916 double lon = sqlite3_column_double(loadPositioned, 5);
917 double lat = sqlite3_column_double(loadPositioned, 6);
918 double elev = sqlite3_column_double(loadPositioned, 7);
919 SGGeod pos = SGGeod::fromDegM(lon, lat, elev);
921 reset(loadPositioned);
924 case FGPositioned::AIRPORT:
925 case FGPositioned::SEAPORT:
926 case FGPositioned::HELIPORT:
927 return loadAirport(rowid, ty, ident, name, pos);
929 case FGPositioned::TOWER:
930 return new AirportTower(prowid, aptId, ident, pos);
932 case FGPositioned::RUNWAY:
933 case FGPositioned::HELIPAD:
934 case FGPositioned::TAXIWAY:
935 return loadRunway(rowid, ty, ident, pos, aptId);
937 case FGPositioned::LOC:
938 case FGPositioned::VOR:
939 case FGPositioned::GS:
940 case FGPositioned::ILS:
941 case FGPositioned::NDB:
942 case FGPositioned::OM:
943 case FGPositioned::MM:
944 case FGPositioned::IM:
945 case FGPositioned::DME:
946 case FGPositioned::TACAN:
947 case FGPositioned::MOBILE_TACAN:
948 return loadNav(rowid, ty, ident, name, pos);
950 case FGPositioned::FIX:
951 return new FGFix(rowid, ident, pos);
953 case FGPositioned::WAYPOINT:
954 case FGPositioned::COUNTRY:
955 case FGPositioned::CITY:
956 case FGPositioned::TOWN:
957 case FGPositioned::VILLAGE:
959 FGPositioned* wpt = new FGPositioned(rowid, ty, ident, pos);
963 case FGPositioned::FREQ_GROUND:
964 case FGPositioned::FREQ_TOWER:
965 case FGPositioned::FREQ_ATIS:
966 case FGPositioned::FREQ_AWOS:
967 case FGPositioned::FREQ_APP_DEP:
968 case FGPositioned::FREQ_ENROUTE:
969 case FGPositioned::FREQ_CLEARANCE:
970 case FGPositioned::FREQ_UNICOM:
971 return loadComm(rowid, ty, ident, name, pos, aptId);
978 bool NavDataCache::NavDataCachePrivate::isCachedFileModified(const SGPath& path, bool verbose)
980 if (!path.exists()) {
981 throw sg_io_exception("isCachedFileModified: Missing file:", path);
984 sqlite_bind_temp_stdstring(statCacheCheck, 1, path.utf8Str());
985 bool isModified = true;
986 sgDebugPriority logLevel = verbose ? SG_WARN : SG_DEBUG;
987 if (execSelect(statCacheCheck)) {
988 time_t modtime = sqlite3_column_int64(statCacheCheck, 0);
989 time_t delta = std::labs(modtime - path.modTime());
992 SG_LOG(SG_NAVCACHE, logLevel, "NavCache: rebuild required for " << path <<
993 ". Timestamps: " << modtime << " != " << path.modTime());
997 SG_LOG(SG_NAVCACHE, SG_DEBUG, "NavCache: no rebuild required for " << path);
1000 isModified = (delta != 0);
1002 SG_LOG(SG_NAVCACHE, logLevel, "NavCache: initial build required for " << path);
1005 reset(statCacheCheck);
1009 static NavDataCache* static_instance = NULL;
1011 NavDataCache::NavDataCache()
1013 const int MAX_TRIES = 3;
1014 SGPath homePath(globals->get_fg_home());
1016 std::ostringstream os;
1017 string_list versionParts = simgear::strutils::split(VERSION, ".");
1018 if (versionParts.size() < 2) {
1019 os << "navdata.cache";
1021 os << "navdata_" << versionParts[0] << "_" << versionParts[1] << ".cache";
1024 homePath.append(os.str());
1026 // permit additional DB connections from the same process
1027 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
1029 for (int t=0; t < MAX_TRIES; ++t) {
1031 d.reset(new NavDataCachePrivate(homePath, this));
1033 //d->checkCacheFile();
1034 // reached this point with no exception, success
1036 } catch (sg_exception& e) {
1037 SG_LOG(SG_NAVCACHE, t == 0 ? SG_WARN : SG_ALERT, "NavCache: init failed:" << e.what()
1038 << " (attempt " << t << ")");
1041 // only wipe the existing if not readonly
1042 if (!fgGetBool("/sim/fghome-readonly", false)) {
1048 double RADIUS_EARTH_M = 7000 * 1000.0; // 7000km is plenty
1049 SGVec3d earthExtent(RADIUS_EARTH_M, RADIUS_EARTH_M, RADIUS_EARTH_M);
1050 Octree::global_spatialOctree =
1051 new Octree::Branch(SGBox<double>(-earthExtent, earthExtent), 1);
1053 d->aptDatPath = SGPath(globals->get_fg_root());
1054 d->aptDatPath.append("Airports/apt.dat.gz");
1056 d->metarDatPath = SGPath(globals->get_fg_root());
1057 d->metarDatPath.append("Airports/metar.dat.gz");
1059 d->navDatPath = SGPath(globals->get_fg_root());
1060 d->navDatPath.append("Navaids/nav.dat.gz");
1062 d->fixDatPath = SGPath(globals->get_fg_root());
1063 d->fixDatPath.append("Navaids/fix.dat.gz");
1065 d->poiDatPath = SGPath(globals->get_fg_root());
1066 d->poiDatPath.append("Navaids/poi.dat.gz");
1068 d->carrierDatPath = SGPath(globals->get_fg_root());
1069 d->carrierDatPath.append("Navaids/carrier_nav.dat.gz");
1071 d->airwayDatPath = SGPath(globals->get_fg_root());
1072 d->airwayDatPath.append("Navaids/awy.dat.gz");
1075 NavDataCache::~NavDataCache()
1077 assert(static_instance == this);
1078 static_instance = NULL;
1082 NavDataCache* NavDataCache::createInstance()
1084 static_instance = new NavDataCache;
1085 return static_instance;
1088 NavDataCache* NavDataCache::instance()
1090 return static_instance;
1093 bool NavDataCache::isRebuildRequired()
1099 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
1100 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: restore-defaults requested, will rebuild cache");
1104 if (d->isCachedFileModified(d->aptDatPath, true) ||
1105 d->isCachedFileModified(d->metarDatPath, true) ||
1106 d->isCachedFileModified(d->navDatPath, true) ||
1107 d->isCachedFileModified(d->fixDatPath, true) ||
1108 d->isCachedFileModified(d->carrierDatPath, true) ||
1109 // since POI loading is disabled on Windows, don't check for it
1110 // this caused: https://code.google.com/p/flightgear-bugs/issues/detail?id=1227
1112 d->isCachedFileModified(d->poiDatPath, true) ||
1114 d->isCachedFileModified(d->airwayDatPath, true))
1116 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: main cache rebuild required");
1120 SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: no main cache rebuild required");
1124 NavDataCache::RebuildPhase NavDataCache::rebuild()
1126 if (!d->rebuilder.get()) {
1127 d->rebuilder.reset(new RebuildThread(this));
1128 d->rebuilder->start();
1131 // poll the rebuild thread
1132 RebuildPhase phase = d->rebuilder->currentPhase();
1133 if (phase == REBUILD_DONE) {
1134 d->rebuilder.reset(); // all done!
1139 unsigned int NavDataCache::rebuildPhaseCompletionPercentage() const
1141 if (!d->rebuilder.get()) {
1145 return d->rebuilder->completionPercent();
1148 void NavDataCache::setRebuildPhaseProgress(RebuildPhase ph, unsigned int percent)
1150 if (!d->rebuilder.get()) {
1154 d->rebuilder->setProgress(ph, percent);
1157 void NavDataCache::doRebuild()
1160 d->close(); // completely close the sqlite object
1161 d->path.remove(); // remove the file on disk
1162 d->init(); // start again from scratch
1164 // initialise the root octree node
1165 d->runSQL("INSERT INTO octree (rowid, children) VALUES (1, 0)");
1169 Transaction txn(this);
1172 airportDBLoad(d->aptDatPath);
1173 SG_LOG(SG_NAVCACHE, SG_INFO, "apt.dat load took:" << st.elapsedMSec());
1175 setRebuildPhaseProgress(REBUILD_UNKNOWN);
1176 metarDataLoad(d->metarDatPath);
1177 stampCacheFile(d->aptDatPath);
1178 stampCacheFile(d->metarDatPath);
1181 loadFixes(d->fixDatPath);
1182 stampCacheFile(d->fixDatPath);
1183 SG_LOG(SG_NAVCACHE, SG_INFO, "fix.dat load took:" << st.elapsedMSec());
1186 navDBInit(d->navDatPath);
1187 stampCacheFile(d->navDatPath);
1188 SG_LOG(SG_NAVCACHE, SG_INFO, "nav.dat load took:" << st.elapsedMSec());
1190 setRebuildPhaseProgress(REBUILD_UNKNOWN);
1193 SG_LOG(SG_NAVCACHE, SG_INFO, "stage 1 commit took:" << st.elapsedMSec());
1197 SG_LOG(SG_NAVCACHE, SG_ALERT, "SKIPPING POI load on Windows");
1200 Transaction txn(this);
1203 poiDBInit(d->poiDatPath);
1204 stampCacheFile(d->poiDatPath);
1205 SG_LOG(SG_NAVCACHE, SG_INFO, "poi.dat load took:" << st.elapsedMSec());
1207 setRebuildPhaseProgress(REBUILD_UNKNOWN);
1210 SG_LOG(SG_NAVCACHE, SG_INFO, "POI commit took:" << st.elapsedMSec());
1215 Transaction txn(this);
1216 loadCarrierNav(d->carrierDatPath);
1217 stampCacheFile(d->carrierDatPath);
1220 Airway::load(d->airwayDatPath);
1221 stampCacheFile(d->airwayDatPath);
1222 SG_LOG(SG_NAVCACHE, SG_INFO, "awy.dat load took:" << st.elapsedMSec());
1224 d->flushDeferredOctreeUpdates();
1226 string sceneryPaths = SGPath::join(globals->get_fg_scenery(), ";");
1227 writeStringProperty("scenery_paths", sceneryPaths);
1231 SG_LOG(SG_NAVCACHE, SG_INFO, "final commit took:" << st.elapsedMSec());
1235 } catch (sg_exception& e) {
1236 SG_LOG(SG_NAVCACHE, SG_ALERT, "caught exception rebuilding navCache:" << e.what());
1240 int NavDataCache::readIntProperty(const string& key)
1242 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1245 if (d->execSelect(d->readPropertyQuery)) {
1246 result = sqlite3_column_int(d->readPropertyQuery, 0);
1248 SG_LOG(SG_NAVCACHE, SG_WARN, "readIntProperty: unknown:" << key);
1251 d->reset(d->readPropertyQuery);
1255 double NavDataCache::readDoubleProperty(const string& key)
1257 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1258 double result = 0.0;
1259 if (d->execSelect(d->readPropertyQuery)) {
1260 result = sqlite3_column_double(d->readPropertyQuery, 0);
1262 SG_LOG(SG_NAVCACHE, SG_WARN, "readDoubleProperty: unknown:" << key);
1265 d->reset(d->readPropertyQuery);
1269 string NavDataCache::readStringProperty(const string& key)
1271 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1273 if (d->execSelect(d->readPropertyQuery)) {
1274 result = (char*) sqlite3_column_text(d->readPropertyQuery, 0);
1276 SG_LOG(SG_NAVCACHE, SG_WARN, "readStringProperty: unknown:" << key);
1279 d->reset(d->readPropertyQuery);
1283 void NavDataCache::writeIntProperty(const string& key, int value)
1285 d->writeIntProperty(key, value);
1288 void NavDataCache::writeStringProperty(const string& key, const string& value)
1290 sqlite_bind_stdstring(d->clearProperty, 1, key);
1291 d->execUpdate(d->clearProperty);
1293 sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1294 sqlite_bind_stdstring(d->writePropertyQuery, 2, value);
1295 d->execUpdate(d->writePropertyQuery);
1298 void NavDataCache::writeDoubleProperty(const string& key, const double& value)
1300 sqlite_bind_stdstring(d->clearProperty, 1, key);
1301 d->execUpdate(d->clearProperty);
1303 sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1304 sqlite3_bind_double(d->writePropertyQuery, 2, value);
1305 d->execUpdate(d->writePropertyQuery);
1308 string_list NavDataCache::readStringListProperty(const string& key)
1310 sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1312 while (d->stepSelect(d->readPropertyQuery)) {
1313 result.push_back((char*) sqlite3_column_text(d->readPropertyQuery, 0));
1315 d->reset(d->readPropertyQuery);
1320 void NavDataCache::writeStringListProperty(const string& key, const string_list& values)
1322 sqlite_bind_stdstring(d->clearProperty, 1, key);
1323 d->execUpdate(d->clearProperty);
1325 BOOST_FOREACH(string value, values) {
1326 sqlite_bind_stdstring(d->writePropertyMulti, 1, key);
1327 sqlite_bind_stdstring(d->writePropertyMulti, 2, value);
1328 d->execInsert(d->writePropertyMulti);
1332 bool NavDataCache::isCachedFileModified(const SGPath& path) const
1334 return d->isCachedFileModified(path, false);
1337 void NavDataCache::stampCacheFile(const SGPath& path)
1339 sqlite_bind_temp_stdstring(d->stampFileCache, 1, path.utf8Str());
1340 sqlite3_bind_int64(d->stampFileCache, 2, path.modTime());
1341 d->execInsert(d->stampFileCache);
1344 void NavDataCache::beginTransaction()
1346 if (d->transactionLevel == 0) {
1347 d->transactionAborted = false;
1348 d->stepSelect(d->beginTransactionStmt);
1349 sqlite3_reset(d->beginTransactionStmt);
1352 ++d->transactionLevel;
1355 void NavDataCache::commitTransaction()
1357 assert(d->transactionLevel > 0);
1358 if (--d->transactionLevel == 0) {
1359 // if a nested transaction aborted, we might end up here, but must
1360 // still abort the entire transaction. That's bad, but safer than
1362 sqlite3_stmt_ptr q = d->transactionAborted ? d->rollbackTransactionStmt : d->commitTransactionStmt;
1366 while (retries < MAX_RETRIES) {
1367 result = sqlite3_step(q);
1368 if (result == SQLITE_DONE) {
1372 // see http://www.sqlite.org/c3ref/get_autocommit.html for a hint
1373 // what's going on here: autocommit in inactive inside BEGIN, so if
1374 // it's active, the DB was rolled-back
1375 if (sqlite3_get_autocommit(d->db)) {
1376 SG_LOG(SG_NAVCACHE, SG_ALERT, "commit: was rolled back!" << retries);
1377 d->transactionAborted = true;
1381 if (result != SQLITE_BUSY) {
1385 SGTimeStamp::sleepForMSec(++retries * 10);
1386 SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache contention on commit, will retry:" << retries);
1387 } // of retry loop for DB busy
1390 if (result != SQLITE_DONE) {
1391 errMsg = sqlite3_errmsg(d->db);
1392 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " for " << result
1393 << " while running:\n\t" << sqlite3_sql(q));
1400 void NavDataCache::abortTransaction()
1402 SG_LOG(SG_NAVCACHE, SG_WARN, "NavCache: aborting transaction");
1404 assert(d->transactionLevel > 0);
1405 if (--d->transactionLevel == 0) {
1406 d->stepSelect(d->rollbackTransactionStmt);
1407 sqlite3_reset(d->rollbackTransactionStmt);
1410 d->transactionAborted = true;
1413 FGPositionedRef NavDataCache::loadById(PositionedID rowid)
1419 PositionedCache::iterator it = d->cache.find(rowid);
1420 if (it != d->cache.end()) {
1422 return it->second; // cache it
1425 sqlite3_int64 aptId;
1426 FGPositioned* pos = d->loadById(rowid, aptId);
1427 d->cache.insert(it, PositionedCache::value_type(rowid, pos));
1430 // when we loaded an ILS, we must apply per-airport changes
1431 if ((pos->type() == FGPositioned::ILS) && (aptId > 0)) {
1432 FGAirport* apt = FGPositioned::loadById<FGAirport>(aptId);
1433 apt->validateILSData();
1439 PositionedID NavDataCache::insertAirport(FGPositioned::Type ty, const string& ident,
1442 // airports have their pos computed based on the avergae runway centres
1443 // so the pos isn't available immediately. Pass a dummy pos and avoid
1444 // doing spatial indexing until later
1445 sqlite3_int64 rowId = d->insertPositioned(ty, ident, name, SGGeod(),
1447 false /* spatial index */);
1449 sqlite3_bind_int64(d->insertAirport, 1, rowId);
1450 d->execInsert(d->insertAirport);
1455 void NavDataCache::updatePosition(PositionedID item, const SGGeod &pos)
1457 if (d->cache.find(item) != d->cache.end()) {
1458 SG_LOG(SG_NAVCACHE, SG_DEBUG, "updating position of an item in the cache");
1459 d->cache[item]->modifyPosition(pos);
1462 SGVec3d cartPos(SGVec3d::fromGeod(pos));
1464 sqlite3_bind_int(d->setAirportPos, 1, item);
1465 sqlite3_bind_double(d->setAirportPos, 2, pos.getLongitudeDeg());
1466 sqlite3_bind_double(d->setAirportPos, 3, pos.getLatitudeDeg());
1467 sqlite3_bind_double(d->setAirportPos, 4, pos.getElevationM());
1469 // bug 905; the octree leaf may change here, but the leaf may already be
1470 // loaded, and caching its children. (Either the old or new leaf!). Worse,
1471 // we may be called here as a result of loading one of those leaf's children.
1472 // instead of dealing with all those possibilites, such as modifying
1473 // the in-memory leaf's STL child container, we simply leave the runtime
1474 // structures alone. This is fine providing items do no move very far, since
1475 // all the spatial searches ultimately use the items' real cartesian position,
1476 // which was updated above.
1477 Octree::Leaf* octreeLeaf = Octree::global_spatialOctree->findLeafForPos(cartPos);
1478 sqlite3_bind_int64(d->setAirportPos, 5, octreeLeaf->guid());
1480 sqlite3_bind_double(d->setAirportPos, 6, cartPos.x());
1481 sqlite3_bind_double(d->setAirportPos, 7, cartPos.y());
1482 sqlite3_bind_double(d->setAirportPos, 8, cartPos.z());
1485 d->execUpdate(d->setAirportPos);
1488 void NavDataCache::insertTower(PositionedID airportId, const SGGeod& pos)
1490 d->insertPositioned(FGPositioned::TOWER, string(), string(),
1491 pos, airportId, true /* spatial index */);
1495 NavDataCache::insertRunway(FGPositioned::Type ty, const string& ident,
1496 const SGGeod& pos, PositionedID apt,
1497 double heading, double length, double width, double displacedThreshold,
1498 double stopway, int surfaceCode)
1500 // only runways are spatially indexed; don't bother indexing taxiways
1502 bool spatialIndex = ( ty == FGPositioned::RUNWAY || ty == FGPositioned::HELIPAD);
1504 sqlite3_int64 rowId = d->insertPositioned(ty, cleanRunwayNo(ident), "", pos, apt,
1506 sqlite3_bind_int64(d->insertRunway, 1, rowId);
1507 sqlite3_bind_double(d->insertRunway, 2, heading);
1508 sqlite3_bind_double(d->insertRunway, 3, length);
1509 sqlite3_bind_double(d->insertRunway, 4, width);
1510 sqlite3_bind_int(d->insertRunway, 5, surfaceCode);
1511 sqlite3_bind_double(d->insertRunway, 6, displacedThreshold);
1512 sqlite3_bind_double(d->insertRunway, 7, stopway);
1514 return d->execInsert(d->insertRunway);
1517 void NavDataCache::setRunwayReciprocal(PositionedID runway, PositionedID recip)
1519 sqlite3_bind_int64(d->setRunwayReciprocal, 1, runway);
1520 sqlite3_bind_int64(d->setRunwayReciprocal, 2, recip);
1521 d->execUpdate(d->setRunwayReciprocal);
1523 // and the opposite direction too!
1524 sqlite3_bind_int64(d->setRunwayReciprocal, 2, runway);
1525 sqlite3_bind_int64(d->setRunwayReciprocal, 1, recip);
1526 d->execUpdate(d->setRunwayReciprocal);
1529 void NavDataCache::setRunwayILS(PositionedID runway, PositionedID ils)
1531 sqlite3_bind_int64(d->setRunwayILS, 1, runway);
1532 sqlite3_bind_int64(d->setRunwayILS, 2, ils);
1533 d->execUpdate(d->setRunwayILS);
1535 // and the in-memory one
1536 if (d->cache.find(runway) != d->cache.end()) {
1537 FGRunway* instance = (FGRunway*) d->cache[runway].ptr();
1538 instance->setILS(ils);
1543 NavDataCache::insertNavaid(FGPositioned::Type ty, const string& ident,
1544 const string& name, const SGGeod& pos,
1545 int freq, int range, double multiuse,
1546 PositionedID apt, PositionedID runway)
1548 bool spatialIndex = true;
1549 if (ty == FGPositioned::MOBILE_TACAN) {
1550 spatialIndex = false;
1553 sqlite3_int64 rowId = d->insertPositioned(ty, ident, name, pos, apt,
1555 sqlite3_bind_int64(d->insertNavaid, 1, rowId);
1556 sqlite3_bind_int(d->insertNavaid, 2, freq);
1557 sqlite3_bind_int(d->insertNavaid, 3, range);
1558 sqlite3_bind_double(d->insertNavaid, 4, multiuse);
1559 sqlite3_bind_int64(d->insertNavaid, 5, runway);
1560 sqlite3_bind_int64(d->insertNavaid, 6, 0);
1561 return d->execInsert(d->insertNavaid);
1564 void NavDataCache::setNavaidColocated(PositionedID navaid, PositionedID colocatedDME)
1566 // Update DB entries...
1567 sqlite3_bind_int64(d->setNavaidColocated, 1, navaid);
1568 sqlite3_bind_int64(d->setNavaidColocated, 2, colocatedDME);
1569 d->execUpdate(d->setNavaidColocated);
1571 // ...and the in-memory copy of the navrecord
1572 if (d->cache.find(navaid) != d->cache.end()) {
1573 FGNavRecord* rec = (FGNavRecord*) d->cache[navaid].get();
1574 rec->setColocatedDME(colocatedDME);
1578 PositionedID NavDataCache::insertCommStation(FGPositioned::Type ty,
1579 const string& name, const SGGeod& pos, int freq, int range,
1582 sqlite3_int64 rowId = d->insertPositioned(ty, "", name, pos, apt, true);
1583 sqlite3_bind_int64(d->insertCommStation, 1, rowId);
1584 sqlite3_bind_int(d->insertCommStation, 2, freq);
1585 sqlite3_bind_int(d->insertCommStation, 3, range);
1586 return d->execInsert(d->insertCommStation);
1589 PositionedID NavDataCache::insertFix(const std::string& ident, const SGGeod& aPos)
1591 return d->insertPositioned(FGPositioned::FIX, ident, string(), aPos, 0, true);
1594 PositionedID NavDataCache::createPOI(FGPositioned::Type ty, const std::string& ident, const SGGeod& aPos)
1596 return d->insertPositioned(ty, ident, string(), aPos, 0,
1597 true /* spatial index */);
1600 bool NavDataCache::removePOI(FGPositioned::Type ty, const std::string& aIdent)
1602 d->removePositionedWithIdent(ty, aIdent);
1603 // should remove from the live cache too?
1608 void NavDataCache::setAirportMetar(const string& icao, bool hasMetar)
1610 sqlite_bind_stdstring(d->setAirportMetar, 1, icao);
1611 sqlite3_bind_int(d->setAirportMetar, 2, hasMetar);
1612 d->execUpdate(d->setAirportMetar);
1615 //------------------------------------------------------------------------------
1616 FGPositionedList NavDataCache::findAllWithIdent( const string& s,
1617 FGPositioned::Filter* filter,
1620 return d->findAllByString(s, "ident", filter, exact);
1623 //------------------------------------------------------------------------------
1624 FGPositionedList NavDataCache::findAllWithName( const string& s,
1625 FGPositioned::Filter* filter,
1628 return d->findAllByString(s, "name", filter, exact);
1631 //------------------------------------------------------------------------------
1632 FGPositionedRef NavDataCache::findClosestWithIdent( const string& aIdent,
1634 FGPositioned::Filter* aFilter )
1636 sqlite_bind_stdstring(d->findClosestWithIdent, 1, aIdent);
1638 sqlite3_bind_int(d->findClosestWithIdent, 2, aFilter->minType());
1639 sqlite3_bind_int(d->findClosestWithIdent, 3, aFilter->maxType());
1640 } else { // full type range
1641 sqlite3_bind_int(d->findClosestWithIdent, 2, FGPositioned::INVALID);
1642 sqlite3_bind_int(d->findClosestWithIdent, 3, FGPositioned::LAST_TYPE);
1645 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
1646 sqlite3_bind_double(d->findClosestWithIdent, 4, cartPos.x());
1647 sqlite3_bind_double(d->findClosestWithIdent, 5, cartPos.y());
1648 sqlite3_bind_double(d->findClosestWithIdent, 6, cartPos.z());
1650 FGPositionedRef result;
1652 while (d->stepSelect(d->findClosestWithIdent)) {
1653 FGPositioned* pos = loadById(sqlite3_column_int64(d->findClosestWithIdent, 0));
1654 if (aFilter && !aFilter->pass(pos)) {
1662 d->reset(d->findClosestWithIdent);
1667 int NavDataCache::getOctreeBranchChildren(int64_t octreeNodeId)
1669 sqlite3_bind_int64(d->getOctreeChildren, 1, octreeNodeId);
1670 d->execSelect1(d->getOctreeChildren);
1671 int children = sqlite3_column_int(d->getOctreeChildren, 0);
1672 d->reset(d->getOctreeChildren);
1676 void NavDataCache::defineOctreeNode(Octree::Branch* pr, Octree::Node* nd)
1678 sqlite3_bind_int64(d->insertOctree, 1, nd->guid());
1679 d->execInsert(d->insertOctree);
1681 #ifdef LAZY_OCTREE_UPDATES
1682 d->deferredOctreeUpdates.insert(pr);
1684 // lowest three bits of node ID are 0..7 index of the child in the parent
1685 int childIndex = nd->guid() & 0x07;
1687 sqlite3_bind_int64(d->updateOctreeChildren, 1, pr->guid());
1688 // mask has bit N set where child N exists
1689 int childMask = 1 << childIndex;
1690 sqlite3_bind_int(d->updateOctreeChildren, 2, childMask);
1691 d->execUpdate(d->updateOctreeChildren);
1696 NavDataCache::getOctreeLeafChildren(int64_t octreeNodeId)
1698 sqlite3_bind_int64(d->getOctreeLeafChildren, 1, octreeNodeId);
1700 TypedPositionedVec r;
1701 while (d->stepSelect(d->getOctreeLeafChildren)) {
1702 FGPositioned::Type ty = static_cast<FGPositioned::Type>
1703 (sqlite3_column_int(d->getOctreeLeafChildren, 1));
1704 r.push_back(std::make_pair(ty,
1705 sqlite3_column_int64(d->getOctreeLeafChildren, 0)));
1708 d->reset(d->getOctreeLeafChildren);
1714 * A special purpose helper (used by FGAirport::searchNamesAndIdents) to
1715 * implement the AirportList dialog. It's unfortunate that it needs to reside
1716 * here, but for now it's least ugly solution.
1718 char** NavDataCache::searchAirportNamesAndIdents(const std::string& aFilter)
1720 sqlite3_stmt_ptr stmt;
1721 unsigned int numMatches = 0, numAllocated = 16;
1722 string searchTerm("%" + aFilter + "%");
1723 if (aFilter.empty()) {
1724 stmt = d->getAllAirports;
1725 numAllocated = 4096; // start much larger for all airports
1727 stmt = d->searchAirports;
1728 sqlite_bind_stdstring(stmt, 1, searchTerm);
1731 char** result = (char**) malloc(sizeof(char*) * numAllocated);
1732 while (d->stepSelect(stmt)) {
1733 if ((numMatches + 1) >= numAllocated) {
1734 numAllocated <<= 1; // double in size!
1735 // reallocate results array
1736 char** nresult = (char**) malloc(sizeof(char*) * numAllocated);
1737 memcpy(nresult, result, sizeof(char*) * numMatches);
1742 // nasty code to avoid excessive string copying and allocations.
1743 // We format results as follows (note whitespace!):
1744 // ' name-of-airport-chars (ident)'
1745 // so the total length is:
1746 // 1 + strlen(name) + 4 + strlen(icao) + 1 + 1 (for the null)
1747 // which gives a grand total of 7 + name-length + icao-length.
1748 // note the ident can be three letters (non-ICAO local strip), four
1749 // (default ICAO) or more (extended format ICAO)
1750 int nameLength = sqlite3_column_bytes(stmt, 1);
1751 int icaoLength = sqlite3_column_bytes(stmt, 0);
1752 char* entry = (char*) malloc(7 + nameLength + icaoLength);
1755 memcpy(dst, sqlite3_column_text(stmt, 1), nameLength);
1761 memcpy(dst, sqlite3_column_text(stmt, 0), icaoLength);
1766 result[numMatches++] = entry;
1769 result[numMatches] = NULL; // end of list marker
1775 NavDataCache::findCommByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
1777 sqlite3_bind_int(d->findCommByFreq, 1, freqKhz);
1779 sqlite3_bind_int(d->findCommByFreq, 2, aFilter->minType());
1780 sqlite3_bind_int(d->findCommByFreq, 3, aFilter->maxType());
1781 } else { // full type range
1782 sqlite3_bind_int(d->findCommByFreq, 2, FGPositioned::FREQ_GROUND);
1783 sqlite3_bind_int(d->findCommByFreq, 3, FGPositioned::FREQ_UNICOM);
1786 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
1787 sqlite3_bind_double(d->findCommByFreq, 4, cartPos.x());
1788 sqlite3_bind_double(d->findCommByFreq, 5, cartPos.y());
1789 sqlite3_bind_double(d->findCommByFreq, 6, cartPos.z());
1790 FGPositionedRef result;
1792 while (d->execSelect(d->findCommByFreq)) {
1793 FGPositioned* p = loadById(sqlite3_column_int64(d->findCommByFreq, 0));
1794 if (aFilter && !aFilter->pass(p)) {
1802 d->reset(d->findCommByFreq);
1807 NavDataCache::findNavaidsByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
1809 sqlite3_bind_int(d->findNavsByFreq, 1, freqKhz);
1811 sqlite3_bind_int(d->findNavsByFreq, 2, aFilter->minType());
1812 sqlite3_bind_int(d->findNavsByFreq, 3, aFilter->maxType());
1813 } else { // full type range
1814 sqlite3_bind_int(d->findNavsByFreq, 2, FGPositioned::NDB);
1815 sqlite3_bind_int(d->findNavsByFreq, 3, FGPositioned::GS);
1818 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
1819 sqlite3_bind_double(d->findNavsByFreq, 4, cartPos.x());
1820 sqlite3_bind_double(d->findNavsByFreq, 5, cartPos.y());
1821 sqlite3_bind_double(d->findNavsByFreq, 6, cartPos.z());
1823 return d->selectIds(d->findNavsByFreq);
1827 NavDataCache::findNavaidsByFreq(int freqKhz, FGPositioned::Filter* aFilter)
1829 sqlite3_bind_int(d->findNavsByFreqNoPos, 1, freqKhz);
1831 sqlite3_bind_int(d->findNavsByFreqNoPos, 2, aFilter->minType());
1832 sqlite3_bind_int(d->findNavsByFreqNoPos, 3, aFilter->maxType());
1833 } else { // full type range
1834 sqlite3_bind_int(d->findNavsByFreqNoPos, 2, FGPositioned::NDB);
1835 sqlite3_bind_int(d->findNavsByFreqNoPos, 3, FGPositioned::GS);
1838 return d->selectIds(d->findNavsByFreqNoPos);
1842 NavDataCache::airportItemsOfType(PositionedID apt,FGPositioned::Type ty,
1843 FGPositioned::Type maxTy)
1845 if (maxTy == FGPositioned::INVALID) {
1846 maxTy = ty; // single-type range
1849 sqlite3_bind_int64(d->getAirportItems, 1, apt);
1850 sqlite3_bind_int(d->getAirportItems, 2, ty);
1851 sqlite3_bind_int(d->getAirportItems, 3, maxTy);
1853 return d->selectIds(d->getAirportItems);
1857 NavDataCache::airportItemWithIdent(PositionedID apt, FGPositioned::Type ty,
1858 const std::string& ident)
1860 sqlite3_bind_int64(d->getAirportItemByIdent, 1, apt);
1861 sqlite_bind_stdstring(d->getAirportItemByIdent, 2, ident);
1862 sqlite3_bind_int(d->getAirportItemByIdent, 3, ty);
1863 PositionedID result = 0;
1865 if (d->execSelect(d->getAirportItemByIdent)) {
1866 result = sqlite3_column_int64(d->getAirportItemByIdent, 0);
1869 d->reset(d->getAirportItemByIdent);
1874 NavDataCache::findAirportRunway(const std::string& aName)
1876 if (aName.empty()) {
1877 return AirportRunwayPair();
1880 string_list parts = simgear::strutils::split(aName);
1881 if (parts.size() < 2) {
1882 SG_LOG(SG_NAVCACHE, SG_WARN, "findAirportRunway: malformed name:" << aName);
1883 return AirportRunwayPair();
1886 AirportRunwayPair result;
1887 sqlite_bind_stdstring(d->findAirportRunway, 1, parts[0]);
1888 sqlite_bind_stdstring(d->findAirportRunway, 2, cleanRunwayNo(parts[1]));
1890 if (d->execSelect(d->findAirportRunway)) {
1891 result = AirportRunwayPair(sqlite3_column_int64(d->findAirportRunway, 0),
1892 sqlite3_column_int64(d->findAirportRunway, 1));
1895 SG_LOG(SG_NAVCACHE, SG_WARN, "findAirportRunway: unknown airport/runway:" << aName);
1898 d->reset(d->findAirportRunway);
1903 NavDataCache::findILS(PositionedID airport, const string& aRunway, const string& navIdent)
1905 string runway(cleanRunwayNo(aRunway));
1907 sqlite_bind_stdstring(d->findILS, 1, navIdent);
1908 sqlite3_bind_int64(d->findILS, 2, airport);
1909 sqlite_bind_stdstring(d->findILS, 3, runway);
1910 PositionedID result = 0;
1911 if (d->execSelect(d->findILS)) {
1912 result = sqlite3_column_int64(d->findILS, 0);
1915 d->reset(d->findILS);
1919 int NavDataCache::findAirway(int network, const string& aName)
1921 sqlite3_bind_int(d->findAirway, 1, network);
1922 sqlite_bind_stdstring(d->findAirway, 2, aName);
1925 if (d->execSelect(d->findAirway)) {
1927 airway = sqlite3_column_int(d->findAirway, 0);
1929 sqlite_bind_stdstring(d->insertAirway, 1, aName);
1930 sqlite3_bind_int(d->insertAirway, 2, network);
1931 airway = d->execInsert(d->insertAirway);
1934 d->reset(d->findAirway);
1938 void NavDataCache::insertEdge(int network, int airwayID, PositionedID from, PositionedID to)
1940 // assume all edges are bidirectional for the moment
1941 for (int i=0; i<2; ++i) {
1942 sqlite3_bind_int(d->insertAirwayEdge, 1, network);
1943 sqlite3_bind_int(d->insertAirwayEdge, 2, airwayID);
1944 sqlite3_bind_int64(d->insertAirwayEdge, 3, from);
1945 sqlite3_bind_int64(d->insertAirwayEdge, 4, to);
1946 d->execInsert(d->insertAirwayEdge);
1948 std::swap(from, to);
1952 bool NavDataCache::isInAirwayNetwork(int network, PositionedID pos)
1954 sqlite3_bind_int(d->isPosInAirway, 1, network);
1955 sqlite3_bind_int64(d->isPosInAirway, 2, pos);
1956 bool ok = d->execSelect(d->isPosInAirway);
1957 d->reset(d->isPosInAirway);
1962 AirwayEdgeVec NavDataCache::airwayEdgesFrom(int network, PositionedID pos)
1964 sqlite3_bind_int(d->airwayEdgesFrom, 1, network);
1965 sqlite3_bind_int64(d->airwayEdgesFrom, 2, pos);
1967 AirwayEdgeVec result;
1968 while (d->stepSelect(d->airwayEdgesFrom)) {
1969 result.push_back(AirwayEdge(
1970 sqlite3_column_int(d->airwayEdgesFrom, 0),
1971 sqlite3_column_int64(d->airwayEdgesFrom, 1)
1975 d->reset(d->airwayEdgesFrom);
1979 PositionedIDVec NavDataCache::airwayWaypts(int id)
1981 sqlite3_bind_int(d->airwayEdges, 1, id);
1983 typedef std::pair<PositionedID, PositionedID> Edge;
1984 typedef std::deque<Edge> EdgeVec;
1985 typedef std::deque<PositionedID> PositionedIDDeque;
1987 // build up the EdgeVec, order is arbitrary
1989 while (d->stepSelect(d->airwayEdges)) {
1990 rawEdges.push_back(Edge(sqlite3_column_int64(d->airwayEdges, 0),
1991 sqlite3_column_int64(d->airwayEdges, 1)
1995 d->reset(d->airwayEdges);
1996 if (rawEdges.empty()) {
1997 return PositionedIDVec();
2001 PositionedIDDeque linearAirway;
2002 PositionedID firstId = rawEdges.front().first,
2003 lastId = rawEdges.front().second;
2004 std::set<PositionedID> seen;
2006 // first edge is trivial
2007 linearAirway.push_back(firstId);
2008 linearAirway.push_back(lastId);
2009 seen.insert(firstId);
2010 seen.insert(lastId);
2011 rawEdges.pop_front();
2013 while (!rawEdges.empty()) {
2014 Edge e = rawEdges.front();
2015 rawEdges.pop_front();
2017 // look for new segments
2018 if (e.first == firstId) {
2019 linearAirway.push_front(e.second);
2020 seen.insert(e.second);
2025 if (e.first == lastId) {
2026 linearAirway.push_back(e.second);
2027 seen.insert(e.second);
2032 // look for seen segments - presumed to be reversed internal edges
2033 if (seen.find(e.first) != seen.end()) {
2034 // if it's the inverse of interior edge, both ends must have been
2035 // seen. Otherwise it should have been an exterior edge and
2036 // handled by the case above.
2037 assert(seen.find(e.second) != seen.end());
2041 // push back to try later on
2042 rawEdges.push_back(e);
2045 return PositionedIDVec(linearAirway.begin(), linearAirway.end());
2048 PositionedID NavDataCache::findNavaidForRunway(PositionedID runway, FGPositioned::Type ty)
2050 sqlite3_bind_int64(d->findNavaidForRunway, 1, runway);
2051 sqlite3_bind_int(d->findNavaidForRunway, 2, ty);
2053 PositionedID result = 0;
2054 if (d->execSelect(d->findNavaidForRunway)) {
2055 result = sqlite3_column_int64(d->findNavaidForRunway, 0);
2058 d->reset(d->findNavaidForRunway);
2062 bool NavDataCache::isReadOnly() const
2067 SGPath NavDataCache::path() const
2072 /////////////////////////////////////////////////////////////////////////////////////////
2073 // Transaction RAII object
2075 NavDataCache::Transaction::Transaction(NavDataCache* cache) :
2080 _instance->beginTransaction();
2083 NavDataCache::Transaction::~Transaction()
2086 SG_LOG(SG_NAVCACHE, SG_INFO, "aborting cache transaction!");
2087 _instance->abortTransaction();
2091 void NavDataCache::Transaction::commit()
2093 assert(!_committed);
2095 _instance->commitTransaction();
2098 /////////////////////////////////////////////////////////////////////////////
2100 class NavDataCache::ThreadedGUISearch::ThreadedGUISearchPrivate : public SGThread
2103 ThreadedGUISearchPrivate() :
2112 int err = sqlite3_step(query);
2113 if (err == SQLITE_DONE) {
2115 } else if (err == SQLITE_ROW) {
2116 PositionedID r = sqlite3_column_int64(query, 0);
2117 SGGuard<SGMutex> g(lock);
2118 results.push_back(r);
2119 } else if (err == SQLITE_BUSY) {
2120 // sleep a tiny amount
2121 SGTimeStamp::sleepForMSec(1);
2123 std::string errMsg = sqlite3_errmsg(db);
2124 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running threaded search query");
2128 SGGuard<SGMutex> g(lock);
2134 sqlite3_stmt_ptr query;
2135 PositionedIDVec results;
2140 NavDataCache::ThreadedGUISearch::ThreadedGUISearch(const std::string& term) :
2141 d(new ThreadedGUISearchPrivate)
2143 SGPath p = NavDataCache::instance()->path();
2144 int openFlags = SQLITE_OPEN_READONLY;
2145 std::string pathUtf8 = p.utf8Str();
2146 sqlite3_open_v2(pathUtf8.c_str(), &d->db, openFlags, NULL);
2148 std::string sql = "SELECT rowid FROM positioned WHERE name LIKE '%" + term
2149 + "%' AND ((type >= 1 AND type <= 3) OR ((type >= 9 AND type <= 11))) ";
2150 sqlite3_prepare_v2(d->db, sql.c_str(), sql.length(), &d->query, NULL);
2155 NavDataCache::ThreadedGUISearch::~ThreadedGUISearch()
2158 SGGuard<SGMutex> g(d->lock);
2163 sqlite3_finalize(d->query);
2164 sqlite3_close_v2(d->db);
2167 PositionedIDVec NavDataCache::ThreadedGUISearch::results() const
2171 SGGuard<SGMutex> g(d->lock);
2177 bool NavDataCache::ThreadedGUISearch::isComplete() const
2179 SGGuard<SGMutex> g(d->lock);
2180 return d->isComplete;
2183 } // of namespace flightgear