]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/NavDataCache.cxx
ea83e861d03db1c08e7599910429a1e23c559b58
[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 #include <sstream>  // for std::ostringstream
33 // boost
34 #include <boost/foreach.hpp>
35
36
37 #ifdef SYSTEM_SQLITE
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.
41   #include "sqlite3.h"
42 #else
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
47
48   #include "fg_sqlite3.h"
49 #endif
50
51 // SimGear
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>
60
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>
69 #include "fix.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>
75 #include "poidb.hxx"
76 #include <Airports/parking.hxx>
77 #include <Airports/gnnode.hxx>
78 #include "CacheSchema.h"
79
80 using std::string;
81
82 #define SG_NAVCACHE SG_NAVAID
83 //#define LAZY_OCTREE_UPDATES 1
84
85 namespace {
86
87 const int MAX_RETRIES = 10;
88
89 const int CACHE_SIZE_KBYTES= 32 * 1024;
90
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)
96 {
97   sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_STATIC);
98 }
99
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)
103 {
104   sqlite3_bind_text(stmt, value, s.c_str(), s.length(), SQLITE_TRANSIENT);
105 }
106
107 typedef sqlite3_stmt* sqlite3_stmt_ptr;
108
109 void f_distanceCartSqrFunction(sqlite3_context* ctx, int argc, sqlite3_value* argv[])
110 {
111   if (argc != 6) {
112     return;
113   }
114
115   SGVec3d posA(sqlite3_value_double(argv[0]),
116                sqlite3_value_double(argv[1]),
117                sqlite3_value_double(argv[2]));
118
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));
123 }
124
125
126 static string cleanRunwayNo(const string& aRwyNo)
127 {
128   if (aRwyNo[0] == 'x') {
129     return string(); // no ident for taxiways
130   }
131
132   string result(aRwyNo);
133   // canonicalise runway ident
134   if ((aRwyNo.size() == 1) || !isdigit(aRwyNo[1])) {
135     result = "0" + aRwyNo;
136   }
137
138   // trim off trailing garbage
139   if (result.size() > 2) {
140     char suffix = toupper(result[2]);
141     if (suffix == 'X') {
142       result = result.substr(0, 2);
143     }
144   }
145
146   return result;
147 }
148
149 } // anonymous namespace
150
151 namespace flightgear
152 {
153
154 /**
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
160  */
161 class RebuildThread : public SGThread
162 {
163 public:
164   RebuildThread(NavDataCache* cache) :
165   _cache(cache),
166     _phase(NavDataCache::REBUILD_UNKNOWN),
167     _completionPercent(0),
168   _isFinished(false)
169   {
170
171   }
172
173   bool isFinished() const
174   {
175     SGGuard<SGMutex> g(_lock);
176     return _isFinished;
177   }
178
179   virtual void run()
180   {
181     SGTimeStamp st;
182     st.stamp();
183     _cache->doRebuild();
184     SG_LOG(SG_NAVCACHE, SG_INFO, "cache rebuild took:" << st.elapsedMSec() << "msec");
185
186     SGGuard<SGMutex> g(_lock);
187     _isFinished = true;
188     _phase = NavDataCache::REBUILD_DONE;
189   }
190
191     NavDataCache::RebuildPhase currentPhase() const
192     {
193         NavDataCache::RebuildPhase ph;
194         SGGuard<SGMutex> g(_lock);
195         ph = _phase;
196         return ph;
197     }
198
199     unsigned int completionPercent() const
200     {
201         unsigned int perc = 0;
202         SGGuard<SGMutex> g(_lock);
203         perc = _completionPercent;
204         return perc;
205     }
206
207     void setProgress(NavDataCache::RebuildPhase ph, unsigned int percent)
208     {
209         SGGuard<SGMutex> g(_lock);
210         _phase = ph;
211         _completionPercent = percent;
212     }
213
214 private:
215   NavDataCache* _cache;
216     NavDataCache::RebuildPhase _phase;
217     unsigned int _completionPercent;
218   mutable SGMutex _lock;
219   bool _isFinished;
220 };
221
222 ////////////////////////////////////////////////////////////////////////////
223
224 typedef std::map<PositionedID, FGPositionedRef> PositionedCache;
225
226 class AirportTower : public FGPositioned
227 {
228 public:
229   AirportTower(PositionedID& guid, PositionedID airport,
230                const string& ident, const SGGeod& pos) :
231     FGPositioned(guid, FGPositioned::TOWER, ident, pos)
232   {
233   }
234 };
235
236 class NavDataCache::NavDataCachePrivate
237 {
238 public:
239   NavDataCachePrivate(const SGPath& p, NavDataCache* o) :
240     outer(o),
241     db(NULL),
242     path(p),
243     readOnly(false),
244     cacheHits(0),
245     cacheMisses(0),
246     transactionLevel(0),
247     transactionAborted(false)
248   {
249   }
250
251   ~NavDataCachePrivate()
252   {
253     close();
254   }
255
256   void init()
257   {
258     SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache at:" << path);
259
260       readOnly = fgGetBool("/sim/fghome-readonly", false);
261
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 = simgear::strutils::convertWindowsLocal8BitToUtf8(path.str());
267     sqlite3_open_v2(pathUtf8.c_str(), &db, openFlags, NULL);
268
269     sqlite3_stmt_ptr checkTables =
270       prepare("SELECT count(*) FROM sqlite_master WHERE name='properties'");
271
272     sqlite3_create_function(db, "distanceCartSqr", 6, SQLITE_ANY, NULL,
273                             f_distanceCartSqrFunction, NULL, NULL);
274
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");
279       initTables();
280       didCreate = true;
281     }
282
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");
286
287     if (didCreate) {
288       writeIntProperty("schema-version", SCHEMA_VERSION);
289     } else {
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");
294       }
295     }
296
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 << ";";
301     runSQL(q.str());
302     prepareQueries();
303   }
304
305   void close()
306   {
307     BOOST_FOREACH(sqlite3_stmt_ptr stmt, prepared) {
308       sqlite3_finalize(stmt);
309     }
310     prepared.clear();
311     sqlite3_close(db);
312   }
313
314   void checkCacheFile()
315   {
316     SG_LOG(SG_NAVCACHE, SG_INFO, "running DB integrity check");
317     SGTimeStamp st;
318     st.stamp();
319
320     sqlite3_stmt_ptr stmt = prepare("PRAGMA quick_check(1)");
321     if (!execSelect(stmt)) {
322       throw sg_exception("DB integrity check failed to run");
323     }
324
325     string v = (char*) sqlite3_column_text(stmt, 0);
326     if (v != "ok") {
327       throw sg_exception("DB integrity check returned:" + v);
328     }
329
330     SG_LOG(SG_NAVCACHE, SG_INFO, "NavDataCache integrity check took:" << st.elapsedMSec());
331     finalize(stmt);
332   }
333
334   bool isCachedFileModified(const SGPath& path, bool verbose);
335
336   void callSqlite(int result, const string& sql)
337   {
338     if (result == SQLITE_OK)
339       return; // all good
340
341     string errMsg;
342     if (result == SQLITE_MISUSE) {
343       errMsg = "Sqlite API abuse";
344       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
345     } else {
346       errMsg = sqlite3_errmsg(db);
347       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running:\n\t" << sql);
348     }
349
350     throw sg_exception("Sqlite error:" + errMsg, sql);
351   }
352
353   void runSQL(const string& sql)
354   {
355     sqlite3_stmt_ptr stmt;
356     callSqlite(sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL), sql);
357
358     try {
359       execSelect(stmt);
360     } catch (sg_exception&) {
361       sqlite3_finalize(stmt);
362       throw; // re-throw
363     }
364
365     sqlite3_finalize(stmt);
366   }
367
368   sqlite3_stmt_ptr prepare(const string& sql)
369   {
370     sqlite3_stmt_ptr stmt;
371     callSqlite(sqlite3_prepare_v2(db, sql.c_str(), sql.length(), &stmt, NULL), sql);
372     prepared.push_back(stmt);
373     return stmt;
374   }
375
376   void finalize(sqlite3_stmt_ptr s)
377   {
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");
381     }
382
383     prepared.erase(it);
384     sqlite3_finalize(s);
385   }
386
387   void reset(sqlite3_stmt_ptr stmt)
388   {
389     assert(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));
394     }
395   }
396
397   bool execSelect(sqlite3_stmt_ptr stmt)
398   {
399     return stepSelect(stmt);
400   }
401
402   bool stepSelect(sqlite3_stmt_ptr stmt)
403   {
404     int retries = 0;
405     int result;
406     while (retries < MAX_RETRIES) {
407       result = sqlite3_step(stmt);
408       if (result == SQLITE_ROW) {
409         return true; // at least one result row
410       }
411
412       if (result == SQLITE_DONE) {
413         return false; // no result rows
414       }
415
416       if (result != SQLITE_BUSY) {
417         break;
418       }
419
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
423
424     if (retries >= MAX_RETRIES) {
425       SG_LOG(SG_NAVCACHE, SG_ALERT, "exceeded maximum number of SQLITE_BUSY retries");
426       return false;
427     }
428
429     string errMsg;
430     if (result == SQLITE_MISUSE) {
431       errMsg = "Sqlite API abuse";
432       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite API abuse");
433     } else {
434       errMsg = sqlite3_errmsg(db);
435       SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " (" << result
436              << ") while running:\n\t" << sqlite3_sql(stmt));
437     }
438
439     throw sg_exception("Sqlite error:" + errMsg, sqlite3_sql(stmt));
440   }
441
442   void execSelect1(sqlite3_stmt_ptr stmt)
443   {
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));
447     }
448   }
449
450   sqlite3_int64 execInsert(sqlite3_stmt_ptr stmt)
451   {
452     execSelect(stmt);
453     sqlite3_int64 rowid = sqlite3_last_insert_rowid(db);
454     reset(stmt);
455     return rowid;
456   }
457
458   void execUpdate(sqlite3_stmt_ptr stmt)
459   {
460     execSelect(stmt);
461     reset(stmt);
462   }
463
464   void initTables()
465   {
466       string_list commands = simgear::strutils::split(SCHEMA_SQL, ";");
467       BOOST_FOREACH(std::string sql, commands) {
468           if (sql.empty()) {
469               continue;
470           }
471
472           runSQL(sql);
473       } // of commands in scheme loop
474   }
475
476   void prepareQueries()
477   {
478     writePropertyMulti = prepare("INSERT INTO properties (key, value) VALUES(?1,?2)");
479
480     beginTransactionStmt = prepare("BEGIN");
481     commitTransactionStmt = prepare("COMMIT");
482     rollbackTransactionStmt = prepare("ROLLBACK");
483
484
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 (?,?)");
490
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");
497
498     getAirportItems = prepare("SELECT rowid FROM positioned WHERE airport=?1 " AND_TYPED);
499
500
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);
505
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");
509
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)");
514
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)");
520
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");
527
528     removePOIQuery = prepare("DELETE FROM positioned WHERE type=?1 AND ident=?2");
529
530   // query statement
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)");
533
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)");
537
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)");
542
543     findNavsByFreqNoPos = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
544                                   "positioned.rowid=navaid.rowid AND freq=?1 " AND_TYPED);
545
546     findNavaidForRunway = prepare("SELECT positioned.rowid FROM positioned, navaid WHERE "
547                                   "positioned.rowid=navaid.rowid AND runway=?1 AND type=?2");
548
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");
552
553 #ifdef LAZY_OCTREE_UPDATES
554     updateOctreeChildren = prepare("UPDATE octree SET children=?2 WHERE rowid=?1");
555 #else
556   // mask the new child value into the existing one
557     updateOctreeChildren = prepare("UPDATE octree SET children=(?2 | children) WHERE rowid=?1");
558 #endif
559
560   // define a new octree node (with no children)
561     insertOctree = prepare("INSERT INTO octree (rowid, children) VALUES (?1, 0)");
562
563     getOctreeLeafChildren = prepare("SELECT rowid, type FROM positioned WHERE octree_node=?1");
564
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);
568
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);
572
573
574     getAirportItemByIdent = prepare("SELECT rowid FROM positioned WHERE airport=?1 AND ident=?2 AND type=?3");
575
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);
580
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)");
589
590     sqlite3_bind_int(findILS, 4, FGPositioned::ILS);
591     sqlite3_bind_int(findILS, 5, FGPositioned::LOC);
592
593   // airways
594     findAirway = prepare("SELECT rowid FROM airway WHERE network=?1 AND ident=?2");
595     insertAirway = prepare("INSERT INTO airway (ident, network) "
596                            "VALUES (?1, ?2)");
597
598     insertAirwayEdge = prepare("INSERT INTO airway_edge (network, airway, a, b) "
599                                "VALUES (?1, ?2, ?3, ?4)");
600
601     isPosInAirway = prepare("SELECT rowid FROM airway_edge WHERE network=?1 AND a=?2");
602
603     airwayEdgesFrom = prepare("SELECT airway, b FROM airway_edge WHERE network=?1 AND a=?2");
604
605     airwayEdges = prepare("SELECT a, b FROM airway_edge WHERE airway=?1");
606   }
607
608   void writeIntProperty(const string& key, int value)
609   {
610     sqlite_bind_stdstring(clearProperty, 1, key);
611     execUpdate(clearProperty);
612
613     sqlite_bind_stdstring(writePropertyQuery, 1, key);
614     sqlite3_bind_int(writePropertyQuery, 2, value);
615     execUpdate(writePropertyQuery);
616   }
617
618
619   FGPositioned* loadById(sqlite_int64 rowId, sqlite3_int64& aptId);
620
621   FGAirport* loadAirport(sqlite_int64 rowId,
622                          FGPositioned::Type ty,
623                          const string& id, const string& name, const SGGeod& pos)
624   {
625     sqlite3_bind_int64(loadAirportStmt, 1, rowId);
626     execSelect1(loadAirportStmt);
627     bool hasMetar = (sqlite3_column_int(loadAirportStmt, 0) > 0);
628     reset(loadAirportStmt);
629
630     return new FGAirport(rowId, id, pos, name, hasMetar, ty);
631   }
632
633   FGRunwayBase* loadRunway(sqlite3_int64 rowId, FGPositioned::Type ty,
634                            const string& id, const SGGeod& pos, PositionedID apt)
635   {
636     sqlite3_bind_int(loadRunwayStmt, 1, rowId);
637     execSelect1(loadRunwayStmt);
638
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);
643
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);
650     } else {
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);
657
658       if (reciprocal > 0) {
659         r->setReciprocalRunway(reciprocal);
660       }
661
662       if (ils > 0) {
663         r->setILS(ils);
664       }
665
666       reset(loadRunwayStmt);
667       return r;
668     }
669   }
670
671   CommStation* loadComm(sqlite3_int64 rowId, FGPositioned::Type ty,
672                         const string& id, const string& name,
673                         const SGGeod& pos,
674                         PositionedID airport)
675   {
676     sqlite3_bind_int64(loadCommStation, 1, rowId);
677     execSelect1(loadCommStation);
678
679     int range = sqlite3_column_int(loadCommStation, 0);
680     int freqKhz = sqlite3_column_int(loadCommStation, 1);
681     reset(loadCommStation);
682
683     CommStation* c = new CommStation(rowId, name, ty, pos, freqKhz, range);
684     c->setAirport(airport);
685     return c;
686   }
687
688   FGPositioned* loadNav(sqlite3_int64 rowId,
689                        FGPositioned::Type ty, const string& id,
690                        const string& name, const SGGeod& pos)
691   {
692     sqlite3_bind_int64(loadNavaid, 1, rowId);
693     execSelect1(loadNavaid);
694
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))
699     {
700       reset(loadNavaid);
701       return new FGMarkerBeaconRecord(rowId, ty, runway, pos);
702     }
703
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);
708     reset(loadNavaid);
709
710     FGNavRecord* n =
711       (ty == FGPositioned::MOBILE_TACAN)
712       ? new FGMobileNavRecord
713             (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway)
714       : new FGNavRecord
715             (rowId, ty, id, name, pos, freq, rangeNm, mulituse, runway);
716
717     if (colocated)
718       n->setColocatedDME(colocated);
719
720     return n;
721   }
722
723   PositionedID insertPositioned(FGPositioned::Type ty, const string& ident,
724                                 const string& name, const SGGeod& pos, PositionedID apt,
725                                 bool spatialIndex)
726   {
727     SGVec3d cartPos(SGVec3d::fromGeod(pos));
728
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());
736
737     if (spatialIndex) {
738       Octree::Leaf* octreeLeaf = Octree::global_spatialOctree->findLeafForPos(cartPos);
739       assert(intersects(octreeLeaf->bbox(), cartPos));
740       sqlite3_bind_int64(insertPositionedQuery, 8, octreeLeaf->guid());
741     } else {
742       sqlite3_bind_null(insertPositionedQuery, 8);
743     }
744
745     sqlite3_bind_double(insertPositionedQuery, 9, cartPos.x());
746     sqlite3_bind_double(insertPositionedQuery, 10, cartPos.y());
747     sqlite3_bind_double(insertPositionedQuery, 11, cartPos.z());
748
749     PositionedID r = execInsert(insertPositionedQuery);
750     return r;
751   }
752
753   FGPositionedList findAllByString(const string& s, const string& column,
754                                      FGPositioned::Filter* filter, bool exact)
755   {
756     string query = s;
757     if (!exact) query += "%";
758
759   // build up SQL query text
760     string matchTerm = exact ? "=?1" : " LIKE ?1";
761     string sql = "SELECT rowid FROM positioned WHERE " + column + matchTerm;
762     if (filter) {
763       sql += " " AND_TYPED;
764     }
765
766   // find or prepare a suitable statement frrm the SQL
767     sqlite3_stmt_ptr stmt = findByStringDict[sql];
768     if (!stmt) {
769       stmt = prepare(sql);
770       findByStringDict[sql] = stmt;
771     }
772
773     sqlite_bind_stdstring(stmt, 1, query);
774     if (filter) {
775       sqlite3_bind_int(stmt, 2, filter->minType());
776       sqlite3_bind_int(stmt, 3, filter->maxType());
777     }
778
779     FGPositionedList result;
780   // run the prepared SQL
781     while (stepSelect(stmt))
782     {
783       FGPositioned* pos = outer->loadById(sqlite3_column_int64(stmt, 0));
784       if (filter && !filter->pass(pos)) {
785         continue;
786       }
787
788       result.push_back(pos);
789     }
790
791     reset(stmt);
792     return result;
793   }
794
795   PositionedIDVec selectIds(sqlite3_stmt_ptr query)
796   {
797     PositionedIDVec result;
798     while (stepSelect(query)) {
799       result.push_back(sqlite3_column_int64(query, 0));
800     }
801     reset(query);
802     return result;
803   }
804
805   double runwayLengthFt(PositionedID rwy)
806   {
807     sqlite3_bind_int64(runwayLengthFtQuery, 1, rwy);
808     execSelect1(runwayLengthFtQuery);
809     double length = sqlite3_column_double(runwayLengthFtQuery, 0);
810     reset(runwayLengthFtQuery);
811     return length;
812   }
813
814   void flushDeferredOctreeUpdates()
815   {
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);
820     }
821
822     deferredOctreeUpdates.clear();
823   }
824
825   void removePositionedWithIdent(FGPositioned::Type ty, const std::string& aIdent)
826   {
827     sqlite3_bind_int(removePOIQuery, 1, ty);
828     sqlite_bind_stdstring(removePOIQuery, 2, aIdent);
829     execUpdate(removePOIQuery);
830     reset(removePOIQuery);
831   }
832
833   NavDataCache* outer;
834   sqlite3* db;
835   SGPath path;
836     bool readOnly;
837
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;
843
844   /**
845    * record the levels of open transaction objects we have
846    */
847   unsigned int transactionLevel;
848   bool transactionAborted;
849   sqlite3_stmt_ptr beginTransactionStmt, commitTransactionStmt, rollbackTransactionStmt;
850
851   SGPath aptDatPath, metarDatPath, navDatPath, fixDatPath, poiDatPath,
852   carrierDatPath, airwayDatPath;
853
854   sqlite3_stmt_ptr readPropertyQuery, writePropertyQuery,
855     stampFileCache, statCacheCheck,
856     loadAirportStmt, loadCommStation, loadPositioned, loadNavaid,
857     loadRunwayStmt;
858   sqlite3_stmt_ptr writePropertyMulti, clearProperty;
859
860   sqlite3_stmt_ptr insertPositionedQuery, insertAirport, insertTower, insertRunway,
861   insertCommStation, insertNavaid;
862   sqlite3_stmt_ptr setAirportMetar, setRunwayReciprocal, setRunwayILS, setNavaidColocated,
863     setAirportPos;
864   sqlite3_stmt_ptr removePOIQuery;
865
866   sqlite3_stmt_ptr findClosestWithIdent;
867 // octree (spatial index) related queries
868   sqlite3_stmt_ptr getOctreeChildren, insertOctree, updateOctreeChildren,
869     getOctreeLeafChildren;
870
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,
876     findILS;
877
878   sqlite3_stmt_ptr runwayLengthFtQuery;
879
880 // airways
881   sqlite3_stmt_ptr findAirway, insertAirwayEdge,
882     isPosInAirway, airwayEdgesFrom,
883     insertAirway, airwayEdges;
884
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
887 // used.
888   std::map<string, sqlite3_stmt_ptr> findByStringDict;
889
890   typedef std::vector<sqlite3_stmt_ptr> StmtVec;
891   StmtVec prepared;
892
893   std::set<Octree::Branch*> deferredOctreeUpdates;
894
895   // if we're performing a rebuild, the thread that is doing the work.
896   // otherwise, NULL
897   std::auto_ptr<RebuildThread> rebuilder;
898 };
899
900 //////////////////////////////////////////////////////////////////////
901
902 FGPositioned* NavDataCache::NavDataCachePrivate::loadById(sqlite3_int64 rowid,
903                                                           sqlite3_int64& aptId)
904 {
905
906   sqlite3_bind_int64(loadPositioned, 1, rowid);
907   execSelect1(loadPositioned);
908
909   assert(rowid == sqlite3_column_int64(loadPositioned, 0));
910   FGPositioned::Type ty = (FGPositioned::Type) sqlite3_column_int(loadPositioned, 1);
911
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);
920
921   reset(loadPositioned);
922
923   switch (ty) {
924     case FGPositioned::AIRPORT:
925     case FGPositioned::SEAPORT:
926     case FGPositioned::HELIPORT:
927       return loadAirport(rowid, ty, ident, name, pos);
928
929     case FGPositioned::TOWER:
930       return new AirportTower(prowid, aptId, ident, pos);
931
932     case FGPositioned::RUNWAY:
933     case FGPositioned::HELIPAD:
934     case FGPositioned::TAXIWAY:
935       return loadRunway(rowid, ty, ident, pos, aptId);
936
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);
949
950     case FGPositioned::FIX:
951       return new FGFix(rowid, ident, pos);
952
953     case FGPositioned::WAYPOINT:
954     case FGPositioned::COUNTRY:
955     case FGPositioned::CITY:
956     case FGPositioned::TOWN:
957     case FGPositioned::VILLAGE:
958     {
959         FGPositioned* wpt = new FGPositioned(rowid, ty, ident, pos);
960       return wpt;
961     }
962
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);
972
973     default:
974       return NULL;
975   }
976 }
977
978 bool NavDataCache::NavDataCachePrivate::isCachedFileModified(const SGPath& path, bool verbose)
979 {
980   if (!path.exists()) {
981     throw sg_io_exception("isCachedFileModified: Missing file:" + path.str());
982   }
983
984   sqlite_bind_temp_stdstring(statCacheCheck, 1, path.str());
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());
990     if (delta != 0)
991     {
992       SG_LOG(SG_NAVCACHE, logLevel, "NavCache: rebuild required for " << path <<
993              ". Timestamps: " << modtime << " != " << path.modTime());
994     }
995     else
996     {
997       SG_LOG(SG_NAVCACHE, SG_DEBUG, "NavCache: no rebuild required for " << path);
998     }
999
1000     isModified = (delta != 0);
1001   } else {
1002     SG_LOG(SG_NAVCACHE, logLevel, "NavCache: initial build required for " << path);
1003   }
1004
1005   reset(statCacheCheck);
1006   return isModified;
1007 }
1008
1009 static NavDataCache* static_instance = NULL;
1010
1011 NavDataCache::NavDataCache()
1012 {
1013   const int MAX_TRIES = 3;
1014   SGPath homePath(globals->get_fg_home());
1015
1016   std::ostringstream os;
1017   string_list versionParts = simgear::strutils::split(VERSION, ".");
1018   if (versionParts.size() < 2) {
1019     os << "navdata.cache";
1020   } else {
1021     os << "navdata_" << versionParts[0] << "_" << versionParts[1] << ".cache";
1022   }
1023
1024   homePath.append(os.str());
1025
1026     // permit additional DB connections from the same process
1027     sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
1028
1029   for (int t=0; t < MAX_TRIES; ++t) {
1030     try {
1031       d.reset(new NavDataCachePrivate(homePath, this));
1032       d->init();
1033       //d->checkCacheFile();
1034     // reached this point with no exception, success
1035       break;
1036     } catch (sg_exception& e) {
1037       SG_LOG(SG_NAVCACHE, t == 0 ? SG_WARN : SG_ALERT, "NavCache: init failed:" << e.what()
1038              << " (attempt " << t << ")");
1039       d.reset();
1040
1041         // only wipe the existing if not readonly
1042         if (!fgGetBool("/sim/fghome-readonly", false)) {
1043             homePath.remove();
1044         }
1045     }
1046   } // of retry loop
1047
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);
1052
1053   d->aptDatPath = SGPath(globals->get_fg_root());
1054   d->aptDatPath.append("Airports/apt.dat.gz");
1055
1056   d->metarDatPath = SGPath(globals->get_fg_root());
1057   d->metarDatPath.append("Airports/metar.dat.gz");
1058
1059   d->navDatPath = SGPath(globals->get_fg_root());
1060   d->navDatPath.append("Navaids/nav.dat.gz");
1061
1062   d->fixDatPath = SGPath(globals->get_fg_root());
1063   d->fixDatPath.append("Navaids/fix.dat.gz");
1064
1065   d->poiDatPath = SGPath(globals->get_fg_root());
1066   d->poiDatPath.append("Navaids/poi.dat.gz");
1067
1068   d->carrierDatPath = SGPath(globals->get_fg_root());
1069   d->carrierDatPath.append("Navaids/carrier_nav.dat.gz");
1070
1071   d->airwayDatPath = SGPath(globals->get_fg_root());
1072   d->airwayDatPath.append("Navaids/awy.dat.gz");
1073 }
1074
1075 NavDataCache::~NavDataCache()
1076 {
1077   assert(static_instance == this);
1078   static_instance = NULL;
1079   d.reset();
1080 }
1081
1082 NavDataCache* NavDataCache::createInstance()
1083 {
1084     static_instance = new NavDataCache;
1085     return static_instance;
1086 }
1087
1088 NavDataCache* NavDataCache::instance()
1089 {
1090   return static_instance;
1091 }
1092
1093 bool NavDataCache::isRebuildRequired()
1094 {
1095     if (d->readOnly) {
1096         return false;
1097     }
1098
1099     if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
1100         SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: restore-defaults requested, will rebuild cache");
1101         return true;
1102     }
1103
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
1111 #ifndef SG_WINDOWS
1112       d->isCachedFileModified(d->poiDatPath, true) ||
1113 #endif
1114       d->isCachedFileModified(d->airwayDatPath, true))
1115   {
1116     SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: main cache rebuild required");
1117     return true;
1118   }
1119
1120   SG_LOG(SG_NAVCACHE, SG_INFO, "NavCache: no main cache rebuild required");
1121   return false;
1122 }
1123
1124 NavDataCache::RebuildPhase NavDataCache::rebuild()
1125 {
1126     if (!d->rebuilder.get()) {
1127         d->rebuilder.reset(new RebuildThread(this));
1128         d->rebuilder->start();
1129     }
1130
1131     // poll the rebuild thread
1132     RebuildPhase phase = d->rebuilder->currentPhase();
1133     if (phase == REBUILD_DONE) {
1134         d->rebuilder.reset(); // all done!
1135     }
1136     return phase;
1137 }
1138
1139 unsigned int NavDataCache::rebuildPhaseCompletionPercentage() const
1140 {
1141     if (!d->rebuilder.get()) {
1142         return 0;
1143     }
1144
1145     return d->rebuilder->completionPercent();
1146 }
1147
1148 void NavDataCache::setRebuildPhaseProgress(RebuildPhase ph, unsigned int percent)
1149 {
1150     if (!d->rebuilder.get()) {
1151         return;
1152     }
1153
1154     d->rebuilder->setProgress(ph, percent);
1155 }
1156
1157 void NavDataCache::doRebuild()
1158 {
1159   try {
1160     d->close(); // completely close the sqlite object
1161     d->path.remove(); // remove the file on disk
1162     d->init(); // start again from scratch
1163
1164     // initialise the root octree node
1165     d->runSQL("INSERT INTO octree (rowid, children) VALUES (1, 0)");
1166
1167     SGTimeStamp st;
1168     {
1169         Transaction txn(this);
1170
1171         st.stamp();
1172         airportDBLoad(d->aptDatPath);
1173         SG_LOG(SG_NAVCACHE, SG_INFO, "apt.dat load took:" << st.elapsedMSec());
1174
1175         setRebuildPhaseProgress(REBUILD_UNKNOWN);
1176         metarDataLoad(d->metarDatPath);
1177         stampCacheFile(d->aptDatPath);
1178         stampCacheFile(d->metarDatPath);
1179
1180         st.stamp();
1181         loadFixes(d->fixDatPath);
1182         stampCacheFile(d->fixDatPath);
1183         SG_LOG(SG_NAVCACHE, SG_INFO, "fix.dat load took:" << st.elapsedMSec());
1184
1185         st.stamp();
1186         navDBInit(d->navDatPath);
1187         stampCacheFile(d->navDatPath);
1188         SG_LOG(SG_NAVCACHE, SG_INFO, "nav.dat load took:" << st.elapsedMSec());
1189
1190         setRebuildPhaseProgress(REBUILD_UNKNOWN);
1191         st.stamp();
1192         txn.commit();
1193         SG_LOG(SG_NAVCACHE, SG_INFO, "stage 1 commit took:" << st.elapsedMSec());
1194     }
1195
1196 #ifdef SG_WINDOWS
1197       SG_LOG(SG_NAVCACHE, SG_ALERT, "SKIPPING POI load on Windows");
1198 #else
1199       {
1200           Transaction txn(this);
1201
1202           st.stamp();
1203           poiDBInit(d->poiDatPath);
1204           stampCacheFile(d->poiDatPath);
1205           SG_LOG(SG_NAVCACHE, SG_INFO, "poi.dat load took:" << st.elapsedMSec());
1206
1207           setRebuildPhaseProgress(REBUILD_UNKNOWN);
1208           st.stamp();
1209           txn.commit();
1210           SG_LOG(SG_NAVCACHE, SG_INFO, "POI commit took:" << st.elapsedMSec());
1211       }
1212 #endif
1213
1214       {
1215           Transaction txn(this);
1216           loadCarrierNav(d->carrierDatPath);
1217           stampCacheFile(d->carrierDatPath);
1218
1219           st.stamp();
1220           Airway::load(d->airwayDatPath);
1221           stampCacheFile(d->airwayDatPath);
1222           SG_LOG(SG_NAVCACHE, SG_INFO, "awy.dat load took:" << st.elapsedMSec());
1223
1224           d->flushDeferredOctreeUpdates();
1225
1226           string sceneryPaths = simgear::strutils::join(globals->get_fg_scenery(), ";");
1227           writeStringProperty("scenery_paths", sceneryPaths);
1228
1229           st.stamp();
1230           txn.commit();
1231           SG_LOG(SG_NAVCACHE, SG_INFO, "final commit took:" << st.elapsedMSec());
1232
1233       }
1234
1235   } catch (sg_exception& e) {
1236     SG_LOG(SG_NAVCACHE, SG_ALERT, "caught exception rebuilding navCache:" << e.what());
1237   }
1238 }
1239
1240 int NavDataCache::readIntProperty(const string& key)
1241 {
1242   sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1243   int result = 0;
1244
1245   if (d->execSelect(d->readPropertyQuery)) {
1246     result = sqlite3_column_int(d->readPropertyQuery, 0);
1247   } else {
1248     SG_LOG(SG_NAVCACHE, SG_WARN, "readIntProperty: unknown:" << key);
1249   }
1250
1251   d->reset(d->readPropertyQuery);
1252   return result;
1253 }
1254
1255 double NavDataCache::readDoubleProperty(const string& key)
1256 {
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);
1261   } else {
1262     SG_LOG(SG_NAVCACHE, SG_WARN, "readDoubleProperty: unknown:" << key);
1263   }
1264
1265   d->reset(d->readPropertyQuery);
1266   return result;
1267 }
1268
1269 string NavDataCache::readStringProperty(const string& key)
1270 {
1271   sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1272   string result;
1273   if (d->execSelect(d->readPropertyQuery)) {
1274     result = (char*) sqlite3_column_text(d->readPropertyQuery, 0);
1275   } else {
1276     SG_LOG(SG_NAVCACHE, SG_WARN, "readStringProperty: unknown:" << key);
1277   }
1278
1279   d->reset(d->readPropertyQuery);
1280   return result;
1281 }
1282
1283 void NavDataCache::writeIntProperty(const string& key, int value)
1284 {
1285   d->writeIntProperty(key, value);
1286 }
1287
1288 void NavDataCache::writeStringProperty(const string& key, const string& value)
1289 {
1290   sqlite_bind_stdstring(d->clearProperty, 1, key);
1291   d->execUpdate(d->clearProperty);
1292
1293   sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1294   sqlite_bind_stdstring(d->writePropertyQuery, 2, value);
1295   d->execUpdate(d->writePropertyQuery);
1296 }
1297
1298 void NavDataCache::writeDoubleProperty(const string& key, const double& value)
1299 {
1300   sqlite_bind_stdstring(d->clearProperty, 1, key);
1301   d->execUpdate(d->clearProperty);
1302
1303   sqlite_bind_stdstring(d->writePropertyQuery, 1, key);
1304   sqlite3_bind_double(d->writePropertyQuery, 2, value);
1305   d->execUpdate(d->writePropertyQuery);
1306 }
1307
1308 string_list NavDataCache::readStringListProperty(const string& key)
1309 {
1310   sqlite_bind_stdstring(d->readPropertyQuery, 1, key);
1311   string_list result;
1312   while (d->stepSelect(d->readPropertyQuery)) {
1313     result.push_back((char*) sqlite3_column_text(d->readPropertyQuery, 0));
1314   }
1315   d->reset(d->readPropertyQuery);
1316
1317   return result;
1318 }
1319
1320 void NavDataCache::writeStringListProperty(const string& key, const string_list& values)
1321 {
1322   sqlite_bind_stdstring(d->clearProperty, 1, key);
1323   d->execUpdate(d->clearProperty);
1324
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);
1329   }
1330 }
1331
1332 bool NavDataCache::isCachedFileModified(const SGPath& path) const
1333 {
1334   return d->isCachedFileModified(path, false);
1335 }
1336
1337 void NavDataCache::stampCacheFile(const SGPath& path)
1338 {
1339   sqlite_bind_temp_stdstring(d->stampFileCache, 1, path.str());
1340   sqlite3_bind_int64(d->stampFileCache, 2, path.modTime());
1341   d->execInsert(d->stampFileCache);
1342 }
1343
1344 void NavDataCache::beginTransaction()
1345 {
1346   if (d->transactionLevel == 0) {
1347     d->transactionAborted = false;
1348     d->stepSelect(d->beginTransactionStmt);
1349     sqlite3_reset(d->beginTransactionStmt);
1350   }
1351
1352   ++d->transactionLevel;
1353 }
1354
1355 void NavDataCache::commitTransaction()
1356 {
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
1361     // committing.
1362     sqlite3_stmt_ptr q = d->transactionAborted ? d->rollbackTransactionStmt : d->commitTransactionStmt;
1363
1364     int retries = 0;
1365     int result;
1366     while (retries < MAX_RETRIES) {
1367       result = sqlite3_step(q);
1368       if (result == SQLITE_DONE) {
1369         break;
1370       }
1371
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;
1378         break;
1379       }
1380
1381       if (result != SQLITE_BUSY) {
1382         break;
1383       }
1384
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
1388
1389     string errMsg;
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));
1394     }
1395
1396     sqlite3_reset(q);
1397   }
1398 }
1399
1400 void NavDataCache::abortTransaction()
1401 {
1402   SG_LOG(SG_NAVCACHE, SG_WARN, "NavCache: aborting transaction");
1403
1404   assert(d->transactionLevel > 0);
1405   if (--d->transactionLevel == 0) {
1406     d->stepSelect(d->rollbackTransactionStmt);
1407     sqlite3_reset(d->rollbackTransactionStmt);
1408   }
1409
1410   d->transactionAborted = true;
1411 }
1412
1413 FGPositionedRef NavDataCache::loadById(PositionedID rowid)
1414 {
1415   if (rowid == 0) {
1416     return NULL;
1417   }
1418
1419   PositionedCache::iterator it = d->cache.find(rowid);
1420   if (it != d->cache.end()) {
1421     d->cacheHits++;
1422     return it->second; // cache it
1423   }
1424
1425   sqlite3_int64 aptId;
1426   FGPositioned* pos = d->loadById(rowid, aptId);
1427   d->cache.insert(it, PositionedCache::value_type(rowid, pos));
1428   d->cacheMisses++;
1429
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();
1434   }
1435
1436   return pos;
1437 }
1438
1439 PositionedID NavDataCache::insertAirport(FGPositioned::Type ty, const string& ident,
1440                                          const string& name)
1441 {
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(),
1446                                             0 /* airport */,
1447                                             false /* spatial index */);
1448
1449   sqlite3_bind_int64(d->insertAirport, 1, rowId);
1450   d->execInsert(d->insertAirport);
1451
1452   return rowId;
1453 }
1454
1455 void NavDataCache::updatePosition(PositionedID item, const SGGeod &pos)
1456 {
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);
1460   }
1461
1462   SGVec3d cartPos(SGVec3d::fromGeod(pos));
1463
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());
1468
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());
1479
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());
1483
1484
1485   d->execUpdate(d->setAirportPos);
1486 }
1487
1488 void NavDataCache::insertTower(PositionedID airportId, const SGGeod& pos)
1489 {
1490   d->insertPositioned(FGPositioned::TOWER, string(), string(),
1491                       pos, airportId, true /* spatial index */);
1492 }
1493
1494 PositionedID
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)
1499 {
1500   // only runways are spatially indexed; don't bother indexing taxiways
1501   // or pavements
1502   bool spatialIndex = ( ty == FGPositioned::RUNWAY || ty == FGPositioned::HELIPAD);
1503
1504   sqlite3_int64 rowId = d->insertPositioned(ty, cleanRunwayNo(ident), "", pos, apt,
1505                                             spatialIndex);
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);
1513
1514   return d->execInsert(d->insertRunway);
1515 }
1516
1517 void NavDataCache::setRunwayReciprocal(PositionedID runway, PositionedID recip)
1518 {
1519   sqlite3_bind_int64(d->setRunwayReciprocal, 1, runway);
1520   sqlite3_bind_int64(d->setRunwayReciprocal, 2, recip);
1521   d->execUpdate(d->setRunwayReciprocal);
1522
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);
1527 }
1528
1529 void NavDataCache::setRunwayILS(PositionedID runway, PositionedID ils)
1530 {
1531   sqlite3_bind_int64(d->setRunwayILS, 1, runway);
1532   sqlite3_bind_int64(d->setRunwayILS, 2, ils);
1533   d->execUpdate(d->setRunwayILS);
1534
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);
1539   }
1540 }
1541
1542 PositionedID
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)
1547 {
1548   bool spatialIndex = true;
1549   if (ty == FGPositioned::MOBILE_TACAN) {
1550     spatialIndex = false;
1551   }
1552
1553   sqlite3_int64 rowId = d->insertPositioned(ty, ident, name, pos, apt,
1554                                             spatialIndex);
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);
1562 }
1563
1564 void NavDataCache::setNavaidColocated(PositionedID navaid, PositionedID colocatedDME)
1565 {
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);
1570
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);
1575   }
1576 }
1577
1578 PositionedID NavDataCache::insertCommStation(FGPositioned::Type ty,
1579                                              const string& name, const SGGeod& pos, int freq, int range,
1580                                              PositionedID apt)
1581 {
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);
1587 }
1588
1589 PositionedID NavDataCache::insertFix(const std::string& ident, const SGGeod& aPos)
1590 {
1591   return d->insertPositioned(FGPositioned::FIX, ident, string(), aPos, 0, true);
1592 }
1593
1594 PositionedID NavDataCache::createPOI(FGPositioned::Type ty, const std::string& ident, const SGGeod& aPos)
1595 {
1596   return d->insertPositioned(ty, ident, string(), aPos, 0,
1597                              true /* spatial index */);
1598 }
1599
1600 bool NavDataCache::removePOI(FGPositioned::Type ty, const std::string& aIdent)
1601 {
1602   d->removePositionedWithIdent(ty, aIdent);
1603   // should remove from the live cache too?
1604
1605     return true;
1606 }
1607
1608 void NavDataCache::setAirportMetar(const string& icao, bool hasMetar)
1609 {
1610   sqlite_bind_stdstring(d->setAirportMetar, 1, icao);
1611   sqlite3_bind_int(d->setAirportMetar, 2, hasMetar);
1612   d->execUpdate(d->setAirportMetar);
1613 }
1614
1615 //------------------------------------------------------------------------------
1616 FGPositionedList NavDataCache::findAllWithIdent( const string& s,
1617                                                  FGPositioned::Filter* filter,
1618                                                  bool exact )
1619 {
1620   return d->findAllByString(s, "ident", filter, exact);
1621 }
1622
1623 //------------------------------------------------------------------------------
1624 FGPositionedList NavDataCache::findAllWithName( const string& s,
1625                                                 FGPositioned::Filter* filter,
1626                                                 bool exact )
1627 {
1628   return d->findAllByString(s, "name", filter, exact);
1629 }
1630
1631 //------------------------------------------------------------------------------
1632 FGPositionedRef NavDataCache::findClosestWithIdent( const string& aIdent,
1633                                                     const SGGeod& aPos,
1634                                                     FGPositioned::Filter* aFilter )
1635 {
1636   sqlite_bind_stdstring(d->findClosestWithIdent, 1, aIdent);
1637   if (aFilter) {
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);
1643   }
1644
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());
1649
1650   FGPositionedRef result;
1651
1652   while (d->stepSelect(d->findClosestWithIdent)) {
1653     FGPositioned* pos = loadById(sqlite3_column_int64(d->findClosestWithIdent, 0));
1654     if (aFilter && !aFilter->pass(pos)) {
1655       continue;
1656     }
1657
1658     result = pos;
1659     break;
1660   }
1661
1662   d->reset(d->findClosestWithIdent);
1663   return result;
1664 }
1665
1666
1667 int NavDataCache::getOctreeBranchChildren(int64_t octreeNodeId)
1668 {
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);
1673   return children;
1674 }
1675
1676 void NavDataCache::defineOctreeNode(Octree::Branch* pr, Octree::Node* nd)
1677 {
1678   sqlite3_bind_int64(d->insertOctree, 1, nd->guid());
1679   d->execInsert(d->insertOctree);
1680
1681 #ifdef LAZY_OCTREE_UPDATES
1682   d->deferredOctreeUpdates.insert(pr);
1683 #else
1684   // lowest three bits of node ID are 0..7 index of the child in the parent
1685   int childIndex = nd->guid() & 0x07;
1686
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);
1692 #endif
1693 }
1694
1695 TypedPositionedVec
1696 NavDataCache::getOctreeLeafChildren(int64_t octreeNodeId)
1697 {
1698   sqlite3_bind_int64(d->getOctreeLeafChildren, 1, octreeNodeId);
1699
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)));
1706   }
1707
1708   d->reset(d->getOctreeLeafChildren);
1709   return r;
1710 }
1711
1712
1713 /**
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.
1717  */
1718 char** NavDataCache::searchAirportNamesAndIdents(const std::string& aFilter)
1719 {
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
1726   } else {
1727     stmt = d->searchAirports;
1728     sqlite_bind_stdstring(stmt, 1, searchTerm);
1729   }
1730
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);
1738       free(result);
1739       result = nresult;
1740     }
1741
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);
1753     char* dst = entry;
1754     *dst++ = ' ';
1755     memcpy(dst, sqlite3_column_text(stmt, 1), nameLength);
1756     dst += nameLength;
1757     *dst++ = ' ';
1758     *dst++ = ' ';
1759     *dst++ = ' ';
1760     *dst++ = '(';
1761     memcpy(dst, sqlite3_column_text(stmt, 0), icaoLength);
1762     dst += icaoLength;
1763     *dst++ = ')';
1764     *dst++ = 0;
1765
1766     result[numMatches++] = entry;
1767   }
1768
1769   result[numMatches] = NULL; // end of list marker
1770   d->reset(stmt);
1771   return result;
1772 }
1773
1774 FGPositionedRef
1775 NavDataCache::findCommByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
1776 {
1777   sqlite3_bind_int(d->findCommByFreq, 1, freqKhz);
1778   if (aFilter) {
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);
1784   }
1785
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;
1791
1792   while (d->execSelect(d->findCommByFreq)) {
1793     FGPositioned* p = loadById(sqlite3_column_int64(d->findCommByFreq, 0));
1794     if (aFilter && !aFilter->pass(p)) {
1795       continue;
1796     }
1797
1798     result = p;
1799     break;
1800   }
1801
1802   d->reset(d->findCommByFreq);
1803   return result;
1804 }
1805
1806 PositionedIDVec
1807 NavDataCache::findNavaidsByFreq(int freqKhz, const SGGeod& aPos, FGPositioned::Filter* aFilter)
1808 {
1809   sqlite3_bind_int(d->findNavsByFreq, 1, freqKhz);
1810   if (aFilter) {
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);
1816   }
1817
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());
1822
1823   return d->selectIds(d->findNavsByFreq);
1824 }
1825
1826 PositionedIDVec
1827 NavDataCache::findNavaidsByFreq(int freqKhz, FGPositioned::Filter* aFilter)
1828 {
1829   sqlite3_bind_int(d->findNavsByFreqNoPos, 1, freqKhz);
1830   if (aFilter) {
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);
1836   }
1837
1838   return d->selectIds(d->findNavsByFreqNoPos);
1839 }
1840
1841 PositionedIDVec
1842 NavDataCache::airportItemsOfType(PositionedID apt,FGPositioned::Type ty,
1843                                  FGPositioned::Type maxTy)
1844 {
1845   if (maxTy == FGPositioned::INVALID) {
1846     maxTy = ty; // single-type range
1847   }
1848
1849   sqlite3_bind_int64(d->getAirportItems, 1, apt);
1850   sqlite3_bind_int(d->getAirportItems, 2, ty);
1851   sqlite3_bind_int(d->getAirportItems, 3, maxTy);
1852
1853   return d->selectIds(d->getAirportItems);
1854 }
1855
1856 PositionedID
1857 NavDataCache::airportItemWithIdent(PositionedID apt, FGPositioned::Type ty,
1858                                    const std::string& ident)
1859 {
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;
1864
1865   if (d->execSelect(d->getAirportItemByIdent)) {
1866     result = sqlite3_column_int64(d->getAirportItemByIdent, 0);
1867   }
1868
1869   d->reset(d->getAirportItemByIdent);
1870   return result;
1871 }
1872
1873 AirportRunwayPair
1874 NavDataCache::findAirportRunway(const std::string& aName)
1875 {
1876   if (aName.empty()) {
1877     return AirportRunwayPair();
1878   }
1879
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();
1884   }
1885
1886   AirportRunwayPair result;
1887   sqlite_bind_stdstring(d->findAirportRunway, 1, parts[0]);
1888   sqlite_bind_stdstring(d->findAirportRunway, 2, cleanRunwayNo(parts[1]));
1889
1890   if (d->execSelect(d->findAirportRunway)) {
1891     result = AirportRunwayPair(sqlite3_column_int64(d->findAirportRunway, 0),
1892                       sqlite3_column_int64(d->findAirportRunway, 1));
1893
1894   } else {
1895     SG_LOG(SG_NAVCACHE, SG_WARN, "findAirportRunway: unknown airport/runway:" << aName);
1896   }
1897
1898   d->reset(d->findAirportRunway);
1899   return result;
1900 }
1901
1902 PositionedID
1903 NavDataCache::findILS(PositionedID airport, const string& aRunway, const string& navIdent)
1904 {
1905   string runway(cleanRunwayNo(aRunway));
1906
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);
1913   }
1914
1915   d->reset(d->findILS);
1916   return result;
1917 }
1918
1919 int NavDataCache::findAirway(int network, const string& aName)
1920 {
1921   sqlite3_bind_int(d->findAirway, 1, network);
1922   sqlite_bind_stdstring(d->findAirway, 2, aName);
1923
1924   int airway = 0;
1925   if (d->execSelect(d->findAirway)) {
1926     // already exists
1927     airway = sqlite3_column_int(d->findAirway, 0);
1928   } else {
1929     sqlite_bind_stdstring(d->insertAirway, 1, aName);
1930     sqlite3_bind_int(d->insertAirway, 2, network);
1931     airway = d->execInsert(d->insertAirway);
1932   }
1933
1934   d->reset(d->findAirway);
1935   return airway;
1936 }
1937
1938 void NavDataCache::insertEdge(int network, int airwayID, PositionedID from, PositionedID to)
1939 {
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);
1947
1948     std::swap(from, to);
1949   }
1950 }
1951
1952 bool NavDataCache::isInAirwayNetwork(int network, PositionedID pos)
1953 {
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);
1958
1959   return ok;
1960 }
1961
1962 AirwayEdgeVec NavDataCache::airwayEdgesFrom(int network, PositionedID pos)
1963 {
1964   sqlite3_bind_int(d->airwayEdgesFrom, 1, network);
1965   sqlite3_bind_int64(d->airwayEdgesFrom, 2, pos);
1966
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)
1972                      ));
1973   }
1974
1975   d->reset(d->airwayEdgesFrom);
1976   return result;
1977 }
1978
1979 PositionedIDVec NavDataCache::airwayWaypts(int id)
1980 {
1981     sqlite3_bind_int(d->airwayEdges, 1, id);
1982
1983     typedef std::pair<PositionedID, PositionedID> Edge;
1984     typedef std::deque<Edge> EdgeVec;
1985     typedef std::deque<PositionedID> PositionedIDDeque;
1986
1987 // build up the EdgeVec, order is arbitrary
1988     EdgeVec rawEdges;
1989     while (d->stepSelect(d->airwayEdges)) {
1990         rawEdges.push_back(Edge(sqlite3_column_int64(d->airwayEdges, 0),
1991                                 sqlite3_column_int64(d->airwayEdges, 1)
1992                                 ));
1993     }
1994
1995     d->reset(d->airwayEdges);
1996     if (rawEdges.empty()) {
1997         return PositionedIDVec();
1998     }
1999
2000 // linearize
2001     PositionedIDDeque linearAirway;
2002     PositionedID firstId = rawEdges.front().first,
2003         lastId = rawEdges.front().second;
2004     std::set<PositionedID> seen;
2005
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();
2012
2013     while (!rawEdges.empty()) {
2014         Edge e = rawEdges.front();
2015         rawEdges.pop_front();
2016
2017     // look for new segments
2018         if (e.first == firstId) {
2019             linearAirway.push_front(e.second);
2020             seen.insert(e.second);
2021             firstId = e.second;
2022             continue;
2023         }
2024
2025         if (e.first == lastId) {
2026             linearAirway.push_back(e.second);
2027             seen.insert(e.second);
2028             lastId = e.second;
2029             continue;
2030         }
2031
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());
2038             continue;
2039         }
2040
2041     // push back to try later on
2042         rawEdges.push_back(e);
2043     }
2044
2045     return PositionedIDVec(linearAirway.begin(), linearAirway.end());
2046 }
2047
2048 PositionedID NavDataCache::findNavaidForRunway(PositionedID runway, FGPositioned::Type ty)
2049 {
2050   sqlite3_bind_int64(d->findNavaidForRunway, 1, runway);
2051   sqlite3_bind_int(d->findNavaidForRunway, 2, ty);
2052
2053   PositionedID result = 0;
2054   if (d->execSelect(d->findNavaidForRunway)) {
2055     result = sqlite3_column_int64(d->findNavaidForRunway, 0);
2056   }
2057
2058   d->reset(d->findNavaidForRunway);
2059   return result;
2060 }
2061
2062 bool NavDataCache::isReadOnly() const
2063 {
2064     return d->readOnly;
2065 }
2066
2067 SGPath NavDataCache::path() const
2068 {
2069     return d->path;
2070 }
2071
2072 /////////////////////////////////////////////////////////////////////////////////////////
2073 // Transaction RAII object
2074
2075 NavDataCache::Transaction::Transaction(NavDataCache* cache) :
2076     _instance(cache),
2077     _committed(false)
2078 {
2079     assert(cache);
2080     _instance->beginTransaction();
2081 }
2082
2083 NavDataCache::Transaction::~Transaction()
2084 {
2085     if (!_committed) {
2086         SG_LOG(SG_NAVCACHE, SG_INFO, "aborting cache transaction!");
2087         _instance->abortTransaction();
2088     }
2089 }
2090
2091 void NavDataCache::Transaction::commit()
2092 {
2093     assert(!_committed);
2094     _committed = true;
2095     _instance->commitTransaction();
2096 }
2097
2098 /////////////////////////////////////////////////////////////////////////////
2099
2100 class NavDataCache::ThreadedGUISearch::ThreadedGUISearchPrivate : public SGThread
2101 {
2102 public:
2103     ThreadedGUISearchPrivate() :
2104         db(NULL),
2105         isComplete(false),
2106         quit(false)
2107     {}
2108
2109     virtual void run()
2110     {
2111         while (!quit) {
2112             int err = sqlite3_step(query);
2113             if (err == SQLITE_DONE) {
2114                 break;
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);
2122             } else {
2123                 std::string errMsg = sqlite3_errmsg(db);
2124                 SG_LOG(SG_NAVCACHE, SG_ALERT, "Sqlite error:" << errMsg << " running threaded search query");
2125             }
2126         }
2127
2128         SGGuard<SGMutex> g(lock);
2129         isComplete = true;
2130     }
2131
2132     SGMutex lock;
2133     sqlite3* db;
2134     sqlite3_stmt_ptr query;
2135     PositionedIDVec results;
2136     bool isComplete;
2137     bool quit;
2138 };
2139
2140 NavDataCache::ThreadedGUISearch::ThreadedGUISearch(const std::string& term) :
2141     d(new ThreadedGUISearchPrivate)
2142 {
2143     SGPath p = NavDataCache::instance()->path();
2144     int openFlags = SQLITE_OPEN_READONLY;
2145     std::string pathUtf8 = simgear::strutils::convertWindowsLocal8BitToUtf8(p.str());
2146     sqlite3_open_v2(pathUtf8.c_str(), &d->db, openFlags, NULL);
2147
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);
2151
2152     d->start();
2153 }
2154
2155 NavDataCache::ThreadedGUISearch::~ThreadedGUISearch()
2156 {
2157     {
2158         SGGuard<SGMutex> g(d->lock);
2159         d->quit = true;
2160     }
2161
2162     d->join();
2163     sqlite3_finalize(d->query);
2164     sqlite3_close_v2(d->db);
2165 }
2166
2167 PositionedIDVec NavDataCache::ThreadedGUISearch::results() const
2168 {
2169     PositionedIDVec r;
2170     {
2171         SGGuard<SGMutex> g(d->lock);
2172         r = d->results;
2173     }
2174     return r;
2175 }
2176
2177 bool NavDataCache::ThreadedGUISearch::isComplete() const
2178 {
2179     SGGuard<SGMutex> g(d->lock);
2180     return d->isComplete;
2181 }
2182
2183 } // of namespace flightgear