sqlite3_accessor.cc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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 <vector>
  17. #include <datasrc/sqlite3_accessor.h>
  18. #include <datasrc/logger.h>
  19. #include <datasrc/data_source.h>
  20. #include <datasrc/factory.h>
  21. #include <datasrc/database.h>
  22. #include <util/filename.h>
  23. using namespace std;
  24. using namespace isc::data;
  25. #define SQLITE_SCHEMA_VERSION 1
  26. namespace isc {
  27. namespace datasrc {
  28. // The following enum and char* array define the SQL statements commonly
  29. // used in this implementation. Corresponding prepared statements (of
  30. // type sqlite3_stmt*) are maintained in the statements_ array of the
  31. // SQLite3Parameters structure.
  32. enum StatementID {
  33. ZONE = 0,
  34. ANY = 1,
  35. ANY_SUB = 2,
  36. BEGIN = 3,
  37. COMMIT = 4,
  38. ROLLBACK = 5,
  39. DEL_ZONE_RECORDS = 6,
  40. ADD_RECORD = 7,
  41. DEL_RECORD = 8,
  42. ITERATE = 9,
  43. FIND_PREVIOUS = 10,
  44. ADD_RECORD_DIFF = 11,
  45. GET_RECORD_DIFF = 12, // This is temporary for testing "add diff"
  46. LOW_DIFF_ID = 13,
  47. HIGH_DIFF_ID = 14,
  48. DIFF_RECS = 15,
  49. NUM_STATEMENTS = 16
  50. };
  51. const char* const text_statements[NUM_STATEMENTS] = {
  52. // note for ANY and ITERATE: the order of the SELECT values is
  53. // specifically chosen to match the enum values in RecordColumns
  54. "SELECT id FROM zones WHERE name=?1 AND rdclass = ?2", // ZONE
  55. "SELECT rdtype, ttl, sigtype, rdata FROM records " // ANY
  56. "WHERE zone_id=?1 AND name=?2",
  57. "SELECT rdtype, ttl, sigtype, rdata " // ANY_SUB
  58. "FROM records WHERE zone_id=?1 AND name LIKE (\"%.\" || ?2)",
  59. "BEGIN", // BEGIN
  60. "COMMIT", // COMMIT
  61. "ROLLBACK", // ROLLBACK
  62. "DELETE FROM records WHERE zone_id=?1", // DEL_ZONE_RECORDS
  63. "INSERT INTO records " // ADD_RECORD
  64. "(zone_id, name, rname, ttl, rdtype, sigtype, rdata) "
  65. "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
  66. "DELETE FROM records WHERE zone_id=?1 AND name=?2 " // DEL_RECORD
  67. "AND rdtype=?3 AND rdata=?4",
  68. "SELECT rdtype, ttl, sigtype, rdata, name FROM records " // ITERATE
  69. "WHERE zone_id = ?1 ORDER BY rname, rdtype",
  70. /*
  71. * This one looks for previous name with NSEC record. It is done by
  72. * using the reversed name. The NSEC is checked because we need to
  73. * skip glue data, which don't have the NSEC.
  74. */
  75. "SELECT name FROM records " // FIND_PREVIOUS
  76. "WHERE zone_id=?1 AND rdtype = 'NSEC' AND "
  77. "rname < $2 ORDER BY rname DESC LIMIT 1",
  78. "INSERT INTO diffs " // ADD_RECORD_DIFF
  79. "(zone_id, version, operation, name, rrtype, ttl, rdata) "
  80. "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
  81. "SELECT name, rrtype, ttl, rdata, version, operation " // GET_RECORD_DIFF
  82. "FROM diffs WHERE zone_id = ?1 ORDER BY id, operation",
  83. // Two statements to select the lowest ID and highest ID in a set of
  84. // differences.
  85. "SELECT id FROM diffs " // LOW_DIFF_ID
  86. "WHERE zone_id=?1 AND version=?2 and OPERATION=?3 "
  87. "ORDER BY id ASC LIMIT 1",
  88. "SELECT id FROM diffs " // HIGH_DIFF_ID
  89. "WHERE zone_id=?1 AND version=?2 and OPERATION=?3 "
  90. "ORDER BY id DESC LIMIT 1",
  91. // In the next statement, note the redundant ID. This is to ensure
  92. // that the columns match the column IDs passed to the iterator
  93. "SELECT rrtype, ttl, id, rdata, name FROM diffs " // DIFF_RECS
  94. "WHERE zone_id=?1 AND id>=?2 and id<=?3 "
  95. "ORDER BY id ASC"
  96. };
  97. struct SQLite3Parameters {
  98. SQLite3Parameters() :
  99. db_(NULL), version_(-1), in_transaction(false), updating_zone(false),
  100. updated_zone_id(-1)
  101. {
  102. for (int i = 0; i < NUM_STATEMENTS; ++i) {
  103. statements_[i] = NULL;
  104. }
  105. }
  106. // This method returns the specified ID of SQLITE3 statement. If it's
  107. // not yet prepared it internally creates a new one. This way we can
  108. // avoid preparing unnecessary statements and minimize the overhead.
  109. sqlite3_stmt*
  110. getStatement(int id) {
  111. assert(id < NUM_STATEMENTS);
  112. if (statements_[id] == NULL) {
  113. assert(db_ != NULL);
  114. sqlite3_stmt* prepared = NULL;
  115. if (sqlite3_prepare_v2(db_, text_statements[id], -1, &prepared,
  116. NULL) != SQLITE_OK) {
  117. isc_throw(SQLite3Error, "Could not prepare SQLite statement: "
  118. << text_statements[id] <<
  119. ": " << sqlite3_errmsg(db_));
  120. }
  121. statements_[id] = prepared;
  122. }
  123. return (statements_[id]);
  124. }
  125. void
  126. finalizeStatements() {
  127. for (int i = 0; i < NUM_STATEMENTS; ++i) {
  128. if (statements_[i] != NULL) {
  129. sqlite3_finalize(statements_[i]);
  130. statements_[i] = NULL;
  131. }
  132. }
  133. }
  134. sqlite3* db_;
  135. int version_;
  136. bool in_transaction; // whether or not a transaction has been started
  137. bool updating_zone; // whether or not updating the zone
  138. int updated_zone_id; // valid only when in_transaction is true
  139. private:
  140. // statements_ are private and must be accessed via getStatement() outside
  141. // of this structure.
  142. sqlite3_stmt* statements_[NUM_STATEMENTS];
  143. };
  144. // This is a helper class to encapsulate the code logic of executing
  145. // a specific SQLite3 statement, ensuring the corresponding prepared
  146. // statement is always reset whether the execution is completed successfully
  147. // or it results in an exception.
  148. // Note that an object of this class is intended to be used for "ephemeral"
  149. // statement, which is completed with a single "step" (normally within a
  150. // single call to an SQLite3Database method). In particular, it cannot be
  151. // used for "SELECT" variants, which generally expect multiple matching rows.
  152. class StatementProcessor {
  153. public:
  154. // desc will be used on failure in the what() message of the resulting
  155. // DataSourceError exception.
  156. StatementProcessor(SQLite3Parameters& dbparameters, StatementID stmt_id,
  157. const char* desc) :
  158. dbparameters_(dbparameters), stmt_(dbparameters.getStatement(stmt_id)),
  159. desc_(desc)
  160. {
  161. sqlite3_clear_bindings(stmt_);
  162. }
  163. ~StatementProcessor() {
  164. sqlite3_reset(stmt_);
  165. }
  166. void exec() {
  167. if (sqlite3_step(stmt_) != SQLITE_DONE) {
  168. sqlite3_reset(stmt_);
  169. isc_throw(DataSourceError, "failed to " << desc_ << ": " <<
  170. sqlite3_errmsg(dbparameters_.db_));
  171. }
  172. }
  173. private:
  174. SQLite3Parameters& dbparameters_;
  175. sqlite3_stmt* stmt_;
  176. const char* const desc_;
  177. };
  178. SQLite3Accessor::SQLite3Accessor(const std::string& filename,
  179. const string& rrclass) :
  180. dbparameters_(new SQLite3Parameters),
  181. filename_(filename),
  182. class_(rrclass),
  183. database_name_("sqlite3_" +
  184. isc::util::Filename(filename).nameAndExtension())
  185. {
  186. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_NEWCONN);
  187. open(filename);
  188. }
  189. boost::shared_ptr<DatabaseAccessor>
  190. SQLite3Accessor::clone() {
  191. return (boost::shared_ptr<DatabaseAccessor>(new SQLite3Accessor(filename_,
  192. class_)));
  193. }
  194. namespace {
  195. // This is a helper class to initialize a Sqlite3 DB safely. An object of
  196. // this class encapsulates all temporary resources that are necessary for
  197. // the initialization, and release them in the destructor. Once everything
  198. // is properly initialized, the move() method moves the allocated resources
  199. // to the main object in an exception free manner. This way, the main code
  200. // for the initialization can be exception safe, and can provide the strong
  201. // exception guarantee.
  202. class Initializer {
  203. public:
  204. ~Initializer() {
  205. if (params_.db_ != NULL) {
  206. sqlite3_close(params_.db_);
  207. }
  208. }
  209. void move(SQLite3Parameters* dst) {
  210. *dst = params_;
  211. params_ = SQLite3Parameters(); // clear everything
  212. }
  213. SQLite3Parameters params_;
  214. };
  215. const char* const SCHEMA_LIST[] = {
  216. "CREATE TABLE schema_version (version INTEGER NOT NULL)",
  217. "INSERT INTO schema_version VALUES (1)",
  218. "CREATE TABLE zones (id INTEGER PRIMARY KEY, "
  219. "name STRING NOT NULL COLLATE NOCASE, "
  220. "rdclass STRING NOT NULL COLLATE NOCASE DEFAULT 'IN', "
  221. "dnssec BOOLEAN NOT NULL DEFAULT 0)",
  222. "CREATE INDEX zones_byname ON zones (name)",
  223. "CREATE TABLE records (id INTEGER PRIMARY KEY, "
  224. "zone_id INTEGER NOT NULL, name STRING NOT NULL COLLATE NOCASE, "
  225. "rname STRING NOT NULL COLLATE NOCASE, ttl INTEGER NOT NULL, "
  226. "rdtype STRING NOT NULL COLLATE NOCASE, sigtype STRING COLLATE NOCASE, "
  227. "rdata STRING NOT NULL)",
  228. "CREATE INDEX records_byname ON records (name)",
  229. "CREATE INDEX records_byrname ON records (rname)",
  230. "CREATE TABLE nsec3 (id INTEGER PRIMARY KEY, zone_id INTEGER NOT NULL, "
  231. "hash STRING NOT NULL COLLATE NOCASE, "
  232. "owner STRING NOT NULL COLLATE NOCASE, "
  233. "ttl INTEGER NOT NULL, rdtype STRING NOT NULL COLLATE NOCASE, "
  234. "rdata STRING NOT NULL)",
  235. "CREATE INDEX nsec3_byhash ON nsec3 (hash)",
  236. "CREATE TABLE diffs (id INTEGER PRIMARY KEY, "
  237. "zone_id INTEGER NOT NULL, "
  238. "version INTEGER NOT NULL, "
  239. "operation INTEGER NOT NULL, "
  240. "name STRING NOT NULL COLLATE NOCASE, "
  241. "rrtype STRING NOT NULL COLLATE NOCASE, "
  242. "ttl INTEGER NOT NULL, "
  243. "rdata STRING NOT NULL)",
  244. NULL
  245. };
  246. sqlite3_stmt*
  247. prepare(sqlite3* const db, const char* const statement) {
  248. sqlite3_stmt* prepared = NULL;
  249. if (sqlite3_prepare_v2(db, statement, -1, &prepared, NULL) != SQLITE_OK) {
  250. isc_throw(SQLite3Error, "Could not prepare SQLite statement: " <<
  251. statement << ": " << sqlite3_errmsg(db));
  252. }
  253. return (prepared);
  254. }
  255. // small function to sleep for 0.1 seconds, needed when waiting for
  256. // exclusive database locks (which should only occur on startup, and only
  257. // when the database has not been created yet)
  258. void doSleep() {
  259. struct timespec req;
  260. req.tv_sec = 0;
  261. req.tv_nsec = 100000000;
  262. nanosleep(&req, NULL);
  263. }
  264. // returns the schema version if the schema version table exists
  265. // returns -1 if it does not
  266. int checkSchemaVersion(sqlite3* db) {
  267. sqlite3_stmt* prepared = NULL;
  268. // At this point in time, the database might be exclusively locked, in
  269. // which case even prepare() will return BUSY, so we may need to try a
  270. // few times
  271. for (size_t i = 0; i < 50; ++i) {
  272. int rc = sqlite3_prepare_v2(db, "SELECT version FROM schema_version",
  273. -1, &prepared, NULL);
  274. if (rc == SQLITE_ERROR) {
  275. // this is the error that is returned when the table does not
  276. // exist
  277. return (-1);
  278. } else if (rc == SQLITE_OK) {
  279. break;
  280. } else if (rc != SQLITE_BUSY || i == 50) {
  281. isc_throw(SQLite3Error, "Unable to prepare version query: "
  282. << rc << " " << sqlite3_errmsg(db));
  283. }
  284. doSleep();
  285. }
  286. if (sqlite3_step(prepared) != SQLITE_ROW) {
  287. isc_throw(SQLite3Error,
  288. "Unable to query version: " << sqlite3_errmsg(db));
  289. }
  290. int version = sqlite3_column_int(prepared, 0);
  291. sqlite3_finalize(prepared);
  292. return (version);
  293. }
  294. // return db version
  295. int create_database(sqlite3* db) {
  296. // try to get an exclusive lock. Once that is obtained, do the version
  297. // check *again*, just in case this process was racing another
  298. //
  299. // try for 5 secs (50*0.1)
  300. int rc;
  301. logger.info(DATASRC_SQLITE_SETUP);
  302. for (size_t i = 0; i < 50; ++i) {
  303. rc = sqlite3_exec(db, "BEGIN EXCLUSIVE TRANSACTION", NULL, NULL,
  304. NULL);
  305. if (rc == SQLITE_OK) {
  306. break;
  307. } else if (rc != SQLITE_BUSY || i == 50) {
  308. isc_throw(SQLite3Error, "Unable to acquire exclusive lock "
  309. "for database creation: " << sqlite3_errmsg(db));
  310. }
  311. doSleep();
  312. }
  313. int schema_version = checkSchemaVersion(db);
  314. if (schema_version == -1) {
  315. for (int i = 0; SCHEMA_LIST[i] != NULL; ++i) {
  316. if (sqlite3_exec(db, SCHEMA_LIST[i], NULL, NULL, NULL) !=
  317. SQLITE_OK) {
  318. isc_throw(SQLite3Error,
  319. "Failed to set up schema " << SCHEMA_LIST[i]);
  320. }
  321. }
  322. sqlite3_exec(db, "COMMIT TRANSACTION", NULL, NULL, NULL);
  323. return (SQLITE_SCHEMA_VERSION);
  324. } else {
  325. return (schema_version);
  326. }
  327. }
  328. void
  329. checkAndSetupSchema(Initializer* initializer) {
  330. sqlite3* const db = initializer->params_.db_;
  331. int schema_version = checkSchemaVersion(db);
  332. if (schema_version != SQLITE_SCHEMA_VERSION) {
  333. schema_version = create_database(db);
  334. }
  335. initializer->params_.version_ = schema_version;
  336. }
  337. }
  338. void
  339. SQLite3Accessor::open(const std::string& name) {
  340. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_CONNOPEN).arg(name);
  341. if (dbparameters_->db_ != NULL) {
  342. // There shouldn't be a way to trigger this anyway
  343. isc_throw(DataSourceError, "Duplicate SQLite open with " << name);
  344. }
  345. Initializer initializer;
  346. if (sqlite3_open(name.c_str(), &initializer.params_.db_) != 0) {
  347. isc_throw(SQLite3Error, "Cannot open SQLite database file: " << name);
  348. }
  349. checkAndSetupSchema(&initializer);
  350. initializer.move(dbparameters_.get());
  351. }
  352. SQLite3Accessor::~SQLite3Accessor() {
  353. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_DROPCONN);
  354. if (dbparameters_->db_ != NULL) {
  355. close();
  356. }
  357. }
  358. void
  359. SQLite3Accessor::close(void) {
  360. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_SQLITE_CONNCLOSE);
  361. if (dbparameters_->db_ == NULL) {
  362. isc_throw(DataSourceError,
  363. "SQLite data source is being closed before open");
  364. }
  365. dbparameters_->finalizeStatements();
  366. sqlite3_close(dbparameters_->db_);
  367. dbparameters_->db_ = NULL;
  368. }
  369. std::pair<bool, int>
  370. SQLite3Accessor::getZone(const std::string& name) const {
  371. int rc;
  372. sqlite3_stmt* const stmt = dbparameters_->getStatement(ZONE);
  373. // Take the statement (simple SELECT id FROM zones WHERE...)
  374. // and prepare it (bind the parameters to it)
  375. sqlite3_reset(stmt);
  376. rc = sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
  377. if (rc != SQLITE_OK) {
  378. isc_throw(SQLite3Error, "Could not bind " << name <<
  379. " to SQL statement (zone)");
  380. }
  381. rc = sqlite3_bind_text(stmt, 2, class_.c_str(), -1, SQLITE_STATIC);
  382. if (rc != SQLITE_OK) {
  383. isc_throw(SQLite3Error, "Could not bind " << class_ <<
  384. " to SQL statement (zone)");
  385. }
  386. // Get the data there and see if it found anything
  387. rc = sqlite3_step(stmt);
  388. if (rc == SQLITE_ROW) {
  389. const int zone_id = sqlite3_column_int(stmt, 0);
  390. sqlite3_reset(stmt);
  391. return (pair<bool, int>(true, zone_id));
  392. } else if (rc == SQLITE_DONE) {
  393. // Free resources
  394. sqlite3_reset(stmt);
  395. return (pair<bool, int>(false, 0));
  396. }
  397. sqlite3_reset(stmt);
  398. isc_throw(DataSourceError, "Unexpected failure in sqlite3_step: " <<
  399. sqlite3_errmsg(dbparameters_->db_));
  400. // Compilers might not realize isc_throw always throws
  401. return (std::pair<bool, int>(false, 0));
  402. }
  403. namespace {
  404. // Conversion to plain char
  405. const char*
  406. convertToPlainChar(const unsigned char* ucp, sqlite3 *db) {
  407. if (ucp == NULL) {
  408. // The field can really be NULL, in which case we return an
  409. // empty string, or sqlite may have run out of memory, in
  410. // which case we raise an error
  411. if (sqlite3_errcode(db) == SQLITE_NOMEM) {
  412. isc_throw(DataSourceError,
  413. "Sqlite3 backend encountered a memory allocation "
  414. "error in sqlite3_column_text()");
  415. } else {
  416. return ("");
  417. }
  418. }
  419. const void* p = ucp;
  420. return (static_cast<const char*>(p));
  421. }
  422. }
  423. class SQLite3Accessor::Context : public DatabaseAccessor::IteratorContext {
  424. public:
  425. // Construct an iterator for all records. When constructed this
  426. // way, the getNext() call will copy all fields
  427. Context(const boost::shared_ptr<const SQLite3Accessor>& accessor, int id) :
  428. iterator_type_(ITT_ALL),
  429. accessor_(accessor),
  430. statement_(NULL),
  431. name_("")
  432. {
  433. // We create the statement now and then just keep getting data from it
  434. statement_ = prepare(accessor->dbparameters_->db_,
  435. text_statements[ITERATE]);
  436. bindZoneId(id);
  437. }
  438. // Construct an iterator for records with a specific name. When constructed
  439. // this way, the getNext() call will copy all fields except name
  440. Context(const boost::shared_ptr<const SQLite3Accessor>& accessor, int id,
  441. const std::string& name, bool subdomains) :
  442. iterator_type_(ITT_NAME),
  443. accessor_(accessor),
  444. statement_(NULL),
  445. name_(name)
  446. {
  447. // We create the statement now and then just keep getting data from it
  448. statement_ = prepare(accessor->dbparameters_->db_,
  449. subdomains ? text_statements[ANY_SUB] :
  450. text_statements[ANY]);
  451. bindZoneId(id);
  452. bindName(name_);
  453. }
  454. bool getNext(std::string (&data)[COLUMN_COUNT]) {
  455. // If there's another row, get it
  456. // If finalize has been called (e.g. when previous getNext() got
  457. // SQLITE_DONE), directly return false
  458. if (statement_ == NULL) {
  459. return false;
  460. }
  461. const int rc(sqlite3_step(statement_));
  462. if (rc == SQLITE_ROW) {
  463. // For both types, we copy the first four columns
  464. copyColumn(data, TYPE_COLUMN);
  465. copyColumn(data, TTL_COLUMN);
  466. copyColumn(data, SIGTYPE_COLUMN);
  467. copyColumn(data, RDATA_COLUMN);
  468. // Only copy Name if we are iterating over every record
  469. if (iterator_type_ == ITT_ALL) {
  470. copyColumn(data, NAME_COLUMN);
  471. }
  472. return (true);
  473. } else if (rc != SQLITE_DONE) {
  474. isc_throw(DataSourceError,
  475. "Unexpected failure in sqlite3_step: " <<
  476. sqlite3_errmsg(accessor_->dbparameters_->db_));
  477. }
  478. finalize();
  479. return (false);
  480. }
  481. virtual ~Context() {
  482. finalize();
  483. }
  484. private:
  485. // Depending on which constructor is called, behaviour is slightly
  486. // different. We keep track of what to do with the iterator type
  487. // See description of getNext() and the constructors
  488. enum IteratorType {
  489. ITT_ALL,
  490. ITT_NAME
  491. };
  492. void copyColumn(std::string (&data)[COLUMN_COUNT], int column) {
  493. data[column] = convertToPlainChar(sqlite3_column_text(statement_,
  494. column),
  495. accessor_->dbparameters_->db_);
  496. }
  497. void bindZoneId(const int zone_id) {
  498. if (sqlite3_bind_int(statement_, 1, zone_id) != SQLITE_OK) {
  499. finalize();
  500. isc_throw(SQLite3Error, "Could not bind int " << zone_id <<
  501. " to SQL statement: " <<
  502. sqlite3_errmsg(accessor_->dbparameters_->db_));
  503. }
  504. }
  505. void bindName(const std::string& name) {
  506. if (sqlite3_bind_text(statement_, 2, name.c_str(), -1,
  507. SQLITE_TRANSIENT) != SQLITE_OK) {
  508. const char* errmsg = sqlite3_errmsg(accessor_->dbparameters_->db_);
  509. finalize();
  510. isc_throw(SQLite3Error, "Could not bind text '" << name <<
  511. "' to SQL statement: " << errmsg);
  512. }
  513. }
  514. void finalize() {
  515. sqlite3_finalize(statement_);
  516. statement_ = NULL;
  517. }
  518. const IteratorType iterator_type_;
  519. boost::shared_ptr<const SQLite3Accessor> accessor_;
  520. sqlite3_stmt* statement_;
  521. const std::string name_;
  522. };
  523. // Methods to retrieve the various iterators
  524. DatabaseAccessor::IteratorContextPtr
  525. SQLite3Accessor::getRecords(const std::string& name, int id,
  526. bool subdomains) const
  527. {
  528. return (IteratorContextPtr(new Context(shared_from_this(), id, name,
  529. subdomains)));
  530. }
  531. DatabaseAccessor::IteratorContextPtr
  532. SQLite3Accessor::getNSEC3Records(const std::string&, int) const {
  533. // TODO: Implement
  534. isc_throw(NotImplemented, "Not implemented yet, see ticket #1760");
  535. }
  536. DatabaseAccessor::IteratorContextPtr
  537. SQLite3Accessor::getAllRecords(int id) const {
  538. return (IteratorContextPtr(new Context(shared_from_this(), id)));
  539. }
  540. /// \brief Difference Iterator
  541. ///
  542. /// This iterator is used to search through the differences table for the
  543. /// resouce records making up an IXFR between two versions of a zone.
  544. class SQLite3Accessor::DiffContext : public DatabaseAccessor::IteratorContext {
  545. public:
  546. /// \brief Constructor
  547. ///
  548. /// Constructs the iterator for the difference sequence. It is
  549. /// passed two parameters, the first and last versions in the difference
  550. /// sequence. Note that because of serial number rollover, it may well
  551. /// be that the start serial number is greater than the end one.
  552. ///
  553. /// \param zone_id ID of the zone (in the zone table)
  554. /// \param start Serial number of first version in difference sequence
  555. /// \param end Serial number of last version in difference sequence
  556. ///
  557. /// \exception any A number of exceptions can be expected
  558. DiffContext(const boost::shared_ptr<const SQLite3Accessor>& accessor,
  559. int zone_id, uint32_t start, uint32_t end) :
  560. accessor_(accessor),
  561. last_status_(SQLITE_ROW)
  562. {
  563. try {
  564. int low_id = findIndex(LOW_DIFF_ID, zone_id, start, DIFF_DELETE);
  565. int high_id = findIndex(HIGH_DIFF_ID, zone_id, end, DIFF_ADD);
  566. // Prepare the statement that will return data values
  567. reset(DIFF_RECS);
  568. bindInt(DIFF_RECS, 1, zone_id);
  569. bindInt(DIFF_RECS, 2, low_id);
  570. bindInt(DIFF_RECS, 3, high_id);
  571. } catch (...) {
  572. // Something wrong, clear up everything.
  573. accessor_->dbparameters_->finalizeStatements();
  574. throw;
  575. }
  576. }
  577. /// \brief Destructor
  578. virtual ~DiffContext()
  579. {}
  580. /// \brief Get Next Diff Record
  581. ///
  582. /// Returns the next difference record in the difference sequence.
  583. ///
  584. /// \param data Array of std::strings COLUMN_COUNT long. The results
  585. /// are returned in this.
  586. ///
  587. /// \return bool true if data is returned, false if not.
  588. ///
  589. /// \exceptions any Varied
  590. bool getNext(std::string (&data)[COLUMN_COUNT]) {
  591. if (last_status_ != SQLITE_DONE) {
  592. // Last call (if any) didn't reach end of result set, so we
  593. // can read another row from it.
  594. //
  595. // Get a pointer to the statement for brevity (this does not
  596. // transfer ownership of the statement to this class, so there is
  597. // no need to tidy up after we have finished using it).
  598. sqlite3_stmt* stmt =
  599. accessor_->dbparameters_->getStatement(DIFF_RECS);
  600. const int rc(sqlite3_step(stmt));
  601. if (rc == SQLITE_ROW) {
  602. // Copy the data across to the output array
  603. copyColumn(DIFF_RECS, data, TYPE_COLUMN);
  604. copyColumn(DIFF_RECS, data, TTL_COLUMN);
  605. copyColumn(DIFF_RECS, data, NAME_COLUMN);
  606. copyColumn(DIFF_RECS, data, RDATA_COLUMN);
  607. } else if (rc != SQLITE_DONE) {
  608. isc_throw(DataSourceError,
  609. "Unexpected failure in sqlite3_step: " <<
  610. sqlite3_errmsg(accessor_->dbparameters_->db_));
  611. }
  612. last_status_ = rc;
  613. }
  614. return (last_status_ == SQLITE_ROW);
  615. }
  616. private:
  617. /// \brief Reset prepared statement
  618. ///
  619. /// Sets up the statement so that new parameters can be attached to it and
  620. /// that it can be used to query for another difference sequence.
  621. ///
  622. /// \param stindex Index of prepared statement to which to bind
  623. void reset(int stindex) {
  624. sqlite3_stmt* stmt = accessor_->dbparameters_->getStatement(stindex);
  625. if ((sqlite3_reset(stmt) != SQLITE_OK) ||
  626. (sqlite3_clear_bindings(stmt) != SQLITE_OK)) {
  627. isc_throw(SQLite3Error, "Could not clear statement bindings in '" <<
  628. text_statements[stindex] << "': " <<
  629. sqlite3_errmsg(accessor_->dbparameters_->db_));
  630. }
  631. }
  632. /// \brief Bind Int
  633. ///
  634. /// Binds an integer to a specific variable in a prepared statement.
  635. ///
  636. /// \param stindex Index of prepared statement to which to bind
  637. /// \param varindex Index of variable to which to bind
  638. /// \param value Value of variable to bind
  639. /// \exception SQLite3Error on an error
  640. void bindInt(int stindex, int varindex, sqlite3_int64 value) {
  641. if (sqlite3_bind_int64(accessor_->dbparameters_->getStatement(stindex),
  642. varindex, value) != SQLITE_OK) {
  643. isc_throw(SQLite3Error, "Could not bind value to parameter " <<
  644. varindex << " in statement '" <<
  645. text_statements[stindex] << "': " <<
  646. sqlite3_errmsg(accessor_->dbparameters_->db_));
  647. }
  648. }
  649. ///\brief Get Single Value
  650. ///
  651. /// Executes a prepared statement (which has parameters bound to it)
  652. /// for which the result of a single value is expected.
  653. ///
  654. /// \param stindex Index of prepared statement in statement table.
  655. ///
  656. /// \return Value of SELECT.
  657. ///
  658. /// \exception TooMuchData Multiple rows returned when one expected
  659. /// \exception TooLittleData Zero rows returned when one expected
  660. /// \exception DataSourceError SQLite3-related error
  661. int getSingleValue(StatementID stindex) {
  662. // Get a pointer to the statement for brevity (does not transfer
  663. // resources)
  664. sqlite3_stmt* stmt = accessor_->dbparameters_->getStatement(stindex);
  665. // Execute the data. Should be just one result
  666. int rc = sqlite3_step(stmt);
  667. int result = -1;
  668. if (rc == SQLITE_ROW) {
  669. // Got some data, extract the value
  670. result = sqlite3_column_int(stmt, 0);
  671. rc = sqlite3_step(stmt);
  672. if (rc == SQLITE_DONE) {
  673. // All OK, exit with the value.
  674. return (result);
  675. } else if (rc == SQLITE_ROW) {
  676. isc_throw(TooMuchData, "request to return one value from "
  677. "diffs table returned multiple values");
  678. }
  679. } else if (rc == SQLITE_DONE) {
  680. // No data in the table. A bare exception with no explanation is
  681. // thrown, as it will be replaced by a more informative one by
  682. // the caller.
  683. isc_throw(TooLittleData, "");
  684. }
  685. // We get here on an error.
  686. isc_throw(DataSourceError, "could not get data from diffs table: " <<
  687. sqlite3_errmsg(accessor_->dbparameters_->db_));
  688. // Keep the compiler happy with a return value.
  689. return (result);
  690. }
  691. /// \brief Find index
  692. ///
  693. /// Executes the prepared statement locating the high or low index in
  694. /// the diffs table and returns that index.
  695. ///
  696. /// \param stmt_id Index of the prepared statement to execute
  697. /// \param zone_id ID of the zone for which the index is being sought
  698. /// \param serial Zone serial number for which an index is being sought.
  699. /// \param diff Code to delete record additions or deletions
  700. ///
  701. /// \return int ID of the row in the difss table corresponding to the
  702. /// statement.
  703. ///
  704. /// \exception TooLittleData Internal error, no result returned when one
  705. /// was expected.
  706. /// \exception NoSuchSerial Serial number not found.
  707. /// \exception NoDiffsData No data for this zone found in diffs table
  708. int findIndex(StatementID stindex, int zone_id, uint32_t serial, int diff) {
  709. // Set up the statement
  710. reset(stindex);
  711. bindInt(stindex, 1, zone_id);
  712. bindInt(stindex, 2, serial);
  713. bindInt(stindex, 3, diff);
  714. // Execute the statement
  715. int result = -1;
  716. try {
  717. result = getSingleValue(stindex);
  718. } catch (const TooLittleData&) {
  719. // No data returned but the SQL query succeeded. Only possibility
  720. // is that there is no entry in the differences table for the given
  721. // zone and version.
  722. isc_throw(NoSuchSerial, "No entry in differences table for " <<
  723. " zone ID " << zone_id << ", serial number " << serial);
  724. }
  725. return (result);
  726. }
  727. /// \brief Copy Column to Output
  728. ///
  729. /// Copies the textual data in the result set to the specified column
  730. /// in the output.
  731. ///
  732. /// \param stindex Index of prepared statement used to access data
  733. /// \param data Array of columns passed to getNext
  734. /// \param column Column of output to copy
  735. void copyColumn(StatementID stindex, std::string (&data)[COLUMN_COUNT],
  736. int column) {
  737. // Get a pointer to the statement for brevity (does not transfer
  738. // resources)
  739. sqlite3_stmt* stmt = accessor_->dbparameters_->getStatement(stindex);
  740. data[column] = convertToPlainChar(sqlite3_column_text(stmt,
  741. column),
  742. accessor_->dbparameters_->db_);
  743. }
  744. // Attributes
  745. boost::shared_ptr<const SQLite3Accessor> accessor_; // Accessor object
  746. int last_status_; // Last status received from sqlite3_step
  747. };
  748. // ... and return the iterator
  749. DatabaseAccessor::IteratorContextPtr
  750. SQLite3Accessor::getDiffs(int id, uint32_t start, uint32_t end) const {
  751. return (IteratorContextPtr(new DiffContext(shared_from_this(), id, start,
  752. end)));
  753. }
  754. pair<bool, int>
  755. SQLite3Accessor::startUpdateZone(const string& zone_name, const bool replace) {
  756. if (dbparameters_->updating_zone) {
  757. isc_throw(DataSourceError,
  758. "duplicate zone update on SQLite3 data source");
  759. }
  760. if (dbparameters_->in_transaction) {
  761. isc_throw(DataSourceError,
  762. "zone update attempt in another SQLite3 transaction");
  763. }
  764. const pair<bool, int> zone_info(getZone(zone_name));
  765. if (!zone_info.first) {
  766. return (zone_info);
  767. }
  768. StatementProcessor(*dbparameters_, BEGIN,
  769. "start an SQLite3 update transaction").exec();
  770. if (replace) {
  771. try {
  772. StatementProcessor delzone_exec(*dbparameters_, DEL_ZONE_RECORDS,
  773. "delete zone records");
  774. sqlite3_stmt* stmt = dbparameters_->getStatement(DEL_ZONE_RECORDS);
  775. sqlite3_clear_bindings(stmt);
  776. if (sqlite3_bind_int(stmt, 1, zone_info.second) != SQLITE_OK) {
  777. isc_throw(DataSourceError,
  778. "failed to bind SQLite3 parameter: " <<
  779. sqlite3_errmsg(dbparameters_->db_));
  780. }
  781. delzone_exec.exec();
  782. } catch (const DataSourceError&) {
  783. // Once we start a transaction, if something unexpected happens
  784. // we need to rollback the transaction so that a subsequent update
  785. // is still possible with this accessor.
  786. StatementProcessor(*dbparameters_, ROLLBACK,
  787. "rollback an SQLite3 transaction").exec();
  788. throw;
  789. }
  790. }
  791. dbparameters_->in_transaction = true;
  792. dbparameters_->updating_zone = true;
  793. dbparameters_->updated_zone_id = zone_info.second;
  794. return (zone_info);
  795. }
  796. void
  797. SQLite3Accessor::startTransaction() {
  798. if (dbparameters_->in_transaction) {
  799. isc_throw(DataSourceError,
  800. "duplicate transaction on SQLite3 data source");
  801. }
  802. StatementProcessor(*dbparameters_, BEGIN,
  803. "start an SQLite3 transaction").exec();
  804. dbparameters_->in_transaction = true;
  805. }
  806. void
  807. SQLite3Accessor::commit() {
  808. if (!dbparameters_->in_transaction) {
  809. isc_throw(DataSourceError, "performing commit on SQLite3 "
  810. "data source without transaction");
  811. }
  812. StatementProcessor(*dbparameters_, COMMIT,
  813. "commit an SQLite3 transaction").exec();
  814. dbparameters_->in_transaction = false;
  815. dbparameters_->updated_zone_id = -1;
  816. }
  817. void
  818. SQLite3Accessor::rollback() {
  819. if (!dbparameters_->in_transaction) {
  820. isc_throw(DataSourceError, "performing rollback on SQLite3 "
  821. "data source without transaction");
  822. }
  823. StatementProcessor(*dbparameters_, ROLLBACK,
  824. "rollback an SQLite3 transaction").exec();
  825. dbparameters_->in_transaction = false;
  826. dbparameters_->updated_zone_id = -1;
  827. }
  828. namespace {
  829. // Commonly used code sequence for adding/deleting record
  830. template <typename COLUMNS_TYPE>
  831. void
  832. doUpdate(SQLite3Parameters& dbparams, StatementID stmt_id,
  833. COLUMNS_TYPE update_params, const char* exec_desc)
  834. {
  835. sqlite3_stmt* const stmt = dbparams.getStatement(stmt_id);
  836. StatementProcessor executer(dbparams, stmt_id, exec_desc);
  837. int param_id = 0;
  838. if (sqlite3_bind_int(stmt, ++param_id, dbparams.updated_zone_id)
  839. != SQLITE_OK) {
  840. isc_throw(DataSourceError, "failed to bind SQLite3 parameter: " <<
  841. sqlite3_errmsg(dbparams.db_));
  842. }
  843. const size_t column_count =
  844. sizeof(update_params) / sizeof(update_params[0]);
  845. for (int i = 0; i < column_count; ++i) {
  846. // The old sqlite3 data source API assumes NULL for an empty column.
  847. // We need to provide compatibility at least for now.
  848. if (sqlite3_bind_text(stmt, ++param_id,
  849. update_params[i].empty() ? NULL :
  850. update_params[i].c_str(),
  851. -1, SQLITE_TRANSIENT) != SQLITE_OK) {
  852. isc_throw(DataSourceError, "failed to bind SQLite3 parameter: " <<
  853. sqlite3_errmsg(dbparams.db_));
  854. }
  855. }
  856. executer.exec();
  857. }
  858. }
  859. void
  860. SQLite3Accessor::addRecordToZone(const string (&columns)[ADD_COLUMN_COUNT]) {
  861. if (!dbparameters_->updating_zone) {
  862. isc_throw(DataSourceError, "adding record to SQLite3 "
  863. "data source without transaction");
  864. }
  865. doUpdate<const string (&)[DatabaseAccessor::ADD_COLUMN_COUNT]>(
  866. *dbparameters_, ADD_RECORD, columns, "add record to zone");
  867. }
  868. void
  869. SQLite3Accessor::deleteRecordInZone(const string (&params)[DEL_PARAM_COUNT]) {
  870. if (!dbparameters_->updating_zone) {
  871. isc_throw(DataSourceError, "deleting record in SQLite3 "
  872. "data source without transaction");
  873. }
  874. doUpdate<const string (&)[DatabaseAccessor::DEL_PARAM_COUNT]>(
  875. *dbparameters_, DEL_RECORD, params, "delete record from zone");
  876. }
  877. void
  878. SQLite3Accessor::addRecordDiff(int zone_id, uint32_t serial,
  879. DiffOperation operation,
  880. const std::string (&params)[DIFF_PARAM_COUNT])
  881. {
  882. if (!dbparameters_->updating_zone) {
  883. isc_throw(DataSourceError, "adding record diff without update "
  884. "transaction on " << getDBName());
  885. }
  886. if (zone_id != dbparameters_->updated_zone_id) {
  887. isc_throw(DataSourceError, "bad zone ID for adding record diff on "
  888. << getDBName() << ": " << zone_id << ", must be "
  889. << dbparameters_->updated_zone_id);
  890. }
  891. sqlite3_stmt* const stmt = dbparameters_->getStatement(ADD_RECORD_DIFF);
  892. StatementProcessor executer(*dbparameters_, ADD_RECORD_DIFF,
  893. "add record diff");
  894. int param_id = 0;
  895. if (sqlite3_bind_int(stmt, ++param_id, zone_id)
  896. != SQLITE_OK) {
  897. isc_throw(DataSourceError, "failed to bind SQLite3 parameter: " <<
  898. sqlite3_errmsg(dbparameters_->db_));
  899. }
  900. if (sqlite3_bind_int64(stmt, ++param_id, serial)
  901. != SQLITE_OK) {
  902. isc_throw(DataSourceError, "failed to bind SQLite3 parameter: " <<
  903. sqlite3_errmsg(dbparameters_->db_));
  904. }
  905. if (sqlite3_bind_int(stmt, ++param_id, operation)
  906. != SQLITE_OK) {
  907. isc_throw(DataSourceError, "failed to bind SQLite3 parameter: " <<
  908. sqlite3_errmsg(dbparameters_->db_));
  909. }
  910. for (int i = 0; i < DIFF_PARAM_COUNT; ++i) {
  911. if (sqlite3_bind_text(stmt, ++param_id, params[i].c_str(),
  912. -1, SQLITE_TRANSIENT) != SQLITE_OK) {
  913. isc_throw(DataSourceError, "failed to bind SQLite3 parameter: " <<
  914. sqlite3_errmsg(dbparameters_->db_));
  915. }
  916. }
  917. executer.exec();
  918. }
  919. vector<vector<string> >
  920. SQLite3Accessor::getRecordDiff(int zone_id) {
  921. sqlite3_stmt* const stmt = dbparameters_->getStatement(GET_RECORD_DIFF);
  922. sqlite3_bind_int(stmt, 1, zone_id);
  923. vector<vector<string> > result;
  924. while (sqlite3_step(stmt) == SQLITE_ROW) {
  925. vector<string> row_result;
  926. for (int i = 0; i < 6; ++i) {
  927. row_result.push_back(convertToPlainChar(sqlite3_column_text(stmt,
  928. i),
  929. dbparameters_->db_));
  930. }
  931. result.push_back(row_result);
  932. }
  933. sqlite3_reset(stmt);
  934. return (result);
  935. }
  936. std::string
  937. SQLite3Accessor::findPreviousName(int zone_id, const std::string& rname)
  938. const
  939. {
  940. sqlite3_stmt* const stmt = dbparameters_->getStatement(FIND_PREVIOUS);
  941. sqlite3_reset(stmt);
  942. sqlite3_clear_bindings(stmt);
  943. if (sqlite3_bind_int(stmt, 1, zone_id) != SQLITE_OK) {
  944. isc_throw(SQLite3Error, "Could not bind zone ID " << zone_id <<
  945. " to SQL statement (find previous): " <<
  946. sqlite3_errmsg(dbparameters_->db_));
  947. }
  948. if (sqlite3_bind_text(stmt, 2, rname.c_str(), -1, SQLITE_STATIC) !=
  949. SQLITE_OK) {
  950. isc_throw(SQLite3Error, "Could not bind name " << rname <<
  951. " to SQL statement (find previous): " <<
  952. sqlite3_errmsg(dbparameters_->db_));
  953. }
  954. std::string result;
  955. const int rc = sqlite3_step(stmt);
  956. if (rc == SQLITE_ROW) {
  957. // We found it
  958. result = convertToPlainChar(sqlite3_column_text(stmt, 0),
  959. dbparameters_->db_);
  960. }
  961. sqlite3_reset(stmt);
  962. if (rc == SQLITE_DONE) {
  963. // No NSEC records here, this DB doesn't support DNSSEC or
  964. // we asked before the apex
  965. isc_throw(isc::NotImplemented, "The zone doesn't support DNSSEC or "
  966. "query before apex");
  967. }
  968. if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
  969. // Some kind of error
  970. isc_throw(SQLite3Error, "Could not get data for previous name");
  971. }
  972. return (result);
  973. }
  974. std::string
  975. SQLite3Accessor::findPreviousNSEC3Hash(int, const std::string&) const {
  976. isc_throw(NotImplemented, "Not implemented yet, see #1760");
  977. }
  978. } // end of namespace datasrc
  979. } // end of namespace isc