sqlite3_accessor.cc 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <sqlite3.h>
  15. #include <string>
  16. #include <utility>
  17. #include <vector>
  18. #include <exceptions/exceptions.h>
  19. #include <dns/name.h>
  20. #include <datasrc/sqlite3_accessor.h>
  21. #include <datasrc/logger.h>
  22. #include <datasrc/data_source.h>
  23. #include <datasrc/factory.h>
  24. #include <datasrc/database.h>
  25. #include <util/filename.h>
  26. using namespace std;
  27. using namespace isc::data;
  28. namespace {
  29. // Expected schema. The major version must match else there is an error. If
  30. // the minor version of the database is less than this, a warning is output.
  31. //
  32. // It is assumed that a program written to run on m.n of the database will run
  33. // with a database version m.p, where p is any number. However, if p < n,
  34. // we assume that the database structure was upgraded for some reason, and that
  35. // some advantage may result if the database is upgraded. Conversely, if p > n,
  36. // The database is at a later version than the program was written for and the
  37. // program may not be taking advantage of features (possibly performance
  38. // improvements) added to the database.
  39. const int SQLITE_SCHEMA_MAJOR_VERSION = 2;
  40. const int SQLITE_SCHEMA_MINOR_VERSION = 1;
  41. }
  42. namespace isc {
  43. namespace datasrc {
  44. // The following enum and char* array define the SQL statements commonly
  45. // used in this implementation. Corresponding prepared statements (of
  46. // type sqlite3_stmt*) are maintained in the statements_ array of the
  47. // SQLite3Parameters structure.
  48. enum StatementID {
  49. ZONE = 0,
  50. ANY = 1,
  51. ANY_SUB = 2,
  52. BEGIN = 3,
  53. COMMIT = 4,
  54. ROLLBACK = 5,
  55. DEL_ZONE_RECORDS = 6,
  56. ADD_RECORD = 7,
  57. DEL_RECORD = 8,
  58. ITERATE_RECORDS = 9,
  59. ITERATE_NSEC3 = 10,
  60. FIND_PREVIOUS = 11,
  61. ADD_RECORD_DIFF = 12,
  62. LOW_DIFF_ID = 13,
  63. HIGH_DIFF_ID = 14,
  64. DIFF_RECS = 15,
  65. NSEC3 = 16,
  66. NSEC3_PREVIOUS = 17,
  67. NSEC3_LAST = 18,
  68. ADD_NSEC3_RECORD = 19,
  69. DEL_ZONE_NSEC3_RECORDS = 20,
  70. DEL_NSEC3_RECORD = 21,
  71. NUM_STATEMENTS = 22
  72. };
  73. const char* const text_statements[NUM_STATEMENTS] = {
  74. // note for ANY and ITERATE: the order of the SELECT values is
  75. // specifically chosen to match the enum values in RecordColumns
  76. "SELECT id FROM zones WHERE name=?1 AND rdclass = ?2", // ZONE
  77. "SELECT rdtype, ttl, sigtype, rdata FROM records " // ANY
  78. "WHERE zone_id=?1 AND name=?2",
  79. // ANY_SUB:
  80. // This query returns records in the specified zone for the domain
  81. // matching the passed name, and its sub-domains.
  82. "SELECT rdtype, ttl, sigtype, rdata "
  83. "FROM records WHERE zone_id=?1 AND rname LIKE ?2",
  84. "BEGIN", // BEGIN
  85. "COMMIT", // COMMIT
  86. "ROLLBACK", // ROLLBACK
  87. "DELETE FROM records WHERE zone_id=?1", // DEL_ZONE_RECORDS
  88. "INSERT INTO records " // ADD_RECORD
  89. "(zone_id, name, rname, ttl, rdtype, sigtype, rdata) "
  90. "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
  91. "DELETE FROM records WHERE zone_id=?1 AND name=?2 " // DEL_RECORD
  92. "AND rdtype=?3 AND rdata=?4",
  93. // ITERATE_RECORDS:
  94. // The following iterates the whole zone in the records table.
  95. "SELECT rdtype, ttl, sigtype, rdata, name FROM records "
  96. "WHERE zone_id = ?1 ORDER BY rname, rdtype",
  97. // ITERATE_NSEC3:
  98. // The following iterates the whole zone in the nsec3 table. As the
  99. // RRSIGs are for NSEC3s, we can hardcode the sigtype.
  100. "SELECT rdtype, ttl, \"NSEC3\", rdata, owner FROM nsec3 "
  101. "WHERE zone_id = ?1 ORDER BY hash, rdtype",
  102. /*
  103. * This one looks for previous name with NSEC record. It is done by
  104. * using the reversed name. The NSEC is checked because we need to
  105. * skip glue data, which don't have the NSEC.
  106. */
  107. "SELECT name FROM records " // FIND_PREVIOUS
  108. "WHERE zone_id=?1 AND rdtype = 'NSEC' AND "
  109. "rname < ?2 ORDER BY rname DESC LIMIT 1",
  110. "INSERT INTO diffs " // ADD_RECORD_DIFF
  111. "(zone_id, version, operation, name, rrtype, ttl, rdata) "
  112. "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
  113. // Two statements to select the lowest ID and highest ID in a set of
  114. // differences.
  115. "SELECT id FROM diffs " // LOW_DIFF_ID
  116. "WHERE zone_id=?1 AND version=?2 and OPERATION=?3 "
  117. "ORDER BY id ASC LIMIT 1",
  118. "SELECT id FROM diffs " // HIGH_DIFF_ID
  119. "WHERE zone_id=?1 AND version=?2 and OPERATION=?3 "
  120. "ORDER BY id DESC LIMIT 1",
  121. // In the next statement, note the redundant ID. This is to ensure
  122. // that the columns match the column IDs passed to the iterator
  123. "SELECT rrtype, ttl, id, rdata, name FROM diffs " // DIFF_RECS
  124. "WHERE zone_id=?1 AND id>=?2 and id<=?3 "
  125. "ORDER BY id ASC",
  126. // NSEC3: Query to get the NSEC3 records
  127. //
  128. // The "1" in SELECT is for positioning the rdata column to the
  129. // expected position, so we can reuse the same code as for other
  130. // lookups.
  131. "SELECT rdtype, ttl, 1, rdata FROM nsec3 WHERE zone_id=?1 AND "
  132. "hash=?2",
  133. // NSEC3_PREVIOUS: For getting the previous NSEC3 hash
  134. "SELECT DISTINCT hash FROM nsec3 WHERE zone_id=?1 AND hash < ?2 "
  135. "ORDER BY hash DESC LIMIT 1",
  136. // NSEC3_LAST: And for wrap-around
  137. "SELECT DISTINCT hash FROM nsec3 WHERE zone_id=?1 "
  138. "ORDER BY hash DESC LIMIT 1",
  139. // ADD_NSEC3_RECORD: Add NSEC3-related (NSEC3 or NSEC3-covering RRSIG) RR
  140. "INSERT INTO nsec3 (zone_id, hash, owner, ttl, rdtype, rdata) "
  141. "VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
  142. // DEL_ZONE_NSEC3_RECORDS: delete all NSEC3-related records from the zone
  143. "DELETE FROM nsec3 WHERE zone_id=?1",
  144. // DEL_NSEC3_RECORD: delete specified NSEC3-related records
  145. "DELETE FROM nsec3 WHERE zone_id=?1 AND hash=?2 "
  146. "AND rdtype=?3 AND rdata=?4"
  147. };
  148. struct SQLite3Parameters {
  149. SQLite3Parameters() :
  150. db_(NULL), major_version_(-1), minor_version_(-1),
  151. in_transaction(false), updating_zone(false), updated_zone_id(-1)
  152. {
  153. for (int i = 0; i < NUM_STATEMENTS; ++i) {
  154. statements_[i] = NULL;
  155. }
  156. }
  157. // This method returns the specified ID of SQLITE3 statement. If it's
  158. // not yet prepared it internally creates a new one. This way we can
  159. // avoid preparing unnecessary statements and minimize the overhead.
  160. sqlite3_stmt*
  161. getStatement(int id) {
  162. assert(id < NUM_STATEMENTS);
  163. if (statements_[id] == NULL) {
  164. assert(db_ != NULL);
  165. sqlite3_stmt* prepared = NULL;
  166. if (sqlite3_prepare_v2(db_, text_statements[id], -1, &prepared,
  167. NULL) != SQLITE_OK) {
  168. isc_throw(SQLite3Error, "Could not prepare SQLite statement: "
  169. << text_statements[id] <<
  170. ": " << sqlite3_errmsg(db_));
  171. }
  172. statements_[id] = prepared;
  173. }
  174. return (statements_[id]);
  175. }
  176. void
  177. finalizeStatements() {
  178. for (int i = 0; i < NUM_STATEMENTS; ++i) {
  179. if (statements_[i] != NULL) {
  180. sqlite3_finalize(statements_[i]);
  181. statements_[i] = NULL;
  182. }
  183. }
  184. }
  185. sqlite3* db_;
  186. int major_version_;
  187. int minor_version_;
  188. bool in_transaction; // whether or not a transaction has been started
  189. bool updating_zone; // whether or not updating the zone
  190. int updated_zone_id; // valid only when in_transaction is true
  191. string updated_zone_origin_; // ditto, and only needed to handle NSEC3s
  192. private:
  193. // statements_ are private and must be accessed via getStatement() outside
  194. // of this structure.
  195. sqlite3_stmt* statements_[NUM_STATEMENTS];
  196. };
  197. // This is a helper class to encapsulate the code logic of executing
  198. // a specific SQLite3 statement, ensuring the corresponding prepared
  199. // statement is always reset whether the execution is completed successfully
  200. // or it results in an exception.
  201. // Note that an object of this class is intended to be used for "ephemeral"
  202. // statement, which is completed with a single "step" (normally within a
  203. // single call to an SQLite3Database method). In particular, it cannot be
  204. // used for "SELECT" variants, which generally expect multiple matching rows.
  205. //
  206. // The bindXXX methods are straightforward wrappers for the corresponding
  207. // sqlite3_bind_xxx functions that make bindings with the given parameters
  208. // on the statement maintained in this class.
  209. class StatementProcessor {
  210. public:
  211. // desc will be used on failure in the what() message of the resulting
  212. // DataSourceError exception.
  213. StatementProcessor(SQLite3Parameters& dbparameters, StatementID stmt_id,
  214. const char* desc) :
  215. dbparameters_(dbparameters), stmt_(dbparameters.getStatement(stmt_id)),
  216. desc_(desc)
  217. {
  218. sqlite3_clear_bindings(stmt_);
  219. }
  220. ~StatementProcessor() {
  221. sqlite3_reset(stmt_);
  222. }
  223. void bindInt(int index, int val) {
  224. if (sqlite3_bind_int(stmt_, index, val) != SQLITE_OK) {
  225. isc_throw(DataSourceError,
  226. "failed to bind SQLite3 parameter: " <<
  227. sqlite3_errmsg(dbparameters_.db_));
  228. }
  229. }
  230. void bindInt64(int index, sqlite3_int64 val) {
  231. if (sqlite3_bind_int64(stmt_, index, val) != SQLITE_OK) {
  232. isc_throw(DataSourceError,
  233. "failed to bind SQLite3 parameter: " <<
  234. sqlite3_errmsg(dbparameters_.db_));
  235. }
  236. }
  237. // For simplicity, we assume val is a NULL-terminated string, and the
  238. // entire non NUL characters are to be bound. The destructor parameter
  239. // is normally either SQLITE_TRANSIENT or SQLITE_STATIC.
  240. void bindText(int index, const char* val, void(*destructor)(void*)) {
  241. if (sqlite3_bind_text(stmt_, index, val, -1, destructor)
  242. != SQLITE_OK) {
  243. isc_throw(DataSourceError, "failed to bind SQLite3 parameter: " <<
  244. sqlite3_errmsg(dbparameters_.db_));
  245. }
  246. }
  247. void exec() {
  248. if (sqlite3_step(stmt_) != SQLITE_DONE) {
  249. sqlite3_reset(stmt_);
  250. isc_throw(DataSourceError, "failed to " << desc_ << ": " <<
  251. sqlite3_errmsg(dbparameters_.db_));
  252. }
  253. }
  254. private:
  255. SQLite3Parameters& dbparameters_;
  256. sqlite3_stmt* stmt_;
  257. const char* const desc_;
  258. };
  259. SQLite3Accessor::SQLite3Accessor(const std::string& filename,
  260. const string& rrclass) :
  261. dbparameters_(new SQLite3Parameters),
  262. filename_(filename),
  263. class_(rrclass),
  264. database_name_("sqlite3_" +
  265. isc::util::Filename(filename).nameAndExtension())
  266. {
  267. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_NEWCONN);
  268. open(filename);
  269. }
  270. boost::shared_ptr<DatabaseAccessor>
  271. SQLite3Accessor::clone() {
  272. return (boost::shared_ptr<DatabaseAccessor>(new SQLite3Accessor(filename_,
  273. class_)));
  274. }
  275. namespace {
  276. // This is a helper class to initialize a Sqlite3 DB safely. An object of
  277. // this class encapsulates all temporary resources that are necessary for
  278. // the initialization, and release them in the destructor. Once everything
  279. // is properly initialized, the move() method moves the allocated resources
  280. // to the main object in an exception free manner. This way, the main code
  281. // for the initialization can be exception safe, and can provide the strong
  282. // exception guarantee.
  283. class Initializer {
  284. public:
  285. ~Initializer() {
  286. if (params_.db_ != NULL) {
  287. sqlite3_close(params_.db_);
  288. }
  289. }
  290. void move(SQLite3Parameters* dst) {
  291. *dst = params_;
  292. params_ = SQLite3Parameters(); // clear everything
  293. }
  294. SQLite3Parameters params_;
  295. };
  296. const char* const SCHEMA_LIST[] = {
  297. "CREATE TABLE schema_version (version INTEGER NOT NULL, "
  298. "minor INTEGER NOT NULL DEFAULT 0)",
  299. "INSERT INTO schema_version VALUES (2, 1)",
  300. "CREATE TABLE zones (id INTEGER PRIMARY KEY, "
  301. "name TEXT NOT NULL COLLATE NOCASE, "
  302. "rdclass TEXT NOT NULL COLLATE NOCASE DEFAULT 'IN', "
  303. "dnssec BOOLEAN NOT NULL DEFAULT 0)",
  304. "CREATE INDEX zones_byname ON zones (name)",
  305. "CREATE TABLE records (id INTEGER PRIMARY KEY, "
  306. "zone_id INTEGER NOT NULL, name TEXT NOT NULL COLLATE NOCASE, "
  307. "rname TEXT NOT NULL COLLATE NOCASE, ttl INTEGER NOT NULL, "
  308. "rdtype TEXT NOT NULL COLLATE NOCASE, sigtype TEXT COLLATE NOCASE, "
  309. "rdata TEXT NOT NULL)",
  310. "CREATE INDEX records_byname ON records (name)",
  311. "CREATE INDEX records_byrname ON records (rname)",
  312. // The next index is a tricky one. It's necessary for
  313. // FIND_PREVIOUS to use the index efficiently; since there's an
  314. // "inequality", the rname column must be placed later. records_byrname
  315. // may not be sufficient especially when the zone is not signed (and
  316. // defining a separate index for rdtype only doesn't work either; SQLite3
  317. // would then create a temporary B-tree for "ORDER BY").
  318. "CREATE INDEX records_bytype_and_rname ON records (rdtype, rname)",
  319. "CREATE TABLE nsec3 (id INTEGER PRIMARY KEY, zone_id INTEGER NOT NULL, "
  320. "hash TEXT NOT NULL COLLATE NOCASE, "
  321. "owner TEXT NOT NULL COLLATE NOCASE, "
  322. "ttl INTEGER NOT NULL, rdtype TEXT NOT NULL COLLATE NOCASE, "
  323. "rdata TEXT NOT NULL)",
  324. "CREATE INDEX nsec3_byhash ON nsec3 (hash)",
  325. "CREATE INDEX nsec3_byhash_and_rdtype ON nsec3 (hash, rdtype)",
  326. "CREATE TABLE diffs (id INTEGER PRIMARY KEY, "
  327. "zone_id INTEGER NOT NULL, "
  328. "version INTEGER NOT NULL, "
  329. "operation INTEGER NOT NULL, "
  330. "name TEXT NOT NULL COLLATE NOCASE, "
  331. "rrtype TEXT NOT NULL COLLATE NOCASE, "
  332. "ttl INTEGER NOT NULL, "
  333. "rdata TEXT NOT NULL)",
  334. NULL
  335. };
  336. sqlite3_stmt*
  337. prepare(sqlite3* const db, const char* const statement) {
  338. sqlite3_stmt* prepared = NULL;
  339. if (sqlite3_prepare_v2(db, statement, -1, &prepared, NULL) != SQLITE_OK) {
  340. isc_throw(SQLite3Error, "Could not prepare SQLite statement: " <<
  341. statement << ": " << sqlite3_errmsg(db));
  342. }
  343. return (prepared);
  344. }
  345. // small function to sleep for 0.1 seconds, needed when waiting for
  346. // exclusive database locks (which should only occur on startup, and only
  347. // when the database has not been created yet)
  348. void doSleep() {
  349. struct timespec req;
  350. req.tv_sec = 0;
  351. req.tv_nsec = 100000000;
  352. nanosleep(&req, NULL);
  353. }
  354. // returns the schema version if the schema version table exists
  355. // returns -1 if it does not
  356. int checkSchemaVersionElement(sqlite3* db, const char* const query) {
  357. sqlite3_stmt* prepared = NULL;
  358. // At this point in time, the database might be exclusively locked, in
  359. // which case even prepare() will return BUSY, so we may need to try a
  360. // few times
  361. for (size_t i = 0; i < 50; ++i) {
  362. int rc = sqlite3_prepare_v2(db, query, -1, &prepared, NULL);
  363. if (rc == SQLITE_ERROR) {
  364. // this is the error that is returned when the table does not
  365. // exist
  366. sqlite3_finalize(prepared);
  367. return (-1);
  368. } else if (rc == SQLITE_OK) {
  369. break;
  370. } else if (rc != SQLITE_BUSY || i == 50) {
  371. sqlite3_finalize(prepared);
  372. isc_throw(SQLite3Error, "Unable to prepare version query: "
  373. << rc << " " << sqlite3_errmsg(db));
  374. }
  375. doSleep();
  376. }
  377. if (sqlite3_step(prepared) != SQLITE_ROW) {
  378. sqlite3_finalize(prepared);
  379. isc_throw(SQLite3Error,
  380. "Unable to query version: " << sqlite3_errmsg(db));
  381. }
  382. int version = sqlite3_column_int(prepared, 0);
  383. sqlite3_finalize(prepared);
  384. return (version);
  385. }
  386. // Returns the schema major and minor version numbers in a pair.
  387. // Returns (-1, -1) if the table does not exist, (1, 0) for a V1
  388. // database, and (n, m) for any other.
  389. pair<int, int> checkSchemaVersion(sqlite3* db) {
  390. int major = checkSchemaVersionElement(db,
  391. "SELECT version FROM schema_version");
  392. if (major == -1) {
  393. return (make_pair(-1, -1));
  394. } else if (major == 1) {
  395. return (make_pair(1, 0));
  396. } else {
  397. int minor = checkSchemaVersionElement(db,
  398. "SELECT minor FROM schema_version");
  399. return (make_pair(major, minor));
  400. }
  401. }
  402. // A helper class used in createDatabase() below so we manage the one shot
  403. // transaction safely.
  404. class ScopedTransaction {
  405. public:
  406. ScopedTransaction(sqlite3* db) : db_(NULL) {
  407. // try for 5 secs (50*0.1)
  408. for (size_t i = 0; i < 50; ++i) {
  409. const int rc = sqlite3_exec(db, "BEGIN EXCLUSIVE TRANSACTION",
  410. NULL, NULL, NULL);
  411. if (rc == SQLITE_OK) {
  412. break;
  413. } else if (rc != SQLITE_BUSY || i == 50) {
  414. isc_throw(SQLite3Error, "Unable to acquire exclusive lock "
  415. "for database creation: " << sqlite3_errmsg(db));
  416. }
  417. doSleep();
  418. }
  419. // Hold the DB pointer once we have successfully acquired the lock.
  420. db_ = db;
  421. }
  422. ~ScopedTransaction() {
  423. if (db_ != NULL) {
  424. // Note: even rollback could fail in theory, but in that case
  425. // we cannot do much for safe recovery anyway. We could at least
  426. // log the event, but for now don't even bother to do that, with
  427. // the expectation that we'll soon stop creating the schema in this
  428. // module.
  429. sqlite3_exec(db_, "ROLLBACK", NULL, NULL, NULL);
  430. }
  431. }
  432. void commit() {
  433. if (sqlite3_exec(db_, "COMMIT TRANSACTION", NULL, NULL, NULL) !=
  434. SQLITE_OK) {
  435. isc_throw(SQLite3Error, "Unable to commit newly created database "
  436. "schema: " << sqlite3_errmsg(db_));
  437. }
  438. db_ = NULL;
  439. }
  440. private:
  441. sqlite3* db_;
  442. };
  443. // return db version
  444. pair<int, int>
  445. createDatabase(sqlite3* db, const std::string& name) {
  446. logger.warn(DATASRC_SQLITE_SETUP).arg(name);
  447. // try to get an exclusive lock. Once that is obtained, do the version
  448. // check *again*, just in case this process was racing another
  449. ScopedTransaction trasaction(db);
  450. pair<int, int> schema_version = checkSchemaVersion(db);
  451. if (schema_version.first == -1) {
  452. for (int i = 0; SCHEMA_LIST[i] != NULL; ++i) {
  453. if (sqlite3_exec(db, SCHEMA_LIST[i], NULL, NULL, NULL) !=
  454. SQLITE_OK) {
  455. isc_throw(SQLite3Error,
  456. "Failed to set up schema " << SCHEMA_LIST[i]);
  457. }
  458. }
  459. trasaction.commit();
  460. // Return the version. We query again to ensure that the only point
  461. // in which the current schema version is defined is in the create
  462. // statements.
  463. schema_version = checkSchemaVersion(db);
  464. }
  465. return (schema_version);
  466. }
  467. void
  468. checkAndSetupSchema(Initializer* initializer, const std::string& name) {
  469. sqlite3* const db = initializer->params_.db_;
  470. pair<int, int> schema_version = checkSchemaVersion(db);
  471. if (schema_version.first == -1) {
  472. schema_version = createDatabase(db, name);
  473. } else if (schema_version.first != SQLITE_SCHEMA_MAJOR_VERSION) {
  474. LOG_ERROR(logger, DATASRC_SQLITE_INCOMPATIBLE_VERSION)
  475. .arg(schema_version.first).arg(schema_version.second)
  476. .arg(SQLITE_SCHEMA_MAJOR_VERSION).arg(SQLITE_SCHEMA_MINOR_VERSION);
  477. isc_throw(IncompatibleDbVersion,
  478. "incompatible SQLite3 database version: " <<
  479. schema_version.first << "." << schema_version.second);
  480. } else if (schema_version.second < SQLITE_SCHEMA_MINOR_VERSION) {
  481. LOG_WARN(logger, DATASRC_SQLITE_COMPATIBLE_VERSION)
  482. .arg(schema_version.first).arg(schema_version.second)
  483. .arg(SQLITE_SCHEMA_MAJOR_VERSION).arg(SQLITE_SCHEMA_MINOR_VERSION);
  484. }
  485. initializer->params_.major_version_ = schema_version.first;
  486. initializer->params_.minor_version_ = schema_version.second;
  487. }
  488. }
  489. void
  490. SQLite3Accessor::open(const std::string& name) {
  491. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_CONNOPEN).arg(name);
  492. if (dbparameters_->db_ != NULL) {
  493. // There shouldn't be a way to trigger this anyway
  494. isc_throw(DataSourceError, "Duplicate SQLite open with " << name);
  495. }
  496. Initializer initializer;
  497. if (sqlite3_open(name.c_str(), &initializer.params_.db_) != 0) {
  498. isc_throw(SQLite3Error, "Cannot open SQLite database file: " << name);
  499. }
  500. checkAndSetupSchema(&initializer, name);
  501. initializer.move(dbparameters_.get());
  502. }
  503. SQLite3Accessor::~SQLite3Accessor() {
  504. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_DROPCONN);
  505. if (dbparameters_->db_ != NULL) {
  506. close();
  507. }
  508. }
  509. void
  510. SQLite3Accessor::close(void) {
  511. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_CONNCLOSE);
  512. if (dbparameters_->db_ == NULL) {
  513. isc_throw(DataSourceError,
  514. "SQLite data source is being closed before open");
  515. }
  516. dbparameters_->finalizeStatements();
  517. sqlite3_close(dbparameters_->db_);
  518. dbparameters_->db_ = NULL;
  519. }
  520. std::pair<bool, int>
  521. SQLite3Accessor::getZone(const std::string& name) const {
  522. int rc;
  523. sqlite3_stmt* const stmt = dbparameters_->getStatement(ZONE);
  524. // Take the statement (simple SELECT id FROM zones WHERE...)
  525. // and prepare it (bind the parameters to it)
  526. sqlite3_reset(stmt);
  527. rc = sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
  528. if (rc != SQLITE_OK) {
  529. isc_throw(SQLite3Error, "Could not bind " << name <<
  530. " to SQL statement (zone)");
  531. }
  532. rc = sqlite3_bind_text(stmt, 2, class_.c_str(), -1, SQLITE_STATIC);
  533. if (rc != SQLITE_OK) {
  534. isc_throw(SQLite3Error, "Could not bind " << class_ <<
  535. " to SQL statement (zone)");
  536. }
  537. // Get the data there and see if it found anything
  538. rc = sqlite3_step(stmt);
  539. if (rc == SQLITE_ROW) {
  540. const int zone_id = sqlite3_column_int(stmt, 0);
  541. sqlite3_reset(stmt);
  542. return (pair<bool, int>(true, zone_id));
  543. } else if (rc == SQLITE_DONE) {
  544. // Free resources
  545. sqlite3_reset(stmt);
  546. return (pair<bool, int>(false, 0));
  547. }
  548. sqlite3_reset(stmt);
  549. isc_throw(DataSourceError, "Unexpected failure in sqlite3_step: " <<
  550. sqlite3_errmsg(dbparameters_->db_));
  551. // Compilers might not realize isc_throw always throws
  552. return (std::pair<bool, int>(false, 0));
  553. }
  554. namespace {
  555. // Conversion to plain char
  556. const char*
  557. convertToPlainChar(const unsigned char* ucp, sqlite3 *db) {
  558. if (ucp == NULL) {
  559. // The field can really be NULL, in which case we return an
  560. // empty string, or sqlite may have run out of memory, in
  561. // which case we raise an error
  562. if (sqlite3_errcode(db) == SQLITE_NOMEM) {
  563. isc_throw(DataSourceError,
  564. "Sqlite3 backend encountered a memory allocation "
  565. "error in sqlite3_column_text()");
  566. } else {
  567. return ("");
  568. }
  569. }
  570. const void* p = ucp;
  571. return (static_cast<const char*>(p));
  572. }
  573. }
  574. class SQLite3Accessor::Context : public DatabaseAccessor::IteratorContext {
  575. public:
  576. // Construct an iterator for all records. When constructed this
  577. // way, the getNext() call will copy all fields
  578. Context(const boost::shared_ptr<const SQLite3Accessor>& accessor, int id) :
  579. iterator_type_(ITT_ALL),
  580. accessor_(accessor),
  581. statement_(NULL),
  582. statement2_(NULL),
  583. rc_(SQLITE_OK),
  584. rc2_(SQLITE_OK),
  585. name_("")
  586. {
  587. // We create the statements now and then just keep getting data
  588. // from them.
  589. statement_ = prepare(accessor->dbparameters_->db_,
  590. text_statements[ITERATE_NSEC3]);
  591. bindZoneId(id);
  592. std::swap(statement_, statement2_);
  593. statement_ = prepare(accessor->dbparameters_->db_,
  594. text_statements[ITERATE_RECORDS]);
  595. bindZoneId(id);
  596. }
  597. // What kind of query it is - selection of the statement for DB
  598. enum QueryType {
  599. QT_ANY, // Directly for a domain
  600. QT_SUBDOMAINS, // Subdomains of a given domain
  601. QT_NSEC3 // Domain in the NSEC3 namespace (the name is is the hash,
  602. // not the whole name)
  603. };
  604. // Construct an iterator for records with a specific name. When constructed
  605. // this way, the getNext() call will copy all fields except name
  606. Context(const boost::shared_ptr<const SQLite3Accessor>& accessor, int id,
  607. const std::string& name, QueryType qtype) :
  608. iterator_type_(qtype == QT_NSEC3 ? ITT_NSEC3 : ITT_NAME),
  609. accessor_(accessor),
  610. statement_(NULL),
  611. statement2_(NULL),
  612. rc_(SQLITE_OK),
  613. rc2_(SQLITE_OK),
  614. name_(name)
  615. {
  616. // Choose the statement text depending on the query type, and
  617. // prepare a statement to get data from it.
  618. switch (qtype) {
  619. case QT_ANY:
  620. statement_ = prepare(accessor->dbparameters_->db_,
  621. text_statements[ANY]);
  622. bindZoneId(id);
  623. bindName(name_);
  624. break;
  625. case QT_SUBDOMAINS:
  626. statement_ = prepare(accessor->dbparameters_->db_,
  627. text_statements[ANY_SUB]);
  628. bindZoneId(id);
  629. // Done once, this should not be very inefficient.
  630. bindName(isc::dns::Name(name_).reverse().toText() + "%");
  631. break;
  632. case QT_NSEC3:
  633. statement_ = prepare(accessor->dbparameters_->db_,
  634. text_statements[NSEC3]);
  635. bindZoneId(id);
  636. bindName(name_);
  637. break;
  638. default:
  639. // Can Not Happen - there isn't any other type of query
  640. // and all the calls to the constructor are from this
  641. // file. Therefore no way to test it throws :-(.
  642. isc_throw(Unexpected,
  643. "Invalid qtype passed - unreachable code branch "
  644. "reached");
  645. }
  646. }
  647. bool getNext(std::string (&data)[COLUMN_COUNT]) {
  648. // If there's another row, get it
  649. // If finalize has been called (e.g. when previous getNext() got
  650. // SQLITE_DONE), directly return false
  651. while (statement_ != NULL) {
  652. rc_ = sqlite3_step(statement_);
  653. if (rc_ == SQLITE_ROW) {
  654. // For both types, we copy the first four columns
  655. copyColumn(data, TYPE_COLUMN);
  656. copyColumn(data, TTL_COLUMN);
  657. // The NSEC3 lookup does not provide the SIGTYPE, it is not
  658. // necessary and not contained in the table.
  659. if (iterator_type_ != ITT_NSEC3) {
  660. copyColumn(data, SIGTYPE_COLUMN);
  661. }
  662. copyColumn(data, RDATA_COLUMN);
  663. // Only copy Name if we are iterating over every record
  664. if (iterator_type_ == ITT_ALL) {
  665. copyColumn(data, NAME_COLUMN);
  666. }
  667. return (true);
  668. } else if (rc_ != SQLITE_DONE) {
  669. isc_throw(DataSourceError,
  670. "Unexpected failure in sqlite3_step: " <<
  671. sqlite3_errmsg(accessor_->dbparameters_->db_));
  672. }
  673. // We are done with statement_. If statement2_ has not been
  674. // used yet, try that one now.
  675. if ((statement2_ == NULL) || (rc2_ != SQLITE_OK)) {
  676. break;
  677. }
  678. std::swap(statement_, statement2_);
  679. std::swap(rc_, rc2_);
  680. }
  681. finalize();
  682. return (false);
  683. }
  684. virtual ~Context() {
  685. finalize();
  686. }
  687. private:
  688. // Depending on which constructor is called, behaviour is slightly
  689. // different. We keep track of what to do with the iterator type
  690. // See description of getNext() and the constructors
  691. enum IteratorType {
  692. ITT_ALL,
  693. ITT_NAME,
  694. ITT_NSEC3
  695. };
  696. void copyColumn(std::string (&data)[COLUMN_COUNT], int column) {
  697. data[column] = convertToPlainChar(sqlite3_column_text(statement_,
  698. column),
  699. accessor_->dbparameters_->db_);
  700. }
  701. void bindZoneId(const int zone_id) {
  702. if (sqlite3_bind_int(statement_, 1, zone_id) != SQLITE_OK) {
  703. finalize();
  704. isc_throw(SQLite3Error, "Could not bind int " << zone_id <<
  705. " to SQL statement: " <<
  706. sqlite3_errmsg(accessor_->dbparameters_->db_));
  707. }
  708. }
  709. void bindName(const std::string& name) {
  710. if (sqlite3_bind_text(statement_, 2, name.c_str(), -1,
  711. SQLITE_TRANSIENT) != SQLITE_OK) {
  712. const char* errmsg = sqlite3_errmsg(accessor_->dbparameters_->db_);
  713. finalize();
  714. isc_throw(SQLite3Error, "Could not bind text '" << name <<
  715. "' to SQL statement: " << errmsg);
  716. }
  717. }
  718. void finalize() {
  719. if (statement_ != NULL) {
  720. sqlite3_finalize(statement_);
  721. statement_ = NULL;
  722. }
  723. if (statement2_ != NULL) {
  724. sqlite3_finalize(statement2_);
  725. statement2_ = NULL;
  726. }
  727. }
  728. const IteratorType iterator_type_;
  729. boost::shared_ptr<const SQLite3Accessor> accessor_;
  730. sqlite3_stmt* statement_;
  731. sqlite3_stmt* statement2_;
  732. int rc_;
  733. int rc2_;
  734. const std::string name_;
  735. };
  736. // Methods to retrieve the various iterators
  737. DatabaseAccessor::IteratorContextPtr
  738. SQLite3Accessor::getRecords(const std::string& name, int id,
  739. bool subdomains) const
  740. {
  741. return (IteratorContextPtr(new Context(shared_from_this(), id, name,
  742. subdomains ?
  743. Context::QT_SUBDOMAINS :
  744. Context::QT_ANY)));
  745. }
  746. DatabaseAccessor::IteratorContextPtr
  747. SQLite3Accessor::getNSEC3Records(const std::string& hash, int id) const {
  748. return (IteratorContextPtr(new Context(shared_from_this(), id, hash,
  749. Context::QT_NSEC3)));
  750. }
  751. DatabaseAccessor::IteratorContextPtr
  752. SQLite3Accessor::getAllRecords(int id) const {
  753. return (IteratorContextPtr(new Context(shared_from_this(), id)));
  754. }
  755. /// \brief Difference Iterator
  756. ///
  757. /// This iterator is used to search through the differences table for the
  758. /// resouce records making up an IXFR between two versions of a zone.
  759. class SQLite3Accessor::DiffContext : public DatabaseAccessor::IteratorContext {
  760. public:
  761. /// \brief Constructor
  762. ///
  763. /// Constructs the iterator for the difference sequence. It is
  764. /// passed two parameters, the first and last versions in the difference
  765. /// sequence. Note that because of serial number rollover, it may well
  766. /// be that the start serial number is greater than the end one.
  767. ///
  768. /// \param zone_id ID of the zone (in the zone table)
  769. /// \param start Serial number of first version in difference sequence
  770. /// \param end Serial number of last version in difference sequence
  771. ///
  772. /// \exception any A number of exceptions can be expected
  773. DiffContext(const boost::shared_ptr<const SQLite3Accessor>& accessor,
  774. int zone_id, uint32_t start, uint32_t end) :
  775. accessor_(accessor),
  776. last_status_(SQLITE_ROW)
  777. {
  778. try {
  779. int low_id = findIndex(LOW_DIFF_ID, zone_id, start, DIFF_DELETE);
  780. int high_id = findIndex(HIGH_DIFF_ID, zone_id, end, DIFF_ADD);
  781. // Prepare the statement that will return data values
  782. reset(DIFF_RECS);
  783. bindInt(DIFF_RECS, 1, zone_id);
  784. bindInt(DIFF_RECS, 2, low_id);
  785. bindInt(DIFF_RECS, 3, high_id);
  786. } catch (...) {
  787. // Something wrong, clear up everything.
  788. accessor_->dbparameters_->finalizeStatements();
  789. throw;
  790. }
  791. }
  792. /// \brief Destructor
  793. virtual ~DiffContext()
  794. {}
  795. /// \brief Get Next Diff Record
  796. ///
  797. /// Returns the next difference record in the difference sequence.
  798. ///
  799. /// \param data Array of std::strings COLUMN_COUNT long. The results
  800. /// are returned in this.
  801. ///
  802. /// \return bool true if data is returned, false if not.
  803. ///
  804. /// \exception any Varied
  805. bool getNext(std::string (&data)[COLUMN_COUNT]) {
  806. if (last_status_ != SQLITE_DONE) {
  807. // Last call (if any) didn't reach end of result set, so we
  808. // can read another row from it.
  809. //
  810. // Get a pointer to the statement for brevity (this does not
  811. // transfer ownership of the statement to this class, so there is
  812. // no need to tidy up after we have finished using it).
  813. sqlite3_stmt* stmt =
  814. accessor_->dbparameters_->getStatement(DIFF_RECS);
  815. const int rc(sqlite3_step(stmt));
  816. if (rc == SQLITE_ROW) {
  817. // Copy the data across to the output array
  818. copyColumn(DIFF_RECS, data, TYPE_COLUMN);
  819. copyColumn(DIFF_RECS, data, TTL_COLUMN);
  820. copyColumn(DIFF_RECS, data, NAME_COLUMN);
  821. copyColumn(DIFF_RECS, data, RDATA_COLUMN);
  822. } else if (rc != SQLITE_DONE) {
  823. isc_throw(DataSourceError,
  824. "Unexpected failure in sqlite3_step: " <<
  825. sqlite3_errmsg(accessor_->dbparameters_->db_));
  826. }
  827. last_status_ = rc;
  828. }
  829. return (last_status_ == SQLITE_ROW);
  830. }
  831. private:
  832. /// \brief Reset prepared statement
  833. ///
  834. /// Sets up the statement so that new parameters can be attached to it and
  835. /// that it can be used to query for another difference sequence.
  836. ///
  837. /// \param stindex Index of prepared statement to which to bind
  838. void reset(int stindex) {
  839. sqlite3_stmt* stmt = accessor_->dbparameters_->getStatement(stindex);
  840. if ((sqlite3_reset(stmt) != SQLITE_OK) ||
  841. (sqlite3_clear_bindings(stmt) != SQLITE_OK)) {
  842. isc_throw(SQLite3Error, "Could not clear statement bindings in '" <<
  843. text_statements[stindex] << "': " <<
  844. sqlite3_errmsg(accessor_->dbparameters_->db_));
  845. }
  846. }
  847. /// \brief Bind Int
  848. ///
  849. /// Binds an integer to a specific variable in a prepared statement.
  850. ///
  851. /// \param stindex Index of prepared statement to which to bind
  852. /// \param varindex Index of variable to which to bind
  853. /// \param value Value of variable to bind
  854. /// \exception SQLite3Error on an error
  855. void bindInt(int stindex, int varindex, sqlite3_int64 value) {
  856. if (sqlite3_bind_int64(accessor_->dbparameters_->getStatement(stindex),
  857. varindex, value) != SQLITE_OK) {
  858. isc_throw(SQLite3Error, "Could not bind value to parameter " <<
  859. varindex << " in statement '" <<
  860. text_statements[stindex] << "': " <<
  861. sqlite3_errmsg(accessor_->dbparameters_->db_));
  862. }
  863. }
  864. ///\brief Get Single Value
  865. ///
  866. /// Executes a prepared statement (which has parameters bound to it)
  867. /// for which the result of a single value is expected.
  868. ///
  869. /// \param stindex Index of prepared statement in statement table.
  870. ///
  871. /// \return Value of SELECT.
  872. ///
  873. /// \exception TooMuchData Multiple rows returned when one expected
  874. /// \exception TooLittleData Zero rows returned when one expected
  875. /// \exception DataSourceError SQLite3-related error
  876. int getSingleValue(StatementID stindex) {
  877. // Get a pointer to the statement for brevity (does not transfer
  878. // resources)
  879. sqlite3_stmt* stmt = accessor_->dbparameters_->getStatement(stindex);
  880. // Execute the data. Should be just one result
  881. int rc = sqlite3_step(stmt);
  882. int result = -1;
  883. if (rc == SQLITE_ROW) {
  884. // Got some data, extract the value
  885. result = sqlite3_column_int(stmt, 0);
  886. rc = sqlite3_step(stmt);
  887. if (rc == SQLITE_DONE) {
  888. // All OK, exit with the value.
  889. return (result);
  890. } else if (rc == SQLITE_ROW) {
  891. isc_throw(TooMuchData, "request to return one value from "
  892. "diffs table returned multiple values");
  893. }
  894. } else if (rc == SQLITE_DONE) {
  895. // No data in the table. A bare exception with no explanation is
  896. // thrown, as it will be replaced by a more informative one by
  897. // the caller.
  898. isc_throw(TooLittleData, "");
  899. }
  900. // We get here on an error.
  901. isc_throw(DataSourceError, "could not get data from diffs table: " <<
  902. sqlite3_errmsg(accessor_->dbparameters_->db_));
  903. // Keep the compiler happy with a return value.
  904. return (result);
  905. }
  906. /// \brief Find index
  907. ///
  908. /// Executes the prepared statement locating the high or low index in
  909. /// the diffs table and returns that index.
  910. ///
  911. /// \param stmt_id Index of the prepared statement to execute
  912. /// \param zone_id ID of the zone for which the index is being sought
  913. /// \param serial Zone serial number for which an index is being sought.
  914. /// \param diff Code to delete record additions or deletions
  915. ///
  916. /// \return int ID of the row in the difss table corresponding to the
  917. /// statement.
  918. ///
  919. /// \exception TooLittleData Internal error, no result returned when one
  920. /// was expected.
  921. /// \exception NoSuchSerial Serial number not found.
  922. /// \exception NoDiffsData No data for this zone found in diffs table
  923. int findIndex(StatementID stindex, int zone_id, uint32_t serial, int diff) {
  924. // Set up the statement
  925. reset(stindex);
  926. bindInt(stindex, 1, zone_id);
  927. bindInt(stindex, 2, serial);
  928. bindInt(stindex, 3, diff);
  929. // Execute the statement
  930. int result = -1;
  931. try {
  932. result = getSingleValue(stindex);
  933. } catch (const TooLittleData&) {
  934. // No data returned but the SQL query succeeded. Only possibility
  935. // is that there is no entry in the differences table for the given
  936. // zone and version.
  937. isc_throw(NoSuchSerial, "No entry in differences table for" <<
  938. " zone ID " << zone_id << ", serial number " << serial);
  939. }
  940. return (result);
  941. }
  942. /// \brief Copy Column to Output
  943. ///
  944. /// Copies the textual data in the result set to the specified column
  945. /// in the output.
  946. ///
  947. /// \param stindex Index of prepared statement used to access data
  948. /// \param data Array of columns passed to getNext
  949. /// \param column Column of output to copy
  950. void copyColumn(StatementID stindex, std::string (&data)[COLUMN_COUNT],
  951. int column) {
  952. // Get a pointer to the statement for brevity (does not transfer
  953. // resources)
  954. sqlite3_stmt* stmt = accessor_->dbparameters_->getStatement(stindex);
  955. data[column] = convertToPlainChar(sqlite3_column_text(stmt,
  956. column),
  957. accessor_->dbparameters_->db_);
  958. }
  959. // Attributes
  960. boost::shared_ptr<const SQLite3Accessor> accessor_; // Accessor object
  961. int last_status_; // Last status received from sqlite3_step
  962. };
  963. // ... and return the iterator
  964. DatabaseAccessor::IteratorContextPtr
  965. SQLite3Accessor::getDiffs(int id, uint32_t start, uint32_t end) const {
  966. return (IteratorContextPtr(new DiffContext(shared_from_this(), id, start,
  967. end)));
  968. }
  969. pair<bool, int>
  970. SQLite3Accessor::startUpdateZone(const string& zone_name, const bool replace) {
  971. if (dbparameters_->updating_zone) {
  972. isc_throw(DataSourceError,
  973. "duplicate zone update on SQLite3 data source");
  974. }
  975. if (dbparameters_->in_transaction) {
  976. isc_throw(DataSourceError,
  977. "zone update attempt in another SQLite3 transaction");
  978. }
  979. const pair<bool, int> zone_info(getZone(zone_name));
  980. if (!zone_info.first) {
  981. return (zone_info);
  982. }
  983. StatementProcessor(*dbparameters_, BEGIN,
  984. "start an SQLite3 update transaction").exec();
  985. if (replace) {
  986. // First, clear all current data from tables.
  987. typedef pair<StatementID, const char* const> StatementSpec;
  988. const StatementSpec delzone_stmts[] =
  989. { StatementSpec(DEL_ZONE_RECORDS, "delete zone records"),
  990. StatementSpec(DEL_ZONE_NSEC3_RECORDS,
  991. "delete zone NSEC3 records") };
  992. try {
  993. for (size_t i = 0;
  994. i < sizeof(delzone_stmts) / sizeof(delzone_stmts[0]);
  995. ++i) {
  996. StatementProcessor delzone_proc(*dbparameters_,
  997. delzone_stmts[i].first,
  998. delzone_stmts[i].second);
  999. delzone_proc.bindInt(1, zone_info.second);
  1000. delzone_proc.exec();
  1001. }
  1002. } catch (const DataSourceError&) {
  1003. // Once we start a transaction, if something unexpected happens
  1004. // we need to rollback the transaction so that a subsequent update
  1005. // is still possible with this accessor.
  1006. StatementProcessor(*dbparameters_, ROLLBACK,
  1007. "rollback an SQLite3 transaction").exec();
  1008. throw;
  1009. }
  1010. }
  1011. dbparameters_->in_transaction = true;
  1012. dbparameters_->updating_zone = true;
  1013. dbparameters_->updated_zone_id = zone_info.second;
  1014. dbparameters_->updated_zone_origin_ = zone_name;
  1015. return (zone_info);
  1016. }
  1017. void
  1018. SQLite3Accessor::startTransaction() {
  1019. if (dbparameters_->in_transaction) {
  1020. isc_throw(DataSourceError,
  1021. "duplicate transaction on SQLite3 data source");
  1022. }
  1023. StatementProcessor(*dbparameters_, BEGIN,
  1024. "start an SQLite3 transaction").exec();
  1025. dbparameters_->in_transaction = true;
  1026. }
  1027. void
  1028. SQLite3Accessor::commit() {
  1029. if (!dbparameters_->in_transaction) {
  1030. isc_throw(DataSourceError, "performing commit on SQLite3 "
  1031. "data source without transaction");
  1032. }
  1033. StatementProcessor(*dbparameters_, COMMIT,
  1034. "commit an SQLite3 transaction").exec();
  1035. dbparameters_->in_transaction = false;
  1036. dbparameters_->updating_zone = false;
  1037. dbparameters_->updated_zone_id = -1;
  1038. dbparameters_->updated_zone_origin_.clear();
  1039. }
  1040. void
  1041. SQLite3Accessor::rollback() {
  1042. if (!dbparameters_->in_transaction) {
  1043. isc_throw(DataSourceError, "performing rollback on SQLite3 "
  1044. "data source without transaction");
  1045. }
  1046. StatementProcessor(*dbparameters_, ROLLBACK,
  1047. "rollback an SQLite3 transaction").exec();
  1048. dbparameters_->in_transaction = false;
  1049. dbparameters_->updating_zone = false;
  1050. dbparameters_->updated_zone_id = -1;
  1051. dbparameters_->updated_zone_origin_.clear();
  1052. }
  1053. namespace {
  1054. // Commonly used code sequence for adding/deleting record
  1055. template <typename COLUMNS_TYPE>
  1056. void
  1057. doUpdate(SQLite3Parameters& dbparams, StatementID stmt_id,
  1058. COLUMNS_TYPE update_params, const char* exec_desc)
  1059. {
  1060. StatementProcessor proc(dbparams, stmt_id, exec_desc);
  1061. int param_id = 0;
  1062. proc.bindInt(++param_id, dbparams.updated_zone_id);
  1063. const size_t column_count =
  1064. sizeof(update_params) / sizeof(update_params[0]);
  1065. for (int i = 0; i < column_count; ++i) {
  1066. // The old sqlite3 data source API assumes NULL for an empty column.
  1067. // We need to provide compatibility at least for now.
  1068. proc.bindText(++param_id, update_params[i].empty() ? NULL :
  1069. update_params[i].c_str(), SQLITE_TRANSIENT);
  1070. }
  1071. proc.exec();
  1072. }
  1073. }
  1074. void
  1075. SQLite3Accessor::addRecordToZone(const string (&columns)[ADD_COLUMN_COUNT]) {
  1076. if (!dbparameters_->updating_zone) {
  1077. isc_throw(DataSourceError, "adding record to SQLite3 "
  1078. "data source without transaction");
  1079. }
  1080. doUpdate<const string (&)[ADD_COLUMN_COUNT]>(
  1081. *dbparameters_, ADD_RECORD, columns, "add record to zone");
  1082. }
  1083. void
  1084. SQLite3Accessor::addNSEC3RecordToZone(
  1085. const string (&columns)[ADD_NSEC3_COLUMN_COUNT])
  1086. {
  1087. if (!dbparameters_->updating_zone) {
  1088. isc_throw(DataSourceError, "adding NSEC3-related record to SQLite3 "
  1089. "data source without transaction");
  1090. }
  1091. // XXX: the current implementation of SQLite3 schema requires the 'owner'
  1092. // column, and the current implementation of getAllRecords() relies on it,
  1093. // while the addNSEC3RecordToZone interface doesn't provide it explicitly.
  1094. // We should revisit it at the design level, but for now we internally
  1095. // convert the given parameter to satisfy the internal requirements.
  1096. const string sqlite3_columns[ADD_NSEC3_COLUMN_COUNT + 1] =
  1097. { columns[ADD_NSEC3_HASH],
  1098. columns[ADD_NSEC3_HASH] + "." + dbparameters_->updated_zone_origin_,
  1099. columns[ADD_NSEC3_TTL],
  1100. columns[ADD_NSEC3_TYPE], columns[ADD_NSEC3_RDATA] };
  1101. doUpdate<const string (&)[ADD_NSEC3_COLUMN_COUNT + 1]>(
  1102. *dbparameters_, ADD_NSEC3_RECORD, sqlite3_columns,
  1103. "add NSEC3 record to zone");
  1104. }
  1105. void
  1106. SQLite3Accessor::deleteRecordInZone(const string (&params)[DEL_PARAM_COUNT]) {
  1107. if (!dbparameters_->updating_zone) {
  1108. isc_throw(DataSourceError, "deleting record in SQLite3 "
  1109. "data source without transaction");
  1110. }
  1111. doUpdate<const string (&)[DEL_PARAM_COUNT]>(
  1112. *dbparameters_, DEL_RECORD, params, "delete record from zone");
  1113. }
  1114. void
  1115. SQLite3Accessor::deleteNSEC3RecordInZone(
  1116. const string (&params)[DEL_PARAM_COUNT])
  1117. {
  1118. if (!dbparameters_->updating_zone) {
  1119. isc_throw(DataSourceError, "deleting NSEC3-related record in SQLite3 "
  1120. "data source without transaction");
  1121. }
  1122. doUpdate<const string (&)[DEL_PARAM_COUNT]>(
  1123. *dbparameters_, DEL_NSEC3_RECORD, params,
  1124. "delete NSEC3 record from zone");
  1125. }
  1126. void
  1127. SQLite3Accessor::addRecordDiff(int zone_id, uint32_t serial,
  1128. DiffOperation operation,
  1129. const std::string (&params)[DIFF_PARAM_COUNT])
  1130. {
  1131. if (!dbparameters_->updating_zone) {
  1132. isc_throw(DataSourceError, "adding record diff without update "
  1133. "transaction on " << getDBName());
  1134. }
  1135. if (zone_id != dbparameters_->updated_zone_id) {
  1136. isc_throw(DataSourceError, "bad zone ID for adding record diff on "
  1137. << getDBName() << ": " << zone_id << ", must be "
  1138. << dbparameters_->updated_zone_id);
  1139. }
  1140. StatementProcessor proc(*dbparameters_, ADD_RECORD_DIFF,
  1141. "add record diff");
  1142. int param_id = 0;
  1143. proc.bindInt(++param_id, zone_id);
  1144. proc.bindInt64(++param_id, serial);
  1145. proc.bindInt(++param_id, operation);
  1146. for (int i = 0; i < DIFF_PARAM_COUNT; ++i) {
  1147. proc.bindText(++param_id, params[i].c_str(), SQLITE_TRANSIENT);
  1148. }
  1149. proc.exec();
  1150. }
  1151. std::string
  1152. SQLite3Accessor::findPreviousName(int zone_id, const std::string& rname)
  1153. const
  1154. {
  1155. sqlite3_stmt* const stmt = dbparameters_->getStatement(FIND_PREVIOUS);
  1156. sqlite3_reset(stmt);
  1157. sqlite3_clear_bindings(stmt);
  1158. if (sqlite3_bind_int(stmt, 1, zone_id) != SQLITE_OK) {
  1159. isc_throw(SQLite3Error, "Could not bind zone ID " << zone_id <<
  1160. " to SQL statement (find previous): " <<
  1161. sqlite3_errmsg(dbparameters_->db_));
  1162. }
  1163. if (sqlite3_bind_text(stmt, 2, rname.c_str(), -1, SQLITE_STATIC) !=
  1164. SQLITE_OK) {
  1165. isc_throw(SQLite3Error, "Could not bind name " << rname <<
  1166. " to SQL statement (find previous): " <<
  1167. sqlite3_errmsg(dbparameters_->db_));
  1168. }
  1169. std::string result;
  1170. const int rc = sqlite3_step(stmt);
  1171. if (rc == SQLITE_ROW) {
  1172. // We found it
  1173. result = convertToPlainChar(sqlite3_column_text(stmt, 0),
  1174. dbparameters_->db_);
  1175. }
  1176. sqlite3_reset(stmt);
  1177. if (rc == SQLITE_DONE) {
  1178. // No NSEC records here, this DB doesn't support DNSSEC or
  1179. // we asked before the apex
  1180. isc_throw(isc::NotImplemented, "The zone doesn't support DNSSEC or "
  1181. "query before apex");
  1182. }
  1183. if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
  1184. // Some kind of error
  1185. isc_throw(SQLite3Error, "Could not get data for previous name");
  1186. }
  1187. return (result);
  1188. }
  1189. std::string
  1190. SQLite3Accessor::findPreviousNSEC3Hash(int zone_id, const std::string& hash)
  1191. const
  1192. {
  1193. sqlite3_stmt* const stmt = dbparameters_->getStatement(NSEC3_PREVIOUS);
  1194. sqlite3_reset(stmt);
  1195. sqlite3_clear_bindings(stmt);
  1196. if (sqlite3_bind_int(stmt, 1, zone_id) != SQLITE_OK) {
  1197. isc_throw(SQLite3Error, "Could not bind zone ID " << zone_id <<
  1198. " to SQL statement (find previous NSEC3): " <<
  1199. sqlite3_errmsg(dbparameters_->db_));
  1200. }
  1201. if (sqlite3_bind_text(stmt, 2, hash.c_str(), -1, SQLITE_STATIC) !=
  1202. SQLITE_OK) {
  1203. isc_throw(SQLite3Error, "Could not bind hash " << hash <<
  1204. " to SQL statement (find previous NSEC3): " <<
  1205. sqlite3_errmsg(dbparameters_->db_));
  1206. }
  1207. std::string result;
  1208. const int rc = sqlite3_step(stmt);
  1209. if (rc == SQLITE_ROW) {
  1210. // We found it
  1211. result = convertToPlainChar(sqlite3_column_text(stmt, 0),
  1212. dbparameters_->db_);
  1213. }
  1214. sqlite3_reset(stmt);
  1215. if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
  1216. // Some kind of error
  1217. isc_throw(SQLite3Error, "Could not get data for previous hash");
  1218. }
  1219. if (rc == SQLITE_DONE) {
  1220. // No NSEC3 records before this hash. This means we should wrap
  1221. // around and take the last one.
  1222. sqlite3_stmt* const stmt = dbparameters_->getStatement(NSEC3_LAST);
  1223. sqlite3_reset(stmt);
  1224. sqlite3_clear_bindings(stmt);
  1225. if (sqlite3_bind_int(stmt, 1, zone_id) != SQLITE_OK) {
  1226. isc_throw(SQLite3Error, "Could not bind zone ID " << zone_id <<
  1227. " to SQL statement (find last NSEC3): " <<
  1228. sqlite3_errmsg(dbparameters_->db_));
  1229. }
  1230. const int rc = sqlite3_step(stmt);
  1231. if (rc == SQLITE_ROW) {
  1232. // We found it
  1233. result = convertToPlainChar(sqlite3_column_text(stmt, 0),
  1234. dbparameters_->db_);
  1235. }
  1236. sqlite3_reset(stmt);
  1237. if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
  1238. // Some kind of error
  1239. isc_throw(SQLite3Error, "Could not get data for last hash");
  1240. }
  1241. if (rc == SQLITE_DONE) {
  1242. // No NSEC3 at all in the zone. Well, bad luck, but you should not
  1243. // have asked in the first place.
  1244. isc_throw(DataSourceError, "No NSEC3 in this zone");
  1245. }
  1246. }
  1247. return (result);
  1248. }
  1249. } // end of namespace datasrc
  1250. } // end of namespace isc