downloads.ItemView -> downloads.Item
[chromium-blink-merge.git] / sql / connection.h
blob19592d9f0e44ed68764b9d25a88d9a65424ba9b7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef SQL_CONNECTION_H_
6 #define SQL_CONNECTION_H_
8 #include <stdint.h>
9 #include <map>
10 #include <set>
11 #include <string>
12 #include <vector>
14 #include "base/callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/macros.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/threading/thread_restrictions.h"
20 #include "base/time/time.h"
21 #include "sql/sql_export.h"
23 struct sqlite3;
24 struct sqlite3_stmt;
26 namespace base {
27 class FilePath;
28 class HistogramBase;
31 namespace sql {
33 class Recovery;
34 class Statement;
36 // To allow some test classes to be friended.
37 namespace test {
38 class ScopedCommitHook;
39 class ScopedScalarFunction;
40 class ScopedMockTimeSource;
43 // Uniquely identifies a statement. There are two modes of operation:
45 // - In the most common mode, you will use the source file and line number to
46 // identify your statement. This is a convienient way to get uniqueness for
47 // a statement that is only used in one place. Use the SQL_FROM_HERE macro
48 // to generate a StatementID.
50 // - In the "custom" mode you may use the statement from different places or
51 // need to manage it yourself for whatever reason. In this case, you should
52 // make up your own unique name and pass it to the StatementID. This name
53 // must be a static string, since this object only deals with pointers and
54 // assumes the underlying string doesn't change or get deleted.
56 // This object is copyable and assignable using the compiler-generated
57 // operator= and copy constructor.
58 class StatementID {
59 public:
60 // Creates a uniquely named statement with the given file ane line number.
61 // Normally you will use SQL_FROM_HERE instead of calling yourself.
62 StatementID(const char* file, int line)
63 : number_(line),
64 str_(file) {
67 // Creates a uniquely named statement with the given user-defined name.
68 explicit StatementID(const char* unique_name)
69 : number_(-1),
70 str_(unique_name) {
73 // This constructor is unimplemented and will generate a linker error if
74 // called. It is intended to try to catch people dynamically generating
75 // a statement name that will be deallocated and will cause a crash later.
76 // All strings must be static and unchanging!
77 explicit StatementID(const std::string& dont_ever_do_this);
79 // We need this to insert into our map.
80 bool operator<(const StatementID& other) const;
82 private:
83 int number_;
84 const char* str_;
87 #define SQL_FROM_HERE sql::StatementID(__FILE__, __LINE__)
89 class Connection;
91 // Abstract the source of timing information for metrics (RecordCommitTime, etc)
92 // to allow testing control.
93 class SQL_EXPORT TimeSource {
94 public:
95 TimeSource() {}
96 virtual ~TimeSource() {}
98 // Return the current time (by default base::TimeTicks::Now()).
99 virtual base::TimeTicks Now();
101 private:
102 DISALLOW_COPY_AND_ASSIGN(TimeSource);
105 class SQL_EXPORT Connection {
106 private:
107 class StatementRef; // Forward declaration, see real one below.
109 public:
110 // The database is opened by calling Open[InMemory](). Any uncommitted
111 // transactions will be rolled back when this object is deleted.
112 Connection();
113 ~Connection();
115 // Pre-init configuration ----------------------------------------------------
117 // Sets the page size that will be used when creating a new database. This
118 // must be called before Init(), and will only have an effect on new
119 // databases.
121 // From sqlite.org: "The page size must be a power of two greater than or
122 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
123 // value for SQLITE_MAX_PAGE_SIZE is 32768."
124 void set_page_size(int page_size) { page_size_ = page_size; }
126 // Sets the number of pages that will be cached in memory by sqlite. The
127 // total cache size in bytes will be page_size * cache_size. This must be
128 // called before Open() to have an effect.
129 void set_cache_size(int cache_size) { cache_size_ = cache_size; }
131 // Call to put the database in exclusive locking mode. There is no "back to
132 // normal" flag because of some additional requirements sqlite puts on this
133 // transaction (requires another access to the DB) and because we don't
134 // actually need it.
136 // Exclusive mode means that the database is not unlocked at the end of each
137 // transaction, which means there may be less time spent initializing the
138 // next transaction because it doesn't have to re-aquire locks.
140 // This must be called before Open() to have an effect.
141 void set_exclusive_locking() { exclusive_locking_ = true; }
143 // Call to cause Open() to restrict access permissions of the
144 // database file to only the owner.
145 // TODO(shess): Currently only supported on OS_POSIX, is a noop on
146 // other platforms.
147 void set_restrict_to_user() { restrict_to_user_ = true; }
149 // Set an error-handling callback. On errors, the error number (and
150 // statement, if available) will be passed to the callback.
152 // If no callback is set, the default action is to crash in debug
153 // mode or return failure in release mode.
154 typedef base::Callback<void(int, Statement*)> ErrorCallback;
155 void set_error_callback(const ErrorCallback& callback) {
156 error_callback_ = callback;
158 bool has_error_callback() const {
159 return !error_callback_.is_null();
161 void reset_error_callback() {
162 error_callback_.Reset();
165 // Set this to enable additional per-connection histogramming. Must be called
166 // before Open().
167 void set_histogram_tag(const std::string& tag);
169 // Record a sparse UMA histogram sample under
170 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
171 // histogram is recorded.
172 void AddTaggedHistogram(const std::string& name, size_t sample) const;
174 // Track various API calls and results. Values corrospond to UMA
175 // histograms, do not modify, or add or delete other than directly
176 // before EVENT_MAX_VALUE.
177 enum Events {
178 // Number of statements run, either with sql::Statement or Execute*().
179 EVENT_STATEMENT_RUN = 0,
181 // Number of rows returned by statements run.
182 EVENT_STATEMENT_ROWS,
184 // Number of statements successfully run (all steps returned SQLITE_DONE or
185 // SQLITE_ROW).
186 EVENT_STATEMENT_SUCCESS,
188 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
189 EVENT_EXECUTE,
191 // Number of rows changed by autocommit statements.
192 EVENT_CHANGES_AUTOCOMMIT,
194 // Number of rows changed by statements in transactions.
195 EVENT_CHANGES,
197 // Count actual SQLite transaction statements (not including nesting).
198 EVENT_BEGIN,
199 EVENT_COMMIT,
200 EVENT_ROLLBACK,
202 // Leave this at the end.
203 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
204 EVENT_MAX_VALUE
206 void RecordEvent(Events event, size_t count);
207 void RecordOneEvent(Events event) {
208 RecordEvent(event, 1);
211 // Run "PRAGMA integrity_check" and post each line of
212 // results into |messages|. Returns the success of running the
213 // statement - per the SQLite documentation, if no errors are found the
214 // call should succeed, and a single value "ok" should be in messages.
215 bool FullIntegrityCheck(std::vector<std::string>* messages);
217 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
218 // interprets the results returning true if the the statement executes
219 // without error and results in a single "ok" value.
220 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
222 // Initialization ------------------------------------------------------------
224 // Initializes the SQL connection for the given file, returning true if the
225 // file could be opened. You can call this or OpenInMemory.
226 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
228 // Initializes the SQL connection for a temporary in-memory database. There
229 // will be no associated file on disk, and the initial database will be
230 // empty. You can call this or Open.
231 bool OpenInMemory() WARN_UNUSED_RESULT;
233 // Create a temporary on-disk database. The database will be
234 // deleted after close. This kind of database is similar to
235 // OpenInMemory() for small databases, but can page to disk if the
236 // database becomes large.
237 bool OpenTemporary() WARN_UNUSED_RESULT;
239 // Returns true if the database has been successfully opened.
240 bool is_open() const { return !!db_; }
242 // Closes the database. This is automatically performed on destruction for
243 // you, but this allows you to close the database early. You must not call
244 // any other functions after closing it. It is permissable to call Close on
245 // an uninitialized or already-closed database.
246 void Close();
248 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
249 // filesystem cache. This can be more efficient than faulting pages
250 // individually. Since this involves blocking I/O, it should only be used if
251 // the caller will immediately read a substantial amount of data from the
252 // database.
254 // TODO(shess): Design a set of histograms or an experiment to inform this
255 // decision. Preloading should almost always improve later performance
256 // numbers for this database simply because it pulls operations forward, but
257 // if the data isn't actually used soon then preloading just slows down
258 // everything else.
259 void Preload();
261 // Try to trim the cache memory used by the database. If |aggressively| is
262 // true, this function will try to free all of the cache memory it can. If
263 // |aggressively| is false, this function will try to cut cache memory
264 // usage by half.
265 void TrimMemory(bool aggressively);
267 // Raze the database to the ground. This approximates creating a
268 // fresh database from scratch, within the constraints of SQLite's
269 // locking protocol (locks and open handles can make doing this with
270 // filesystem operations problematic). Returns true if the database
271 // was razed.
273 // false is returned if the database is locked by some other
274 // process. RazeWithTimeout() may be used if appropriate.
276 // NOTE(shess): Raze() will DCHECK in the following situations:
277 // - database is not open.
278 // - the connection has a transaction open.
279 // - a SQLite issue occurs which is structural in nature (like the
280 // statements used are broken).
281 // Since Raze() is expected to be called in unexpected situations,
282 // these all return false, since it is unlikely that the caller
283 // could fix them.
285 // The database's page size is taken from |page_size_|. The
286 // existing database's |auto_vacuum| setting is lost (the
287 // possibility of corruption makes it unreliable to pull it from the
288 // existing database). To re-enable on the empty database requires
289 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
291 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
292 // so Raze() sets auto_vacuum to 1.
294 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
295 // TODO(shess): Bake auto_vacuum into Connection's API so it can
296 // just pick up the default.
297 bool Raze();
298 bool RazeWithTimout(base::TimeDelta timeout);
300 // Breaks all outstanding transactions (as initiated by
301 // BeginTransaction()), closes the SQLite database, and poisons the
302 // object so that all future operations against the Connection (or
303 // its Statements) fail safely, without side effects.
305 // This is intended as an alternative to Close() in error callbacks.
306 // Close() should still be called at some point.
307 void Poison();
309 // Raze() the database and Poison() the handle. Returns the return
310 // value from Raze().
311 // TODO(shess): Rename to RazeAndPoison().
312 bool RazeAndClose();
314 // Delete the underlying database files associated with |path|.
315 // This should be used on a database which has no existing
316 // connections. If any other connections are open to the same
317 // database, this could cause odd results or corruption (for
318 // instance if a hot journal is deleted but the associated database
319 // is not).
321 // Returns true if the database file and associated journals no
322 // longer exist, false otherwise. If the database has never
323 // existed, this will return true.
324 static bool Delete(const base::FilePath& path);
326 // Transactions --------------------------------------------------------------
328 // Transaction management. We maintain a virtual transaction stack to emulate
329 // nested transactions since sqlite can't do nested transactions. The
330 // limitation is you can't roll back a sub transaction: if any transaction
331 // fails, all transactions open will also be rolled back. Any nested
332 // transactions after one has rolled back will return fail for Begin(). If
333 // Begin() fails, you must not call Commit or Rollback().
335 // Normally you should use sql::Transaction to manage a transaction, which
336 // will scope it to a C++ context.
337 bool BeginTransaction();
338 void RollbackTransaction();
339 bool CommitTransaction();
341 // Rollback all outstanding transactions. Use with care, there may
342 // be scoped transactions on the stack.
343 void RollbackAllTransactions();
345 // Returns the current transaction nesting, which will be 0 if there are
346 // no open transactions.
347 int transaction_nesting() const { return transaction_nesting_; }
349 // Attached databases---------------------------------------------------------
351 // SQLite supports attaching multiple database files to a single
352 // handle. Attach the database in |other_db_path| to the current
353 // handle under |attachment_point|. |attachment_point| should only
354 // contain characters from [a-zA-Z0-9_].
356 // Note that calling attach or detach with an open transaction is an
357 // error.
358 bool AttachDatabase(const base::FilePath& other_db_path,
359 const char* attachment_point);
360 bool DetachDatabase(const char* attachment_point);
362 // Statements ----------------------------------------------------------------
364 // Executes the given SQL string, returning true on success. This is
365 // normally used for simple, 1-off statements that don't take any bound
366 // parameters and don't return any data (e.g. CREATE TABLE).
368 // This will DCHECK if the |sql| contains errors.
370 // Do not use ignore_result() to ignore all errors. Use
371 // ExecuteAndReturnErrorCode() and ignore only specific errors.
372 bool Execute(const char* sql) WARN_UNUSED_RESULT;
374 // Like Execute(), but returns the error code given by SQLite.
375 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
377 // Returns true if we have a statement with the given identifier already
378 // cached. This is normally not necessary to call, but can be useful if the
379 // caller has to dynamically build up SQL to avoid doing so if it's already
380 // cached.
381 bool HasCachedStatement(const StatementID& id) const;
383 // Returns a statement for the given SQL using the statement cache. It can
384 // take a nontrivial amount of work to parse and compile a statement, so
385 // keeping commonly-used ones around for future use is important for
386 // performance.
388 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
389 // the code will crash in debug). The caller must deal with this eventuality,
390 // either by checking validity of the |sql| before calling, by correctly
391 // handling the return of an inert statement, or both.
393 // The StatementID and the SQL must always correspond to one-another. The
394 // ID is the lookup into the cache, so crazy things will happen if you use
395 // different SQL with the same ID.
397 // You will normally use the SQL_FROM_HERE macro to generate a statement
398 // ID associated with the current line of code. This gives uniqueness without
399 // you having to manage unique names. See StatementID above for more.
401 // Example:
402 // sql::Statement stmt(connection_.GetCachedStatement(
403 // SQL_FROM_HERE, "SELECT * FROM foo"));
404 // if (!stmt)
405 // return false; // Error creating statement.
406 scoped_refptr<StatementRef> GetCachedStatement(const StatementID& id,
407 const char* sql);
409 // Used to check a |sql| statement for syntactic validity. If the statement is
410 // valid SQL, returns true.
411 bool IsSQLValid(const char* sql);
413 // Returns a non-cached statement for the given SQL. Use this for SQL that
414 // is only executed once or only rarely (there is overhead associated with
415 // keeping a statement cached).
417 // See GetCachedStatement above for examples and error information.
418 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
420 // Info querying -------------------------------------------------------------
422 // Returns true if the given table (or index) exists. Instead of
423 // test-then-create, callers should almost always prefer "CREATE TABLE IF NOT
424 // EXISTS" or "CREATE INDEX IF NOT EXISTS".
425 bool DoesTableExist(const char* table_name) const;
426 bool DoesIndexExist(const char* index_name) const;
428 // Returns true if a column with the given name exists in the given table.
429 bool DoesColumnExist(const char* table_name, const char* column_name) const;
431 // Returns sqlite's internal ID for the last inserted row. Valid only
432 // immediately after an insert.
433 int64_t GetLastInsertRowId() const;
435 // Returns sqlite's count of the number of rows modified by the last
436 // statement executed. Will be 0 if no statement has executed or the database
437 // is closed.
438 int GetLastChangeCount() const;
440 // Errors --------------------------------------------------------------------
442 // Returns the error code associated with the last sqlite operation.
443 int GetErrorCode() const;
445 // Returns the errno associated with GetErrorCode(). See
446 // SQLITE_LAST_ERRNO in SQLite documentation.
447 int GetLastErrno() const;
449 // Returns a pointer to a statically allocated string associated with the
450 // last sqlite operation.
451 const char* GetErrorMessage() const;
453 // Return a reproducible representation of the schema equivalent to
454 // running the following statement at a sqlite3 command-line:
455 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
456 std::string GetSchema() const;
458 // Clients which provide an error_callback don't see the
459 // error-handling at the end of OnSqliteError(). Expose to allow
460 // those clients to work appropriately with ScopedErrorIgnorer in
461 // tests.
462 static bool ShouldIgnoreSqliteError(int error);
464 private:
465 // For recovery module.
466 friend class Recovery;
468 // Allow test-support code to set/reset error ignorer.
469 friend class ScopedErrorIgnorer;
471 // Statement accesses StatementRef which we don't want to expose to everybody
472 // (they should go through Statement).
473 friend class Statement;
475 friend class test::ScopedCommitHook;
476 friend class test::ScopedScalarFunction;
477 friend class test::ScopedMockTimeSource;
479 // Internal initialize function used by both Init and InitInMemory. The file
480 // name is always 8 bits since we want to use the 8-bit version of
481 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
483 // |retry_flag| controls retrying the open if the error callback
484 // addressed errors using RazeAndClose().
485 enum Retry {
486 NO_RETRY = 0,
487 RETRY_ON_POISON
489 bool OpenInternal(const std::string& file_name, Retry retry_flag);
491 // Internal close function used by Close() and RazeAndClose().
492 // |forced| indicates that orderly-shutdown checks should not apply.
493 void CloseInternal(bool forced);
495 // Check whether the current thread is allowed to make IO calls, but only
496 // if database wasn't open in memory. Function is inlined to be a no-op in
497 // official build.
498 void AssertIOAllowed() {
499 if (!in_memory_)
500 base::ThreadRestrictions::AssertIOAllowed();
503 // Internal helper for DoesTableExist and DoesIndexExist.
504 bool DoesTableOrIndexExist(const char* name, const char* type) const;
506 // Accessors for global error-ignorer, for injecting behavior during tests.
507 // See test/scoped_error_ignorer.h.
508 typedef base::Callback<bool(int)> ErrorIgnorerCallback;
509 static ErrorIgnorerCallback* current_ignorer_cb_;
510 static void SetErrorIgnorer(ErrorIgnorerCallback* ignorer);
511 static void ResetErrorIgnorer();
513 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
514 // Refcounting allows us to give these statements out to sql::Statement
515 // objects while also optionally maintaining a cache of compiled statements
516 // by just keeping a refptr to these objects.
518 // A statement ref can be valid, in which case it can be used, or invalid to
519 // indicate that the statement hasn't been created yet, has an error, or has
520 // been destroyed.
522 // The Connection may revoke a StatementRef in some error cases, so callers
523 // should always check validity before using.
524 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
525 public:
526 // |connection| is the sql::Connection instance associated with
527 // the statement, and is used for tracking outstanding statements
528 // and for error handling. Set to NULL for invalid or untracked
529 // refs. |stmt| is the actual statement, and should only be NULL
530 // to create an invalid ref. |was_valid| indicates whether the
531 // statement should be considered valid for diagnistic purposes.
532 // |was_valid| can be true for NULL |stmt| if the connection has
533 // been forcibly closed by an error handler.
534 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
536 // When true, the statement can be used.
537 bool is_valid() const { return !!stmt_; }
539 // When true, the statement is either currently valid, or was
540 // previously valid but the connection was forcibly closed. Used
541 // for diagnostic checks.
542 bool was_valid() const { return was_valid_; }
544 // If we've not been linked to a connection, this will be NULL.
545 // TODO(shess): connection_ can be NULL in case of GetUntrackedStatement(),
546 // which prevents Statement::OnError() from forwarding errors.
547 Connection* connection() const { return connection_; }
549 // Returns the sqlite statement if any. If the statement is not active,
550 // this will return NULL.
551 sqlite3_stmt* stmt() const { return stmt_; }
553 // Destroys the compiled statement and marks it NULL. The statement will
554 // no longer be active. |forced| is used to indicate if orderly-shutdown
555 // checks should apply (see Connection::RazeAndClose()).
556 void Close(bool forced);
558 // Check whether the current thread is allowed to make IO calls, but only
559 // if database wasn't open in memory.
560 void AssertIOAllowed() { if (connection_) connection_->AssertIOAllowed(); }
562 private:
563 friend class base::RefCounted<StatementRef>;
565 ~StatementRef();
567 Connection* connection_;
568 sqlite3_stmt* stmt_;
569 bool was_valid_;
571 DISALLOW_COPY_AND_ASSIGN(StatementRef);
573 friend class StatementRef;
575 // Executes a rollback statement, ignoring all transaction state. Used
576 // internally in the transaction management code.
577 void DoRollback();
579 // Called by a StatementRef when it's being created or destroyed. See
580 // open_statements_ below.
581 void StatementRefCreated(StatementRef* ref);
582 void StatementRefDeleted(StatementRef* ref);
584 // Called when a sqlite function returns an error, which is passed
585 // as |err|. The return value is the error code to be reflected
586 // back to client code. |stmt| is non-NULL if the error relates to
587 // an sql::Statement instance. |sql| is non-NULL if the error
588 // relates to non-statement sql code (Execute, for instance). Both
589 // can be NULL, but both should never be set.
590 // NOTE(shess): Originally, the return value was intended to allow
591 // error handlers to transparently convert errors into success.
592 // Unfortunately, transactions are not generally restartable, so
593 // this did not work out.
594 int OnSqliteError(int err, Statement* stmt, const char* sql);
596 // Like |Execute()|, but retries if the database is locked.
597 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
598 WARN_UNUSED_RESULT;
600 // Internal helper for const functions. Like GetUniqueStatement(),
601 // except the statement is not entered into open_statements_,
602 // allowing this function to be const. Open statements can block
603 // closing the database, so only use in cases where the last ref is
604 // released before close could be called (which should always be the
605 // case for const functions).
606 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
608 bool IntegrityCheckHelper(
609 const char* pragma_sql,
610 std::vector<std::string>* messages) WARN_UNUSED_RESULT;
612 // Record time spent executing explicit COMMIT statements.
613 void RecordCommitTime(const base::TimeDelta& delta);
615 // Record time in DML (Data Manipulation Language) statements such as INSERT
616 // or UPDATE outside of an explicit transaction. Due to implementation
617 // limitations time spent on DDL (Data Definition Language) statements such as
618 // ALTER and CREATE is not included.
619 void RecordAutoCommitTime(const base::TimeDelta& delta);
621 // Record all time spent on updating the database. This includes CommitTime()
622 // and AutoCommitTime(), plus any time spent spilling to the journal if
623 // transactions do not fit in cache.
624 void RecordUpdateTime(const base::TimeDelta& delta);
626 // Record all time spent running statements, including time spent doing
627 // updates and time spent on read-only queries.
628 void RecordQueryTime(const base::TimeDelta& delta);
630 // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is
631 // true, autocommit time if the database is not in a transaction, or update
632 // time if the database is in a transaction. Also records change count to
633 // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT.
634 void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only);
636 // Helper to return the current time from the time source.
637 base::TimeTicks Now() {
638 return clock_->Now();
641 // The actual sqlite database. Will be NULL before Init has been called or if
642 // Init resulted in an error.
643 sqlite3* db_;
645 // Parameters we'll configure in sqlite before doing anything else. Zero means
646 // use the default value.
647 int page_size_;
648 int cache_size_;
649 bool exclusive_locking_;
650 bool restrict_to_user_;
652 // All cached statements. Keeping a reference to these statements means that
653 // they'll remain active.
654 typedef std::map<StatementID, scoped_refptr<StatementRef> >
655 CachedStatementMap;
656 CachedStatementMap statement_cache_;
658 // A list of all StatementRefs we've given out. Each ref must register with
659 // us when it's created or destroyed. This allows us to potentially close
660 // any open statements when we encounter an error.
661 typedef std::set<StatementRef*> StatementRefSet;
662 StatementRefSet open_statements_;
664 // Number of currently-nested transactions.
665 int transaction_nesting_;
667 // True if any of the currently nested transactions have been rolled back.
668 // When we get to the outermost transaction, this will determine if we do
669 // a rollback instead of a commit.
670 bool needs_rollback_;
672 // True if database is open with OpenInMemory(), False if database is open
673 // with Open().
674 bool in_memory_;
676 // |true| if the connection was closed using RazeAndClose(). Used
677 // to enable diagnostics to distinguish calls to never-opened
678 // databases (incorrect use of the API) from calls to once-valid
679 // databases.
680 bool poisoned_;
682 ErrorCallback error_callback_;
684 // Tag for auxiliary histograms.
685 std::string histogram_tag_;
687 // Linear histogram for RecordEvent().
688 base::HistogramBase* stats_histogram_;
690 // Histogram for tracking time taken in commit.
691 base::HistogramBase* commit_time_histogram_;
693 // Histogram for tracking time taken in autocommit updates.
694 base::HistogramBase* autocommit_time_histogram_;
696 // Histogram for tracking time taken in updates (including commit and
697 // autocommit).
698 base::HistogramBase* update_time_histogram_;
700 // Histogram for tracking time taken in all queries.
701 base::HistogramBase* query_time_histogram_;
703 // Source for timing information, provided to allow tests to inject time
704 // changes.
705 scoped_ptr<TimeSource> clock_;
707 DISALLOW_COPY_AND_ASSIGN(Connection);
710 } // namespace sql
712 #endif // SQL_CONNECTION_H_