]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/NavDataCache.cxx
Trying to bullet-proof the traffic code.
[flightgear.git] / src / Navaids / NavDataCache.cxx
1 // NavDataCache.cxx - defines a unified binary cache for navigation
2 // data, parsed from various text / XML sources.
3
4 // Written by James Turner, started 2012.
5 //
6 // Copyright (C) 2012  James Turner
7 //
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.
12 //
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.
17 //
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.
21
22 #ifdef HAVE_CONFIG_H
23 # include "config.h"
24 #endif
25
26 #include "NavDataCache.hxx"
27
28 // std
29 #include <map>
30 #include <cassert>
31 #include <stdint.h> // for int64_t
32 // boost
33 #include <boost/foreach.hpp>
34
35
36 #ifdef SYSTEM_SQLITE
37 // the standard sqlite3.h doesn't give a way to set SQLITE_UINT64_TYPE,
38 // so we have to hope sizeof(int64_t) matches sizeof(sqlite3_int64).
39 // otherwise things will go bad quickly.
40   #include "sqlite3.h"
41 #else
42 // to ensure compatability between sqlite3_int64 and PositionedID,
43 // force the type used by sqlite to match PositionedID explicitly
44 #define SQLITE_INT64_TYPE int64_t
45 #define SQLITE_UINT64_TYPE uint64_t
46
47   #include "fg_sqlite3.h"
48 #endif
49
50 // SimGear
51 #include <simgear/sg_inlines.h>
52 #include <simgear/structure/exception.hxx>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/bucket/newbucket.hxx>
55 #include <simgear/misc/sg_path.hxx>
56 #include <simgear/misc/strutils.hxx>
57 #include <simgear/threads/SGThread.hxx>
58 #include <simgear/threads/SGGuard.hxx>
59
60 #include <Main/globals.hxx>
61 #include <Main/fg_props.hxx>
62 #include <Main/options.hxx>
63 #include "markerbeacon.hxx"
64 #include "navrecord.hxx"
65 #include <Airports/airport.hxx>
66 #include <Airports/runways.hxx>
67 #include <ATC/CommStation.hxx>
68 #include "fix.hxx"
69 #include <Navaids/fixlist.hxx>
70 #include <Navaids/navdb.hxx>
71 #include "PositionedOctree.hxx"
72 #include <Airports/apt_loader.hxx>
73 #include <Navaids/airways.hxx>
74 #include "poidb.hxx"
75 #include <Airports/parking.hxx>
76 #include <Airports/gnnode.hxx>
77 #include "CacheSchema.h"
78
79 using std::string;
80
81 #define SG_NAVCACHE SG_NAVAID
82 //#define LAZY_OCTREE_UPDATES 1
83
84 namespace {
85
86 const int MAX_RETRIES = 10;
87
88 const int CACHE_SIZE_KBYTES= 32 * 1024;
89
90 // bind a std::string to a sqlite statement. The std::string must live the
91 // entire duration of the statement execution - do not pass a temporary
92 // std::string, or the compiler may delete it, freeing the C-string storage,
93 // and causing subtle memory corruption bugs!
94 void sqlite_bind_stdstring(sqlite3_stmt* stmt, int value, const std::string& s)
95 {
96   sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_STATIC);
97 }
98
99 // variant of the above, which does not care about the lifetime of the
100 // passed std::string
101 void sqlite_bind_temp_stdstring(sqlite3_stmt* stmt, int value, const std::string& s)
102 {
103   sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_TRANSIENT);
104 }
105
106 typedef sqlite3_stmt* sqlite3_stmt_ptr;
107
108 void f_distanceCartSqrFunction(sqlite3_context* ctx, int argc, sqlite3_value* argv[])
109 {
110   if (argc != 6) {
111     return;
112   }
113
114   SGVec3d posA(sqlite3_value_double(argv[0]),
115                sqlite3_value_double(argv[1]),
116                sqlite3_value_double(argv[2]));
117
118   SGVec3d posB(sqlite3_value_double(argv[3]),
119                sqlite3_value_double(argv[4]),
120                sqlite3_value_double(argv[5]));
121   sqlite3_result_double(ctx, distSqr(posA, posB));
122 }
123
124
125 static string cleanRunwayNo(const string& aRwyNo)
126 {
127   if (aRwyNo[0] == 'x') {
128     return string(); // no ident for taxiways
129   }
130
131   string result(aRwyNo);
132   // canonicalise runway ident
133   if ((aRwyNo.size() == 1) || !isdigit(aRwyNo[1])) {
134     result = "0" + aRwyNo;
135   }
136
137   // trim off trailing garbage
138   if (result.size() > 2) {
139     char suffix = toupper(result[2]);
140     if (suffix == 'X') {
141       result = result.substr(0, 2);
142     }
143   }
144
145   return result;
146 }
147
148 } // anonymous namespace
149
150 namespace flightgear
151 {
152
153 /**
154  * Thread encapsulating a cache rebuild. This is not used to parallelise
155  * the rebuild - we must still wait until completion before doing other
156  * startup, since many things rely on a complete cache. The thread is used
157  * so we don't block the main event loop for an unacceptable duration,
158  * which causes 'not responding' / spinning beachballs on Windows & Mac
159  */
160 class RebuildThread : public SGThread
161 {
162 public:
163   RebuildThread(NavDataCache* cache) :
164   _cache(cache),
165     _phase(NavDataCache::REBUILD_UNKNOWN),
166     _completionPercent(0),
167   _isFinished(false)
168   {
169
170   }
171
172   bool isFinished() const
173   {
174     SGGuard<SGMutex> g(_lock);
175     return _isFinished;
176   }
177
178   virtual void run()
179   {
180     SGTimeStamp st;
181     st.stamp();
182     _cache->doRebuild();
183     SG_LOG(SG_NAVCACHE, SG_INFO, "cache rebuild took:" << st.elapsedMSec() << "msec");
184
185     SGGuard<SGMutex> g(_lock);
186     _isFinished = true;
187     _phase = NavDataCache::REBUILD_DONE;
188   }
189
190     NavDataCache::RebuildPhase currentPhase() const
191     {
192         NavDataCache::RebuildPhase ph;
193         SGGuard<SGMutex> g(_lock);
194         ph = _phase;
195         return ph;
196     }
197
198     unsigned int completionPercent() const
199     {
200         unsigned int perc = 0;
201         SGGuard<SGMutex> g(_lock);
202         perc = _completionPercent;
203         return perc;
204     }
205
206     void setProgress(NavDataCache::RebuildPhase ph, unsigned int percent)
207     {
208         SGGuard<SGMutex> g(_lock);
209         _phase = ph;
210         _completionPercent = percent;
211     }
212
213 private:
214   NavDataCache* _cache;
215     NavDataCache::RebuildPhase _phase;
216     unsigned int _completionPercent;
217   mutable SGMutex _lock;
218   bool _isFinished;
219 };
220
221 ////////////////////////////////////////////////////////////////////////////
222
223 typedef std::map<PositionedID, FGPositionedRef> PositionedCache;
224
225 class AirportTower : public FGPositioned
226 {
227 public:
228   AirportTower(PositionedID& guid, PositionedID airport,
229                const string& ident, const SGGeod& pos) :
230     FGPositioned(guid, FGPositioned::TOWER, ident, pos)
231   {
232   }
233 };
234
235 class NavDataCache::NavDataCachePrivate
236 {
237 public:
238   NavDataCachePrivate(const SGPath& p, NavDataCache* o) :
239     outer(o),
240     db(NULL),
241     path(p),
242     readOnly(false),
243     cacheHits(0),
244     cacheMisses(0),
245     transactionLevel(0),
246     transactionAborted(false)
247   {
248   }
249
250   ~NavDataCachePrivate()
251   {
252     close();
253   }
254
255   void init()
256   {
257     SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache at:" << path);
258
259       readOnly = fgGetBool("/sim/fghome-readonly", false);
260
261       int openFlags = readOnly ? SQLITE_OPEN_READONLY :
262         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
263       // see http://code.google.com/p/flightgear-bugs/issues/detail?id=1055
264       // for the UTF8 / path logic here
265         std::string pathUtf8 = simgear::strutils::convertWindowsLocal8BitToUtf8(path.str());
266     sqlite3_open_v2(pathUtf8.c_str(), &db, openFlags, NULL);
267
268     sqlite3_stmt_ptr checkTables =
269       prepare("SELECT count(*) FROM sqlite_master WHERE name='properties'");
270
271     sqlite3_create_function(db, "distanceCartSqr", 6, SQLITE_ANY, NULL,
272                             f_distanceCartSqrFunction, NULL, NULL);
273
274     execSelect(checkTables);
275     bool didCreate = false;
276     if (!readOnly && (sqlite3_column_int(checkTables, 0) == 0)) {
277       SG_LOG(SG_NAVCACHE, SG_INFO, "will create tables");
278       initTables();
279       didCreate = true;
280     }
281
282     readPropertyQuery = prepare("SELECT value FROM properties WHERE key=?");
283     writePropertyQuery = prepare("INSERT INTO properties (key, value) VALUES (?,?)");
284     clearProperty = prepare("DELETE FROM properties WHERE key=?1");
285
286     if (didCreate) {
287       writeIntProperty("schema-version", SCHEMA_VERSION);
288     } else {
289       int schemaVersion = outer->readIntProperty("schema-version");
290       if (schemaVersion != SCHEMA_VERSION) {
291         SG_LOG(SG_NAVCACHE, SG_INFO, "Navcache schema mismatch, will rebuild");
292         throw sg_exception("Navcache schema has changed");
293       }
294     }
295
296     // see http://www.sqlite.org/pragma.html#pragma_cache_size
297     // for the details, small cache would cause thrashing.
298     std::ostringstream q;
299     q << "PRAGMA cache_size=-" << CACHE_SIZE_KBYTES << ";";
300     runSQL(q.str());
301     prepareQueries();
302   }
303
304   void close()
305   {
306     BOOST_FOREACH(sqlite3_stmt_ptr stmt, prepared) {
307       sqlite3_finalize(stmt);
308     }
309     prepared.clear();
310     sqlite3_close(db);
311   }
312
313   void checkCacheFile()
314   {
315     SG_LOG(SG_NAVCACHE, SG_INFO, "running DB integrity check");
316     SGTimeStamp st;
317     st.stamp();
318
319     sqlite3_stmt_ptr stmt = prepare("PRAGMA quick_check(1)");
320     if (!execSelect(stmt)) {
321       throw sg_exception("DB integrity check failed to run");
322     }
323
324     string v = (char*) sqlite3_column_text(stmt, 0);
325     if (v != "ok") {
326       throw sg_exception("DB integrity check returned:" + v);
327     }
328
329     SG_LOG(SG_NAVCACHE, SG_INFO, "NavDataCache integrity check took:" << st.elapsedMSec());
330     finalize(stmt);
331   }
332
333   bool isCachedFileModified(const SGPath& path, bool verbose);
334
335   void callSqlite(int result, const string& sql)
336   {
337     if (result == SQLITE_OK)
338       return; // all good
339
340     string errMsg;
341     if (result == SQLITE_MISUSE) {
342       errMsg = "Sqlite API abuse";
343       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
344     } else {
345       errMsg = sqlite3_errmsg(db);
346       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running:\n\t" << sql);
347     }
348
349     throw sg_exception("Sqlite error:" + errMsg, sql);
350   }
351
352   void runSQL(const string& sql)
353   {
354     sqlite3_stmt_ptr stmt;
355     callSqlite(sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL), sql);
356
357     try {
358       execSelect(stmt);
359     } catch (sg_exception&) {
360       sqlite3_finalize(stmt);
361       throw; // re-throw
362     }
363
364     sqlite3_finalize(stmt);
365   }
366
367   sqlite3_stmt_ptr prepare(const string& sql)
368   {
369     sqlite3_stmt_ptr stmt;
370     callSqlite(sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL), sql);
371     prepared.push_back(stmt);
372     return stmt;
373   }
374
375   void finalize(sqlite3_stmt_ptr s)
376   {
377     StmtVec::iterator it = std::find(prepared.begin(), prepared.end(), s);
378     if (it == prepared.end()) {
379       throw sg_exception("Finalising statement that was not prepared");
380     }
381
382     prepared.erase(it);
383     sqlite3_finalize(s);
384   }
385
386   void reset(sqlite3_stmt_ptr stmt)
387   {
388     assert(stmt);
389     if (sqlite3_reset(stmt) != SQLITE_OK) {
390       string errMsg = sqlite3_errmsg(db);
391       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error resetting:" << errMsg);
392       throw sg_exception("Sqlite error resetting:" + errMsg, sqlite3_sql(stmt));
393     }
394   }
395
396   bool execSelect(sqlite3_stmt_ptr stmt)
397   {
398     return stepSelect(stmt);
399   }
400
401   bool stepSelect(sqlite3_stmt_ptr stmt)
402   {
403     int retries = 0;
404     int result;
405     while (retries < MAX_RETRIES) {
406       result = sqlite3_step(stmt);
407       if (result == SQLITE_ROW) {
408         return true; // at least one result row
409       }
410
411       if (result == SQLITE_DONE) {
412         return false; // no result rows
413       }
414
415       if (result != SQLITE_BUSY) {
416         break;
417       }
418
419       SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache contention on select, will retry:" << retries);
420       SGTimeStamp::sleepForMSec(++retries * 10);
421     } // of retry loop for DB locked
422
423     if (retries >= MAX_RETRIES) {
424       SG_LOG(SG_NAVCACHE, SG_ALERT, "exceeded maximum number of SQLITE_BUSY retries");
425       return false;
426     }
427
428     string errMsg;
429     if (result == SQLITE_MISUSE) {
430       errMsg = "Sqlite API abuse";
431       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
432     } else {
433       errMsg = sqlite3_errmsg(db);
434       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " (" << result
435              << ") while running:\n\t" << sqlite3_sql(stmt));
436     }
437
438     throw sg_exception("Sqlite error:" + errMsg, sqlite3_sql(stmt));
439   }
440
441   void execSelect1(sqlite3_stmt_ptr stmt)
442   {
443     if (!execSelect(stmt)) {
444       SG_LOG(SG_NAVCACHE, SG_WARN, "empty SELECT running:\n\t" << sqlite3_sql(stmt));
445       throw sg_exception("no results returned for select", sqlite3_sql(stmt));
446     }
447   }
448
449   sqlite3_int64 execInsert(sqlite3_stmt_ptr stmt)
450   {
451     execSelect(stmt);
452     sqlite3_int64 rowid = sqlite3_last_insert_rowid(db);
453     reset(stmt);
454     return rowid;
455   }
456
457   void execUpdate(sqlite3_stmt_ptr stmt)
458   {
459     execSelect(stmt);
460     reset(stmt);
461   }
462
463   void initTables()
464   {
465       string_list commands = simgear::strutils::split(SCHEMA_SQL, ";");
466       BOOST_FOREACH(std::string sql, commands) {
467           if (sql.empty()) {
468               continue;
469           }
470
471           runSQL(sql);
472       } // of commands in scheme loop
473   }
474
475   void prepareQueries()
476   {
477     writePropertyMulti = prepare("INSERT INTO properties (key, value) VALUES(?1,?2)");
478
479     beginTransactionStmt = prepare("BEGIN");
480     commitTransactionStmt = prepare("COMMIT");
481     rollbackTransactionStmt = prepare("ROLLBACK");
482
483
484 #define POSITIONED_COLS "rowid, type, ident, name, airport, lon, lat, elev_m, octree_node"
485 #define AND_TYPED "AND type>=?2 AND type <=?3"
486     statCacheCheck = prepare("SELECT stamp FROM stat_cache WHERE path=?");
487     stampFileCache = prepare("INSERT OR REPLACE INTO stat_cache "
488                              "(path, stamp) VALUES (?,?)");
489
490     loadPositioned = prepare("SELECT " POSITIONED_COLS " FROM positioned WHERE rowid=?");
491     loadAirportStmt = prepare("SELECT has_metar FROM airport WHERE rowid=?");
492     loadNavaid = prepare("SELECT range_nm, freq, multiuse, runway, colocated FROM navaid WHERE rowid=?");
493     loadCommStation = prepare("SELECT freq_khz, range_nm FROM comm WHERE rowid=?");
494     loadRunwayStmt = prepare("SELECT heading, length_ft, width_m, surface, displaced_threshold,"
495                              "stopway, reciprocal, ils FROM runway WHERE rowid=?1");
496
497     getAirportItems = prepare("SELECT rowid FROM positioned WHERE airport=?1 " AND_TYPED);
498
499
500     setAirportMetar = prepare("UPDATE airport SET has_metar=?2 WHERE rowid="
501                               "(SELECT rowid FROM positioned WHERE ident=?1 AND type>=?3 AND type <=?4)");
502     sqlite3_bind_int(setAirportMetar, 3, FGPositioned::AIRPORT);
503     sqlite3_bind_int(setAirportMetar, 4, FGPositioned::SEAPORT);
504
505     setRunwayReciprocal = prepare("UPDATE runway SET reciprocal=?2 WHERE rowid=?1");
506     setRunwayILS = prepare("UPDATE runway SET ils=?2 WHERE rowid=?1");
507     setNavaidColocated = prepare("UPDATE navaid SET colocated=?2 WHERE rowid=?1");
508
509     insertPositionedQuery = prepare("INSERT INTO positioned "
510                                     "(type, ident, name, airport, lon, lat, elev_m, octree_node, "
511                                     "cart_x, cart_y, cart_z)"
512                                     " VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)");
513
514     setAirportPos = prepare("UPDATE positioned SET lon=?2, lat=?3, elev_m=?4, octree_node=?5, "
515                             "cart_x=?6, cart_y=?7, cart_z=?8 WHERE rowid=?1");
516     insertAirport = prepare("INSERT INTO airport (rowid, has_metar) VALUES (?, ?)");
517     insertNavaid = prepare("INSERT INTO navaid (rowid, freq, range_nm, multiuse, runway, colocated)"
518                            " VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
519
520     insertCommStation = prepare("INSERT INTO comm (rowid, freq_khz, range_nm)"
521                                 " VALUES (?, ?, ?)");
522     insertRunway = prepare("INSERT INTO runway "
523                            "(rowid, heading, length_ft, width_m, surface, displaced_threshold, stopway, reciprocal)"
524                            " VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)");
525     runwayLengthFtQuery = prepare("SELECT length_ft FROM runway WHERE rowid=?1");
526
527     removePOIQuery = prepare("DELETE FROM positioned WHERE type=?1 AND ident=?2");
528
529   // query statement
530     findClosestWithIdent = prepare("SELECT rowid FROM positioned WHERE ident=?1 "
531                                    AND_TYPED " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
532
533     findCommByFreq = prepare("SELECT positioned.rowid FROM positioned, comm WHERE "
534                              "positioned.rowid=comm.rowid AND freq_khz=?1 "
535                              AND_TYPED " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
536
537     findNavsByFreq = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
538                              "positioned.rowid=navaid.rowid "
539                              "AND navaid.freq=?1 " AND_TYPED
540                              " ORDER BY distanceCartSqr(cart_x, cart_y, cart_z, ?4, ?5, ?6)");
541
542     findNavsByFreqNoPos = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
543                                   "positioned.rowid=navaid.rowid AND freq=?1 " AND_TYPED);
544
545     findNavaidForRunway = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
546                                   "positioned.rowid=navaid.rowid AND runway=?1 AND type=?2");
547
548   // for an octree branch, return the child octree nodes which exist,
549   // described as a bit-mask
550     getOctreeChildren = prepare("SELECT children FROM octree WHERE rowid=?1");
551
552 #ifdef LAZY_OCTREE_UPDATES
553     updateOctreeChildren = prepare("UPDATE octree SET children=?2 WHERE rowid=?1");
554 #else
555   // mask the new child value into the existing one
556     updateOctreeChildren = prepare("UPDATE octree SET children=(?2 | children) WHERE rowid=?1");
557 #endif
558
559   // define a new octree node (with no children)
560     insertOctree = prepare("INSERT INTO octree (rowid, children) VALUES (?1, 0)");
561
562     getOctreeLeafChildren = prepare("SELECT rowid, type FROM positioned WHERE octree_node=?1");
563
564     searchAirports = prepare("SELECT ident, name FROM positioned WHERE (name LIKE ?1 OR ident LIKE ?1) " AND_TYPED);
565     sqlite3_bind_int(searchAirports, 2, FGPositioned::AIRPORT);
566     sqlite3_bind_int(searchAirports, 3, FGPositioned::SEAPORT);
567
568     getAllAirports = prepare("SELECT ident, name FROM positioned WHERE type>=?1 AND type <=?2");
569     sqlite3_bind_int(getAllAirports, 1, FGPositioned::AIRPORT);
570     sqlite3_bind_int(getAllAirports, 2, FGPositioned::SEAPORT);
571
572
573     getAirportItemByIdent = prepare("SELECT rowid FROM positioned WHERE airport=?1 AND ident=?2 AND type=?3");
574
575     findAirportRunway = prepare("SELECT airport, rowid FROM positioned WHERE ident=?2 AND type=?3 AND airport="
576                                 "(SELECT rowid FROM positioned WHERE type=?4 AND ident=?1)");
577     sqlite3_bind_int(findAirportRunway, 3, FGPositioned::RUNWAY);
578     sqlite3_bind_int(findAirportRunway, 4, FGPositioned::AIRPORT);
579
580     // three-way join to get the navaid ident and runway ident in a single select.
581     // we're joining positioned to itself by the navaid runway, with the complication
582     // that we need to join the navaids table to get the runway ID.
583     // we also need to filter by type to excluse glideslope (GS) matches
584     findILS = prepare("SELECT nav.rowid FROM positioned AS nav, positioned AS rwy, navaid WHERE "
585                       "nav.ident=?1 AND nav.airport=?2 AND rwy.ident=?3 "
586                       "AND rwy.rowid = navaid.runway AND navaid.rowid=nav.rowid "
587                       "AND (nav.type=?4 OR nav.type=?5)");
588
589     sqlite3_bind_int(findILS, 4, FGPositioned::ILS);
590     sqlite3_bind_int(findILS, 5, FGPositioned::LOC);
591
592   // airways
593     findAirway = prepare("SELECT rowid FROM airway WHERE network=?1 AND ident=?2");
594     insertAirway = prepare("INSERT INTO airway (ident, network) "
595                            "VALUES (?1, ?2)");
596
597     insertAirwayEdge = prepare("INSERT INTO airway_edge (network, airway, a, b) "
598                                "VALUES (?1, ?2, ?3, ?4)");
599
600     isPosInAirway = prepare("SELECT rowid FROM airway_edge WHERE network=?1 AND a=?2");
601
602     airwayEdgesFrom = prepare("SELECT airway, b FROM airway_edge WHERE network=?1 AND a=?2");
603
604     airwayEdges = prepare("SELECT a, b FROM airway_edge WHERE airway=?1");
605   }
606
607   void writeIntProperty(const string& key, int value)
608   {
609     sqlite_bind_stdstring(clearProperty, 1, key);
610     execUpdate(clearProperty);
611
612     sqlite_bind_stdstring(writePropertyQuery, 1, key);
613     sqlite3_bind_int(writePropertyQuery, 2, value);
614     execUpdate(writePropertyQuery);
615   }
616
617
618   FGPositioned* loadById(sqlite_int64 rowId, sqlite3_int64& aptId);
619
620   FGAirport* loadAirport(sqlite_int64 rowId,
621                          FGPositioned::Type ty,
622                          const string& id, const string& name, const SGGeod& pos)
623   {
624     sqlite3_bind_int64(loadAirportStmt, 1, rowId);
625     execSelect1(loadAirportStmt);
626     bool hasMetar = (sqlite3_column_int(loadAirportStmt, 0) > 0);
627     reset(loadAirportStmt);
628
629     return new FGAirport(rowId, id, pos, name, hasMetar, ty);
630   }
631
632   FGRunwayBase* loadRunway(sqlite3_int64 rowId, FGPositioned::Type ty,
633                            const string& id, const SGGeod& pos, PositionedID apt)
634   {
635     sqlite3_bind_int(loadRunwayStmt, 1, rowId);
636     execSelect1(loadRunwayStmt);
637
638     double heading = sqlite3_column_double(loadRunwayStmt, 0);
639     double lengthM = sqlite3_column_int(loadRunwayStmt, 1);
640     double widthM = sqlite3_column_double(loadRunwayStmt, 2);
641     int surface = sqlite3_column_int(loadRunwayStmt, 3);
642
643     if (ty == FGPositioned::TAXIWAY) {
644       reset(loadRunwayStmt);
645       return new FGTaxiway(rowId, id, pos, heading, lengthM, widthM, surface);
646     } else if (ty == FGPositioned::HELIPAD) {
647         reset(loadRunwayStmt);
648         return new FGHelipad(rowId, apt, id, pos, heading, lengthM, widthM, surface);
649     } else {
650       double displacedThreshold = sqlite3_column_double(loadRunwayStmt, 4);
651       double stopway = sqlite3_column_double(loadRunwayStmt, 5);
652       PositionedID reciprocal = sqlite3_column_int64(loadRunwayStmt, 6);
653       PositionedID ils = sqlite3_column_int64(loadRunwayStmt, 7);
654       FGRunway* r = new FGRunway(rowId, apt, id, pos, heading, lengthM, widthM,
655                           displacedThreshold, stopway, surface);
656
657       if (reciprocal > 0) {
658         r->setReciprocalRunway(reciprocal);
659       }
660
661       if (ils > 0) {
662         r->setILS(ils);
663       }
664
665       reset(loadRunwayStmt);
666       return r;
667     }
668   }
669
670   CommStation* loadComm(sqlite3_int64 rowId, FGPositioned::Type ty,
671                         const string& id, const string& name,
672                         const SGGeod& pos,
673                         PositionedID airport)
674   {
675     sqlite3_bind_int64(loadCommStation, 1, rowId);
676     execSelect1(loadCommStation);
677
678     int range = sqlite3_column_int(loadCommStation, 0);
679     int freqKhz = sqlite3_column_int(loadCommStation, 1);
680     reset(loadCommStation);
681
682     CommStation* c = new CommStation(rowId, name, ty, pos, freqKhz, range);
683     c->setAirport(airport);
684     return c;
685   }
686
687   FGPositioned* loadNav(sqlite3_int64 rowId,
688                        FGPositioned::Type ty, const string& id,
689                        const string& name, const SGGeod& pos)
690   {
691     sqlite3_bind_int64(loadNavaid, 1, rowId);
692     execSelect1(loadNavaid);
693
694     PositionedID runway = sqlite3_column_int64(loadNavaid, 3);
695     // marker beacons are light-weight
696     if ((ty == FGPositioned::OM) || (ty == FGPositioned::IM) ||
697         (ty == FGPositioned::MM))
698     {
699       reset(loadNavaid);
700       return new FGMarkerBeaconRecord(rowId, ty, runway, pos);
701     }
702
703     int rangeNm = sqlite3_column_int(loadNavaid, 0),
704     freq = sqlite3_column_int(loadNavaid, 1);
705     double mulituse = sqlite3_column_double(loadNavaid, 2);
706     PositionedID colocated = sqlite3_column_int64(loadNavaid, 4);
707     reset(loadNavaid);
708
709     FGNavRecord* n =
710       (ty == FGPositioned::MOBILE_TACAN)
711       ? new FGMobileNavRecord
712             (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway)
713       : new FGNavRecord
714             (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway);
715
716     if (colocated)
717       n->setColocatedDME(colocated);
718
719     return n;
720   }
721
722   PositionedID insertPositioned(FGPositioned::Type ty, const string& ident,
723                                 const string& name, const SGGeod& pos, PositionedID apt,
724                                 bool spatialIndex)
725   {
726     SGVec3d cartPos(SGVec3d::fromGeod(pos));
727
728     sqlite3_bind_int(insertPositionedQuery, 1, ty);
729     sqlite_bind_stdstring(insertPositionedQuery, 2, ident);
730     sqlite_bind_stdstring(insertPositionedQuery, 3, name);
731     sqlite3_bind_int64(insertPositionedQuery, 4, apt);
732     sqlite3_bind_double(insertPositionedQuery, 5, pos.getLongitudeDeg());
733     sqlite3_bind_double(insertPositionedQuery, 6, pos.getLatitudeDeg());
734     sqlite3_bind_double(insertPositionedQuery, 7, pos.getElevationM());
735
736     if (spatialIndex) {
737       Octree::Leaf* octreeLeaf = Octree::global_spatialOctree->findLeafForPos(cartPos);
738       assert(intersects(octreeLeaf->bbox(), cartPos));
739       sqlite3_bind_int64(insertPositionedQuery, 8, octreeLeaf->guid());
740     } else {
741       sqlite3_bind_null(insertPositionedQuery, 8);
742     }
743
744     sqlite3_bind_double(insertPositionedQuery, 9, cartPos.x());
745     sqlite3_bind_double(insertPositionedQuery, 10, cartPos.y());
746     sqlite3_bind_double(insertPositionedQuery, 11, cartPos.z());
747
748     PositionedID r = execInsert(insertPositionedQuery);
749     return r;
750   }
751
752   FGPositionedList findAllByString(const string& s, const string& column,
753                                      FGPositioned::Filter* filter, bool exact)
754   {
755     string query = s;
756     if (!exact) query += "%";
757
758   // build up SQL query text
759     string matchTerm = exact ? "=?1" : " LIKE ?1";
760     string sql = "SELECT rowid FROM positioned WHERE " + column + matchTerm;
761     if (filter) {
762       sql += " " AND_TYPED;
763     }
764
765   // find or prepare a suitable statement frrm the SQL
766     sqlite3_stmt_ptr stmt = findByStringDict[sql];
767     if (!stmt) {
768       stmt = prepare(sql);
769       findByStringDict[sql] = stmt;
770     }
771
772     sqlite_bind_stdstring(stmt, 1, query);
773     if (filter) {
774       sqlite3_bind_int(stmt, 2, filter->minType());
775       sqlite3_bind_int(stmt, 3, filter->maxType());
776     }
777
778     FGPositionedList result;
779   // run the prepared SQL
780     while (stepSelect(stmt))
781     {
782       FGPositioned* pos = outer->loadById(sqlite3_column_int64(stmt, 0));
783       if (filter && !filter->pass(pos)) {
784         continue;
785       }
786
787       result.push_back(pos);
788     }
789
790     reset(stmt);
791     return result;
792   }
793
794   PositionedIDVec selectIds(sqlite3_stmt_ptr query)
795   {
796     PositionedIDVec result;
797     while (stepSelect(query)) {
798       result.push_back(sqlite3_column_int64(query, 0));
799     }
800     reset(query);
801     return result;
802   }
803
804   double runwayLengthFt(PositionedID rwy)
805   {
806     sqlite3_bind_int64(runwayLengthFtQuery, 1, rwy);
807     execSelect1(runwayLengthFtQuery);
808     double length = sqlite3_column_double(runwayLengthFtQuery, 0);
809     reset(runwayLengthFtQuery);
810     return length;
811   }
812
813   void flushDeferredOctreeUpdates()
814   {
815     BOOST_FOREACH(Octree::Branch* nd, deferredOctreeUpdates) {
816       sqlite3_bind_int64(updateOctreeChildren, 1, nd->guid());
817       sqlite3_bind_int(updateOctreeChildren, 2, nd->childMask());
818       execUpdate(updateOctreeChildren);
819     }
820
821     deferredOctreeUpdates.clear();
822   }
823
824   void removePositionedWithIdent(FGPositioned::Type ty, const std::string& aIdent)
825   {
826     sqlite3_bind_int(removePOIQuery, 1, ty);
827     sqlite_bind_stdstring(removePOIQuery, 2, aIdent);
828     execUpdate(removePOIQuery);
829     reset(removePOIQuery);
830   }
831
832   NavDataCache* outer;
833   sqlite3* db;
834   SGPath path;
835     bool readOnly;
836
837   /// the actual cache of ID -> instances. This holds an owning reference,
838   /// so once items are in the cache they will never be deleted until
839   /// the cache drops its reference
840   PositionedCache cache;
841   unsigned int cacheHits, cacheMisses;
842
843   /**
844    * record the levels of open transaction objects we have
845    */
846   unsigned int transactionLevel;
847   bool transactionAborted;
848   sqlite3_stmt_ptr beginTransactionStmt, commitTransactionStmt, rollbackTransactionStmt;
849
850   SGPath aptDatPath, metarDatPath, navDatPath, fixDatPath, poiDatPath,
851   carrierDatPath, airwayDatPath;
852
853   sqlite3_stmt_ptr readPropertyQuery, writePropertyQuery,
854     stampFileCache, statCacheCheck,
855     loadAirportStmt, loadCommStation, loadPositioned, loadNavaid,
856     loadRunwayStmt;
857   sqlite3_stmt_ptr writePropertyMulti, clearProperty;
858
859   sqlite3_stmt_ptr insertPositionedQuery, insertAirport, insertTower, insertRunway,
860   insertCommStation, insertNavaid;
861   sqlite3_stmt_ptr setAirportMetar, setRunwayReciprocal, setRunwayILS, setNavaidColocated,
862     setAirportPos;
863   sqlite3_stmt_ptr removePOIQuery;
864
865   sqlite3_stmt_ptr findClosestWithIdent;
866 // octree (spatial index) related queries
867   sqlite3_stmt_ptr getOctreeChildren, insertOctree, updateOctreeChildren,
868     getOctreeLeafChildren;
869
870   sqlite3_stmt_ptr searchAirports, getAllAirports;
871   sqlite3_stmt_ptr findCommByFreq, findNavsByFreq,
872   findNavsByFreqNoPos, findNavaidForRunway;
873   sqlite3_stmt_ptr getAirportItems, getAirportItemByIdent;
874   sqlite3_stmt_ptr findAirportRunway,
875     findILS;
876
877   sqlite3_stmt_ptr runwayLengthFtQuery;
878
879 // airways
880   sqlite3_stmt_ptr findAirway, insertAirwayEdge,
881     isPosInAirway, airwayEdgesFrom,
882     insertAirway, airwayEdges;
883
884 // since there's many permutations of ident/name queries, we create
885 // them programtically, but cache the exact query by its raw SQL once
886 // used.
887   std::map<string, sqlite3_stmt_ptr> findByStringDict;
888
889   typedef std::vector<sqlite3_stmt_ptr> StmtVec;
890   StmtVec prepared;
891
892   std::set<Octree::Branch*> deferredOctreeUpdates;
893
894   // if we're performing a rebuild, the thread that is doing the work.
895   // otherwise, NULL
896   std::auto_ptr<RebuildThread> rebuilder;
897 };
898
899 //////////////////////////////////////////////////////////////////////
900
901 FGPositioned* NavDataCache::NavDataCachePrivate::loadById(sqlite3_int64 rowid,
902                                                           sqlite3_int64& aptId)
903 {
904
905   sqlite3_bind_int64(loadPositioned, 1, rowid);
906   execSelect1(loadPositioned);
907
908   assert(rowid == sqlite3_column_int64(loadPositioned, 0));
909   FGPositioned::Type ty = (FGPositioned::Type) sqlite3_column_int(loadPositioned, 1);
910
911   PositionedID prowid = static_cast<PositionedID>(rowid);
912   string ident = (char*) sqlite3_column_text(loadPositioned, 2);
913   string name = (char*) sqlite3_column_text(loadPositioned, 3);
914   aptId = sqlite3_column_int64(loadPositioned, 4);
915   double lon = sqlite3_column_double(loadPositioned, 5);
916   double lat = sqlite3_column_double(loadPositioned, 6);
917   double elev = sqlite3_column_double(loadPositioned, 7);
918   SGGeod pos = SGGeod::fromDegM(lon, lat, elev);
919
920   reset(loadPositioned);
921
922   switch (ty) {
923     case FGPositioned::AIRPORT:
924     case FGPositioned::SEAPORT:
925     case FGPositioned::HELIPORT:
926       return loadAirport(rowid, ty, ident, name, pos);
927
928     case FGPositioned::TOWER:
929       return new AirportTower(prowid, aptId, ident, pos);
930
931     case FGPositioned::RUNWAY:
932     case FGPositioned::HELIPAD:
933     case FGPositioned::TAXIWAY:
934       return loadRunway(rowid, ty, ident, pos, aptId);
935
936     case FGPositioned::LOC:
937     case FGPositioned::VOR:
938     case FGPositioned::GS:
939     case FGPositioned::ILS:
940     case FGPositioned::NDB:
941     case FGPositioned::OM:
942     case FGPositioned::MM:
943     case FGPositioned::IM:
944     case FGPositioned::DME:
945     case FGPositioned::TACAN:
946     case FGPositioned::MOBILE_TACAN:
947       return loadNav(rowid, ty, ident, name, pos);
948
949     case FGPositioned::FIX:
950       return new FGFix(rowid, ident, pos);
951
952     case FGPositioned::WAYPOINT:
953     case FGPositioned::COUNTRY:
954     case FGPositioned::CITY:
955     case FGPositioned::TOWN:
956     case FGPositioned::VILLAGE:
957     {
958         FGPositioned* wpt = new FGPositioned(rowid, ty, ident, pos);
959       return wpt;
960     }
961
962     case FGPositioned::FREQ_GROUND:
963     case FGPositioned::FREQ_TOWER:
964     case FGPositioned::FREQ_ATIS:
965     case FGPositioned::FREQ_AWOS:
966     case FGPositioned::FREQ_APP_DEP:
967     case FGPositioned::FREQ_ENROUTE:
968     case FGPositioned::FREQ_CLEARANCE:
969     case FGPositioned::FREQ_UNICOM:
970       return loadComm(rowid, ty, ident, name, pos, aptId);
971
972     default:
973       return NULL;
974   }
975 }
976
977 bool NavDataCache::NavDataCachePrivate::isCachedFileModified(const SGPath& path, bool verbose)
978 {
979   if (!path.exists()) {
980     throw sg_io_exception("isCachedFileModified: Missing file:" + path.str());
981   }
982
983   sqlite_bind_temp_stdstring(statCacheCheck, 1, path.str());
984   bool isModified = true;
985   sgDebugPriority logLevel = verbose ? SG_WARN : SG_DEBUG;
986   if (execSelect(statCacheCheck)) {
987     time_t modtime = sqlite3_column_int64(statCacheCheck, 0);
988     time_t delta = std::labs(modtime - path.modTime());
989     if (delta != 0)
990     {
991       SG_LOG(SG_NAVCACHE, logLevel, "NavCache: rebuild required for " << path <<
992              ". Timestamps: " << modtime << " != " << path.modTime());
993     }
994     else
995     {
996       SG_LOG(SG_NAVCACHE, SG_DEBUG, "NavCache: no rebuild required for " << path);
997     }
998
999     isModified = (delta != 0);
1000   } else {
1001     SG_LOG(SG_NAVCACHE, logLevel, "NavCache: initial build required for " << path);
1002   }
1003
1004   reset(statCacheCheck);
1005   return isModified;
1006 }
1007
1008 static NavDataCache* static_instance = NULL;
1009
1010 NavDataCache::NavDataCache()
1011 {
1012   const int MAX_TRIES = 3;
1013   SGPath homePath(globals->get_fg_home());
1014
1015   std::ostringstream os;
1016   string_list versionParts = simgear::strutils::split(VERSION, ".");
1017   if (versionParts.size() < 2) {
1018     os << "navdata.cache";
1019   } else {
1020     os << "navdata_" << versionParts[0] << "_" << versionParts[1] << ".cache";
1021   }
1022
1023   homePath.append(os.str());
1024
1025     // permit additional DB connections from the same process
1026     sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
1027
1028   for (int t=0; t < MAX_TRIES; ++t) {
1029     try {
1030       d.reset(new NavDataCachePrivate(homePath, this));
1031       d->init();
1032       //d->checkCacheFile();
1033     // reached this point with no exception, success
1034       break;
1035     } catch (sg_exception& e) {
1036       SG_LOG(SG_NAVCACHE, t == 0 ? SG_WARN : SG_ALERT, "NavCache: init failed:" << e.what()
1037              << " (attempt " << t << ")");
1038       d.reset();
1039
1040         // only wipe the existing if not readonly
1041         if (!fgGetBool("/sim/fghome-readonly", false)) {
1042             homePath.remove();
1043         }
1044     }
1045   } // of retry loop
1046
1047   double RADIUS_EARTH_M = 7000 * 1000.0; // 7000km is plenty
1048   SGVec3d earthExtent(RADIUS_EARTH_M, RADIUS_EARTH_M, RADIUS_EARTH_M);
1049   Octree::global_spatialOctree =
1050     new Octree::Branch(SGBox<double>(-earthExtent, earthExtent), 1);
1051
1052   d->aptDatPath = SGPath(globals->get_fg_root());
1053   d->aptDatPath.append("Airports/apt.dat.gz");
1054
1055   d->metarDatPath = SGPath(globals->get_fg_root());
1056   d->metarDatPath.append("Airports/metar.dat.gz");
1057
1058   d->navDatPath = SGPath(globals->get_fg_root());
1059   d->navDatPath.append("Navaids/nav.dat.gz");
1060
1061   d->fixDatPath = SGPath(globals->get_fg_root());
1062   d->fixDatPath.append("Navaids/fix.dat.gz");
1063
1064   d->poiDatPath = SGPath(globals->get_fg_root());
1065   d->poiDatPath.append("Navaids/poi.dat.gz");
1066
1067   d->carrierDatPath = SGPath(globals->get_fg_root());
1068   d->carrierDatPath.append("Navaids/carrier_nav.dat.gz");
1069
1070   d->airwayDatPath = SGPath(globals->get_fg_root());
1071   d->airwayDatPath.append("Navaids/awy.dat.gz");
1072 }
1073
1074 NavDataCache::~NavDataCache()
1075 {
1076   assert(static_instance == this);
1077   static_instance = NULL;
1078   d.reset();
1079 }
1080
1081 NavDataCache* NavDataCache::createInstance()
1082 {
1083     static_instance = new NavDataCache;
1084     return static_instance;
1085 }
1086
1087 NavDataCache* NavDataCache::instance()
1088 {
1089   return static_instance;
1090 }
1091
1092 bool NavDataCache::isRebuildRequired()
1093 {
1094     if (d->readOnly) {
1095         return false;
1096     }
1097
1098     if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
1099         SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: restore-defaults requested, will rebuild cache");
1100         return true;
1101     }
1102
1103   if (d->isCachedFileModified(d->aptDatPath, true) ||
1104       d->isCachedFileModified(d->metarDatPath, true) ||
1105       d->isCachedFileModified(d->navDatPath, true) ||
1106       d->isCachedFileModified(d->fixDatPath, true) ||
1107       d->isCachedFileModified(d->carrierDatPath, true) ||
1108 // since POI loading is disabled on Windows, don't check for it
1109 // this caused: https://code.google.com/p/flightgear-bugs/issues/detail?id=1227
1110 #ifndef SG_WINDOWS
1111       d->isCachedFileModified(d->poiDatPath, true) ||
1112 #endif
1113       d->isCachedFileModified(d->airwayDatPath, true))
1114   {
1115     SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: main cache rebuild required");
1116     return true;
1117   }
1118
1119   SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: no main cache rebuild required");
1120   return false;
1121 }
1122
1123 NavDataCache::RebuildPhase NavDataCache::rebuild()
1124 {
1125     if (!d->rebuilder.get()) {
1126         d->rebuilder.reset(new RebuildThread(this));
1127         d->rebuilder->start();
1128     }
1129
1130     // poll the rebuild thread
1131     RebuildPhase phase = d->rebuilder->currentPhase();
1132     if (phase == REBUILD_DONE) {
1133         d->rebuilder.reset(); // all done!
1134     }
1135     return phase;
1136 }
1137
1138 unsigned int NavDataCache::rebuildPhaseCompletionPercentage() const
1139 {
1140     if (!d->rebuilder.get()) {
1141         return 0;
1142     }
1143
1144     return d->rebuilder->completionPercent();
1145 }
1146
1147 void NavDataCache::setRebuildPhaseProgress(RebuildPhase ph, unsigned int percent)
1148 {
1149     if (!d->rebuilder.get()) {
1150         return;
1151     }
1152
1153     d->rebuilder->setProgress(ph, percent);
1154 }
1155
1156 void NavDataCache::doRebuild()
1157 {
1158   try {
1159     d->close(); // completely close the sqlite object
1160     d->path.remove(); // remove the file on disk
1161     d->init(); // start again from scratch
1162
1163     // initialise the root octree node
1164     d->runSQL("INSERT INTO octree (rowid, children) VALUES (1, 0)");
1165
1166     SGTimeStamp st;
1167     {
1168         Transaction txn(this);
1169
1170         st.stamp();
1171         airportDBLoad(d->aptDatPath);
1172         SG_LOG(SG_NAVCACHE, SG_INFO, "apt.dat load took:" << st.elapsedMSec());
1173
1174         setRebuildPhaseProgress(REBUILD_UNKNOWN);
1175         metarDataLoad(d->metarDatPath);
1176         stampCacheFile(d->aptDatPath);
1177         stampCacheFile(d->metarDatPath);
1178
1179         st.stamp();
1180         loadFixes(d->fixDatPath);
1181         stampCacheFile(d->fixDatPath);
1182         SG_LOG(SG_NAVCACHE, SG_INFO, "fix.dat load took:" << st.elapsedMSec());
1183
1184         st.stamp();
1185         navDBInit(d->navDatPath);
1186         stampCacheFile(d->navDatPath);
1187         SG_LOG(SG_NAVCACHE, SG_INFO, "nav.dat load took:" << st.elapsedMSec());
1188
1189         setRebuildPhaseProgress(REBUILD_UNKNOWN);
1190         st.stamp();
1191         txn.commit();
1192         SG_LOG(SG_NAVCACHE, SG_INFO, "stage 1 commit took:" << st.elapsedMSec());
1193     }
1194
1195 #ifdef SG_WINDOWS
1196       SG_LOG(SG_NAVCACHE, SG_ALERT, "SKIPPING POI load on Windows");
1197 #else
1198       {
1199           Transaction txn(this);
1200
1201           st.stamp();
1202           poiDBInit(d->poiDatPath);
1203           stampCacheFile(d->poiDatPath);
1204           SG_LOG(SG_NAVCACHE, SG_INFO, "poi.dat load took:" << st.elapsedMSec());
1205
1206           setRebuildPhaseProgress(REBUILD_UNKNOWN);
1207           st.stamp();
1208           txn.commit();
1209           SG_LOG(SG_NAVCACHE, SG_INFO, "POI commit took:" << st.elapsedMSec());
1210       }
1211 #endif
1212
1213       {
1214           Transaction txn(this);
1215           loadCarrierNav(d->carrierDatPath);
1216           stampCacheFile(d->carrierDatPath);
1217
1218           st.stamp();
1219           Airway::load(d->airwayDatPath);
1220           stampCacheFile(d->airwayDatPath);
1221           SG_LOG(SG_NAVCACHE, SG_INFO, "awy.dat load took:" << st.elapsedMSec());
1222
1223           d->flushDeferredOctreeUpdates();
1224
1225           string sceneryPaths = simgear::strutils::join(globals->get_fg_scenery(), ";");
1226           writeStringProperty("scenery_paths", sceneryPaths);
1227
1228           st.stamp();
1229           txn.commit();
1230           SG_LOG(SG_NAVCACHE, SG_INFO, "final commit took:" << st.elapsedMSec());
1231
1232       }
1233
1234   } catch (sg_exception& e) {
1235     SG_LOG(SG_NAVCACHE, SG_ALERT, "caught exception rebuilding navCache:" << e.what());
1236   }
1237 }
1238
1239 int NavDataCache::readIntProperty(const string& key)
1240 {
1241   sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1242   int result = 0;
1243
1244   if (d->execSelect(d->readPropertyQuery)) {
1245     result = sqlite3_column_int(d->readPropertyQuery, 0);
1246   } else {
1247     SG_LOG(SG_NAVCACHE, SG_WARN, "readIntProperty: unknown:" << key);
1248   }
1249
1250   d->reset(d->readPropertyQuery);
1251   return result;
1252 }
1253
1254 double NavDataCache::readDoubleProperty(const string& key)
1255 {
1256   sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1257   double result = 0.0;
1258   if (d->execSelect(d->readPropertyQuery)) {
1259     result = sqlite3_column_double(d->readPropertyQuery, 0);
1260   } else {
1261     SG_LOG(SG_NAVCACHE, SG_WARN, "readDoubleProperty: unknown:" << key);
1262   }
1263
1264   d->reset(d->readPropertyQuery);
1265   return result;
1266 }
1267
1268 string NavDataCache::readStringProperty(const string& key)
1269 {
1270   sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1271   string result;
1272   if (d->execSelect(d->readPropertyQuery)) {
1273     result = (char*) sqlite3_column_text(d->readPropertyQuery, 0);
1274   } else {
1275     SG_LOG(SG_NAVCACHE, SG_WARN, "readStringProperty: unknown:" << key);
1276   }
1277
1278   d->reset(d->readPropertyQuery);
1279   return result;
1280 }
1281
1282 void NavDataCache::writeIntProperty(const string& key, int value)
1283 {
1284   d->writeIntProperty(key, value);
1285 }
1286
1287 void NavDataCache::writeStringProperty(const string& key, const string& value)
1288 {
1289   sqlite_bind_stdstring(d->clearProperty, 1, key);
1290   d->execUpdate(d->clearProperty);
1291
1292   sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1293   sqlite_bind_stdstring(d->writePropertyQuery, 2, value);
1294   d->execUpdate(d->writePropertyQuery);
1295 }
1296
1297 void NavDataCache::writeDoubleProperty(const string& key, const double& value)
1298 {
1299   sqlite_bind_stdstring(d->clearProperty, 1, key);
1300   d->execUpdate(d->clearProperty);
1301
1302   sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1303   sqlite3_bind_double(d->writePropertyQuery, 2, value);
1304   d->execUpdate(d->writePropertyQuery);
1305 }
1306
1307 string_list NavDataCache::readStringListProperty(const string& key)
1308 {
1309   sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1310   string_list result;
1311   while (d->stepSelect(d->readPropertyQuery)) {
1312     result.push_back((char*) sqlite3_column_text(d->readPropertyQuery, 0));
1313   }
1314   d->reset(d->readPropertyQuery);
1315
1316   return result;
1317 }
1318
1319 void NavDataCache::writeStringListProperty(const string& key, const string_list& values)
1320 {
1321   sqlite_bind_stdstring(d->clearProperty, 1, key);
1322   d->execUpdate(d->clearProperty);
1323
1324   BOOST_FOREACH(string value, values) {
1325     sqlite_bind_stdstring(d->writePropertyMulti, 1, key);
1326     sqlite_bind_stdstring(d->writePropertyMulti, 2, value);
1327     d->execInsert(d->writePropertyMulti);
1328   }
1329 }
1330
1331 bool NavDataCache::isCachedFileModified(const SGPath& path) const
1332 {
1333   return d->isCachedFileModified(path, false);
1334 }
1335
1336 void NavDataCache::stampCacheFile(const SGPath& path)
1337 {
1338   sqlite_bind_temp_stdstring(d->stampFileCache, 1, path.str());
1339   sqlite3_bind_int64(d->stampFileCache, 2, path.modTime());
1340   d->execInsert(d->stampFileCache);
1341 }
1342
1343 void NavDataCache::beginTransaction()
1344 {
1345   if (d->transactionLevel == 0) {
1346     d->transactionAborted = false;
1347     d->stepSelect(d->beginTransactionStmt);
1348     sqlite3_reset(d->beginTransactionStmt);
1349   }
1350
1351   ++d->transactionLevel;
1352 }
1353
1354 void NavDataCache::commitTransaction()
1355 {
1356   assert(d->transactionLevel > 0);
1357   if (--d->transactionLevel == 0) {
1358     // if a nested transaction aborted, we might end up here, but must
1359     // still abort the entire transaction. That's bad, but safer than
1360     // committing.
1361     sqlite3_stmt_ptr q = d->transactionAborted ? d->rollbackTransactionStmt : d->commitTransactionStmt;
1362
1363     int retries = 0;
1364     int result;
1365     while (retries < MAX_RETRIES) {
1366       result = sqlite3_step(q);
1367       if (result == SQLITE_DONE) {
1368         break;
1369       }
1370
1371       // see http://www.sqlite.org/c3ref/get_autocommit.html for a hint
1372       // what's going on here: autocommit in inactive inside BEGIN, so if
1373       // it's active, the DB was rolled-back
1374       if (sqlite3_get_autocommit(d->db)) {
1375         SG_LOG(SG_NAVCACHE, SG_ALERT, "commit: was rolled back!" << retries);
1376         d->transactionAborted = true;
1377         break;
1378       }
1379
1380       if (result != SQLITE_BUSY) {
1381         break;
1382       }
1383
1384       SGTimeStamp::sleepForMSec(++retries * 10);
1385       SG_LOG(SG_NAVCACHE, SG_ALERT, "NavCache contention on commit, will retry:" << retries);
1386     } // of retry loop for DB busy
1387
1388     string errMsg;
1389     if (result != SQLITE_DONE) {
1390       errMsg = sqlite3_errmsg(d->db);
1391       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " for  " << result
1392              << " while running:\n\t" << sqlite3_sql(q));
1393     }
1394
1395     sqlite3_reset(q);
1396   }
1397 }
1398
1399 void NavDataCache::abortTransaction()
1400 {
1401   SG_LOG(SG_NAVCACHE, SG_WARN, "NavCache: aborting transaction");
1402
1403   assert(d->transactionLevel > 0);
1404   if (--d->transactionLevel == 0) {
1405     d->stepSelect(d->rollbackTransactionStmt);
1406     sqlite3_reset(d->rollbackTransactionStmt);
1407   }
1408
1409   d->transactionAborted = true;
1410 }
1411
1412 FGPositionedRef NavDataCache::loadById(PositionedID rowid)
1413 {
1414   if (rowid == 0) {
1415     return NULL;
1416   }
1417
1418   PositionedCache::iterator it = d->cache.find(rowid);
1419   if (it != d->cache.end()) {
1420     d->cacheHits++;
1421     return it->second; // cache it
1422   }
1423
1424   sqlite3_int64 aptId;
1425   FGPositioned* pos = d->loadById(rowid, aptId);
1426   d->cache.insert(it, PositionedCache::value_type(rowid, pos));
1427   d->cacheMisses++;
1428
1429   // when we loaded an ILS, we must apply per-airport changes
1430   if ((pos->type() == FGPositioned::ILS) && (aptId > 0)) {
1431     FGAirport* apt = FGPositioned::loadById<FGAirport>(aptId);
1432     apt->validateILSData();
1433   }
1434
1435   return pos;
1436 }
1437
1438 PositionedID NavDataCache::insertAirport(FGPositioned::Type ty, const string& ident,
1439                                          const string& name)
1440 {
1441   // airports have their pos computed based on the avergae runway centres
1442   // so the pos isn't available immediately. Pass a dummy pos and avoid
1443   // doing spatial indexing until later
1444   sqlite3_int64 rowId = d->insertPositioned(ty, ident, name, SGGeod(),
1445                                             0 /* airport */,
1446                                             false /* spatial index */);
1447
1448   sqlite3_bind_int64(d->insertAirport, 1, rowId);
1449   d->execInsert(d->insertAirport);
1450
1451   return rowId;
1452 }
1453
1454 void NavDataCache::updatePosition(PositionedID item, const SGGeod &pos)
1455 {
1456   if (d->cache.find(item) != d->cache.end()) {
1457     SG_LOG(SG_NAVCACHE, SG_DEBUG, "updating position of an item in the cache");
1458     d->cache[item]->modifyPosition(pos);
1459   }
1460
1461   SGVec3d cartPos(SGVec3d::fromGeod(pos));
1462
1463   sqlite3_bind_int(d->setAirportPos, 1, item);
1464   sqlite3_bind_double(d->setAirportPos, 2, pos.getLongitudeDeg());
1465   sqlite3_bind_double(d->setAirportPos, 3, pos.getLatitudeDeg());
1466   sqlite3_bind_double(d->setAirportPos, 4, pos.getElevationM());
1467
1468 // bug 905; the octree leaf may change here, but the leaf may already be
1469 // loaded, and caching its children. (Either the old or new leaf!). Worse,
1470 // we may be called here as a result of loading one of those leaf's children.
1471 // instead of dealing with all those possibilites, such as modifying
1472 // the in-memory leaf's STL child container, we simply leave the runtime
1473 // structures alone. This is fine providing items do no move very far, since
1474 // all the spatial searches ultimately use the items' real cartesian position,
1475 // which was updated above.
1476   Octree::Leaf* octreeLeaf = Octree::global_spatialOctree->findLeafForPos(cartPos);
1477   sqlite3_bind_int64(d->setAirportPos, 5, octreeLeaf->guid());
1478
1479   sqlite3_bind_double(d->setAirportPos, 6, cartPos.x());
1480   sqlite3_bind_double(d->setAirportPos, 7, cartPos.y());
1481   sqlite3_bind_double(d->setAirportPos, 8, cartPos.z());
1482
1483
1484   d->execUpdate(d->setAirportPos);
1485 }
1486
1487 void NavDataCache::insertTower(PositionedID airportId, const SGGeod& pos)
1488 {
1489   d->insertPositioned(FGPositioned::TOWER, string(), string(),
1490                       pos, airportId, true /* spatial index */);
1491 }
1492
1493 PositionedID
1494 NavDataCache::insertRunway(FGPositioned::Type ty, const string& ident,
1495                            const SGGeod& pos, PositionedID apt,
1496                            double heading, double length, double width, double displacedThreshold,
1497                            double stopway, int surfaceCode)
1498 {
1499   // only runways are spatially indexed; don't bother indexing taxiways
1500   // or pavements
1501   bool spatialIndex = ( ty == FGPositioned::RUNWAY || ty == FGPositioned::HELIPAD);
1502
1503   sqlite3_int64 rowId = d->insertPositioned(ty, cleanRunwayNo(ident), "", pos, apt,
1504                                             spatialIndex);
1505   sqlite3_bind_int64(d->insertRunway, 1, rowId);
1506   sqlite3_bind_double(d->insertRunway, 2, heading);
1507   sqlite3_bind_double(d->insertRunway, 3, length);
1508   sqlite3_bind_double(d->insertRunway, 4, width);
1509   sqlite3_bind_int(d->insertRunway, 5, surfaceCode);
1510   sqlite3_bind_double(d->insertRunway, 6, displacedThreshold);
1511   sqlite3_bind_double(d->insertRunway, 7, stopway);
1512
1513   return d->execInsert(d->insertRunway);
1514 }
1515
1516 void NavDataCache::setRunwayReciprocal(PositionedID runway, PositionedID recip)
1517 {
1518   sqlite3_bind_int64(d->setRunwayReciprocal, 1, runway);
1519   sqlite3_bind_int64(d->setRunwayReciprocal, 2, recip);
1520   d->execUpdate(d->setRunwayReciprocal);
1521
1522 // and the opposite direction too!
1523   sqlite3_bind_int64(d->setRunwayReciprocal, 2, runway);
1524   sqlite3_bind_int64(d->setRunwayReciprocal, 1, recip);
1525   d->execUpdate(d->setRunwayReciprocal);
1526 }
1527
1528 void NavDataCache::setRunwayILS(PositionedID runway, PositionedID ils)
1529 {
1530   sqlite3_bind_int64(d->setRunwayILS, 1, runway);
1531   sqlite3_bind_int64(d->setRunwayILS, 2, ils);
1532   d->execUpdate(d->setRunwayILS);
1533
1534   // and the in-memory one
1535   if (d->cache.find(runway) != d->cache.end()) {
1536     FGRunway* instance = (FGRunway*) d->cache[runway].ptr();
1537     instance->setILS(ils);
1538   }
1539 }
1540
1541 PositionedID
1542 NavDataCache::insertNavaid(FGPositioned::Type ty, const string& ident,
1543                           const string& name, const SGGeod& pos,
1544                            int freq, int range, double multiuse,
1545                            PositionedID apt, PositionedID runway)
1546 {
1547   bool spatialIndex = true;
1548   if (ty == FGPositioned::MOBILE_TACAN) {
1549     spatialIndex = false;
1550   }
1551
1552   sqlite3_int64 rowId = d->insertPositioned(ty, ident, name, pos, apt,
1553                                             spatialIndex);
1554   sqlite3_bind_int64(d->insertNavaid, 1, rowId);
1555   sqlite3_bind_int(d->insertNavaid, 2, freq);
1556   sqlite3_bind_int(d->insertNavaid, 3, range);
1557   sqlite3_bind_double(d->insertNavaid, 4, multiuse);
1558   sqlite3_bind_int64(d->insertNavaid, 5, runway);
1559   sqlite3_bind_int64(d->insertNavaid, 6, 0);
1560   return d->execInsert(d->insertNavaid);
1561 }
1562
1563 void NavDataCache::setNavaidColocated(PositionedID navaid, PositionedID colocatedDME)
1564 {
1565   // Update DB entries...
1566   sqlite3_bind_int64(d->setNavaidColocated, 1, navaid);
1567   sqlite3_bind_int64(d->setNavaidColocated, 2, colocatedDME);
1568   d->execUpdate(d->setNavaidColocated);
1569
1570   // ...and the in-memory copy of the navrecord
1571   if (d->cache.find(navaid) != d->cache.end()) {
1572     FGNavRecord* rec = (FGNavRecord*) d->cache[navaid].get();
1573     rec->setColocatedDME(colocatedDME);
1574   }
1575 }
1576
1577 PositionedID NavDataCache::insertCommStation(FGPositioned::Type ty,
1578                                              const string& name, const SGGeod& pos, int freq, int range,
1579                                              PositionedID apt)
1580 {
1581   sqlite3_int64 rowId = d->insertPositioned(ty, "", name, pos, apt, true);
1582   sqlite3_bind_int64(d->insertCommStation, 1, rowId);
1583   sqlite3_bind_int(d->insertCommStation, 2, freq);
1584   sqlite3_bind_int(d->insertCommStation, 3, range);
1585   return d->execInsert(d->insertCommStation);
1586 }
1587
1588 PositionedID NavDataCache::insertFix(const std::string& ident, const SGGeod& aPos)
1589 {
1590   return d->insertPositioned(FGPositioned::FIX, ident, string(), aPos, 0, true);
1591 }
1592
1593 PositionedID NavDataCache::createPOI(FGPositioned::Type ty, const std::string& ident, const SGGeod& aPos)
1594 {
1595   return d->insertPositioned(ty, ident, string(), aPos, 0,
1596                              true /* spatial index */);
1597 }
1598
1599 bool NavDataCache::removePOI(FGPositioned::Type ty, const std::string& aIdent)
1600 {
1601   d->removePositionedWithIdent(ty, aIdent);
1602   // should remove from the live cache too?
1603
1604     return true;
1605 }
1606
1607 void NavDataCache::setAirportMetar(const string& icao, bool hasMetar)
1608 {
1609   sqlite_bind_stdstring(d->setAirportMetar, 1, icao);
1610   sqlite3_bind_int(d->setAirportMetar, 2, hasMetar);
1611   d->execUpdate(d->setAirportMetar);
1612 }
1613
1614 //------------------------------------------------------------------------------
1615 FGPositionedList NavDataCache::findAllWithIdent( const string& s,
1616                                                  FGPositioned::Filter* filter,
1617                                                  bool exact )
1618 {
1619   return d->findAllByString(s, "ident", filter, exact);
1620 }
1621
1622 //------------------------------------------------------------------------------
1623 FGPositionedList NavDataCache::findAllWithName( const string& s,
1624                                                 FGPositioned::Filter* filter,
1625                                                 bool exact )
1626 {
1627   return d->findAllByString(s, "name", filter, exact);
1628 }
1629
1630 //------------------------------------------------------------------------------
1631 FGPositionedRef NavDataCache::findClosestWithIdent( const string& aIdent,
1632                                                     const SGGeod& aPos,
1633                                                     FGPositioned::Filter* aFilter )
1634 {
1635   sqlite_bind_stdstring(d->findClosestWithIdent, 1, aIdent);
1636   if (aFilter) {
1637     sqlite3_bind_int(d->findClosestWithIdent, 2, aFilter->minType());
1638     sqlite3_bind_int(d->findClosestWithIdent, 3, aFilter->maxType());
1639   } else { // full type range
1640     sqlite3_bind_int(d->findClosestWithIdent, 2, FGPositioned::INVALID);
1641     sqlite3_bind_int(d->findClosestWithIdent, 3, FGPositioned::LAST_TYPE);
1642   }
1643
1644   SGVec3d cartPos(SGVec3d::fromGeod(aPos));
1645   sqlite3_bind_double(d->findClosestWithIdent, 4, cartPos.x());
1646   sqlite3_bind_double(d->findClosestWithIdent, 5, cartPos.y());
1647   sqlite3_bind_double(d->findClosestWithIdent, 6, cartPos.z());
1648
1649   FGPositionedRef result;
1650
1651   while (d->stepSelect(d->findClosestWithIdent)) {
1652     FGPositioned* pos = loadById(sqlite3_column_int64(d->findClosestWithIdent, 0));
1653     if (aFilter && !aFilter->pass(pos)) {
1654       continue;
1655     }
1656
1657     result = pos;
1658     break;
1659   }
1660
1661   d->reset(d->findClosestWithIdent);
1662   return result;
1663 }
1664
1665
1666 int NavDataCache::getOctreeBranchChildren(int64_t octreeNodeId)
1667 {
1668   sqlite3_bind_int64(d->getOctreeChildren, 1, octreeNodeId);
1669   d->execSelect1(d->getOctreeChildren);
1670   int children = sqlite3_column_int(d->getOctreeChildren, 0);
1671   d->reset(d->getOctreeChildren);
1672   return children;
1673 }
1674
1675 void NavDataCache::defineOctreeNode(Octree::Branch* pr, Octree::Node* nd)
1676 {
1677   sqlite3_bind_int64(d->insertOctree, 1, nd->guid());
1678   d->execInsert(d->insertOctree);
1679
1680 #ifdef LAZY_OCTREE_UPDATES
1681   d->deferredOctreeUpdates.insert(pr);
1682 #else
1683   // lowest three bits of node ID are 0..7 index of the child in the parent
1684   int childIndex = nd->guid() & 0x07;
1685
1686   sqlite3_bind_int64(d->updateOctreeChildren, 1, pr->guid());
1687 // mask has bit N set where child N exists
1688   int childMask = 1 << childIndex;
1689   sqlite3_bind_int(d->updateOctreeChildren, 2, childMask);
1690   d->execUpdate(d->updateOctreeChildren);
1691 #endif
1692 }
1693
1694 TypedPositionedVec
1695 NavDataCache::getOctreeLeafChildren(int64_t octreeNodeId)
1696 {
1697   sqlite3_bind_int64(d->getOctreeLeafChildren, 1, octreeNodeId);
1698
1699   TypedPositionedVec r;
1700   while (d->stepSelect(d->getOctreeLeafChildren)) {
1701     FGPositioned::Type ty = static_cast<FGPositioned::Type>
1702       (sqlite3_column_int(d->getOctreeLeafChildren, 1));
1703     r.push_back(std::make_pair(ty,
1704                 sqlite3_column_int64(d->getOctreeLeafChildren, 0)));
1705   }
1706
1707   d->reset(d->getOctreeLeafChildren);
1708   return r;
1709 }
1710
1711
1712 /**
1713  * A special purpose helper (used by FGAirport::searchNamesAndIdents) to
1714  * implement the AirportList dialog. It's unfortunate that it needs to reside
1715  * here, but for now it's least ugly solution.
1716  */
1717 char** NavDataCache::searchAirportNamesAndIdents(const std::string& aFilter)
1718 {
1719   sqlite3_stmt_ptr stmt;
1720   unsigned int numMatches = 0, numAllocated = 16;
1721   string searchTerm("%" + aFilter + "%");
1722   if (aFilter.empty()) {
1723     stmt = d->getAllAirports;
1724     numAllocated = 4096; // start much larger for all airports
1725   } else {
1726     stmt = d->searchAirports;
1727     sqlite_bind_stdstring(stmt, 1, searchTerm);
1728   }
1729
1730   char** result = (char**) malloc(sizeof(char*) * numAllocated);
1731   while (d->stepSelect(stmt)) {
1732     if ((numMatches + 1) >= numAllocated) {
1733       numAllocated <<= 1; // double in size!
1734     // reallocate results array
1735       char** nresult = (char**) malloc(sizeof(char*) * numAllocated);
1736       memcpy(nresult, result, sizeof(char*) * numMatches);
1737       free(result);
1738       result = nresult;
1739     }
1740
1741     // nasty code to avoid excessive string copying and allocations.
1742     // We format results as follows (note whitespace!):
1743     //   ' name-of-airport-chars   (ident)'
1744     // so the total length is:
1745     //    1 + strlen(name) + 4 + strlen(icao) + 1 + 1 (for the null)
1746     // which gives a grand total of 7 + name-length + icao-length.
1747     // note the ident can be three letters (non-ICAO local strip), four
1748     // (default ICAO) or more (extended format ICAO)
1749     int nameLength = sqlite3_column_bytes(stmt, 1);
1750     int icaoLength = sqlite3_column_bytes(stmt, 0);
1751     char* entry = (char*) malloc(7 + nameLength + icaoLength);
1752     char* dst = entry;
1753     *dst++ = ' ';
1754     memcpy(dst, sqlite3_column_text(stmt, 1), nameLength);
1755     dst += nameLength;
1756     *dst++ = ' ';
1757     *dst++ = ' ';
1758     *dst++ = ' ';
1759     *dst++ = '(';
1760     memcpy(dst, sqlite3_column_text(stmt, 0), icaoLength);
1761     dst += icaoLength;
1762     *dst++ = ')';
1763     *dst++ = 0;
1764
1765     result[numMatches++] = entry;
1766   }
1767
1768   result[numMatches] = NULL; // end of list marker
1769   d->reset(stmt);
1770   return result;
1771 }
1772
1773 FGPositionedRef
1774 NavDataCache::findCommByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
1775 {
1776   sqlite3_bind_int(d->findCommByFreq, 1, freqKhz);
1777   if (aFilter) {
1778     sqlite3_bind_int(d->findCommByFreq, 2, aFilter->minType());
1779     sqlite3_bind_int(d->findCommByFreq, 3, aFilter->maxType());
1780   } else { // full type range
1781     sqlite3_bind_int(d->findCommByFreq, 2, FGPositioned::FREQ_GROUND);
1782     sqlite3_bind_int(d->findCommByFreq, 3, FGPositioned::FREQ_UNICOM);
1783   }
1784
1785   SGVec3d cartPos(SGVec3d::fromGeod(aPos));
1786   sqlite3_bind_double(d->findCommByFreq, 4, cartPos.x());
1787   sqlite3_bind_double(d->findCommByFreq, 5, cartPos.y());
1788   sqlite3_bind_double(d->findCommByFreq, 6, cartPos.z());
1789   FGPositionedRef result;
1790
1791   while (d->execSelect(d->findCommByFreq)) {
1792     FGPositioned* p = loadById(sqlite3_column_int64(d->findCommByFreq, 0));
1793     if (aFilter && !aFilter->pass(p)) {
1794       continue;
1795     }
1796
1797     result = p;
1798     break;
1799   }
1800
1801   d->reset(d->findCommByFreq);
1802   return result;
1803 }
1804
1805 PositionedIDVec
1806 NavDataCache::findNavaidsByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
1807 {
1808   sqlite3_bind_int(d->findNavsByFreq, 1, freqKhz);
1809   if (aFilter) {
1810     sqlite3_bind_int(d->findNavsByFreq, 2, aFilter->minType());
1811     sqlite3_bind_int(d->findNavsByFreq, 3, aFilter->maxType());
1812   } else { // full type range
1813     sqlite3_bind_int(d->findNavsByFreq, 2, FGPositioned::NDB);
1814     sqlite3_bind_int(d->findNavsByFreq, 3, FGPositioned::GS);
1815   }
1816
1817   SGVec3d cartPos(SGVec3d::fromGeod(aPos));
1818   sqlite3_bind_double(d->findNavsByFreq, 4, cartPos.x());
1819   sqlite3_bind_double(d->findNavsByFreq, 5, cartPos.y());
1820   sqlite3_bind_double(d->findNavsByFreq, 6, cartPos.z());
1821
1822   return d->selectIds(d->findNavsByFreq);
1823 }
1824
1825 PositionedIDVec
1826 NavDataCache::findNavaidsByFreq(int freqKhz, FGPositioned::Filter* aFilter)
1827 {
1828   sqlite3_bind_int(d->findNavsByFreqNoPos, 1, freqKhz);
1829   if (aFilter) {
1830     sqlite3_bind_int(d->findNavsByFreqNoPos, 2, aFilter->minType());
1831     sqlite3_bind_int(d->findNavsByFreqNoPos, 3, aFilter->maxType());
1832   } else { // full type range
1833     sqlite3_bind_int(d->findNavsByFreqNoPos, 2, FGPositioned::NDB);
1834     sqlite3_bind_int(d->findNavsByFreqNoPos, 3, FGPositioned::GS);
1835   }
1836
1837   return d->selectIds(d->findNavsByFreqNoPos);
1838 }
1839
1840 PositionedIDVec
1841 NavDataCache::airportItemsOfType(PositionedID apt,FGPositioned::Type ty,
1842                                  FGPositioned::Type maxTy)
1843 {
1844   if (maxTy == FGPositioned::INVALID) {
1845     maxTy = ty; // single-type range
1846   }
1847
1848   sqlite3_bind_int64(d->getAirportItems, 1, apt);
1849   sqlite3_bind_int(d->getAirportItems, 2, ty);
1850   sqlite3_bind_int(d->getAirportItems, 3, maxTy);
1851
1852   return d->selectIds(d->getAirportItems);
1853 }
1854
1855 PositionedID
1856 NavDataCache::airportItemWithIdent(PositionedID apt, FGPositioned::Type ty,
1857                                    const std::string& ident)
1858 {
1859   sqlite3_bind_int64(d->getAirportItemByIdent, 1, apt);
1860   sqlite_bind_stdstring(d->getAirportItemByIdent, 2, ident);
1861   sqlite3_bind_int(d->getAirportItemByIdent, 3, ty);
1862   PositionedID result = 0;
1863
1864   if (d->execSelect(d->getAirportItemByIdent)) {
1865     result = sqlite3_column_int64(d->getAirportItemByIdent, 0);
1866   }
1867
1868   d->reset(d->getAirportItemByIdent);
1869   return result;
1870 }
1871
1872 AirportRunwayPair
1873 NavDataCache::findAirportRunway(const std::string& aName)
1874 {
1875   if (aName.empty()) {
1876     return AirportRunwayPair();
1877   }
1878
1879   string_list parts = simgear::strutils::split(aName);
1880   if (parts.size() < 2) {
1881     SG_LOG(SG_NAVCACHE, SG_WARN, "findAirportRunway: malformed name:" << aName);
1882     return AirportRunwayPair();
1883   }
1884
1885   AirportRunwayPair result;
1886   sqlite_bind_stdstring(d->findAirportRunway, 1, parts[0]);
1887   sqlite_bind_stdstring(d->findAirportRunway, 2, cleanRunwayNo(parts[1]));
1888
1889   if (d->execSelect(d->findAirportRunway)) {
1890     result = AirportRunwayPair(sqlite3_column_int64(d->findAirportRunway, 0),
1891                       sqlite3_column_int64(d->findAirportRunway, 1));
1892
1893   } else {
1894     SG_LOG(SG_NAVCACHE, SG_WARN, "findAirportRunway: unknown airport/runway:" << aName);
1895   }
1896
1897   d->reset(d->findAirportRunway);
1898   return result;
1899 }
1900
1901 PositionedID
1902 NavDataCache::findILS(PositionedID airport, const string& aRunway, const string& navIdent)
1903 {
1904   string runway(cleanRunwayNo(aRunway));
1905
1906   sqlite_bind_stdstring(d->findILS, 1, navIdent);
1907   sqlite3_bind_int64(d->findILS, 2, airport);
1908   sqlite_bind_stdstring(d->findILS, 3, runway);
1909   PositionedID result = 0;
1910   if (d->execSelect(d->findILS)) {
1911     result = sqlite3_column_int64(d->findILS, 0);
1912   }
1913
1914   d->reset(d->findILS);
1915   return result;
1916 }
1917
1918 int NavDataCache::findAirway(int network, const string& aName)
1919 {
1920   sqlite3_bind_int(d->findAirway, 1, network);
1921   sqlite_bind_stdstring(d->findAirway, 2, aName);
1922
1923   int airway = 0;
1924   if (d->execSelect(d->findAirway)) {
1925     // already exists
1926     airway = sqlite3_column_int(d->findAirway, 0);
1927   } else {
1928     sqlite_bind_stdstring(d->insertAirway, 1, aName);
1929     sqlite3_bind_int(d->insertAirway, 2, network);
1930     airway = d->execInsert(d->insertAirway);
1931   }
1932
1933   d->reset(d->findAirway);
1934   return airway;
1935 }
1936
1937 void NavDataCache::insertEdge(int network, int airwayID, PositionedID from, PositionedID to)
1938 {
1939   // assume all edges are bidirectional for the moment
1940   for (int i=0; i<2; ++i) {
1941     sqlite3_bind_int(d->insertAirwayEdge, 1, network);
1942     sqlite3_bind_int(d->insertAirwayEdge, 2, airwayID);
1943     sqlite3_bind_int64(d->insertAirwayEdge, 3, from);
1944     sqlite3_bind_int64(d->insertAirwayEdge, 4, to);
1945     d->execInsert(d->insertAirwayEdge);
1946
1947     std::swap(from, to);
1948   }
1949 }
1950
1951 bool NavDataCache::isInAirwayNetwork(int network, PositionedID pos)
1952 {
1953   sqlite3_bind_int(d->isPosInAirway, 1, network);
1954   sqlite3_bind_int64(d->isPosInAirway, 2, pos);
1955   bool ok = d->execSelect(d->isPosInAirway);
1956   d->reset(d->isPosInAirway);
1957
1958   return ok;
1959 }
1960
1961 AirwayEdgeVec NavDataCache::airwayEdgesFrom(int network, PositionedID pos)
1962 {
1963   sqlite3_bind_int(d->airwayEdgesFrom, 1, network);
1964   sqlite3_bind_int64(d->airwayEdgesFrom, 2, pos);
1965
1966   AirwayEdgeVec result;
1967   while (d->stepSelect(d->airwayEdgesFrom)) {
1968     result.push_back(AirwayEdge(
1969                      sqlite3_column_int(d->airwayEdgesFrom, 0),
1970                      sqlite3_column_int64(d->airwayEdgesFrom, 1)
1971                      ));
1972   }
1973
1974   d->reset(d->airwayEdgesFrom);
1975   return result;
1976 }
1977
1978 PositionedIDVec NavDataCache::airwayWaypts(int id)
1979 {
1980     sqlite3_bind_int(d->airwayEdges, 1, id);
1981
1982     typedef std::pair<PositionedID, PositionedID> Edge;
1983     typedef std::deque<Edge> EdgeVec;
1984     typedef std::deque<PositionedID> PositionedIDDeque;
1985
1986 // build up the EdgeVec, order is arbitrary
1987     EdgeVec rawEdges;
1988     while (d->stepSelect(d->airwayEdges)) {
1989         rawEdges.push_back(Edge(sqlite3_column_int64(d->airwayEdges, 0),
1990                                 sqlite3_column_int64(d->airwayEdges, 1)
1991                                 ));
1992     }
1993
1994     d->reset(d->airwayEdges);
1995     if (rawEdges.empty()) {
1996         return PositionedIDVec();
1997     }
1998
1999 // linearize
2000     PositionedIDDeque linearAirway;
2001     PositionedID firstId = rawEdges.front().first,
2002         lastId = rawEdges.front().second;
2003     std::set<PositionedID> seen;
2004
2005     // first edge is trivial
2006     linearAirway.push_back(firstId);
2007     linearAirway.push_back(lastId);
2008     seen.insert(firstId);
2009     seen.insert(lastId);
2010     rawEdges.pop_front();
2011
2012     while (!rawEdges.empty()) {
2013         Edge e = rawEdges.front();
2014         rawEdges.pop_front();
2015
2016     // look for new segments
2017         if (e.first == firstId) {
2018             linearAirway.push_front(e.second);
2019             seen.insert(e.second);
2020             firstId = e.second;
2021             continue;
2022         }
2023
2024         if (e.first == lastId) {
2025             linearAirway.push_back(e.second);
2026             seen.insert(e.second);
2027             lastId = e.second;
2028             continue;
2029         }
2030
2031     // look for seen segments - presumed to be reversed internal edges
2032         if (seen.find(e.first) != seen.end()) {
2033             // if it's the inverse of interior edge, both ends must have been
2034             // seen. Otherwise it should have been an exterior edge and
2035             // handled by the case above.
2036             assert(seen.find(e.second) != seen.end());
2037             continue;
2038         }
2039
2040     // push back to try later on
2041         rawEdges.push_back(e);
2042     }
2043
2044     return PositionedIDVec(linearAirway.begin(), linearAirway.end());
2045 }
2046
2047 PositionedID NavDataCache::findNavaidForRunway(PositionedID runway, FGPositioned::Type ty)
2048 {
2049   sqlite3_bind_int64(d->findNavaidForRunway, 1, runway);
2050   sqlite3_bind_int(d->findNavaidForRunway, 2, ty);
2051
2052   PositionedID result = 0;
2053   if (d->execSelect(d->findNavaidForRunway)) {
2054     result = sqlite3_column_int64(d->findNavaidForRunway, 0);
2055   }
2056
2057   d->reset(d->findNavaidForRunway);
2058   return result;
2059 }
2060
2061 bool NavDataCache::isReadOnly() const
2062 {
2063     return d->readOnly;
2064 }
2065
2066 SGPath NavDataCache::path() const
2067 {
2068     return d->path;
2069 }
2070
2071 /////////////////////////////////////////////////////////////////////////////////////////
2072 // Transaction RAII object
2073
2074 NavDataCache::Transaction::Transaction(NavDataCache* cache) :
2075     _instance(cache),
2076     _committed(false)
2077 {
2078     assert(cache);
2079     _instance->beginTransaction();
2080 }
2081
2082 NavDataCache::Transaction::~Transaction()
2083 {
2084     if (!_committed) {
2085         SG_LOG(SG_NAVCACHE, SG_INFO, "aborting cache transaction!");
2086         _instance->abortTransaction();
2087     }
2088 }
2089
2090 void NavDataCache::Transaction::commit()
2091 {
2092     assert(!_committed);
2093     _committed = true;
2094     _instance->commitTransaction();
2095 }
2096
2097 /////////////////////////////////////////////////////////////////////////////
2098
2099 class NavDataCache::ThreadedGUISearch::ThreadedGUISearchPrivate : public SGThread
2100 {
2101 public:
2102     ThreadedGUISearchPrivate() :
2103         db(NULL),
2104         isComplete(false),
2105         quit(false)
2106     {}
2107
2108     virtual void run()
2109     {
2110         while (!quit) {
2111             int err = sqlite3_step(query);
2112             if (err == SQLITE_DONE) {
2113                 break;
2114             } else if (err == SQLITE_ROW) {
2115                 PositionedID r = sqlite3_column_int64(query, 0);
2116                 SGGuard<SGMutex> g(lock);
2117                 results.push_back(r);
2118             } else if (err == SQLITE_BUSY) {
2119                 // sleep a tiny amount
2120                 SGTimeStamp::sleepForMSec(1);
2121             } else {
2122                 std::string errMsg = sqlite3_errmsg(db);
2123                 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running threaded search query");
2124             }
2125         }
2126
2127         SGGuard<SGMutex> g(lock);
2128         isComplete = true;
2129     }
2130
2131     SGMutex lock;
2132     sqlite3* db;
2133     sqlite3_stmt_ptr query;
2134     PositionedIDVec results;
2135     bool isComplete;
2136     bool quit;
2137 };
2138
2139 NavDataCache::ThreadedGUISearch::ThreadedGUISearch(const std::string& term) :
2140     d(new ThreadedGUISearchPrivate)
2141 {
2142     SGPath p = NavDataCache::instance()->path();
2143     int openFlags = SQLITE_OPEN_READONLY;
2144     std::string pathUtf8 = simgear::strutils::convertWindowsLocal8BitToUtf8(p.str());
2145     sqlite3_open_v2(pathUtf8.c_str(), &d->db, openFlags, NULL);
2146
2147     std::string sql = "SELECT rowid FROM positioned WHERE name LIKE '%" + term
2148         + "%' AND ((type >= 1 AND type <= 3) OR ((type >= 9 AND type <= 11))) ";
2149     sqlite3_prepare_v2(d->db, sql.c_str(), sql.length(), &d->query, NULL);
2150
2151     d->start();
2152 }
2153
2154 NavDataCache::ThreadedGUISearch::~ThreadedGUISearch()
2155 {
2156     {
2157         SGGuard<SGMutex> g(d->lock);
2158         d->quit = true;
2159     }
2160
2161     d->join();
2162     sqlite3_finalize(d->query);
2163     sqlite3_close_v2(d->db);
2164 }
2165
2166 PositionedIDVec NavDataCache::ThreadedGUISearch::results() const
2167 {
2168     PositionedIDVec r;
2169     {
2170         SGGuard<SGMutex> g(d->lock);
2171         r = d->results;
2172     }
2173     return r;
2174 }
2175
2176 bool NavDataCache::ThreadedGUISearch::isComplete() const
2177 {
2178     SGGuard<SGMutex> g(d->lock);
2179     return d->isComplete;
2180 }
2181
2182 } // of namespace flightgear