1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
10 #include "nsAutoPtr.h"
11 #include "nsThreadUtils.h"
13 #include "nsIFileURL.h"
14 #include "nsIXPConnect.h"
15 #include "mozilla/Telemetry.h"
16 #include "mozilla/Mutex.h"
17 #include "mozilla/CondVar.h"
18 #include "mozilla/Attributes.h"
19 #include "mozilla/ErrorNames.h"
20 #include "mozilla/Unused.h"
21 #include "mozilla/dom/quota/QuotaObject.h"
22 #include "mozilla/ScopeExit.h"
24 #include "mozIStorageAggregateFunction.h"
25 #include "mozIStorageCompletionCallback.h"
26 #include "mozIStorageFunction.h"
28 #include "mozStorageAsyncStatementExecution.h"
29 #include "mozStorageSQLFunctions.h"
30 #include "mozStorageConnection.h"
31 #include "mozStorageService.h"
32 #include "mozStorageStatement.h"
33 #include "mozStorageAsyncStatement.h"
34 #include "mozStorageArgValueArray.h"
35 #include "mozStoragePrivateHelpers.h"
36 #include "mozStorageStatementData.h"
37 #include "StorageBaseStatementInternal.h"
38 #include "SQLCollations.h"
39 #include "FileSystemModule.h"
40 #include "mozStorageHelper.h"
41 #include "GeckoProfiler.h"
43 #include "mozilla/Logging.h"
44 #include "mozilla/Printf.h"
45 #include "nsProxyRelease.h"
48 #define MIN_AVAILABLE_BYTES_PER_CHUNKED_GROWTH 524288000 // 500 MiB
50 // Maximum size of the pages cache per connection.
51 #define MAX_CACHE_SIZE_KIBIBYTES 2048 // 2 MiB
53 mozilla::LazyLogModule
gStorageLog("mozStorage");
55 // Checks that the protected code is running on the main-thread only if the
56 // connection was also opened on it.
58 # define CHECK_MAINTHREAD_ABUSE() \
60 nsCOMPtr<nsIThread> mainThread = do_GetMainThread(); \
61 NS_WARNING_ASSERTION( \
62 threadOpenedOn == mainThread || !NS_IsMainThread(), \
63 "Using Storage synchronous API on main-thread, but " \
64 "the connection was " \
65 "opened on another thread."); \
68 # define CHECK_MAINTHREAD_ABUSE() \
76 using mozilla::dom::quota::QuotaObject
;
78 const char* GetVFSName();
82 int nsresultToSQLiteResult(nsresult aXPCOMResultCode
) {
83 if (NS_SUCCEEDED(aXPCOMResultCode
)) {
87 switch (aXPCOMResultCode
) {
88 case NS_ERROR_FILE_CORRUPTED
:
89 return SQLITE_CORRUPT
;
90 case NS_ERROR_FILE_ACCESS_DENIED
:
91 return SQLITE_CANTOPEN
;
92 case NS_ERROR_STORAGE_BUSY
:
94 case NS_ERROR_FILE_IS_LOCKED
:
96 case NS_ERROR_FILE_READ_ONLY
:
97 return SQLITE_READONLY
;
98 case NS_ERROR_STORAGE_IOERR
:
100 case NS_ERROR_FILE_NO_DEVICE_SPACE
:
102 case NS_ERROR_OUT_OF_MEMORY
:
104 case NS_ERROR_UNEXPECTED
:
105 return SQLITE_MISUSE
;
108 case NS_ERROR_STORAGE_CONSTRAINT
:
109 return SQLITE_CONSTRAINT
;
114 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Must return in switch above!");
117 ////////////////////////////////////////////////////////////////////////////////
118 //// Variant Specialization Functions (variantToSQLiteT)
120 int sqlite3_T_int(sqlite3_context
* aCtx
, int aValue
) {
121 ::sqlite3_result_int(aCtx
, aValue
);
125 int sqlite3_T_int64(sqlite3_context
* aCtx
, sqlite3_int64 aValue
) {
126 ::sqlite3_result_int64(aCtx
, aValue
);
130 int sqlite3_T_double(sqlite3_context
* aCtx
, double aValue
) {
131 ::sqlite3_result_double(aCtx
, aValue
);
135 int sqlite3_T_text(sqlite3_context
* aCtx
, const nsCString
& aValue
) {
136 ::sqlite3_result_text(aCtx
, aValue
.get(), aValue
.Length(), SQLITE_TRANSIENT
);
140 int sqlite3_T_text16(sqlite3_context
* aCtx
, const nsString
& aValue
) {
141 ::sqlite3_result_text16(
143 aValue
.Length() * sizeof(char16_t
), // Number of bytes.
148 int sqlite3_T_null(sqlite3_context
* aCtx
) {
149 ::sqlite3_result_null(aCtx
);
153 int sqlite3_T_blob(sqlite3_context
* aCtx
, const void* aData
, int aSize
) {
154 ::sqlite3_result_blob(aCtx
, aData
, aSize
, free
);
158 #include "variantToSQLiteT_impl.h"
160 ////////////////////////////////////////////////////////////////////////////////
165 int (*registerFunc
)(sqlite3
*, const char*);
168 Module gModules
[] = {{"filesystem", RegisterFileSystemModule
}};
170 ////////////////////////////////////////////////////////////////////////////////
173 int tracefunc(unsigned aReason
, void* aClosure
, void* aP
, void* aX
) {
175 case SQLITE_TRACE_STMT
: {
176 // aP is a pointer to the prepared statement.
177 sqlite3_stmt
* stmt
= static_cast<sqlite3_stmt
*>(aP
);
178 // aX is a pointer to a string containing the unexpanded SQL or a comment,
179 // starting with "--"" in case of a trigger.
180 char* expanded
= static_cast<char*>(aX
);
181 // Simulate what sqlite_trace was doing.
182 if (!::strncmp(expanded
, "--", 2)) {
183 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
184 ("TRACE_STMT on %p: '%s'", aClosure
, expanded
));
186 char* sql
= ::sqlite3_expanded_sql(stmt
);
187 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
188 ("TRACE_STMT on %p: '%s'", aClosure
, sql
));
193 case SQLITE_TRACE_PROFILE
: {
194 // aX is pointer to a 64bit integer containing nanoseconds it took to
195 // execute the last command.
196 sqlite_int64 time
= *(static_cast<sqlite_int64
*>(aX
)) / 1000000;
198 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
199 ("TRACE_TIME on %p: %lldms", aClosure
, time
));
207 void basicFunctionHelper(sqlite3_context
* aCtx
, int aArgc
,
208 sqlite3_value
** aArgv
) {
209 void* userData
= ::sqlite3_user_data(aCtx
);
211 mozIStorageFunction
* func
= static_cast<mozIStorageFunction
*>(userData
);
213 RefPtr
<ArgValueArray
> arguments(new ArgValueArray(aArgc
, aArgv
));
214 if (!arguments
) return;
216 nsCOMPtr
<nsIVariant
> result
;
217 nsresult rv
= func
->OnFunctionCall(arguments
, getter_AddRefs(result
));
219 nsAutoCString errorMessage
;
220 GetErrorName(rv
, errorMessage
);
221 errorMessage
.InsertLiteral("User function returned ", 0);
222 errorMessage
.Append('!');
224 NS_WARNING(errorMessage
.get());
226 ::sqlite3_result_error(aCtx
, errorMessage
.get(), -1);
227 ::sqlite3_result_error_code(aCtx
, nsresultToSQLiteResult(rv
));
230 int retcode
= variantToSQLiteT(aCtx
, result
);
231 if (retcode
!= SQLITE_OK
) {
232 NS_WARNING("User function returned invalid data type!");
233 ::sqlite3_result_error(aCtx
, "User function returned invalid data type",
238 void aggregateFunctionStepHelper(sqlite3_context
* aCtx
, int aArgc
,
239 sqlite3_value
** aArgv
) {
240 void* userData
= ::sqlite3_user_data(aCtx
);
241 mozIStorageAggregateFunction
* func
=
242 static_cast<mozIStorageAggregateFunction
*>(userData
);
244 RefPtr
<ArgValueArray
> arguments(new ArgValueArray(aArgc
, aArgv
));
245 if (!arguments
) return;
247 if (NS_FAILED(func
->OnStep(arguments
)))
248 NS_WARNING("User aggregate step function returned error code!");
251 void aggregateFunctionFinalHelper(sqlite3_context
* aCtx
) {
252 void* userData
= ::sqlite3_user_data(aCtx
);
253 mozIStorageAggregateFunction
* func
=
254 static_cast<mozIStorageAggregateFunction
*>(userData
);
256 RefPtr
<nsIVariant
> result
;
257 if (NS_FAILED(func
->OnFinal(getter_AddRefs(result
)))) {
258 NS_WARNING("User aggregate final function returned error code!");
259 ::sqlite3_result_error(
260 aCtx
, "User aggregate final function returned error code", -1);
264 if (variantToSQLiteT(aCtx
, result
) != SQLITE_OK
) {
265 NS_WARNING("User aggregate final function returned invalid data type!");
266 ::sqlite3_result_error(
267 aCtx
, "User aggregate final function returned invalid data type", -1);
272 * This code is heavily based on the sample at:
273 * http://www.sqlite.org/unlock_notify.html
275 class UnlockNotification
{
278 : mMutex("UnlockNotification mMutex"),
279 mCondVar(mMutex
, "UnlockNotification condVar"),
283 MutexAutoLock
lock(mMutex
);
285 (void)mCondVar
.Wait();
290 MutexAutoLock
lock(mMutex
);
292 (void)mCondVar
.Notify();
301 void UnlockNotifyCallback(void** aArgs
, int aArgsSize
) {
302 for (int i
= 0; i
< aArgsSize
; i
++) {
303 UnlockNotification
* notification
=
304 static_cast<UnlockNotification
*>(aArgs
[i
]);
305 notification
->Signal();
309 int WaitForUnlockNotify(sqlite3
* aDatabase
) {
310 UnlockNotification notification
;
312 ::sqlite3_unlock_notify(aDatabase
, UnlockNotifyCallback
, ¬ification
);
313 MOZ_ASSERT(srv
== SQLITE_LOCKED
|| srv
== SQLITE_OK
);
314 if (srv
== SQLITE_OK
) {
321 ////////////////////////////////////////////////////////////////////////////////
324 class AsyncCloseConnection final
: public Runnable
{
326 AsyncCloseConnection(Connection
* aConnection
, sqlite3
* aNativeConnection
,
327 nsIRunnable
* aCallbackEvent
)
328 : Runnable("storage::AsyncCloseConnection"),
329 mConnection(aConnection
),
330 mNativeConnection(aNativeConnection
),
331 mCallbackEvent(aCallbackEvent
) {}
333 NS_IMETHOD
Run() override
{
334 // This code is executed on the background thread
335 MOZ_ASSERT(NS_GetCurrentThread() != mConnection
->threadOpenedOn
);
337 nsCOMPtr
<nsIRunnable
> event
=
338 NewRunnableMethod("storage::Connection::shutdownAsyncThread",
339 mConnection
, &Connection::shutdownAsyncThread
);
340 MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(event
));
343 (void)mConnection
->internalClose(mNativeConnection
);
346 if (mCallbackEvent
) {
347 nsCOMPtr
<nsIThread
> thread
;
348 (void)NS_GetMainThread(getter_AddRefs(thread
));
349 (void)thread
->Dispatch(mCallbackEvent
, NS_DISPATCH_NORMAL
);
355 ~AsyncCloseConnection() override
{
356 NS_ReleaseOnMainThreadSystemGroup("AsyncCloseConnection::mConnection",
357 mConnection
.forget());
358 NS_ReleaseOnMainThreadSystemGroup("AsyncCloseConnection::mCallbackEvent",
359 mCallbackEvent
.forget());
363 RefPtr
<Connection
> mConnection
;
364 sqlite3
* mNativeConnection
;
365 nsCOMPtr
<nsIRunnable
> mCallbackEvent
;
369 * An event used to initialize the clone of a connection.
371 * Must be executed on the clone's async execution thread.
373 class AsyncInitializeClone final
: public Runnable
{
376 * @param aConnection The connection being cloned.
377 * @param aClone The clone.
378 * @param aReadOnly If |true|, the clone is read only.
379 * @param aCallback A callback to trigger once initialization
380 * is complete. This event will be called on
381 * aClone->threadOpenedOn.
383 AsyncInitializeClone(Connection
* aConnection
, Connection
* aClone
,
384 const bool aReadOnly
,
385 mozIStorageCompletionCallback
* aCallback
)
386 : Runnable("storage::AsyncInitializeClone"),
387 mConnection(aConnection
),
389 mReadOnly(aReadOnly
),
390 mCallback(aCallback
) {
391 MOZ_ASSERT(NS_IsMainThread());
394 NS_IMETHOD
Run() override
{
395 MOZ_ASSERT(!NS_IsMainThread());
396 nsresult rv
= mConnection
->initializeClone(mClone
, mReadOnly
);
398 return Dispatch(rv
, nullptr);
400 return Dispatch(NS_OK
,
401 NS_ISUPPORTS_CAST(mozIStorageAsyncConnection
*, mClone
));
405 nsresult
Dispatch(nsresult aResult
, nsISupports
* aValue
) {
406 RefPtr
<CallbackComplete
> event
=
407 new CallbackComplete(aResult
, aValue
, mCallback
.forget());
408 return mClone
->threadOpenedOn
->Dispatch(event
, NS_DISPATCH_NORMAL
);
411 ~AsyncInitializeClone() override
{
412 nsCOMPtr
<nsIThread
> thread
;
413 DebugOnly
<nsresult
> rv
= NS_GetMainThread(getter_AddRefs(thread
));
414 MOZ_ASSERT(NS_SUCCEEDED(rv
));
416 // Handle ambiguous nsISupports inheritance.
417 NS_ProxyRelease("AsyncInitializeClone::mConnection", thread
,
418 mConnection
.forget());
419 NS_ProxyRelease("AsyncInitializeClone::mClone", thread
, mClone
.forget());
421 // Generally, the callback will be released by CallbackComplete.
422 // However, if for some reason Run() is not executed, we still
423 // need to ensure that it is released here.
424 NS_ProxyRelease("AsyncInitializeClone::mCallback", thread
,
428 RefPtr
<Connection
> mConnection
;
429 RefPtr
<Connection
> mClone
;
430 const bool mReadOnly
;
431 nsCOMPtr
<mozIStorageCompletionCallback
> mCallback
;
435 * A listener for async connection closing.
437 class CloseListener final
: public mozIStorageCompletionCallback
{
440 CloseListener() : mClosed(false) {}
442 NS_IMETHOD
Complete(nsresult
, nsISupports
*) override
{
450 ~CloseListener() = default;
453 NS_IMPL_ISUPPORTS(CloseListener
, mozIStorageCompletionCallback
)
457 ////////////////////////////////////////////////////////////////////////////////
460 Connection::Connection(Service
* aService
, int aFlags
,
461 ConnectionOperation aSupportedOperations
,
462 bool aIgnoreLockingMode
)
463 : sharedAsyncExecutionMutex("Connection::sharedAsyncExecutionMutex"),
464 sharedDBMutex("Connection::sharedDBMutex"),
465 threadOpenedOn(do_GetCurrentThread()),
467 mAsyncExecutionThreadShuttingDown(false),
468 mConnectionClosed(false),
469 mDefaultTransactionType(mozIStorageConnection::TRANSACTION_DEFERRED
),
470 mTransactionInProgress(false),
472 mProgressHandler(nullptr),
474 mIgnoreLockingMode(aIgnoreLockingMode
),
475 mStorageService(aService
),
476 mSupportedOperations(aSupportedOperations
) {
477 MOZ_ASSERT(!mIgnoreLockingMode
|| mFlags
& SQLITE_OPEN_READONLY
,
478 "Can't ignore locking for a non-readonly connection!");
479 mStorageService
->registerConnection(this);
482 Connection::~Connection() {
483 // Failsafe Close() occurs in our custom Release method because of
484 // complications related to Close() potentially invoking AsyncClose() which
485 // will increment our refcount.
486 MOZ_ASSERT(!mAsyncExecutionThread
,
487 "The async thread has not been shutdown properly!");
490 NS_IMPL_ADDREF(Connection
)
492 NS_INTERFACE_MAP_BEGIN(Connection
)
493 NS_INTERFACE_MAP_ENTRY(mozIStorageAsyncConnection
)
494 NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor
)
495 NS_INTERFACE_MAP_ENTRY(mozIStorageConnection
)
496 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports
, mozIStorageConnection
)
499 // This is identical to what NS_IMPL_RELEASE provides, but with the
500 // extra |1 == count| case.
501 NS_IMETHODIMP_(MozExternalRefCountType
) Connection::Release(void) {
502 MOZ_ASSERT(0 != mRefCnt
, "dup release");
503 nsrefcnt count
= --mRefCnt
;
504 NS_LOG_RELEASE(this, count
, "Connection");
506 // If the refcount went to 1, the single reference must be from
507 // gService->mConnections (in class |Service|). And the code calling
508 // Release is either:
509 // - The "user" code that had created the connection, releasing on any
511 // - One of Service's getConnections() callers had acquired a strong
512 // reference to the Connection that out-lived the last "user" reference,
513 // and now that just got dropped. Note that this reference could be
514 // getting dropped on the main thread or Connection->threadOpenedOn
515 // (because of the NewRunnableMethod used by minimizeMemory).
517 // Either way, we should now perform our failsafe Close() and unregister.
518 // However, we only want to do this once, and the reality is that our
519 // refcount could go back up above 1 and down again at any time if we are
520 // off the main thread and getConnections() gets called on the main thread,
521 // so we use an atomic here to do this exactly once.
522 if (mDestroying
.compareExchange(false, true)) {
523 // Close the connection, dispatching to the opening thread if we're not
524 // on that thread already and that thread is still accepting runnables.
525 // We do this because it's possible we're on the main thread because of
526 // getConnections(), and we REALLY don't want to transfer I/O to the main
527 // thread if we can avoid it.
528 if (threadOpenedOn
->IsOnCurrentThread()) {
529 // This could cause SpinningSynchronousClose() to be invoked and AddRef
530 // triggered for AsyncCloseConnection's strong ref if the conn was ever
531 // use for async purposes. (Main-thread only, though.)
532 Unused
<< synchronousClose();
534 nsCOMPtr
<nsIRunnable
> event
=
535 NewRunnableMethod("storage::Connection::synchronousClose", this,
536 &Connection::synchronousClose
);
538 threadOpenedOn
->Dispatch(event
.forget(), NS_DISPATCH_NORMAL
))) {
539 // The target thread was dead and so we've just leaked our runnable.
540 // This should not happen because our non-main-thread consumers should
541 // be explicitly closing their connections, not relying on us to close
542 // them for them. (It's okay to let a statement go out of scope for
543 // automatic cleanup, but not a Connection.)
545 "Leaked Connection::synchronousClose(), ownership fail.");
546 Unused
<< synchronousClose();
550 // This will drop its strong reference right here, right now.
551 mStorageService
->unregisterConnection(this);
553 } else if (0 == count
) {
554 mRefCnt
= 1; /* stabilize */
555 #if 0 /* enable this to find non-threadsafe destructors: */
556 NS_ASSERT_OWNINGTHREAD(Connection
);
564 int32_t Connection::getSqliteRuntimeStatus(int32_t aStatusOption
,
565 int32_t* aMaxValue
) {
566 MOZ_ASSERT(connectionReady(), "A connection must exist at this point");
567 int curr
= 0, max
= 0;
569 ::sqlite3_db_status(mDBConn
, aStatusOption
, &curr
, &max
, 0);
570 MOZ_ASSERT(NS_SUCCEEDED(convertResultCode(rc
)));
571 if (aMaxValue
) *aMaxValue
= max
;
575 nsIEventTarget
* Connection::getAsyncExecutionTarget() {
576 NS_ENSURE_TRUE(threadOpenedOn
== NS_GetCurrentThread(), nullptr);
578 // Don't return the asynchronous thread if we are shutting down.
579 if (mAsyncExecutionThreadShuttingDown
) {
583 // Create the async thread if there's none yet.
584 if (!mAsyncExecutionThread
) {
585 static nsThreadPoolNaming naming
;
586 nsresult rv
= NS_NewNamedThread(naming
.GetNextThreadName("mozStorage"),
587 getter_AddRefs(mAsyncExecutionThread
));
589 NS_WARNING("Failed to create async thread.");
592 mAsyncExecutionThread
->SetNameForWakeupTelemetry(
593 NS_LITERAL_CSTRING("mozStorage (all)"));
596 return mAsyncExecutionThread
;
599 nsresult
Connection::initialize() {
600 NS_ASSERTION(!connectionReady(),
601 "Initialize called on already opened database!");
602 MOZ_ASSERT(!mIgnoreLockingMode
, "Can't ignore locking on an in-memory db.");
603 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
605 // in memory database requested, sqlite uses a magic file name
606 int srv
= ::sqlite3_open_v2(":memory:", &mDBConn
, mFlags
, GetVFSName());
607 if (srv
!= SQLITE_OK
) {
609 return convertResultCode(srv
);
612 #ifdef MOZ_SQLITE_FTS3_TOKENIZER
614 ::sqlite3_db_config(mDBConn
, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, 1, 0);
615 MOZ_ASSERT(srv
== SQLITE_OK
,
616 "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
619 // Do not set mDatabaseFile or mFileURL here since this is a "memory"
622 nsresult rv
= initializeInternal();
623 NS_ENSURE_SUCCESS(rv
, rv
);
628 nsresult
Connection::initialize(nsIFile
* aDatabaseFile
) {
629 NS_ASSERTION(aDatabaseFile
, "Passed null file!");
630 NS_ASSERTION(!connectionReady(),
631 "Initialize called on already opened database!");
632 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
634 mDatabaseFile
= aDatabaseFile
;
637 nsresult rv
= aDatabaseFile
->GetPath(path
);
638 NS_ENSURE_SUCCESS(rv
, rv
);
641 static const char* sIgnoreLockingVFS
= "win32-none";
643 static const char* sIgnoreLockingVFS
= "unix-none";
645 const char* vfs
= mIgnoreLockingMode
? sIgnoreLockingVFS
: GetVFSName();
647 int srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
,
649 if (srv
!= SQLITE_OK
) {
651 return convertResultCode(srv
);
654 #ifdef MOZ_SQLITE_FTS3_TOKENIZER
656 ::sqlite3_db_config(mDBConn
, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, 1, 0);
657 MOZ_ASSERT(srv
== SQLITE_OK
,
658 "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
661 // Do not set mFileURL here since this is database does not have an associated
663 mDatabaseFile
= aDatabaseFile
;
665 rv
= initializeInternal();
666 NS_ENSURE_SUCCESS(rv
, rv
);
671 nsresult
Connection::initialize(nsIFileURL
* aFileURL
) {
672 NS_ASSERTION(aFileURL
, "Passed null file URL!");
673 NS_ASSERTION(!connectionReady(),
674 "Initialize called on already opened database!");
675 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
677 nsCOMPtr
<nsIFile
> databaseFile
;
678 nsresult rv
= aFileURL
->GetFile(getter_AddRefs(databaseFile
));
679 NS_ENSURE_SUCCESS(rv
, rv
);
682 rv
= aFileURL
->GetSpec(spec
);
683 NS_ENSURE_SUCCESS(rv
, rv
);
685 int srv
= ::sqlite3_open_v2(spec
.get(), &mDBConn
, mFlags
, GetVFSName());
686 if (srv
!= SQLITE_OK
) {
688 return convertResultCode(srv
);
691 #ifdef MOZ_SQLITE_FTS3_TOKENIZER
693 ::sqlite3_db_config(mDBConn
, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, 1, 0);
694 MOZ_ASSERT(srv
== SQLITE_OK
,
695 "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
698 // Set both mDatabaseFile and mFileURL here.
700 mDatabaseFile
= databaseFile
;
702 rv
= initializeInternal();
703 NS_ENSURE_SUCCESS(rv
, rv
);
708 nsresult
Connection::initializeInternal() {
711 auto guard
= MakeScopeExit([&]() { initializeFailed(); });
714 const char* dbPath
= ::sqlite3_db_filename(mDBConn
, "main");
717 const char* telemetryFilename
=
718 ::sqlite3_uri_parameter(dbPath
, "telemetryFilename");
719 if (telemetryFilename
) {
720 if (NS_WARN_IF(*telemetryFilename
== '\0')) {
721 return NS_ERROR_INVALID_ARG
;
723 mTelemetryFilename
= telemetryFilename
;
727 if (mTelemetryFilename
.IsEmpty()) {
728 mTelemetryFilename
= getFilename();
729 MOZ_ASSERT(!mTelemetryFilename
.IsEmpty());
732 // Properly wrap the database handle's mutex.
733 sharedDBMutex
.initWithMutex(sqlite3_db_mutex(mDBConn
));
735 // SQLite tracing can slow down queries (especially long queries)
736 // significantly. Don't trace unless the user is actively monitoring SQLite.
737 if (MOZ_LOG_TEST(gStorageLog
, LogLevel::Debug
)) {
738 ::sqlite3_trace_v2(mDBConn
, SQLITE_TRACE_STMT
| SQLITE_TRACE_PROFILE
,
742 gStorageLog
, LogLevel::Debug
,
743 ("Opening connection to '%s' (%p)", mTelemetryFilename
.get(), this));
746 int64_t pageSize
= Service::getDefaultPageSize();
748 // Set page_size to the preferred default value. This is effective only if
749 // the database has just been created, otherwise, if the database does not
750 // use WAL journal mode, a VACUUM operation will updated its page_size.
751 nsAutoCString
pageSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
752 "PRAGMA page_size = ");
753 pageSizeQuery
.AppendInt(pageSize
);
754 int srv
= executeSql(mDBConn
, pageSizeQuery
.get());
755 if (srv
!= SQLITE_OK
) {
756 return convertResultCode(srv
);
759 // Setting the cache_size forces the database open, verifying if it is valid
760 // or corrupt. So this is executed regardless it being actually needed.
761 // The cache_size is calculated from the actual page_size, to save memory.
762 nsAutoCString
cacheSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
763 "PRAGMA cache_size = ");
764 cacheSizeQuery
.AppendInt(-MAX_CACHE_SIZE_KIBIBYTES
);
765 srv
= executeSql(mDBConn
, cacheSizeQuery
.get());
766 if (srv
!= SQLITE_OK
) {
767 return convertResultCode(srv
);
770 #if defined(MOZ_MEMORY_TEMP_STORE_PRAGMA)
771 (void)ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA temp_store = 2;"));
774 // Register our built-in SQL functions.
775 srv
= registerFunctions(mDBConn
);
776 if (srv
!= SQLITE_OK
) {
777 return convertResultCode(srv
);
780 // Register our built-in SQL collating sequences.
781 srv
= registerCollations(mDBConn
, mStorageService
);
782 if (srv
!= SQLITE_OK
) {
783 return convertResultCode(srv
);
786 // Set the synchronous PRAGMA, according to the preference.
787 switch (Service::getSynchronousPref()) {
789 (void)ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = FULL;"));
792 (void)ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = OFF;"));
796 (void)ExecuteSimpleSQL(
797 NS_LITERAL_CSTRING("PRAGMA synchronous = NORMAL;"));
801 // Initialization succeeded, we can stop guarding for failures.
806 nsresult
Connection::initializeOnAsyncThread(nsIFile
* aStorageFile
) {
807 MOZ_ASSERT(threadOpenedOn
!= NS_GetCurrentThread());
808 nsresult rv
= aStorageFile
? initialize(aStorageFile
) : initialize();
810 // Shutdown the async thread, since initialization failed.
811 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
812 mAsyncExecutionThreadShuttingDown
= true;
813 nsCOMPtr
<nsIRunnable
> event
=
814 NewRunnableMethod("Connection::shutdownAsyncThread", this,
815 &Connection::shutdownAsyncThread
);
816 Unused
<< NS_DispatchToMainThread(event
);
821 void Connection::initializeFailed() {
823 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
824 mConnectionClosed
= true;
826 MOZ_ALWAYS_TRUE(::sqlite3_close(mDBConn
) == SQLITE_OK
);
828 sharedDBMutex
.destroy();
831 nsresult
Connection::databaseElementExists(
832 enum DatabaseElementType aElementType
, const nsACString
& aElementName
,
834 if (!connectionReady()) {
835 return NS_ERROR_NOT_AVAILABLE
;
837 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
842 // When constructing the query, make sure to SELECT the correct db's
843 // sqlite_master if the user is prefixing the element with a specific db. ex:
845 nsCString
query("SELECT name FROM (SELECT * FROM ");
846 nsDependentCSubstring element
;
847 int32_t ind
= aElementName
.FindChar('.');
848 if (ind
== kNotFound
) {
849 element
.Assign(aElementName
);
851 nsDependentCSubstring
db(Substring(aElementName
, 0, ind
+ 1));
852 element
.Assign(Substring(aElementName
, ind
+ 1, aElementName
.Length()));
856 "sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = "
859 switch (aElementType
) {
861 query
.AppendLiteral("index");
864 query
.AppendLiteral("table");
867 query
.AppendLiteral("' AND name ='");
868 query
.Append(element
);
872 int srv
= prepareStatement(mDBConn
, query
, &stmt
);
873 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
875 srv
= stepStatement(mDBConn
, stmt
);
876 // we just care about the return value from step
877 (void)::sqlite3_finalize(stmt
);
879 if (srv
== SQLITE_ROW
) {
883 if (srv
== SQLITE_DONE
) {
888 return convertResultCode(srv
);
891 bool Connection::findFunctionByInstance(nsISupports
* aInstance
) {
892 sharedDBMutex
.assertCurrentThreadOwns();
894 for (auto iter
= mFunctions
.Iter(); !iter
.Done(); iter
.Next()) {
895 if (iter
.UserData().function
== aInstance
) {
903 int Connection::sProgressHelper(void* aArg
) {
904 Connection
* _this
= static_cast<Connection
*>(aArg
);
905 return _this
->progressHandler();
908 int Connection::progressHandler() {
909 sharedDBMutex
.assertCurrentThreadOwns();
910 if (mProgressHandler
) {
912 nsresult rv
= mProgressHandler
->OnProgress(this, &result
);
913 if (NS_FAILED(rv
)) return 0; // Don't break request
914 return result
? 1 : 0;
919 nsresult
Connection::setClosedState() {
920 // Ensure that we are on the correct thread to close the database.
922 nsresult rv
= threadOpenedOn
->IsOnCurrentThread(&onOpenedThread
);
923 NS_ENSURE_SUCCESS(rv
, rv
);
924 if (!onOpenedThread
) {
925 NS_ERROR("Must close the database on the thread that you opened it with!");
926 return NS_ERROR_UNEXPECTED
;
929 // Flag that we are shutting down the async thread, so that
930 // getAsyncExecutionTarget knows not to expose/create the async thread.
932 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
933 NS_ENSURE_FALSE(mAsyncExecutionThreadShuttingDown
, NS_ERROR_UNEXPECTED
);
934 mAsyncExecutionThreadShuttingDown
= true;
936 // Set the property to null before closing the connection, otherwise the
937 // other functions in the module may try to use the connection after it is
944 bool Connection::operationSupported(ConnectionOperation aOperationType
) {
945 if (aOperationType
== ASYNCHRONOUS
) {
946 // Async operations are supported for all connections, on any thread.
949 // Sync operations are supported for sync connections (on any thread), and
950 // async connections on a background thread.
951 MOZ_ASSERT(aOperationType
== SYNCHRONOUS
);
952 return mSupportedOperations
== SYNCHRONOUS
|| !NS_IsMainThread();
955 nsresult
Connection::ensureOperationSupported(
956 ConnectionOperation aOperationType
) {
957 if (NS_WARN_IF(!operationSupported(aOperationType
))) {
959 if (NS_IsMainThread()) {
960 nsCOMPtr
<nsIXPConnect
> xpc
= nsIXPConnect::XPConnect();
961 Unused
<< xpc
->DebugDumpJSStack(false, false, false);
965 "Don't use async connections synchronously on the main thread");
966 return NS_ERROR_NOT_AVAILABLE
;
971 bool Connection::isConnectionReadyOnThisThread() {
972 MOZ_ASSERT_IF(connectionReady(), !mConnectionClosed
);
973 if (mAsyncExecutionThread
&& mAsyncExecutionThread
->IsOnCurrentThread()) {
976 return connectionReady();
979 bool Connection::isClosing() {
980 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
981 return mAsyncExecutionThreadShuttingDown
&& !mConnectionClosed
;
984 bool Connection::isClosed() {
985 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
986 return mConnectionClosed
;
989 bool Connection::isClosed(MutexAutoLock
& lock
) { return mConnectionClosed
; }
991 bool Connection::isAsyncExecutionThreadAvailable() {
992 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
993 return mAsyncExecutionThread
&& !mAsyncExecutionThreadShuttingDown
;
996 void Connection::shutdownAsyncThread() {
997 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
998 MOZ_ASSERT(mAsyncExecutionThread
);
999 MOZ_ASSERT(mAsyncExecutionThreadShuttingDown
);
1001 MOZ_ALWAYS_SUCCEEDS(mAsyncExecutionThread
->Shutdown());
1002 mAsyncExecutionThread
= nullptr;
1005 nsresult
Connection::internalClose(sqlite3
* aNativeConnection
) {
1007 { // Make sure we have marked our async thread as shutting down.
1008 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1009 MOZ_ASSERT(mAsyncExecutionThreadShuttingDown
,
1010 "Did not call setClosedState!");
1011 MOZ_ASSERT(!isClosed(lockedScope
), "Unexpected closed state");
1015 if (MOZ_LOG_TEST(gStorageLog
, LogLevel::Debug
)) {
1016 nsAutoCString
leafName(":memory");
1017 if (mDatabaseFile
) (void)mDatabaseFile
->GetNativeLeafName(leafName
);
1018 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
1019 ("Closing connection to '%s'", leafName
.get()));
1022 // At this stage, we may still have statements that need to be
1023 // finalized. Attempt to close the database connection. This will
1024 // always disconnect any virtual tables and cleanly finalize their
1025 // internal statements. Once this is done, closing may fail due to
1026 // unfinalized client statements, in which case we need to finalize
1027 // these statements and close again.
1029 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1030 mConnectionClosed
= true;
1033 // Nothing else needs to be done if we don't have a connection here.
1034 if (!aNativeConnection
) return NS_OK
;
1036 int srv
= ::sqlite3_close(aNativeConnection
);
1038 if (srv
== SQLITE_BUSY
) {
1040 // Nothing else should change the connection or statements status until we
1042 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1043 // We still have non-finalized statements. Finalize them.
1044 sqlite3_stmt
* stmt
= nullptr;
1045 while ((stmt
= ::sqlite3_next_stmt(aNativeConnection
, stmt
))) {
1046 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
1047 ("Auto-finalizing SQL statement '%s' (%p)", ::sqlite3_sql(stmt
),
1051 SmprintfPointer msg
= ::mozilla::Smprintf(
1052 "SQL statement '%s' (%p) should have been finalized before closing "
1054 ::sqlite3_sql(stmt
), stmt
);
1055 NS_WARNING(msg
.get());
1058 srv
= ::sqlite3_finalize(stmt
);
1061 if (srv
!= SQLITE_OK
) {
1062 SmprintfPointer msg
= ::mozilla::Smprintf(
1063 "Could not finalize SQL statement (%p)", stmt
);
1064 NS_WARNING(msg
.get());
1068 // Ensure that the loop continues properly, whether closing has
1069 // succeeded or not.
1070 if (srv
== SQLITE_OK
) {
1074 // Scope exiting will unlock the mutex before we invoke sqlite3_close()
1075 // again, since Sqlite will try to acquire it.
1078 // Now that all statements have been finalized, we
1079 // should be able to close.
1080 srv
= ::sqlite3_close(aNativeConnection
);
1082 "Had to forcibly close the database connection because not all "
1083 "the statements have been finalized.");
1086 if (srv
== SQLITE_OK
) {
1087 sharedDBMutex
.destroy();
1090 "sqlite3_close failed. There are probably outstanding "
1091 "statements that are listed above!");
1094 return convertResultCode(srv
);
1097 nsCString
Connection::getFilename() {
1098 nsCString
leafname(":memory:");
1099 if (mDatabaseFile
) {
1100 (void)mDatabaseFile
->GetNativeLeafName(leafname
);
1105 int Connection::stepStatement(sqlite3
* aNativeConnection
,
1106 sqlite3_stmt
* aStatement
) {
1107 MOZ_ASSERT(aStatement
);
1109 AUTO_PROFILER_LABEL_DYNAMIC_CSTR("Connection::stepStatement", OTHER
,
1110 ::sqlite3_sql(aStatement
));
1112 bool checkedMainThread
= false;
1113 TimeStamp startTime
= TimeStamp::Now();
1115 // The connection may have been closed if the executing statement has been
1116 // created and cached after a call to asyncClose() but before the actual
1117 // sqlite3_close(). This usually happens when other tasks using cached
1118 // statements are asynchronously scheduled for execution and any of them ends
1119 // up after asyncClose. See bug 728653 for details.
1120 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1122 (void)::sqlite3_extended_result_codes(aNativeConnection
, 1);
1125 while ((srv
= ::sqlite3_step(aStatement
)) == SQLITE_LOCKED_SHAREDCACHE
) {
1126 if (!checkedMainThread
) {
1127 checkedMainThread
= true;
1128 if (::NS_IsMainThread()) {
1129 NS_WARNING("We won't allow blocking on the main thread!");
1134 srv
= WaitForUnlockNotify(aNativeConnection
);
1135 if (srv
!= SQLITE_OK
) {
1139 ::sqlite3_reset(aStatement
);
1142 // Report very slow SQL statements to Telemetry
1143 TimeDuration duration
= TimeStamp::Now() - startTime
;
1144 const uint32_t threshold
= NS_IsMainThread()
1145 ? Telemetry::kSlowSQLThresholdForMainThread
1146 : Telemetry::kSlowSQLThresholdForHelperThreads
;
1147 if (duration
.ToMilliseconds() >= threshold
) {
1148 nsDependentCString
statementString(::sqlite3_sql(aStatement
));
1149 Telemetry::RecordSlowSQLStatement(statementString
, mTelemetryFilename
,
1150 duration
.ToMilliseconds());
1153 (void)::sqlite3_extended_result_codes(aNativeConnection
, 0);
1154 // Drop off the extended result bits of the result code.
1158 int Connection::prepareStatement(sqlite3
* aNativeConnection
,
1159 const nsCString
& aSQL
, sqlite3_stmt
** _stmt
) {
1160 // We should not even try to prepare statements after the connection has
1162 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1164 bool checkedMainThread
= false;
1166 (void)::sqlite3_extended_result_codes(aNativeConnection
, 1);
1169 while ((srv
= ::sqlite3_prepare_v2(aNativeConnection
, aSQL
.get(), -1, _stmt
,
1170 nullptr)) == SQLITE_LOCKED_SHAREDCACHE
) {
1171 if (!checkedMainThread
) {
1172 checkedMainThread
= true;
1173 if (::NS_IsMainThread()) {
1174 NS_WARNING("We won't allow blocking on the main thread!");
1179 srv
= WaitForUnlockNotify(aNativeConnection
);
1180 if (srv
!= SQLITE_OK
) {
1185 if (srv
!= SQLITE_OK
) {
1187 warnMsg
.AppendLiteral("The SQL statement '");
1188 warnMsg
.Append(aSQL
);
1189 warnMsg
.AppendLiteral("' could not be compiled due to an error: ");
1190 warnMsg
.Append(::sqlite3_errmsg(aNativeConnection
));
1193 NS_WARNING(warnMsg
.get());
1195 MOZ_LOG(gStorageLog
, LogLevel::Error
, ("%s", warnMsg
.get()));
1198 (void)::sqlite3_extended_result_codes(aNativeConnection
, 0);
1199 // Drop off the extended result bits of the result code.
1200 int rc
= srv
& 0xFF;
1201 // sqlite will return OK on a comment only string and set _stmt to nullptr.
1202 // The callers of this function are used to only checking the return value,
1203 // so it is safer to return an error code.
1204 if (rc
== SQLITE_OK
&& *_stmt
== nullptr) {
1205 return SQLITE_MISUSE
;
1211 int Connection::executeSql(sqlite3
* aNativeConnection
, const char* aSqlString
) {
1212 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1214 AUTO_PROFILER_LABEL_DYNAMIC_CSTR("Connection::executeSql", OTHER
, aSqlString
);
1216 TimeStamp startTime
= TimeStamp::Now();
1218 ::sqlite3_exec(aNativeConnection
, aSqlString
, nullptr, nullptr, nullptr);
1220 // Report very slow SQL statements to Telemetry
1221 TimeDuration duration
= TimeStamp::Now() - startTime
;
1222 const uint32_t threshold
= NS_IsMainThread()
1223 ? Telemetry::kSlowSQLThresholdForMainThread
1224 : Telemetry::kSlowSQLThresholdForHelperThreads
;
1225 if (duration
.ToMilliseconds() >= threshold
) {
1226 nsDependentCString
statementString(aSqlString
);
1227 Telemetry::RecordSlowSQLStatement(statementString
, mTelemetryFilename
,
1228 duration
.ToMilliseconds());
1234 ////////////////////////////////////////////////////////////////////////////////
1235 //// nsIInterfaceRequestor
1238 Connection::GetInterface(const nsIID
& aIID
, void** _result
) {
1239 if (aIID
.Equals(NS_GET_IID(nsIEventTarget
))) {
1240 nsIEventTarget
* background
= getAsyncExecutionTarget();
1241 NS_IF_ADDREF(background
);
1242 *_result
= background
;
1245 return NS_ERROR_NO_INTERFACE
;
1248 ////////////////////////////////////////////////////////////////////////////////
1249 //// mozIStorageConnection
1252 Connection::Close() {
1253 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1254 if (NS_FAILED(rv
)) {
1257 return synchronousClose();
1260 nsresult
Connection::synchronousClose() {
1261 if (!connectionReady()) {
1262 return NS_ERROR_NOT_INITIALIZED
;
1266 // Since we're accessing mAsyncExecutionThread, we need to be on the opener
1267 // thread. We make this check outside of debug code below in setClosedState,
1268 // but this is here to be explicit.
1269 bool onOpenerThread
= false;
1270 (void)threadOpenedOn
->IsOnCurrentThread(&onOpenerThread
);
1271 MOZ_ASSERT(onOpenerThread
);
1274 // Make sure we have not executed any asynchronous statements.
1275 // If this fails, the mDBConn may be left open, resulting in a leak.
1276 // We'll try to finalize the pending statements and close the connection.
1277 if (isAsyncExecutionThreadAvailable()) {
1279 if (NS_IsMainThread()) {
1280 nsCOMPtr
<nsIXPConnect
> xpc
= nsIXPConnect::XPConnect();
1281 Unused
<< xpc
->DebugDumpJSStack(false, false, false);
1285 "Close() was invoked on a connection that executed asynchronous "
1287 "Should have used asyncClose().");
1288 // Try to close the database regardless, to free up resources.
1289 Unused
<< SpinningSynchronousClose();
1290 return NS_ERROR_UNEXPECTED
;
1293 // setClosedState nullifies our connection pointer, so we take a raw pointer
1294 // off it, to pass it through the close procedure.
1295 sqlite3
* nativeConn
= mDBConn
;
1296 nsresult rv
= setClosedState();
1297 NS_ENSURE_SUCCESS(rv
, rv
);
1299 return internalClose(nativeConn
);
1303 Connection::SpinningSynchronousClose() {
1304 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1305 if (NS_FAILED(rv
)) {
1308 if (threadOpenedOn
!= NS_GetCurrentThread()) {
1309 return NS_ERROR_NOT_SAME_THREAD
;
1312 // As currently implemented, we can't spin to wait for an existing AsyncClose.
1313 // Our only existing caller will never have called close; assert if misused
1314 // so that no new callers assume this works after an AsyncClose.
1315 MOZ_DIAGNOSTIC_ASSERT(connectionReady());
1316 if (!connectionReady()) {
1317 return NS_ERROR_UNEXPECTED
;
1320 RefPtr
<CloseListener
> listener
= new CloseListener();
1321 rv
= AsyncClose(listener
);
1322 NS_ENSURE_SUCCESS(rv
, rv
);
1323 MOZ_ALWAYS_TRUE(SpinEventLoopUntil([&]() { return listener
->mClosed
; }));
1324 MOZ_ASSERT(isClosed(), "The connection should be closed at this point");
1330 Connection::AsyncClose(mozIStorageCompletionCallback
* aCallback
) {
1331 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1332 // Check if AsyncClose or Close were already invoked.
1333 if (!connectionReady()) {
1334 return NS_ERROR_NOT_INITIALIZED
;
1336 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1337 if (NS_FAILED(rv
)) {
1341 // The two relevant factors at this point are whether we have a database
1342 // connection and whether we have an async execution thread. Here's what the
1343 // states mean and how we handle them:
1345 // - (mDBConn && asyncThread): The expected case where we are either an
1346 // async connection or a sync connection that has been used asynchronously.
1347 // Either way the caller must call us and not Close(). Nothing surprising
1348 // about this. We'll dispatch AsyncCloseConnection to the already-existing
1351 // - (mDBConn && !asyncThread): A somewhat unusual case where the caller
1352 // opened the connection synchronously and was planning to use it
1353 // asynchronously, but never got around to using it asynchronously before
1354 // needing to shutdown. This has been observed to happen for the cookie
1355 // service in a case where Firefox shuts itself down almost immediately
1356 // after startup (for unknown reasons). In the Firefox shutdown case,
1357 // we may also fail to create a new async execution thread if one does not
1358 // already exist. (nsThreadManager will refuse to create new threads when
1359 // it has already been told to shutdown.) As such, we need to handle a
1360 // failure to create the async execution thread by falling back to
1361 // synchronous Close() and also dispatching the completion callback because
1362 // at least Places likes to spin a nested event loop that depends on the
1363 // callback being invoked.
1365 // Note that we have considered not trying to spin up the async execution
1366 // thread in this case if it does not already exist, but the overhead of
1367 // thread startup (if successful) is significantly less expensive than the
1368 // worst-case potential I/O hit of synchronously closing a database when we
1369 // could close it asynchronously.
1371 // - (!mDBConn && asyncThread): This happens in some but not all cases where
1372 // OpenAsyncDatabase encountered a problem opening the database. If it
1373 // happened in all cases AsyncInitDatabase would just shut down the thread
1374 // directly and we would avoid this case. But it doesn't, so for simplicity
1375 // and consistency AsyncCloseConnection knows how to handle this and we
1376 // act like this was the (mDBConn && asyncThread) case in this method.
1378 // - (!mDBConn && !asyncThread): The database was never successfully opened or
1379 // Close() or AsyncClose() has already been called (at least) once. This is
1380 // undeniably a misuse case by the caller. We could optimize for this
1381 // case by adding an additional check of mAsyncExecutionThread without using
1382 // getAsyncExecutionTarget() to avoid wastefully creating a thread just to
1383 // shut it down. But this complicates the method for broken caller code
1384 // whereas we're still correct and safe without the special-case.
1385 nsIEventTarget
* asyncThread
= getAsyncExecutionTarget();
1387 // Create our callback event if we were given a callback. This will
1388 // eventually be dispatched in all cases, even if we fall back to Close() and
1389 // the database wasn't open and we return an error. The rationale is that
1390 // no existing consumer checks our return value and several of them like to
1391 // spin nested event loops until the callback fires. Given that, it seems
1392 // preferable for us to dispatch the callback in all cases. (Except the
1393 // wrong thread misuse case we bailed on up above. But that's okay because
1394 // that is statically wrong whereas these edge cases are dynamic.)
1395 nsCOMPtr
<nsIRunnable
> completeEvent
;
1397 completeEvent
= newCompletionEvent(aCallback
);
1401 // We were unable to create an async thread, so we need to fall back to
1402 // using normal Close(). Since there is no async thread, Close() will
1403 // not complain about that. (Close() may, however, complain if the
1404 // connection is closed, but that's okay.)
1405 if (completeEvent
) {
1406 // Closing the database is more important than returning an error code
1407 // about a failure to dispatch, especially because all existing native
1408 // callers ignore our return value.
1409 Unused
<< NS_DispatchToMainThread(completeEvent
.forget());
1411 MOZ_ALWAYS_SUCCEEDS(synchronousClose());
1412 // Return a success inconditionally here, since Close() is unlikely to fail
1413 // and we want to reassure the consumer that its callback will be invoked.
1417 // setClosedState nullifies our connection pointer, so we take a raw pointer
1418 // off it, to pass it through the close procedure.
1419 sqlite3
* nativeConn
= mDBConn
;
1420 rv
= setClosedState();
1421 NS_ENSURE_SUCCESS(rv
, rv
);
1423 // Create and dispatch our close event to the background thread.
1424 nsCOMPtr
<nsIRunnable
> closeEvent
=
1425 new AsyncCloseConnection(this, nativeConn
, completeEvent
);
1426 rv
= asyncThread
->Dispatch(closeEvent
, NS_DISPATCH_NORMAL
);
1427 NS_ENSURE_SUCCESS(rv
, rv
);
1433 Connection::AsyncClone(bool aReadOnly
,
1434 mozIStorageCompletionCallback
* aCallback
) {
1435 AUTO_PROFILER_LABEL("Connection::AsyncClone", OTHER
);
1437 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1438 if (!connectionReady()) {
1439 return NS_ERROR_NOT_INITIALIZED
;
1441 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1442 if (NS_FAILED(rv
)) {
1445 if (!mDatabaseFile
) return NS_ERROR_UNEXPECTED
;
1449 // Turn off SQLITE_OPEN_READWRITE, and set SQLITE_OPEN_READONLY.
1450 flags
= (~SQLITE_OPEN_READWRITE
& flags
) | SQLITE_OPEN_READONLY
;
1451 // Turn off SQLITE_OPEN_CREATE.
1452 flags
= (~SQLITE_OPEN_CREATE
& flags
);
1455 // The cloned connection will still implement the synchronous API, but throw
1456 // if any synchronous methods are called on the main thread.
1457 RefPtr
<Connection
> clone
=
1458 new Connection(mStorageService
, flags
, ASYNCHRONOUS
);
1460 RefPtr
<AsyncInitializeClone
> initEvent
=
1461 new AsyncInitializeClone(this, clone
, aReadOnly
, aCallback
);
1462 // Dispatch to our async thread, since the originating connection must remain
1463 // valid and open for the whole cloning process. This also ensures we are
1464 // properly serialized with a `close` operation, rather than race with it.
1465 nsCOMPtr
<nsIEventTarget
> target
= getAsyncExecutionTarget();
1467 return NS_ERROR_UNEXPECTED
;
1469 return target
->Dispatch(initEvent
, NS_DISPATCH_NORMAL
);
1472 nsresult
Connection::initializeClone(Connection
* aClone
, bool aReadOnly
) {
1473 nsresult rv
= mFileURL
? aClone
->initialize(mFileURL
)
1474 : aClone
->initialize(mDatabaseFile
);
1475 if (NS_FAILED(rv
)) {
1479 auto guard
= MakeScopeExit([&]() { aClone
->initializeFailed(); });
1481 rv
= aClone
->SetDefaultTransactionType(mDefaultTransactionType
);
1482 NS_ENSURE_SUCCESS(rv
, rv
);
1484 // Re-attach on-disk databases that were attached to the original connection.
1486 nsCOMPtr
<mozIStorageStatement
> stmt
;
1487 rv
= CreateStatement(NS_LITERAL_CSTRING("PRAGMA database_list"),
1488 getter_AddRefs(stmt
));
1489 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1490 bool hasResult
= false;
1491 while (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1493 rv
= stmt
->GetUTF8String(1, name
);
1494 if (NS_SUCCEEDED(rv
) && !name
.EqualsLiteral("main") &&
1495 !name
.EqualsLiteral("temp")) {
1497 rv
= stmt
->GetUTF8String(2, path
);
1498 if (NS_SUCCEEDED(rv
) && !path
.IsEmpty()) {
1499 nsCOMPtr
<mozIStorageStatement
> attachStmt
;
1500 rv
= aClone
->CreateStatement(
1501 NS_LITERAL_CSTRING("ATTACH DATABASE :path AS ") + name
,
1502 getter_AddRefs(attachStmt
));
1503 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1504 rv
= attachStmt
->BindUTF8StringByName(NS_LITERAL_CSTRING("path"),
1506 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1507 rv
= attachStmt
->Execute();
1508 MOZ_ASSERT(NS_SUCCEEDED(rv
),
1509 "couldn't re-attach database to cloned connection");
1515 // Copy over pragmas from the original connection.
1516 // LIMITATION WARNING! Many of these pragmas are actually scoped to the
1517 // schema ("main" and any other attached databases), and this implmentation
1518 // fails to propagate them. This is being addressed on trunk.
1519 static const char* pragmas
[] = {
1520 "cache_size", "temp_store", "foreign_keys", "journal_size_limit",
1521 "synchronous", "wal_autocheckpoint", "busy_timeout"};
1522 for (auto& pragma
: pragmas
) {
1523 // Read-only connections just need cache_size and temp_store pragmas.
1524 if (aReadOnly
&& ::strcmp(pragma
, "cache_size") != 0 &&
1525 ::strcmp(pragma
, "temp_store") != 0) {
1529 nsAutoCString
pragmaQuery("PRAGMA ");
1530 pragmaQuery
.Append(pragma
);
1531 nsCOMPtr
<mozIStorageStatement
> stmt
;
1532 rv
= CreateStatement(pragmaQuery
, getter_AddRefs(stmt
));
1533 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1534 bool hasResult
= false;
1535 if (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1536 pragmaQuery
.AppendLiteral(" = ");
1537 pragmaQuery
.AppendInt(stmt
->AsInt32(0));
1538 rv
= aClone
->ExecuteSimpleSQL(pragmaQuery
);
1539 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1543 // Copy over temporary tables, triggers, and views from the original
1544 // connections. Entities in `sqlite_temp_master` are only visible to the
1545 // connection that created them.
1547 rv
= aClone
->ExecuteSimpleSQL(NS_LITERAL_CSTRING("BEGIN TRANSACTION"));
1548 NS_ENSURE_SUCCESS(rv
, rv
);
1550 nsCOMPtr
<mozIStorageStatement
> stmt
;
1552 CreateStatement(NS_LITERAL_CSTRING("SELECT sql FROM sqlite_temp_master "
1553 "WHERE type IN ('table', 'view', "
1554 "'index', 'trigger')"),
1555 getter_AddRefs(stmt
));
1556 // Propagate errors, because failing to copy triggers might cause schema
1557 // coherency issues when writing to the database from the cloned connection.
1558 NS_ENSURE_SUCCESS(rv
, rv
);
1559 bool hasResult
= false;
1560 while (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1561 nsAutoCString query
;
1562 rv
= stmt
->GetUTF8String(0, query
);
1563 NS_ENSURE_SUCCESS(rv
, rv
);
1565 // The `CREATE` SQL statements in `sqlite_temp_master` omit the `TEMP`
1566 // keyword. We need to add it back, or we'll recreate temporary entities
1567 // as persistent ones. `sqlite_temp_master` also holds `CREATE INDEX`
1568 // statements, but those don't need `TEMP` keywords.
1569 if (StringBeginsWith(query
, NS_LITERAL_CSTRING("CREATE TABLE ")) ||
1570 StringBeginsWith(query
, NS_LITERAL_CSTRING("CREATE TRIGGER ")) ||
1571 StringBeginsWith(query
, NS_LITERAL_CSTRING("CREATE VIEW "))) {
1572 query
.Replace(0, 6, "CREATE TEMP");
1575 rv
= aClone
->ExecuteSimpleSQL(query
);
1576 NS_ENSURE_SUCCESS(rv
, rv
);
1579 rv
= aClone
->ExecuteSimpleSQL(NS_LITERAL_CSTRING("COMMIT"));
1580 NS_ENSURE_SUCCESS(rv
, rv
);
1583 // Copy any functions that have been added to this connection.
1584 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1585 for (auto iter
= mFunctions
.Iter(); !iter
.Done(); iter
.Next()) {
1586 const nsACString
& key
= iter
.Key();
1587 Connection::FunctionInfo data
= iter
.UserData();
1589 MOZ_ASSERT(data
.type
== Connection::FunctionInfo::SIMPLE
||
1590 data
.type
== Connection::FunctionInfo::AGGREGATE
,
1591 "Invalid function type!");
1593 if (data
.type
== Connection::FunctionInfo::SIMPLE
) {
1594 mozIStorageFunction
* function
=
1595 static_cast<mozIStorageFunction
*>(data
.function
.get());
1596 rv
= aClone
->CreateFunction(key
, data
.numArgs
, function
);
1597 if (NS_FAILED(rv
)) {
1598 NS_WARNING("Failed to copy function to cloned connection");
1602 mozIStorageAggregateFunction
* function
=
1603 static_cast<mozIStorageAggregateFunction
*>(data
.function
.get());
1604 rv
= aClone
->CreateAggregateFunction(key
, data
.numArgs
, function
);
1605 if (NS_FAILED(rv
)) {
1606 NS_WARNING("Failed to copy aggregate function to cloned connection");
1616 Connection::Clone(bool aReadOnly
, mozIStorageConnection
** _connection
) {
1617 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1619 AUTO_PROFILER_LABEL("Connection::Clone", OTHER
);
1621 if (!connectionReady()) {
1622 return NS_ERROR_NOT_INITIALIZED
;
1624 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1625 if (NS_FAILED(rv
)) {
1628 if (!mDatabaseFile
) return NS_ERROR_UNEXPECTED
;
1632 // Turn off SQLITE_OPEN_READWRITE, and set SQLITE_OPEN_READONLY.
1633 flags
= (~SQLITE_OPEN_READWRITE
& flags
) | SQLITE_OPEN_READONLY
;
1634 // Turn off SQLITE_OPEN_CREATE.
1635 flags
= (~SQLITE_OPEN_CREATE
& flags
);
1638 RefPtr
<Connection
> clone
=
1639 new Connection(mStorageService
, flags
, mSupportedOperations
);
1641 rv
= initializeClone(clone
, aReadOnly
);
1642 if (NS_FAILED(rv
)) {
1646 NS_IF_ADDREF(*_connection
= clone
);
1651 Connection::Interrupt() {
1652 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1653 if (!connectionReady()) {
1654 return NS_ERROR_NOT_INITIALIZED
;
1656 if (operationSupported(SYNCHRONOUS
) || !(mFlags
& SQLITE_OPEN_READONLY
)) {
1657 // Interrupting a synchronous connection from the same thread doesn't make
1658 // sense, and read-write connections aren't safe to interrupt.
1659 return NS_ERROR_INVALID_ARG
;
1661 ::sqlite3_interrupt(mDBConn
);
1666 Connection::GetDefaultPageSize(int32_t* _defaultPageSize
) {
1667 *_defaultPageSize
= Service::getDefaultPageSize();
1672 Connection::GetConnectionReady(bool* _ready
) {
1673 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1674 *_ready
= connectionReady();
1679 Connection::GetDatabaseFile(nsIFile
** _dbFile
) {
1680 if (!connectionReady()) {
1681 return NS_ERROR_NOT_INITIALIZED
;
1683 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1684 if (NS_FAILED(rv
)) {
1688 NS_IF_ADDREF(*_dbFile
= mDatabaseFile
);
1694 Connection::GetLastInsertRowID(int64_t* _id
) {
1695 if (!connectionReady()) {
1696 return NS_ERROR_NOT_INITIALIZED
;
1698 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1699 if (NS_FAILED(rv
)) {
1703 sqlite_int64 id
= ::sqlite3_last_insert_rowid(mDBConn
);
1710 Connection::GetAffectedRows(int32_t* _rows
) {
1711 if (!connectionReady()) {
1712 return NS_ERROR_NOT_INITIALIZED
;
1714 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1715 if (NS_FAILED(rv
)) {
1719 *_rows
= ::sqlite3_changes(mDBConn
);
1725 Connection::GetLastError(int32_t* _error
) {
1726 if (!connectionReady()) {
1727 return NS_ERROR_NOT_INITIALIZED
;
1729 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1730 if (NS_FAILED(rv
)) {
1734 *_error
= ::sqlite3_errcode(mDBConn
);
1740 Connection::GetLastErrorString(nsACString
& _errorString
) {
1741 if (!connectionReady()) {
1742 return NS_ERROR_NOT_INITIALIZED
;
1744 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1745 if (NS_FAILED(rv
)) {
1749 const char* serr
= ::sqlite3_errmsg(mDBConn
);
1750 _errorString
.Assign(serr
);
1756 Connection::GetSchemaVersion(int32_t* _version
) {
1757 if (!connectionReady()) {
1758 return NS_ERROR_NOT_INITIALIZED
;
1760 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1761 if (NS_FAILED(rv
)) {
1765 nsCOMPtr
<mozIStorageStatement
> stmt
;
1766 (void)CreateStatement(NS_LITERAL_CSTRING("PRAGMA user_version"),
1767 getter_AddRefs(stmt
));
1768 NS_ENSURE_TRUE(stmt
, NS_ERROR_OUT_OF_MEMORY
);
1772 if (NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
)
1773 *_version
= stmt
->AsInt32(0);
1779 Connection::SetSchemaVersion(int32_t aVersion
) {
1780 if (!connectionReady()) {
1781 return NS_ERROR_NOT_INITIALIZED
;
1783 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1784 if (NS_FAILED(rv
)) {
1788 nsAutoCString
stmt(NS_LITERAL_CSTRING("PRAGMA user_version = "));
1789 stmt
.AppendInt(aVersion
);
1791 return ExecuteSimpleSQL(stmt
);
1795 Connection::CreateStatement(const nsACString
& aSQLStatement
,
1796 mozIStorageStatement
** _stmt
) {
1797 NS_ENSURE_ARG_POINTER(_stmt
);
1798 if (!connectionReady()) {
1799 return NS_ERROR_NOT_INITIALIZED
;
1801 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1802 if (NS_FAILED(rv
)) {
1806 RefPtr
<Statement
> statement(new Statement());
1807 NS_ENSURE_TRUE(statement
, NS_ERROR_OUT_OF_MEMORY
);
1809 rv
= statement
->initialize(this, mDBConn
, aSQLStatement
);
1810 NS_ENSURE_SUCCESS(rv
, rv
);
1813 statement
.forget(&rawPtr
);
1819 Connection::CreateAsyncStatement(const nsACString
& aSQLStatement
,
1820 mozIStorageAsyncStatement
** _stmt
) {
1821 NS_ENSURE_ARG_POINTER(_stmt
);
1822 if (!connectionReady()) {
1823 return NS_ERROR_NOT_INITIALIZED
;
1825 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1826 if (NS_FAILED(rv
)) {
1830 RefPtr
<AsyncStatement
> statement(new AsyncStatement());
1831 NS_ENSURE_TRUE(statement
, NS_ERROR_OUT_OF_MEMORY
);
1833 rv
= statement
->initialize(this, mDBConn
, aSQLStatement
);
1834 NS_ENSURE_SUCCESS(rv
, rv
);
1836 AsyncStatement
* rawPtr
;
1837 statement
.forget(&rawPtr
);
1843 Connection::ExecuteSimpleSQL(const nsACString
& aSQLStatement
) {
1844 CHECK_MAINTHREAD_ABUSE();
1845 if (!connectionReady()) {
1846 return NS_ERROR_NOT_INITIALIZED
;
1848 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1849 if (NS_FAILED(rv
)) {
1853 int srv
= executeSql(mDBConn
, PromiseFlatCString(aSQLStatement
).get());
1854 return convertResultCode(srv
);
1858 Connection::ExecuteAsync(
1859 const nsTArray
<RefPtr
<mozIStorageBaseStatement
>>& aStatements
,
1860 mozIStorageStatementCallback
* aCallback
,
1861 mozIStoragePendingStatement
** _handle
) {
1862 nsTArray
<StatementData
> stmts(aStatements
.Length());
1863 for (uint32_t i
= 0; i
< aStatements
.Length(); i
++) {
1864 nsCOMPtr
<StorageBaseStatementInternal
> stmt
=
1865 do_QueryInterface(aStatements
[i
]);
1867 // Obtain our StatementData.
1869 nsresult rv
= stmt
->getAsynchronousStatementData(data
);
1870 NS_ENSURE_SUCCESS(rv
, rv
);
1872 NS_ASSERTION(stmt
->getOwner() == this,
1873 "Statement must be from this database connection!");
1875 // Now append it to our array.
1876 NS_ENSURE_TRUE(stmts
.AppendElement(data
), NS_ERROR_OUT_OF_MEMORY
);
1879 // Dispatch to the background
1880 return AsyncExecuteStatements::execute(stmts
, this, mDBConn
, aCallback
,
1885 Connection::ExecuteSimpleSQLAsync(const nsACString
& aSQLStatement
,
1886 mozIStorageStatementCallback
* aCallback
,
1887 mozIStoragePendingStatement
** _handle
) {
1888 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1890 nsCOMPtr
<mozIStorageAsyncStatement
> stmt
;
1891 nsresult rv
= CreateAsyncStatement(aSQLStatement
, getter_AddRefs(stmt
));
1892 if (NS_FAILED(rv
)) {
1896 nsCOMPtr
<mozIStoragePendingStatement
> pendingStatement
;
1897 rv
= stmt
->ExecuteAsync(aCallback
, getter_AddRefs(pendingStatement
));
1898 if (NS_FAILED(rv
)) {
1902 pendingStatement
.forget(_handle
);
1907 Connection::TableExists(const nsACString
& aTableName
, bool* _exists
) {
1908 return databaseElementExists(TABLE
, aTableName
, _exists
);
1912 Connection::IndexExists(const nsACString
& aIndexName
, bool* _exists
) {
1913 return databaseElementExists(INDEX
, aIndexName
, _exists
);
1917 Connection::GetTransactionInProgress(bool* _inProgress
) {
1918 if (!connectionReady()) {
1919 return NS_ERROR_NOT_INITIALIZED
;
1921 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1922 if (NS_FAILED(rv
)) {
1926 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1927 *_inProgress
= mTransactionInProgress
;
1932 Connection::GetDefaultTransactionType(int32_t* _type
) {
1933 *_type
= mDefaultTransactionType
;
1938 Connection::SetDefaultTransactionType(int32_t aType
) {
1939 NS_ENSURE_ARG_RANGE(aType
, TRANSACTION_DEFERRED
, TRANSACTION_EXCLUSIVE
);
1940 mDefaultTransactionType
= aType
;
1945 Connection::GetVariableLimit(int32_t* _limit
) {
1946 if (!connectionReady()) {
1947 return NS_ERROR_NOT_INITIALIZED
;
1949 int limit
= ::sqlite3_limit(mDBConn
, SQLITE_LIMIT_VARIABLE_NUMBER
, -1);
1951 return NS_ERROR_UNEXPECTED
;
1958 Connection::BeginTransaction() {
1959 if (!connectionReady()) {
1960 return NS_ERROR_NOT_INITIALIZED
;
1962 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1963 if (NS_FAILED(rv
)) {
1967 return beginTransactionInternal(mDBConn
, mDefaultTransactionType
);
1970 nsresult
Connection::beginTransactionInternal(sqlite3
* aNativeConnection
,
1971 int32_t aTransactionType
) {
1972 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1973 if (mTransactionInProgress
) return NS_ERROR_FAILURE
;
1975 switch (aTransactionType
) {
1976 case TRANSACTION_DEFERRED
:
1977 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN DEFERRED"));
1979 case TRANSACTION_IMMEDIATE
:
1980 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN IMMEDIATE"));
1982 case TRANSACTION_EXCLUSIVE
:
1983 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN EXCLUSIVE"));
1986 return NS_ERROR_ILLEGAL_VALUE
;
1988 if (NS_SUCCEEDED(rv
)) mTransactionInProgress
= true;
1993 Connection::CommitTransaction() {
1994 if (!connectionReady()) {
1995 return NS_ERROR_NOT_INITIALIZED
;
1997 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1998 if (NS_FAILED(rv
)) {
2002 return commitTransactionInternal(mDBConn
);
2005 nsresult
Connection::commitTransactionInternal(sqlite3
* aNativeConnection
) {
2006 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2007 if (!mTransactionInProgress
) return NS_ERROR_UNEXPECTED
;
2009 convertResultCode(executeSql(aNativeConnection
, "COMMIT TRANSACTION"));
2010 if (NS_SUCCEEDED(rv
)) mTransactionInProgress
= false;
2015 Connection::RollbackTransaction() {
2016 if (!connectionReady()) {
2017 return NS_ERROR_NOT_INITIALIZED
;
2019 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2020 if (NS_FAILED(rv
)) {
2024 return rollbackTransactionInternal(mDBConn
);
2027 nsresult
Connection::rollbackTransactionInternal(sqlite3
* aNativeConnection
) {
2028 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2029 if (!mTransactionInProgress
) return NS_ERROR_UNEXPECTED
;
2032 convertResultCode(executeSql(aNativeConnection
, "ROLLBACK TRANSACTION"));
2033 if (NS_SUCCEEDED(rv
)) mTransactionInProgress
= false;
2038 Connection::CreateTable(const char* aTableName
, const char* aTableSchema
) {
2039 if (!connectionReady()) {
2040 return NS_ERROR_NOT_INITIALIZED
;
2042 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2043 if (NS_FAILED(rv
)) {
2047 SmprintfPointer buf
=
2048 ::mozilla::Smprintf("CREATE TABLE %s (%s)", aTableName
, aTableSchema
);
2049 if (!buf
) return NS_ERROR_OUT_OF_MEMORY
;
2051 int srv
= executeSql(mDBConn
, buf
.get());
2053 return convertResultCode(srv
);
2057 Connection::CreateFunction(const nsACString
& aFunctionName
,
2058 int32_t aNumArguments
,
2059 mozIStorageFunction
* aFunction
) {
2060 if (!connectionReady()) {
2061 return NS_ERROR_NOT_INITIALIZED
;
2063 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2064 if (NS_FAILED(rv
)) {
2068 // Check to see if this function is already defined. We only check the name
2069 // because a function can be defined with the same body but different names.
2070 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2071 NS_ENSURE_FALSE(mFunctions
.Get(aFunctionName
, nullptr), NS_ERROR_FAILURE
);
2073 int srv
= ::sqlite3_create_function(
2074 mDBConn
, nsPromiseFlatCString(aFunctionName
).get(), aNumArguments
,
2075 SQLITE_ANY
, aFunction
, basicFunctionHelper
, nullptr, nullptr);
2076 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2078 FunctionInfo info
= {aFunction
, Connection::FunctionInfo::SIMPLE
,
2080 mFunctions
.Put(aFunctionName
, info
);
2086 Connection::CreateAggregateFunction(const nsACString
& aFunctionName
,
2087 int32_t aNumArguments
,
2088 mozIStorageAggregateFunction
* aFunction
) {
2089 if (!connectionReady()) {
2090 return NS_ERROR_NOT_INITIALIZED
;
2092 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2093 if (NS_FAILED(rv
)) {
2097 // Check to see if this function name is already defined.
2098 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2099 NS_ENSURE_FALSE(mFunctions
.Get(aFunctionName
, nullptr), NS_ERROR_FAILURE
);
2101 // Because aggregate functions depend on state across calls, you cannot have
2102 // the same instance use the same name. We want to enumerate all functions
2103 // and make sure this instance is not already registered.
2104 NS_ENSURE_FALSE(findFunctionByInstance(aFunction
), NS_ERROR_FAILURE
);
2106 int srv
= ::sqlite3_create_function(
2107 mDBConn
, nsPromiseFlatCString(aFunctionName
).get(), aNumArguments
,
2108 SQLITE_ANY
, aFunction
, nullptr, aggregateFunctionStepHelper
,
2109 aggregateFunctionFinalHelper
);
2110 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2112 FunctionInfo info
= {aFunction
, Connection::FunctionInfo::AGGREGATE
,
2114 mFunctions
.Put(aFunctionName
, info
);
2120 Connection::RemoveFunction(const nsACString
& aFunctionName
) {
2121 if (!connectionReady()) {
2122 return NS_ERROR_NOT_INITIALIZED
;
2124 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2125 if (NS_FAILED(rv
)) {
2129 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2130 NS_ENSURE_TRUE(mFunctions
.Get(aFunctionName
, nullptr), NS_ERROR_FAILURE
);
2132 int srv
= ::sqlite3_create_function(
2133 mDBConn
, nsPromiseFlatCString(aFunctionName
).get(), 0, SQLITE_ANY
,
2134 nullptr, nullptr, nullptr, nullptr);
2135 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2137 mFunctions
.Remove(aFunctionName
);
2143 Connection::SetProgressHandler(int32_t aGranularity
,
2144 mozIStorageProgressHandler
* aHandler
,
2145 mozIStorageProgressHandler
** _oldHandler
) {
2146 if (!connectionReady()) {
2147 return NS_ERROR_NOT_INITIALIZED
;
2149 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2150 if (NS_FAILED(rv
)) {
2154 // Return previous one
2155 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2156 NS_IF_ADDREF(*_oldHandler
= mProgressHandler
);
2158 if (!aHandler
|| aGranularity
<= 0) {
2162 mProgressHandler
= aHandler
;
2163 ::sqlite3_progress_handler(mDBConn
, aGranularity
, sProgressHelper
, this);
2169 Connection::RemoveProgressHandler(mozIStorageProgressHandler
** _oldHandler
) {
2170 if (!connectionReady()) {
2171 return NS_ERROR_NOT_INITIALIZED
;
2173 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2174 if (NS_FAILED(rv
)) {
2178 // Return previous one
2179 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2180 NS_IF_ADDREF(*_oldHandler
= mProgressHandler
);
2182 mProgressHandler
= nullptr;
2183 ::sqlite3_progress_handler(mDBConn
, 0, nullptr, nullptr);
2189 Connection::SetGrowthIncrement(int32_t aChunkSize
,
2190 const nsACString
& aDatabaseName
) {
2191 if (!connectionReady()) {
2192 return NS_ERROR_NOT_INITIALIZED
;
2194 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2195 if (NS_FAILED(rv
)) {
2199 // Bug 597215: Disk space is extremely limited on Android
2200 // so don't preallocate space. This is also not effective
2201 // on log structured file systems used by Android devices
2202 #if !defined(ANDROID) && !defined(MOZ_PLATFORM_MAEMO)
2203 // Don't preallocate if less than 500MiB is available.
2204 int64_t bytesAvailable
;
2205 rv
= mDatabaseFile
->GetDiskSpaceAvailable(&bytesAvailable
);
2206 NS_ENSURE_SUCCESS(rv
, rv
);
2207 if (bytesAvailable
< MIN_AVAILABLE_BYTES_PER_CHUNKED_GROWTH
) {
2208 return NS_ERROR_FILE_TOO_BIG
;
2211 (void)::sqlite3_file_control(mDBConn
,
2212 aDatabaseName
.Length()
2213 ? nsPromiseFlatCString(aDatabaseName
).get()
2215 SQLITE_FCNTL_CHUNK_SIZE
, &aChunkSize
);
2221 Connection::EnableModule(const nsACString
& aModuleName
) {
2222 if (!connectionReady()) {
2223 return NS_ERROR_NOT_INITIALIZED
;
2225 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2226 if (NS_FAILED(rv
)) {
2230 for (auto& gModule
: gModules
) {
2231 struct Module
* m
= &gModule
;
2232 if (aModuleName
.Equals(m
->name
)) {
2233 int srv
= m
->registerFunc(mDBConn
, m
->name
);
2234 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2240 return NS_ERROR_FAILURE
;
2243 // Implemented in TelemetryVFS.cpp
2244 already_AddRefed
<QuotaObject
> GetQuotaObjectForFile(sqlite3_file
* pFile
);
2247 Connection::GetQuotaObjects(QuotaObject
** aDatabaseQuotaObject
,
2248 QuotaObject
** aJournalQuotaObject
) {
2249 MOZ_ASSERT(aDatabaseQuotaObject
);
2250 MOZ_ASSERT(aJournalQuotaObject
);
2252 if (!connectionReady()) {
2253 return NS_ERROR_NOT_INITIALIZED
;
2255 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2256 if (NS_FAILED(rv
)) {
2261 int srv
= ::sqlite3_file_control(mDBConn
, nullptr, SQLITE_FCNTL_FILE_POINTER
,
2263 if (srv
!= SQLITE_OK
) {
2264 return convertResultCode(srv
);
2267 RefPtr
<QuotaObject
> databaseQuotaObject
= GetQuotaObjectForFile(file
);
2269 srv
= ::sqlite3_file_control(mDBConn
, nullptr, SQLITE_FCNTL_JOURNAL_POINTER
,
2271 if (srv
!= SQLITE_OK
) {
2272 return convertResultCode(srv
);
2275 RefPtr
<QuotaObject
> journalQuotaObject
= GetQuotaObjectForFile(file
);
2277 databaseQuotaObject
.forget(aDatabaseQuotaObject
);
2278 journalQuotaObject
.forget(aJournalQuotaObject
);
2282 } // namespace storage
2283 } // namespace mozilla