sqlite3_accessor.cc 50 KB

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