michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- michael@0: * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ : michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #ifndef mozilla_storage_Connection_h michael@0: #define mozilla_storage_Connection_h michael@0: michael@0: #include "nsAutoPtr.h" michael@0: #include "nsCOMPtr.h" michael@0: #include "mozilla/Mutex.h" michael@0: #include "nsProxyRelease.h" michael@0: #include "nsThreadUtils.h" michael@0: #include "nsIInterfaceRequestor.h" michael@0: michael@0: #include "nsDataHashtable.h" michael@0: #include "mozIStorageProgressHandler.h" michael@0: #include "SQLiteMutex.h" michael@0: #include "mozIStorageConnection.h" michael@0: #include "mozStorageService.h" michael@0: #include "mozIStorageAsyncConnection.h" michael@0: #include "mozIStorageCompletionCallback.h" michael@0: michael@0: #include "nsIMutableArray.h" michael@0: #include "mozilla/Attributes.h" michael@0: michael@0: #include "sqlite3.h" michael@0: michael@0: struct PRLock; michael@0: class nsIFile; michael@0: class nsIFileURL; michael@0: class nsIEventTarget; michael@0: class nsIThread; michael@0: michael@0: namespace mozilla { michael@0: namespace storage { michael@0: michael@0: class Connection MOZ_FINAL : public mozIStorageConnection michael@0: , public nsIInterfaceRequestor michael@0: { michael@0: public: michael@0: NS_DECL_THREADSAFE_ISUPPORTS michael@0: NS_DECL_MOZISTORAGEASYNCCONNECTION michael@0: NS_DECL_MOZISTORAGECONNECTION michael@0: NS_DECL_NSIINTERFACEREQUESTOR michael@0: michael@0: /** michael@0: * Structure used to describe user functions on the database connection. michael@0: */ michael@0: struct FunctionInfo { michael@0: enum FunctionType { michael@0: SIMPLE, michael@0: AGGREGATE michael@0: }; michael@0: michael@0: nsCOMPtr function; michael@0: FunctionType type; michael@0: int32_t numArgs; michael@0: }; michael@0: michael@0: /** michael@0: * @param aService michael@0: * Pointer to the storage service. Held onto for the lifetime of the michael@0: * connection. michael@0: * @param aFlags michael@0: * The flags to pass to sqlite3_open_v2. michael@0: * @param aAsyncOnly michael@0: * If |true|, the Connection only implements asynchronous interface: michael@0: * - |mozIStorageAsyncConnection|; michael@0: * If |false|, the result also implements synchronous interface: michael@0: * - |mozIStorageConnection|. michael@0: */ michael@0: Connection(Service *aService, int aFlags, bool aAsyncOnly); michael@0: michael@0: /** michael@0: * Creates the connection to an in-memory database. michael@0: */ michael@0: nsresult initialize(); michael@0: michael@0: /** michael@0: * Creates the connection to the database. michael@0: * michael@0: * @param aDatabaseFile michael@0: * The nsIFile of the location of the database to open, or create if it michael@0: * does not exist. michael@0: */ michael@0: nsresult initialize(nsIFile *aDatabaseFile); michael@0: michael@0: /** michael@0: * Creates the connection to the database. michael@0: * michael@0: * @param aFileURL michael@0: * The nsIFileURL of the location of the database to open, or create if it michael@0: * does not exist. michael@0: */ michael@0: nsresult initialize(nsIFileURL *aFileURL); michael@0: michael@0: /** michael@0: * Fetches runtime status information for this connection. michael@0: * michael@0: * @param aStatusOption One of the SQLITE_DBSTATUS options defined at michael@0: * http://www.sqlite.org/c3ref/c_dbstatus_options.html michael@0: * @param [optional] aMaxValue if provided, will be set to the highest michael@0: * istantaneous value. michael@0: * @return the current value for the specified option. michael@0: */ michael@0: int32_t getSqliteRuntimeStatus(int32_t aStatusOption, michael@0: int32_t* aMaxValue=nullptr); michael@0: /** michael@0: * Registers/unregisters a commit hook callback. michael@0: * michael@0: * @param aCallbackFn a callback function to be invoked on transactions michael@0: * commit. Pass nullptr to unregister the current callback. michael@0: * @param [optional] aData if provided, will be passed to the callback. michael@0: * @see http://sqlite.org/c3ref/commit_hook.html michael@0: */ michael@0: void setCommitHook(int (*aCallbackFn)(void *) , void *aData=nullptr) { michael@0: MOZ_ASSERT(mDBConn, "A connection must exist at this point"); michael@0: ::sqlite3_commit_hook(mDBConn, aCallbackFn, aData); michael@0: }; michael@0: michael@0: /** michael@0: * Lazily creates and returns a background execution thread. In the future, michael@0: * the thread may be re-claimed if left idle, so you should call this michael@0: * method just before you dispatch and not save the reference. michael@0: * michael@0: * @returns an event target suitable for asynchronous statement execution. michael@0: */ michael@0: nsIEventTarget *getAsyncExecutionTarget(); michael@0: michael@0: /** michael@0: * Mutex used by asynchronous statements to protect state. The mutex is michael@0: * declared on the connection object because there is no contention between michael@0: * asynchronous statements (they are serialized on mAsyncExecutionThread). michael@0: * Currently protects: michael@0: * - Connection.mAsyncExecutionThreadShuttingDown michael@0: * - Connection.mAsyncExecutionThread michael@0: * - Connection.mConnectionClosed michael@0: * - AsyncExecuteStatements.mCancelRequested michael@0: */ michael@0: Mutex sharedAsyncExecutionMutex; michael@0: michael@0: /** michael@0: * Wraps the mutex that SQLite gives us from sqlite3_db_mutex. This is public michael@0: * because we already expose the sqlite3* native connection and proper michael@0: * operation of the deadlock detector requires everyone to use the same single michael@0: * SQLiteMutex instance for correctness. michael@0: */ michael@0: SQLiteMutex sharedDBMutex; michael@0: michael@0: /** michael@0: * References the thread this database was opened on. This MUST be thread it is michael@0: * closed on. michael@0: */ michael@0: const nsCOMPtr threadOpenedOn; michael@0: michael@0: /** michael@0: * Closes the SQLite database, and warns about any non-finalized statements. michael@0: */ michael@0: nsresult internalClose(sqlite3 *aDBConn); michael@0: michael@0: /** michael@0: * Obtains the filename of the connection. Useful for logging. michael@0: */ michael@0: nsCString getFilename(); michael@0: michael@0: /** michael@0: * Creates an sqlite3 prepared statement object from an SQL string. michael@0: * michael@0: * @param aNativeConnection michael@0: * The underlying Sqlite connection to prepare the statement with. michael@0: * @param aSQL michael@0: * The SQL statement string to compile. michael@0: * @param _stmt michael@0: * New sqlite3_stmt object. michael@0: * @return the result from sqlite3_prepare_v2. michael@0: */ michael@0: int prepareStatement(sqlite3* aNativeConnection, michael@0: const nsCString &aSQL, sqlite3_stmt **_stmt); michael@0: michael@0: /** michael@0: * Performs a sqlite3_step on aStatement, while properly handling SQLITE_LOCKED michael@0: * when not on the main thread by waiting until we are notified. michael@0: * michael@0: * @param aNativeConnection michael@0: * The underlying Sqlite connection to step the statement with. michael@0: * @param aStatement michael@0: * A pointer to a sqlite3_stmt object. michael@0: * @return the result from sqlite3_step. michael@0: */ michael@0: int stepStatement(sqlite3* aNativeConnection, sqlite3_stmt* aStatement); michael@0: michael@0: /** michael@0: * Raw connection transaction management. michael@0: * michael@0: * @see BeginTransactionAs, CommitTransaction, RollbackTransaction. michael@0: */ michael@0: nsresult beginTransactionInternal(sqlite3 *aNativeConnection, michael@0: int32_t aTransactionType=TRANSACTION_DEFERRED); michael@0: nsresult commitTransactionInternal(sqlite3 *aNativeConnection); michael@0: nsresult rollbackTransactionInternal(sqlite3 *aNativeConnection); michael@0: michael@0: bool connectionReady(); michael@0: michael@0: /** michael@0: * True if this connection is shutting down but not yet closed. michael@0: */ michael@0: bool isClosing(); michael@0: michael@0: /** michael@0: * True if the underlying connection is closed. michael@0: * Any sqlite resources may be lost when this returns true, so nothing should michael@0: * try to use them. michael@0: */ michael@0: bool isClosed(); michael@0: michael@0: nsresult initializeClone(Connection *aClone, bool aReadOnly); michael@0: michael@0: private: michael@0: ~Connection(); michael@0: nsresult initializeInternal(nsIFile *aDatabaseFile); michael@0: michael@0: /** michael@0: * Sets the database into a closed state so no further actions can be michael@0: * performed. michael@0: * michael@0: * @note mDBConn is set to nullptr in this method. michael@0: */ michael@0: nsresult setClosedState(); michael@0: michael@0: /** michael@0: * Helper for calls to sqlite3_exec. Reports long delays to Telemetry. michael@0: * michael@0: * @param aNativeConnection michael@0: * The underlying Sqlite connection to execute the query with. michael@0: * @param aSqlString michael@0: * SQL string to execute michael@0: * @return the result from sqlite3_exec. michael@0: */ michael@0: int executeSql(sqlite3 *aNativeConnection, const char *aSqlString); michael@0: michael@0: /** michael@0: * Describes a certain primitive type in the database. michael@0: * michael@0: * Possible Values Are: michael@0: * INDEX - To check for the existence of an index michael@0: * TABLE - To check for the existence of a table michael@0: */ michael@0: enum DatabaseElementType { michael@0: INDEX, michael@0: TABLE michael@0: }; michael@0: michael@0: /** michael@0: * Determines if the specified primitive exists. michael@0: * michael@0: * @param aElementType michael@0: * The type of element to check the existence of michael@0: * @param aElementName michael@0: * The name of the element to check for michael@0: * @returns true if element exists, false otherwise michael@0: */ michael@0: nsresult databaseElementExists(enum DatabaseElementType aElementType, michael@0: const nsACString& aElementName, michael@0: bool *_exists); michael@0: michael@0: bool findFunctionByInstance(nsISupports *aInstance); michael@0: michael@0: static int sProgressHelper(void *aArg); michael@0: // Generic progress handler michael@0: // Dispatch call to registered progress handler, michael@0: // if there is one. Do nothing in other cases. michael@0: int progressHandler(); michael@0: michael@0: sqlite3 *mDBConn; michael@0: nsCOMPtr mFileURL; michael@0: nsCOMPtr mDatabaseFile; michael@0: michael@0: /** michael@0: * Lazily created thread for asynchronous statement execution. Consumers michael@0: * should use getAsyncExecutionTarget rather than directly accessing this michael@0: * field. michael@0: */ michael@0: nsCOMPtr mAsyncExecutionThread; michael@0: michael@0: /** michael@0: * Set to true by Close() or AsyncClose() prior to shutdown. michael@0: * michael@0: * If false, we guarantee both that the underlying sqlite3 database michael@0: * connection is still open and that getAsyncExecutionTarget() can michael@0: * return a thread. Once true, either the sqlite3 database michael@0: * connection is being shutdown or it has been michael@0: * shutdown. Additionally, once true, getAsyncExecutionTarget() michael@0: * returns null. michael@0: * michael@0: * This variable should be accessed while holding the michael@0: * sharedAsyncExecutionMutex. michael@0: */ michael@0: bool mAsyncExecutionThreadShuttingDown; michael@0: michael@0: /** michael@0: * Set to true just prior to calling sqlite3_close on the michael@0: * connection. michael@0: * michael@0: * This variable should be accessed while holding the michael@0: * sharedAsyncExecutionMutex. michael@0: */ michael@0: bool mConnectionClosed; michael@0: michael@0: /** michael@0: * Tracks if we have a transaction in progress or not. Access protected by michael@0: * sharedDBMutex. michael@0: */ michael@0: bool mTransactionInProgress; michael@0: michael@0: /** michael@0: * Stores the mapping of a given function by name to its instance. Access is michael@0: * protected by sharedDBMutex. michael@0: */ michael@0: nsDataHashtable mFunctions; michael@0: michael@0: /** michael@0: * Stores the registered progress handler for the database connection. Access michael@0: * is protected by sharedDBMutex. michael@0: */ michael@0: nsCOMPtr mProgressHandler; michael@0: michael@0: /** michael@0: * Stores the flags we passed to sqlite3_open_v2. michael@0: */ michael@0: const int mFlags; michael@0: michael@0: // This is here for two reasons: 1) It's used to make sure that the michael@0: // connections do not outlive the service. 2) Our custom collating functions michael@0: // call its localeCompareStrings() method. michael@0: nsRefPtr mStorageService; michael@0: michael@0: /** michael@0: * If |false|, this instance supports synchronous operations michael@0: * and it can be cast to |mozIStorageConnection|. michael@0: */ michael@0: const bool mAsyncOnly; michael@0: }; michael@0: michael@0: michael@0: /** michael@0: * A Runnable designed to call a mozIStorageCompletionCallback on michael@0: * the appropriate thread. michael@0: */ michael@0: class CallbackComplete MOZ_FINAL : public nsRunnable michael@0: { michael@0: public: michael@0: /** michael@0: * @param aValue The result to pass to the callback. It must michael@0: * already be owned by the main thread. michael@0: * @param aCallback The callback. It must already be owned by the michael@0: * main thread. michael@0: */ michael@0: CallbackComplete(nsresult aStatus, michael@0: nsISupports* aValue, michael@0: already_AddRefed aCallback) michael@0: : mStatus(aStatus) michael@0: , mValue(aValue) michael@0: , mCallback(aCallback) michael@0: { michael@0: } michael@0: michael@0: NS_IMETHOD Run() { michael@0: MOZ_ASSERT(NS_IsMainThread()); michael@0: nsresult rv = mCallback->Complete(mStatus, mValue); michael@0: michael@0: // Ensure that we release on the main thread michael@0: mValue = nullptr; michael@0: mCallback = nullptr; michael@0: return rv; michael@0: } michael@0: michael@0: private: michael@0: nsresult mStatus; michael@0: nsCOMPtr mValue; michael@0: // This is a nsRefPtr and not a nsCOMPtr because michael@0: // nsCOMP would cause an off-main thread QI, which michael@0: // is not a good idea (and crashes XPConnect). michael@0: nsRefPtr mCallback; michael@0: }; michael@0: michael@0: } // namespace storage michael@0: } // namespace mozilla michael@0: michael@0: #endif // mozilla_storage_Connection_h