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/. */
7 #include "nsThreadUtils.h"
9 #include "nsIFileURL.h"
10 #include "nsIXPConnect.h"
11 #include "mozilla/AppShutdown.h"
12 #include "mozilla/Telemetry.h"
13 #include "mozilla/Mutex.h"
14 #include "mozilla/CondVar.h"
15 #include "mozilla/Attributes.h"
16 #include "mozilla/ErrorNames.h"
17 #include "mozilla/Unused.h"
18 #include "mozilla/dom/quota/QuotaObject.h"
19 #include "mozilla/ScopeExit.h"
20 #include "mozilla/SpinEventLoopUntil.h"
21 #include "mozilla/StaticPrefs_storage.h"
23 #include "mozIStorageCompletionCallback.h"
24 #include "mozIStorageFunction.h"
26 #include "mozStorageAsyncStatementExecution.h"
27 #include "mozStorageSQLFunctions.h"
28 #include "mozStorageConnection.h"
29 #include "mozStorageService.h"
30 #include "mozStorageStatement.h"
31 #include "mozStorageAsyncStatement.h"
32 #include "mozStorageArgValueArray.h"
33 #include "mozStoragePrivateHelpers.h"
34 #include "mozStorageStatementData.h"
35 #include "StorageBaseStatementInternal.h"
36 #include "SQLCollations.h"
37 #include "FileSystemModule.h"
38 #include "mozStorageHelper.h"
40 #include "mozilla/Logging.h"
41 #include "mozilla/Printf.h"
42 #include "mozilla/ProfilerLabels.h"
43 #include "nsProxyRelease.h"
44 #include "nsURLHelper.h"
46 #define MIN_AVAILABLE_BYTES_PER_CHUNKED_GROWTH 524288000 // 500 MiB
48 // Maximum size of the pages cache per connection.
49 #define MAX_CACHE_SIZE_KIBIBYTES 2048 // 2 MiB
51 mozilla::LazyLogModule
gStorageLog("mozStorage");
53 // Checks that the protected code is running on the main-thread only if the
54 // connection was also opened on it.
56 # define CHECK_MAINTHREAD_ABUSE() \
58 NS_WARNING_ASSERTION( \
59 eventTargetOpenedOn == GetMainThreadSerialEventTarget() || \
61 "Using Storage synchronous API on main-thread, but " \
62 "the connection was opened on another thread."); \
65 # define CHECK_MAINTHREAD_ABUSE() \
70 namespace mozilla::storage
{
72 using mozilla::dom::quota::QuotaObject
;
73 using mozilla::Telemetry::AccumulateCategoricalKeyed
;
74 using mozilla::Telemetry::LABELS_SQLITE_STORE_OPEN
;
75 using mozilla::Telemetry::LABELS_SQLITE_STORE_QUERY
;
77 const char* GetTelemetryVFSName(bool);
78 const char* GetQuotaVFSName();
79 const char* GetObfuscatingVFSName();
83 int nsresultToSQLiteResult(nsresult aXPCOMResultCode
) {
84 if (NS_SUCCEEDED(aXPCOMResultCode
)) {
88 switch (aXPCOMResultCode
) {
89 case NS_ERROR_FILE_CORRUPTED
:
90 return SQLITE_CORRUPT
;
91 case NS_ERROR_FILE_ACCESS_DENIED
:
92 return SQLITE_CANTOPEN
;
93 case NS_ERROR_STORAGE_BUSY
:
95 case NS_ERROR_FILE_IS_LOCKED
:
97 case NS_ERROR_FILE_READ_ONLY
:
98 return SQLITE_READONLY
;
99 case NS_ERROR_STORAGE_IOERR
:
101 case NS_ERROR_FILE_NO_DEVICE_SPACE
:
103 case NS_ERROR_OUT_OF_MEMORY
:
105 case NS_ERROR_UNEXPECTED
:
106 return SQLITE_MISUSE
;
109 case NS_ERROR_STORAGE_CONSTRAINT
:
110 return SQLITE_CONSTRAINT
;
115 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Must return in switch above!");
118 ////////////////////////////////////////////////////////////////////////////////
119 //// Variant Specialization Functions (variantToSQLiteT)
121 int sqlite3_T_int(sqlite3_context
* aCtx
, int aValue
) {
122 ::sqlite3_result_int(aCtx
, aValue
);
126 int sqlite3_T_int64(sqlite3_context
* aCtx
, sqlite3_int64 aValue
) {
127 ::sqlite3_result_int64(aCtx
, aValue
);
131 int sqlite3_T_double(sqlite3_context
* aCtx
, double aValue
) {
132 ::sqlite3_result_double(aCtx
, aValue
);
136 int sqlite3_T_text(sqlite3_context
* aCtx
, const nsCString
& aValue
) {
137 ::sqlite3_result_text(aCtx
, aValue
.get(), aValue
.Length(), SQLITE_TRANSIENT
);
141 int sqlite3_T_text16(sqlite3_context
* aCtx
, const nsString
& aValue
) {
142 ::sqlite3_result_text16(
144 aValue
.Length() * sizeof(char16_t
), // Number of bytes.
149 int sqlite3_T_null(sqlite3_context
* aCtx
) {
150 ::sqlite3_result_null(aCtx
);
154 int sqlite3_T_blob(sqlite3_context
* aCtx
, const void* aData
, int aSize
) {
155 ::sqlite3_result_blob(aCtx
, aData
, aSize
, free
);
159 #include "variantToSQLiteT_impl.h"
161 ////////////////////////////////////////////////////////////////////////////////
166 int (*registerFunc
)(sqlite3
*, const char*);
169 Module gModules
[] = {{"filesystem", RegisterFileSystemModule
}};
171 ////////////////////////////////////////////////////////////////////////////////
174 int tracefunc(unsigned aReason
, void* aClosure
, void* aP
, void* aX
) {
176 case SQLITE_TRACE_STMT
: {
177 // aP is a pointer to the prepared statement.
178 sqlite3_stmt
* stmt
= static_cast<sqlite3_stmt
*>(aP
);
179 // aX is a pointer to a string containing the unexpanded SQL or a comment,
180 // starting with "--"" in case of a trigger.
181 char* expanded
= static_cast<char*>(aX
);
182 // Simulate what sqlite_trace was doing.
183 if (!::strncmp(expanded
, "--", 2)) {
184 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
185 ("TRACE_STMT on %p: '%s'", aClosure
, expanded
));
187 char* sql
= ::sqlite3_expanded_sql(stmt
);
188 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
189 ("TRACE_STMT on %p: '%s'", aClosure
, sql
));
194 case SQLITE_TRACE_PROFILE
: {
195 // aX is pointer to a 64bit integer containing nanoseconds it took to
196 // execute the last command.
197 sqlite_int64 time
= *(static_cast<sqlite_int64
*>(aX
)) / 1000000;
199 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
200 ("TRACE_TIME on %p: %lldms", aClosure
, time
));
208 void basicFunctionHelper(sqlite3_context
* aCtx
, int aArgc
,
209 sqlite3_value
** aArgv
) {
210 void* userData
= ::sqlite3_user_data(aCtx
);
212 mozIStorageFunction
* func
= static_cast<mozIStorageFunction
*>(userData
);
214 RefPtr
<ArgValueArray
> arguments(new ArgValueArray(aArgc
, aArgv
));
215 if (!arguments
) return;
217 nsCOMPtr
<nsIVariant
> result
;
218 nsresult rv
= func
->OnFunctionCall(arguments
, getter_AddRefs(result
));
220 nsAutoCString errorMessage
;
221 GetErrorName(rv
, errorMessage
);
222 errorMessage
.InsertLiteral("User function returned ", 0);
223 errorMessage
.Append('!');
225 NS_WARNING(errorMessage
.get());
227 ::sqlite3_result_error(aCtx
, errorMessage
.get(), -1);
228 ::sqlite3_result_error_code(aCtx
, nsresultToSQLiteResult(rv
));
231 int retcode
= variantToSQLiteT(aCtx
, result
);
232 if (retcode
!= SQLITE_OK
) {
233 NS_WARNING("User function returned invalid data type!");
234 ::sqlite3_result_error(aCtx
, "User function returned invalid data type",
240 * This code is heavily based on the sample at:
241 * http://www.sqlite.org/unlock_notify.html
243 class UnlockNotification
{
246 : mMutex("UnlockNotification mMutex"),
247 mCondVar(mMutex
, "UnlockNotification condVar"),
251 MutexAutoLock
lock(mMutex
);
253 (void)mCondVar
.Wait();
258 MutexAutoLock
lock(mMutex
);
260 (void)mCondVar
.Notify();
264 Mutex mMutex MOZ_UNANNOTATED
;
269 void UnlockNotifyCallback(void** aArgs
, int aArgsSize
) {
270 for (int i
= 0; i
< aArgsSize
; i
++) {
271 UnlockNotification
* notification
=
272 static_cast<UnlockNotification
*>(aArgs
[i
]);
273 notification
->Signal();
277 int WaitForUnlockNotify(sqlite3
* aDatabase
) {
278 UnlockNotification notification
;
280 ::sqlite3_unlock_notify(aDatabase
, UnlockNotifyCallback
, ¬ification
);
281 MOZ_ASSERT(srv
== SQLITE_LOCKED
|| srv
== SQLITE_OK
);
282 if (srv
== SQLITE_OK
) {
289 ////////////////////////////////////////////////////////////////////////////////
292 class AsyncCloseConnection final
: public Runnable
{
294 AsyncCloseConnection(Connection
* aConnection
, sqlite3
* aNativeConnection
,
295 nsIRunnable
* aCallbackEvent
)
296 : Runnable("storage::AsyncCloseConnection"),
297 mConnection(aConnection
),
298 mNativeConnection(aNativeConnection
),
299 mCallbackEvent(aCallbackEvent
) {}
301 NS_IMETHOD
Run() override
{
302 // Make sure we don't dispatch to the current thread.
303 MOZ_ASSERT(!IsOnCurrentSerialEventTarget(mConnection
->eventTargetOpenedOn
));
305 nsCOMPtr
<nsIRunnable
> event
=
306 NewRunnableMethod("storage::Connection::shutdownAsyncThread",
307 mConnection
, &Connection::shutdownAsyncThread
);
308 MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(event
));
311 (void)mConnection
->internalClose(mNativeConnection
);
314 if (mCallbackEvent
) {
315 nsCOMPtr
<nsIThread
> thread
;
316 (void)NS_GetMainThread(getter_AddRefs(thread
));
317 (void)thread
->Dispatch(mCallbackEvent
, NS_DISPATCH_NORMAL
);
323 ~AsyncCloseConnection() override
{
324 NS_ReleaseOnMainThread("AsyncCloseConnection::mConnection",
325 mConnection
.forget());
326 NS_ReleaseOnMainThread("AsyncCloseConnection::mCallbackEvent",
327 mCallbackEvent
.forget());
331 RefPtr
<Connection
> mConnection
;
332 sqlite3
* mNativeConnection
;
333 nsCOMPtr
<nsIRunnable
> mCallbackEvent
;
337 * An event used to initialize the clone of a connection.
339 * Must be executed on the clone's async execution thread.
341 class AsyncInitializeClone final
: public Runnable
{
344 * @param aConnection The connection being cloned.
345 * @param aClone The clone.
346 * @param aReadOnly If |true|, the clone is read only.
347 * @param aCallback A callback to trigger once initialization
348 * is complete. This event will be called on
349 * aClone->eventTargetOpenedOn.
351 AsyncInitializeClone(Connection
* aConnection
, Connection
* aClone
,
352 const bool aReadOnly
,
353 mozIStorageCompletionCallback
* aCallback
)
354 : Runnable("storage::AsyncInitializeClone"),
355 mConnection(aConnection
),
357 mReadOnly(aReadOnly
),
358 mCallback(aCallback
) {
359 MOZ_ASSERT(NS_IsMainThread());
362 NS_IMETHOD
Run() override
{
363 MOZ_ASSERT(!NS_IsMainThread());
364 nsresult rv
= mConnection
->initializeClone(mClone
, mReadOnly
);
366 return Dispatch(rv
, nullptr);
368 return Dispatch(NS_OK
,
369 NS_ISUPPORTS_CAST(mozIStorageAsyncConnection
*, mClone
));
373 nsresult
Dispatch(nsresult aResult
, nsISupports
* aValue
) {
374 RefPtr
<CallbackComplete
> event
=
375 new CallbackComplete(aResult
, aValue
, mCallback
.forget());
376 return mClone
->eventTargetOpenedOn
->Dispatch(event
, NS_DISPATCH_NORMAL
);
379 ~AsyncInitializeClone() override
{
380 nsCOMPtr
<nsIThread
> thread
;
381 DebugOnly
<nsresult
> rv
= NS_GetMainThread(getter_AddRefs(thread
));
382 MOZ_ASSERT(NS_SUCCEEDED(rv
));
384 // Handle ambiguous nsISupports inheritance.
385 NS_ProxyRelease("AsyncInitializeClone::mConnection", thread
,
386 mConnection
.forget());
387 NS_ProxyRelease("AsyncInitializeClone::mClone", thread
, mClone
.forget());
389 // Generally, the callback will be released by CallbackComplete.
390 // However, if for some reason Run() is not executed, we still
391 // need to ensure that it is released here.
392 NS_ProxyRelease("AsyncInitializeClone::mCallback", thread
,
396 RefPtr
<Connection
> mConnection
;
397 RefPtr
<Connection
> mClone
;
398 const bool mReadOnly
;
399 nsCOMPtr
<mozIStorageCompletionCallback
> mCallback
;
403 * A listener for async connection closing.
405 class CloseListener final
: public mozIStorageCompletionCallback
{
408 CloseListener() : mClosed(false) {}
410 NS_IMETHOD
Complete(nsresult
, nsISupports
*) override
{
418 ~CloseListener() = default;
421 NS_IMPL_ISUPPORTS(CloseListener
, mozIStorageCompletionCallback
)
423 class AsyncVacuumEvent final
: public Runnable
{
425 AsyncVacuumEvent(Connection
* aConnection
,
426 mozIStorageCompletionCallback
* aCallback
,
427 bool aUseIncremental
, int32_t aSetPageSize
)
428 : Runnable("storage::AsyncVacuum"),
429 mConnection(aConnection
),
430 mCallback(aCallback
),
431 mUseIncremental(aUseIncremental
),
432 mSetPageSize(aSetPageSize
),
433 mStatus(NS_ERROR_UNEXPECTED
) {}
435 NS_IMETHOD
Run() override
{
436 // This is initially dispatched to the helper thread, then re-dispatched
437 // to the opener thread, where it will callback.
438 if (IsOnCurrentSerialEventTarget(mConnection
->eventTargetOpenedOn
)) {
439 // Send the completion event.
441 mozilla::Unused
<< mCallback
->Complete(mStatus
, nullptr);
446 // Ensure to invoke the callback regardless of errors.
447 auto guard
= MakeScopeExit([&]() {
448 mConnection
->mIsStatementOnHelperThreadInterruptible
= false;
449 mozilla::Unused
<< mConnection
->eventTargetOpenedOn
->Dispatch(
450 this, NS_DISPATCH_NORMAL
);
453 // Get list of attached databases.
454 nsCOMPtr
<mozIStorageStatement
> stmt
;
455 nsresult rv
= mConnection
->CreateStatement(MOZ_STORAGE_UNIQUIFY_QUERY_STR
456 "PRAGMA database_list"_ns
,
457 getter_AddRefs(stmt
));
458 NS_ENSURE_SUCCESS(rv
, rv
);
459 // We must accumulate names and loop through them later, otherwise VACUUM
460 // will see an ongoing statement and bail out.
461 nsTArray
<nsCString
> schemaNames
;
462 bool hasResult
= false;
463 while (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
465 rv
= stmt
->GetUTF8String(1, name
);
466 if (NS_SUCCEEDED(rv
) && !name
.EqualsLiteral("temp")) {
467 schemaNames
.AppendElement(name
);
471 // Mark this vacuum as an interruptible operation, so it can be interrupted
472 // if the connection closes during shutdown.
473 mConnection
->mIsStatementOnHelperThreadInterruptible
= true;
474 for (const nsCString
& schemaName
: schemaNames
) {
475 rv
= this->Vacuum(schemaName
);
477 // This is sub-optimal since it's only keeping the last error reason,
478 // but it will do for now.
485 nsresult
Vacuum(const nsACString
& aSchemaName
) {
486 // Abort if we're in shutdown.
487 if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed
)) {
488 return NS_ERROR_ABORT
;
490 int32_t removablePages
= mConnection
->RemovablePagesInFreeList(aSchemaName
);
491 if (!removablePages
) {
492 // There's no empty pages to remove, so skip this vacuum for now.
496 bool needsFullVacuum
= true;
499 nsAutoCString
query(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA ");
500 query
.Append(aSchemaName
);
501 query
.AppendLiteral(".page_size = ");
502 query
.AppendInt(mSetPageSize
);
503 nsCOMPtr
<mozIStorageStatement
> stmt
;
504 rv
= mConnection
->ExecuteSimpleSQL(query
);
505 NS_ENSURE_SUCCESS(rv
, rv
);
508 // Check auto_vacuum.
510 nsAutoCString
query(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA ");
511 query
.Append(aSchemaName
);
512 query
.AppendLiteral(".auto_vacuum");
513 nsCOMPtr
<mozIStorageStatement
> stmt
;
514 rv
= mConnection
->CreateStatement(query
, getter_AddRefs(stmt
));
515 NS_ENSURE_SUCCESS(rv
, rv
);
516 bool hasResult
= false;
517 bool changeAutoVacuum
= false;
518 if (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
519 bool isIncrementalVacuum
= stmt
->AsInt32(0) == 2;
520 changeAutoVacuum
= isIncrementalVacuum
!= mUseIncremental
;
521 if (isIncrementalVacuum
&& !changeAutoVacuum
) {
522 needsFullVacuum
= false;
525 // Changing auto_vacuum is only supported on the main schema.
526 if (aSchemaName
.EqualsLiteral("main") && changeAutoVacuum
) {
527 nsAutoCString
query(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA ");
528 query
.Append(aSchemaName
);
529 query
.AppendLiteral(".auto_vacuum = ");
530 query
.AppendInt(mUseIncremental
? 2 : 0);
531 rv
= mConnection
->ExecuteSimpleSQL(query
);
532 NS_ENSURE_SUCCESS(rv
, rv
);
536 if (needsFullVacuum
) {
537 nsAutoCString
query(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"VACUUM ");
538 query
.Append(aSchemaName
);
539 rv
= mConnection
->ExecuteSimpleSQL(query
);
540 // TODO (Bug 1818039): Report failed vacuum telemetry.
541 NS_ENSURE_SUCCESS(rv
, rv
);
543 nsAutoCString
query(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA ");
544 query
.Append(aSchemaName
);
545 query
.AppendLiteral(".incremental_vacuum(");
546 query
.AppendInt(removablePages
);
547 query
.AppendLiteral(")");
548 rv
= mConnection
->ExecuteSimpleSQL(query
);
549 NS_ENSURE_SUCCESS(rv
, rv
);
555 ~AsyncVacuumEvent() override
{
556 NS_ReleaseOnMainThread("AsyncVacuum::mConnection", mConnection
.forget());
557 NS_ReleaseOnMainThread("AsyncVacuum::mCallback", mCallback
.forget());
561 RefPtr
<Connection
> mConnection
;
562 nsCOMPtr
<mozIStorageCompletionCallback
> mCallback
;
563 bool mUseIncremental
;
564 int32_t mSetPageSize
;
565 Atomic
<nsresult
> mStatus
;
570 ////////////////////////////////////////////////////////////////////////////////
573 Connection::Connection(Service
* aService
, int aFlags
,
574 ConnectionOperation aSupportedOperations
,
575 bool aInterruptible
, bool aIgnoreLockingMode
)
576 : sharedAsyncExecutionMutex("Connection::sharedAsyncExecutionMutex"),
577 sharedDBMutex("Connection::sharedDBMutex"),
578 eventTargetOpenedOn(WrapNotNull(GetCurrentSerialEventTarget())),
579 mIsStatementOnHelperThreadInterruptible(false),
581 mDefaultTransactionType(mozIStorageConnection::TRANSACTION_DEFERRED
),
583 mProgressHandler(nullptr),
584 mStorageService(aService
),
586 mTransactionNestingLevel(0),
587 mSupportedOperations(aSupportedOperations
),
588 mInterruptible(aSupportedOperations
== Connection::ASYNCHRONOUS
||
590 mIgnoreLockingMode(aIgnoreLockingMode
),
591 mAsyncExecutionThreadShuttingDown(false),
592 mConnectionClosed(false),
593 mGrowthChunkSize(0) {
594 MOZ_ASSERT(!mIgnoreLockingMode
|| mFlags
& SQLITE_OPEN_READONLY
,
595 "Can't ignore locking for a non-readonly connection!");
596 mStorageService
->registerConnection(this);
599 Connection::~Connection() {
600 // Failsafe Close() occurs in our custom Release method because of
601 // complications related to Close() potentially invoking AsyncClose() which
602 // will increment our refcount.
603 MOZ_ASSERT(!mAsyncExecutionThread
,
604 "The async thread has not been shutdown properly!");
607 NS_IMPL_ADDREF(Connection
)
609 NS_INTERFACE_MAP_BEGIN(Connection
)
610 NS_INTERFACE_MAP_ENTRY(mozIStorageAsyncConnection
)
611 NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor
)
612 NS_INTERFACE_MAP_ENTRY(mozIStorageConnection
)
613 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports
, mozIStorageConnection
)
616 // This is identical to what NS_IMPL_RELEASE provides, but with the
617 // extra |1 == count| case.
618 NS_IMETHODIMP_(MozExternalRefCountType
) Connection::Release(void) {
619 MOZ_ASSERT(0 != mRefCnt
, "dup release");
620 nsrefcnt count
= --mRefCnt
;
621 NS_LOG_RELEASE(this, count
, "Connection");
623 // If the refcount went to 1, the single reference must be from
624 // gService->mConnections (in class |Service|). And the code calling
625 // Release is either:
626 // - The "user" code that had created the connection, releasing on any
628 // - One of Service's getConnections() callers had acquired a strong
629 // reference to the Connection that out-lived the last "user" reference,
630 // and now that just got dropped. Note that this reference could be
631 // getting dropped on the main thread or Connection->eventTargetOpenedOn
632 // (because of the NewRunnableMethod used by minimizeMemory).
634 // Either way, we should now perform our failsafe Close() and unregister.
635 // However, we only want to do this once, and the reality is that our
636 // refcount could go back up above 1 and down again at any time if we are
637 // off the main thread and getConnections() gets called on the main thread,
638 // so we use an atomic here to do this exactly once.
639 if (mDestroying
.compareExchange(false, true)) {
640 // Close the connection, dispatching to the opening event target if we're
641 // not on that event target already and that event target is still
642 // accepting runnables. We do this because it's possible we're on the main
643 // thread because of getConnections(), and we REALLY don't want to
644 // transfer I/O to the main thread if we can avoid it.
645 if (IsOnCurrentSerialEventTarget(eventTargetOpenedOn
)) {
646 // This could cause SpinningSynchronousClose() to be invoked and AddRef
647 // triggered for AsyncCloseConnection's strong ref if the conn was ever
648 // use for async purposes. (Main-thread only, though.)
649 Unused
<< synchronousClose();
651 nsCOMPtr
<nsIRunnable
> event
=
652 NewRunnableMethod("storage::Connection::synchronousClose", this,
653 &Connection::synchronousClose
);
654 if (NS_FAILED(eventTargetOpenedOn
->Dispatch(event
.forget(),
655 NS_DISPATCH_NORMAL
))) {
656 // The event target was dead and so we've just leaked our runnable.
657 // This should not happen because our non-main-thread consumers should
658 // be explicitly closing their connections, not relying on us to close
659 // them for them. (It's okay to let a statement go out of scope for
660 // automatic cleanup, but not a Connection.)
662 "Leaked Connection::synchronousClose(), ownership fail.");
663 Unused
<< synchronousClose();
667 // This will drop its strong reference right here, right now.
668 mStorageService
->unregisterConnection(this);
670 } else if (0 == count
) {
671 mRefCnt
= 1; /* stabilize */
672 #if 0 /* enable this to find non-threadsafe destructors: */
673 NS_ASSERT_OWNINGTHREAD(Connection
);
681 int32_t Connection::getSqliteRuntimeStatus(int32_t aStatusOption
,
682 int32_t* aMaxValue
) {
683 MOZ_ASSERT(connectionReady(), "A connection must exist at this point");
684 int curr
= 0, max
= 0;
686 ::sqlite3_db_status(mDBConn
, aStatusOption
, &curr
, &max
, 0);
687 MOZ_ASSERT(NS_SUCCEEDED(convertResultCode(rc
)));
688 if (aMaxValue
) *aMaxValue
= max
;
692 nsIEventTarget
* Connection::getAsyncExecutionTarget() {
693 NS_ENSURE_TRUE(IsOnCurrentSerialEventTarget(eventTargetOpenedOn
), nullptr);
695 // Don't return the asynchronous event target if we are shutting down.
696 if (mAsyncExecutionThreadShuttingDown
) {
700 // Create the async event target if there's none yet.
701 if (!mAsyncExecutionThread
) {
702 static nsThreadPoolNaming naming
;
703 nsresult rv
= NS_NewNamedThread(naming
.GetNextThreadName("mozStorage"),
704 getter_AddRefs(mAsyncExecutionThread
));
706 NS_WARNING("Failed to create async thread.");
709 mAsyncExecutionThread
->SetNameForWakeupTelemetry("mozStorage (all)"_ns
);
712 return mAsyncExecutionThread
;
715 void Connection::RecordOpenStatus(nsresult rv
) {
716 nsCString histogramKey
= mTelemetryFilename
;
718 if (histogramKey
.IsEmpty()) {
719 histogramKey
.AssignLiteral("unknown");
722 if (NS_SUCCEEDED(rv
)) {
723 AccumulateCategoricalKeyed(histogramKey
, LABELS_SQLITE_STORE_OPEN::success
);
728 case NS_ERROR_FILE_CORRUPTED
:
729 AccumulateCategoricalKeyed(histogramKey
,
730 LABELS_SQLITE_STORE_OPEN::corrupt
);
732 case NS_ERROR_STORAGE_IOERR
:
733 AccumulateCategoricalKeyed(histogramKey
,
734 LABELS_SQLITE_STORE_OPEN::diskio
);
736 case NS_ERROR_FILE_ACCESS_DENIED
:
737 case NS_ERROR_FILE_IS_LOCKED
:
738 case NS_ERROR_FILE_READ_ONLY
:
739 AccumulateCategoricalKeyed(histogramKey
,
740 LABELS_SQLITE_STORE_OPEN::access
);
742 case NS_ERROR_FILE_NO_DEVICE_SPACE
:
743 AccumulateCategoricalKeyed(histogramKey
,
744 LABELS_SQLITE_STORE_OPEN::diskspace
);
747 AccumulateCategoricalKeyed(histogramKey
,
748 LABELS_SQLITE_STORE_OPEN::failure
);
752 void Connection::RecordQueryStatus(int srv
) {
753 nsCString histogramKey
= mTelemetryFilename
;
755 if (histogramKey
.IsEmpty()) {
756 histogramKey
.AssignLiteral("unknown");
764 // Note that these are returned when we intentionally cancel a statement so
765 // they aren't indicating a failure.
767 case SQLITE_INTERRUPT
:
768 AccumulateCategoricalKeyed(histogramKey
,
769 LABELS_SQLITE_STORE_QUERY::success
);
773 AccumulateCategoricalKeyed(histogramKey
,
774 LABELS_SQLITE_STORE_QUERY::corrupt
);
777 case SQLITE_CANTOPEN
:
779 case SQLITE_READONLY
:
780 AccumulateCategoricalKeyed(histogramKey
,
781 LABELS_SQLITE_STORE_QUERY::access
);
785 AccumulateCategoricalKeyed(histogramKey
,
786 LABELS_SQLITE_STORE_QUERY::diskio
);
790 AccumulateCategoricalKeyed(histogramKey
,
791 LABELS_SQLITE_STORE_QUERY::diskspace
);
793 case SQLITE_CONSTRAINT
:
795 case SQLITE_MISMATCH
:
797 AccumulateCategoricalKeyed(histogramKey
,
798 LABELS_SQLITE_STORE_QUERY::misuse
);
801 AccumulateCategoricalKeyed(histogramKey
, LABELS_SQLITE_STORE_QUERY::busy
);
804 AccumulateCategoricalKeyed(histogramKey
,
805 LABELS_SQLITE_STORE_QUERY::failure
);
809 nsresult
Connection::initialize(const nsACString
& aStorageKey
,
810 const nsACString
& aName
) {
811 MOZ_ASSERT(aStorageKey
.Equals(kMozStorageMemoryStorageKey
));
812 NS_ASSERTION(!connectionReady(),
813 "Initialize called on already opened database!");
814 MOZ_ASSERT(!mIgnoreLockingMode
, "Can't ignore locking on an in-memory db.");
815 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
817 mStorageKey
= aStorageKey
;
820 // in memory database requested, sqlite uses a magic file name
822 const nsAutoCString path
=
823 mName
.IsEmpty() ? nsAutoCString(":memory:"_ns
)
824 : "file:"_ns
+ mName
+ "?mode=memory&cache=shared"_ns
;
826 mTelemetryFilename
.AssignLiteral(":memory:");
828 int srv
= ::sqlite3_open_v2(path
.get(), &mDBConn
, mFlags
,
829 GetTelemetryVFSName(true));
830 if (srv
!= SQLITE_OK
) {
832 nsresult rv
= convertResultCode(srv
);
833 RecordOpenStatus(rv
);
837 #ifdef MOZ_SQLITE_FTS3_TOKENIZER
839 ::sqlite3_db_config(mDBConn
, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, 1, 0);
840 MOZ_ASSERT(srv
== SQLITE_OK
,
841 "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
844 // Do not set mDatabaseFile or mFileURL here since this is a "memory"
847 nsresult rv
= initializeInternal();
848 RecordOpenStatus(rv
);
849 NS_ENSURE_SUCCESS(rv
, rv
);
854 nsresult
Connection::initialize(nsIFile
* aDatabaseFile
) {
855 NS_ASSERTION(aDatabaseFile
, "Passed null file!");
856 NS_ASSERTION(!connectionReady(),
857 "Initialize called on already opened database!");
858 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
860 // Do not set mFileURL here since this is database does not have an associated
862 mDatabaseFile
= aDatabaseFile
;
863 aDatabaseFile
->GetNativeLeafName(mTelemetryFilename
);
866 nsresult rv
= aDatabaseFile
->GetPath(path
);
867 NS_ENSURE_SUCCESS(rv
, rv
);
869 bool exclusive
= StaticPrefs::storage_sqlite_exclusiveLock_enabled();
871 if (mIgnoreLockingMode
) {
873 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
, mFlags
,
874 "readonly-immutable-nolock");
876 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
, mFlags
,
877 GetTelemetryVFSName(exclusive
));
878 if (exclusive
&& (srv
== SQLITE_LOCKED
|| srv
== SQLITE_BUSY
)) {
879 // Retry without trying to get an exclusive lock.
881 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
,
882 mFlags
, GetTelemetryVFSName(false));
885 if (srv
!= SQLITE_OK
) {
887 rv
= convertResultCode(srv
);
888 RecordOpenStatus(rv
);
892 rv
= initializeInternal();
894 (rv
== NS_ERROR_STORAGE_BUSY
|| rv
== NS_ERROR_FILE_IS_LOCKED
)) {
895 // Usually SQLite will fail to acquire an exclusive lock on opening, but in
896 // some cases it may successfully open the database and then lock on the
897 // first query execution. When initializeInternal fails it closes the
898 // connection, so we can try to restart it in non-exclusive mode.
899 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
, mFlags
,
900 GetTelemetryVFSName(false));
901 if (srv
== SQLITE_OK
) {
902 rv
= initializeInternal();
906 RecordOpenStatus(rv
);
907 NS_ENSURE_SUCCESS(rv
, rv
);
912 nsresult
Connection::initialize(nsIFileURL
* aFileURL
,
913 const nsACString
& aTelemetryFilename
) {
914 NS_ASSERTION(aFileURL
, "Passed null file URL!");
915 NS_ASSERTION(!connectionReady(),
916 "Initialize called on already opened database!");
917 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
919 nsCOMPtr
<nsIFile
> databaseFile
;
920 nsresult rv
= aFileURL
->GetFile(getter_AddRefs(databaseFile
));
921 NS_ENSURE_SUCCESS(rv
, rv
);
923 // Set both mDatabaseFile and mFileURL here.
925 mDatabaseFile
= databaseFile
;
927 if (!aTelemetryFilename
.IsEmpty()) {
928 mTelemetryFilename
= aTelemetryFilename
;
930 databaseFile
->GetNativeLeafName(mTelemetryFilename
);
934 rv
= aFileURL
->GetSpec(spec
);
935 NS_ENSURE_SUCCESS(rv
, rv
);
937 // If there is a key specified, we need to use the obfuscating VFS.
939 rv
= aFileURL
->GetQuery(query
);
940 NS_ENSURE_SUCCESS(rv
, rv
);
943 bool hasDirectoryLockId
= false;
945 MOZ_ALWAYS_TRUE(URLParams::Parse(
946 query
, [&hasKey
, &hasDirectoryLockId
](const nsAString
& aName
,
947 const nsAString
& aValue
) {
948 if (aName
.EqualsLiteral("key")) {
952 if (aName
.EqualsLiteral("directoryLockId")) {
953 hasDirectoryLockId
= true;
959 bool exclusive
= StaticPrefs::storage_sqlite_exclusiveLock_enabled();
961 const char* const vfs
= hasKey
? GetObfuscatingVFSName()
962 : hasDirectoryLockId
? GetQuotaVFSName()
963 : GetTelemetryVFSName(exclusive
);
965 int srv
= ::sqlite3_open_v2(spec
.get(), &mDBConn
, mFlags
, vfs
);
966 if (srv
!= SQLITE_OK
) {
968 rv
= convertResultCode(srv
);
969 RecordOpenStatus(rv
);
973 rv
= initializeInternal();
974 RecordOpenStatus(rv
);
975 NS_ENSURE_SUCCESS(rv
, rv
);
980 nsresult
Connection::initializeInternal() {
982 auto guard
= MakeScopeExit([&]() { initializeFailed(); });
984 mConnectionClosed
= false;
986 #ifdef MOZ_SQLITE_FTS3_TOKENIZER
987 DebugOnly
<int> srv2
=
988 ::sqlite3_db_config(mDBConn
, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, 1, 0);
989 MOZ_ASSERT(srv2
== SQLITE_OK
,
990 "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
993 MOZ_ASSERT(!mTelemetryFilename
.IsEmpty(),
994 "A telemetry filename should have been set by now.");
996 // Properly wrap the database handle's mutex.
997 sharedDBMutex
.initWithMutex(sqlite3_db_mutex(mDBConn
));
999 // SQLite tracing can slow down queries (especially long queries)
1000 // significantly. Don't trace unless the user is actively monitoring SQLite.
1001 if (MOZ_LOG_TEST(gStorageLog
, LogLevel::Debug
)) {
1002 ::sqlite3_trace_v2(mDBConn
, SQLITE_TRACE_STMT
| SQLITE_TRACE_PROFILE
,
1006 gStorageLog
, LogLevel::Debug
,
1007 ("Opening connection to '%s' (%p)", mTelemetryFilename
.get(), this));
1010 int64_t pageSize
= Service::kDefaultPageSize
;
1012 // Set page_size to the preferred default value. This is effective only if
1013 // the database has just been created, otherwise, if the database does not
1014 // use WAL journal mode, a VACUUM operation will updated its page_size.
1015 nsAutoCString
pageSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
1016 "PRAGMA page_size = ");
1017 pageSizeQuery
.AppendInt(pageSize
);
1018 int srv
= executeSql(mDBConn
, pageSizeQuery
.get());
1019 if (srv
!= SQLITE_OK
) {
1020 return convertResultCode(srv
);
1023 // Setting the cache_size forces the database open, verifying if it is valid
1024 // or corrupt. So this is executed regardless it being actually needed.
1025 // The cache_size is calculated from the actual page_size, to save memory.
1026 nsAutoCString
cacheSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
1027 "PRAGMA cache_size = ");
1028 cacheSizeQuery
.AppendInt(-MAX_CACHE_SIZE_KIBIBYTES
);
1029 srv
= executeSql(mDBConn
, cacheSizeQuery
.get());
1030 if (srv
!= SQLITE_OK
) {
1031 return convertResultCode(srv
);
1034 // Register our built-in SQL functions.
1035 srv
= registerFunctions(mDBConn
);
1036 if (srv
!= SQLITE_OK
) {
1037 return convertResultCode(srv
);
1040 // Register our built-in SQL collating sequences.
1041 srv
= registerCollations(mDBConn
, mStorageService
);
1042 if (srv
!= SQLITE_OK
) {
1043 return convertResultCode(srv
);
1046 // Set the default synchronous value. Each consumer can switch this
1047 // accordingly to their needs.
1048 #if defined(ANDROID)
1049 // Android prefers synchronous = OFF for performance reasons.
1050 Unused
<< ExecuteSimpleSQL("PRAGMA synchronous = OFF;"_ns
);
1052 // Normal is the suggested value for WAL journals.
1053 Unused
<< ExecuteSimpleSQL("PRAGMA synchronous = NORMAL;"_ns
);
1056 // Initialization succeeded, we can stop guarding for failures.
1061 nsresult
Connection::initializeOnAsyncThread(nsIFile
* aStorageFile
) {
1062 MOZ_ASSERT(!IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1063 nsresult rv
= aStorageFile
1064 ? initialize(aStorageFile
)
1065 : initialize(kMozStorageMemoryStorageKey
, VoidCString());
1066 if (NS_FAILED(rv
)) {
1067 // Shutdown the async thread, since initialization failed.
1068 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1069 mAsyncExecutionThreadShuttingDown
= true;
1070 nsCOMPtr
<nsIRunnable
> event
=
1071 NewRunnableMethod("Connection::shutdownAsyncThread", this,
1072 &Connection::shutdownAsyncThread
);
1073 Unused
<< NS_DispatchToMainThread(event
);
1078 void Connection::initializeFailed() {
1080 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1081 mConnectionClosed
= true;
1083 MOZ_ALWAYS_TRUE(::sqlite3_close(mDBConn
) == SQLITE_OK
);
1085 sharedDBMutex
.destroy();
1088 nsresult
Connection::databaseElementExists(
1089 enum DatabaseElementType aElementType
, const nsACString
& aElementName
,
1091 if (!connectionReady()) {
1092 return NS_ERROR_NOT_AVAILABLE
;
1094 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1095 if (NS_FAILED(rv
)) {
1099 // When constructing the query, make sure to SELECT the correct db's
1100 // sqlite_master if the user is prefixing the element with a specific db. ex:
1102 nsCString
query("SELECT name FROM (SELECT * FROM ");
1103 nsDependentCSubstring element
;
1104 int32_t ind
= aElementName
.FindChar('.');
1105 if (ind
== kNotFound
) {
1106 element
.Assign(aElementName
);
1108 nsDependentCSubstring
db(Substring(aElementName
, 0, ind
+ 1));
1109 element
.Assign(Substring(aElementName
, ind
+ 1, aElementName
.Length()));
1112 query
.AppendLiteral(
1113 "sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = "
1116 switch (aElementType
) {
1118 query
.AppendLiteral("index");
1121 query
.AppendLiteral("table");
1124 query
.AppendLiteral("' AND name ='");
1125 query
.Append(element
);
1129 int srv
= prepareStatement(mDBConn
, query
, &stmt
);
1130 if (srv
!= SQLITE_OK
) {
1131 RecordQueryStatus(srv
);
1132 return convertResultCode(srv
);
1135 srv
= stepStatement(mDBConn
, stmt
);
1136 // we just care about the return value from step
1137 (void)::sqlite3_finalize(stmt
);
1139 RecordQueryStatus(srv
);
1141 if (srv
== SQLITE_ROW
) {
1145 if (srv
== SQLITE_DONE
) {
1150 return convertResultCode(srv
);
1153 bool Connection::findFunctionByInstance(mozIStorageFunction
* aInstance
) {
1154 sharedDBMutex
.assertCurrentThreadOwns();
1156 for (const auto& data
: mFunctions
.Values()) {
1157 if (data
.function
== aInstance
) {
1165 int Connection::sProgressHelper(void* aArg
) {
1166 Connection
* _this
= static_cast<Connection
*>(aArg
);
1167 return _this
->progressHandler();
1170 int Connection::progressHandler() {
1171 sharedDBMutex
.assertCurrentThreadOwns();
1172 if (mProgressHandler
) {
1174 nsresult rv
= mProgressHandler
->OnProgress(this, &result
);
1175 if (NS_FAILED(rv
)) return 0; // Don't break request
1176 return result
? 1 : 0;
1181 nsresult
Connection::setClosedState() {
1182 // Flag that we are shutting down the async thread, so that
1183 // getAsyncExecutionTarget knows not to expose/create the async thread.
1184 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1185 NS_ENSURE_FALSE(mAsyncExecutionThreadShuttingDown
, NS_ERROR_UNEXPECTED
);
1187 mAsyncExecutionThreadShuttingDown
= true;
1189 // Set the property to null before closing the connection, otherwise the
1190 // other functions in the module may try to use the connection after it is
1197 bool Connection::operationSupported(ConnectionOperation aOperationType
) {
1198 if (aOperationType
== ASYNCHRONOUS
) {
1199 // Async operations are supported for all connections, on any thread.
1202 // Sync operations are supported for sync connections (on any thread), and
1203 // async connections on a background thread.
1204 MOZ_ASSERT(aOperationType
== SYNCHRONOUS
);
1205 return mSupportedOperations
== SYNCHRONOUS
|| !NS_IsMainThread();
1208 nsresult
Connection::ensureOperationSupported(
1209 ConnectionOperation aOperationType
) {
1210 if (NS_WARN_IF(!operationSupported(aOperationType
))) {
1212 if (NS_IsMainThread()) {
1213 nsCOMPtr
<nsIXPConnect
> xpc
= nsIXPConnect::XPConnect();
1214 Unused
<< xpc
->DebugDumpJSStack(false, false, false);
1218 "Don't use async connections synchronously on the main thread");
1219 return NS_ERROR_NOT_AVAILABLE
;
1224 bool Connection::isConnectionReadyOnThisThread() {
1225 MOZ_ASSERT_IF(connectionReady(), !mConnectionClosed
);
1226 if (mAsyncExecutionThread
&& mAsyncExecutionThread
->IsOnCurrentThread()) {
1229 return connectionReady();
1232 bool Connection::isClosing() {
1233 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1234 return mAsyncExecutionThreadShuttingDown
&& !mConnectionClosed
;
1237 bool Connection::isClosed() {
1238 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1239 return mConnectionClosed
;
1242 bool Connection::isClosed(MutexAutoLock
& lock
) { return mConnectionClosed
; }
1244 bool Connection::isAsyncExecutionThreadAvailable() {
1245 MOZ_ASSERT(IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1246 return mAsyncExecutionThread
&& !mAsyncExecutionThreadShuttingDown
;
1249 void Connection::shutdownAsyncThread() {
1250 MOZ_ASSERT(IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1251 MOZ_ASSERT(mAsyncExecutionThread
);
1252 MOZ_ASSERT(mAsyncExecutionThreadShuttingDown
);
1254 MOZ_ALWAYS_SUCCEEDS(mAsyncExecutionThread
->Shutdown());
1255 mAsyncExecutionThread
= nullptr;
1258 nsresult
Connection::internalClose(sqlite3
* aNativeConnection
) {
1260 { // Make sure we have marked our async thread as shutting down.
1261 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1262 MOZ_ASSERT(mAsyncExecutionThreadShuttingDown
,
1263 "Did not call setClosedState!");
1264 MOZ_ASSERT(!isClosed(lockedScope
), "Unexpected closed state");
1268 if (MOZ_LOG_TEST(gStorageLog
, LogLevel::Debug
)) {
1269 nsAutoCString
leafName(":memory");
1270 if (mDatabaseFile
) (void)mDatabaseFile
->GetNativeLeafName(leafName
);
1271 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
1272 ("Closing connection to '%s'", leafName
.get()));
1275 // At this stage, we may still have statements that need to be
1276 // finalized. Attempt to close the database connection. This will
1277 // always disconnect any virtual tables and cleanly finalize their
1278 // internal statements. Once this is done, closing may fail due to
1279 // unfinalized client statements, in which case we need to finalize
1280 // these statements and close again.
1282 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1283 mConnectionClosed
= true;
1286 // Nothing else needs to be done if we don't have a connection here.
1287 if (!aNativeConnection
) return NS_OK
;
1289 int srv
= ::sqlite3_close(aNativeConnection
);
1291 if (srv
== SQLITE_BUSY
) {
1293 // Nothing else should change the connection or statements status until we
1295 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1296 // We still have non-finalized statements. Finalize them.
1297 sqlite3_stmt
* stmt
= nullptr;
1298 while ((stmt
= ::sqlite3_next_stmt(aNativeConnection
, stmt
))) {
1299 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
1300 ("Auto-finalizing SQL statement '%s' (%p)", ::sqlite3_sql(stmt
),
1304 SmprintfPointer msg
= ::mozilla::Smprintf(
1305 "SQL statement '%s' (%p) should have been finalized before closing "
1307 ::sqlite3_sql(stmt
), stmt
);
1308 NS_WARNING(msg
.get());
1311 srv
= ::sqlite3_finalize(stmt
);
1314 if (srv
!= SQLITE_OK
) {
1315 SmprintfPointer msg
= ::mozilla::Smprintf(
1316 "Could not finalize SQL statement (%p)", stmt
);
1317 NS_WARNING(msg
.get());
1321 // Ensure that the loop continues properly, whether closing has
1322 // succeeded or not.
1323 if (srv
== SQLITE_OK
) {
1327 // Scope exiting will unlock the mutex before we invoke sqlite3_close()
1328 // again, since Sqlite will try to acquire it.
1331 // Now that all statements have been finalized, we
1332 // should be able to close.
1333 srv
= ::sqlite3_close(aNativeConnection
);
1335 "Had to forcibly close the database connection because not all "
1336 "the statements have been finalized.");
1339 if (srv
== SQLITE_OK
) {
1340 sharedDBMutex
.destroy();
1343 "sqlite3_close failed. There are probably outstanding "
1344 "statements that are listed above!");
1347 return convertResultCode(srv
);
1350 nsCString
Connection::getFilename() { return mTelemetryFilename
; }
1352 int Connection::stepStatement(sqlite3
* aNativeConnection
,
1353 sqlite3_stmt
* aStatement
) {
1354 MOZ_ASSERT(aStatement
);
1356 AUTO_PROFILER_LABEL_DYNAMIC_CSTR("Connection::stepStatement", OTHER
,
1357 ::sqlite3_sql(aStatement
));
1359 bool checkedMainThread
= false;
1360 TimeStamp startTime
= TimeStamp::Now();
1362 // The connection may have been closed if the executing statement has been
1363 // created and cached after a call to asyncClose() but before the actual
1364 // sqlite3_close(). This usually happens when other tasks using cached
1365 // statements are asynchronously scheduled for execution and any of them ends
1366 // up after asyncClose. See bug 728653 for details.
1367 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1369 (void)::sqlite3_extended_result_codes(aNativeConnection
, 1);
1372 while ((srv
= ::sqlite3_step(aStatement
)) == SQLITE_LOCKED_SHAREDCACHE
) {
1373 if (!checkedMainThread
) {
1374 checkedMainThread
= true;
1375 if (::NS_IsMainThread()) {
1376 NS_WARNING("We won't allow blocking on the main thread!");
1381 srv
= WaitForUnlockNotify(aNativeConnection
);
1382 if (srv
!= SQLITE_OK
) {
1386 ::sqlite3_reset(aStatement
);
1389 // Report very slow SQL statements to Telemetry
1390 TimeDuration duration
= TimeStamp::Now() - startTime
;
1391 const uint32_t threshold
= NS_IsMainThread()
1392 ? Telemetry::kSlowSQLThresholdForMainThread
1393 : Telemetry::kSlowSQLThresholdForHelperThreads
;
1394 if (duration
.ToMilliseconds() >= threshold
) {
1395 nsDependentCString
statementString(::sqlite3_sql(aStatement
));
1396 Telemetry::RecordSlowSQLStatement(statementString
, mTelemetryFilename
,
1397 duration
.ToMilliseconds());
1400 (void)::sqlite3_extended_result_codes(aNativeConnection
, 0);
1401 // Drop off the extended result bits of the result code.
1405 int Connection::prepareStatement(sqlite3
* aNativeConnection
,
1406 const nsCString
& aSQL
, sqlite3_stmt
** _stmt
) {
1407 // We should not even try to prepare statements after the connection has
1409 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1411 bool checkedMainThread
= false;
1413 (void)::sqlite3_extended_result_codes(aNativeConnection
, 1);
1416 while ((srv
= ::sqlite3_prepare_v2(aNativeConnection
, aSQL
.get(), -1, _stmt
,
1417 nullptr)) == SQLITE_LOCKED_SHAREDCACHE
) {
1418 if (!checkedMainThread
) {
1419 checkedMainThread
= true;
1420 if (::NS_IsMainThread()) {
1421 NS_WARNING("We won't allow blocking on the main thread!");
1426 srv
= WaitForUnlockNotify(aNativeConnection
);
1427 if (srv
!= SQLITE_OK
) {
1432 if (srv
!= SQLITE_OK
) {
1434 warnMsg
.AppendLiteral("The SQL statement '");
1435 warnMsg
.Append(aSQL
);
1436 warnMsg
.AppendLiteral("' could not be compiled due to an error: ");
1437 warnMsg
.Append(::sqlite3_errmsg(aNativeConnection
));
1440 NS_WARNING(warnMsg
.get());
1442 MOZ_LOG(gStorageLog
, LogLevel::Error
, ("%s", warnMsg
.get()));
1445 (void)::sqlite3_extended_result_codes(aNativeConnection
, 0);
1446 // Drop off the extended result bits of the result code.
1447 int rc
= srv
& 0xFF;
1448 // sqlite will return OK on a comment only string and set _stmt to nullptr.
1449 // The callers of this function are used to only checking the return value,
1450 // so it is safer to return an error code.
1451 if (rc
== SQLITE_OK
&& *_stmt
== nullptr) {
1452 return SQLITE_MISUSE
;
1458 int Connection::executeSql(sqlite3
* aNativeConnection
, const char* aSqlString
) {
1459 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1461 AUTO_PROFILER_LABEL_DYNAMIC_CSTR("Connection::executeSql", OTHER
, aSqlString
);
1463 TimeStamp startTime
= TimeStamp::Now();
1465 ::sqlite3_exec(aNativeConnection
, aSqlString
, nullptr, nullptr, nullptr);
1466 RecordQueryStatus(srv
);
1468 // Report very slow SQL statements to Telemetry
1469 TimeDuration duration
= TimeStamp::Now() - startTime
;
1470 const uint32_t threshold
= NS_IsMainThread()
1471 ? Telemetry::kSlowSQLThresholdForMainThread
1472 : Telemetry::kSlowSQLThresholdForHelperThreads
;
1473 if (duration
.ToMilliseconds() >= threshold
) {
1474 nsDependentCString
statementString(aSqlString
);
1475 Telemetry::RecordSlowSQLStatement(statementString
, mTelemetryFilename
,
1476 duration
.ToMilliseconds());
1482 ////////////////////////////////////////////////////////////////////////////////
1483 //// nsIInterfaceRequestor
1486 Connection::GetInterface(const nsIID
& aIID
, void** _result
) {
1487 if (aIID
.Equals(NS_GET_IID(nsIEventTarget
))) {
1488 nsIEventTarget
* background
= getAsyncExecutionTarget();
1489 NS_IF_ADDREF(background
);
1490 *_result
= background
;
1493 return NS_ERROR_NO_INTERFACE
;
1496 ////////////////////////////////////////////////////////////////////////////////
1497 //// mozIStorageConnection
1500 Connection::Close() {
1501 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1502 if (NS_FAILED(rv
)) {
1505 return synchronousClose();
1508 nsresult
Connection::synchronousClose() {
1509 if (!connectionReady()) {
1510 return NS_ERROR_NOT_INITIALIZED
;
1514 // Since we're accessing mAsyncExecutionThread, we need to be on the opener
1515 // event target. We make this check outside of debug code below in
1516 // setClosedState, but this is here to be explicit.
1517 MOZ_ASSERT(IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1520 // Make sure we have not executed any asynchronous statements.
1521 // If this fails, the mDBConn may be left open, resulting in a leak.
1522 // We'll try to finalize the pending statements and close the connection.
1523 if (isAsyncExecutionThreadAvailable()) {
1525 if (NS_IsMainThread()) {
1526 nsCOMPtr
<nsIXPConnect
> xpc
= nsIXPConnect::XPConnect();
1527 Unused
<< xpc
->DebugDumpJSStack(false, false, false);
1531 "Close() was invoked on a connection that executed asynchronous "
1533 "Should have used asyncClose().");
1534 // Try to close the database regardless, to free up resources.
1535 Unused
<< SpinningSynchronousClose();
1536 return NS_ERROR_UNEXPECTED
;
1539 // setClosedState nullifies our connection pointer, so we take a raw pointer
1540 // off it, to pass it through the close procedure.
1541 sqlite3
* nativeConn
= mDBConn
;
1542 nsresult rv
= setClosedState();
1543 NS_ENSURE_SUCCESS(rv
, rv
);
1545 return internalClose(nativeConn
);
1549 Connection::SpinningSynchronousClose() {
1550 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1551 if (NS_FAILED(rv
)) {
1554 if (!IsOnCurrentSerialEventTarget(eventTargetOpenedOn
)) {
1555 return NS_ERROR_NOT_SAME_THREAD
;
1558 // As currently implemented, we can't spin to wait for an existing AsyncClose.
1559 // Our only existing caller will never have called close; assert if misused
1560 // so that no new callers assume this works after an AsyncClose.
1561 MOZ_DIAGNOSTIC_ASSERT(connectionReady());
1562 if (!connectionReady()) {
1563 return NS_ERROR_UNEXPECTED
;
1566 RefPtr
<CloseListener
> listener
= new CloseListener();
1567 rv
= AsyncClose(listener
);
1568 NS_ENSURE_SUCCESS(rv
, rv
);
1570 SpinEventLoopUntil("storage::Connection::SpinningSynchronousClose"_ns
,
1571 [&]() { return listener
->mClosed
; }));
1572 MOZ_ASSERT(isClosed(), "The connection should be closed at this point");
1578 Connection::AsyncClose(mozIStorageCompletionCallback
* aCallback
) {
1579 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1580 // Check if AsyncClose or Close were already invoked.
1581 if (!connectionReady()) {
1582 return NS_ERROR_NOT_INITIALIZED
;
1584 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1585 if (NS_FAILED(rv
)) {
1589 // The two relevant factors at this point are whether we have a database
1590 // connection and whether we have an async execution thread. Here's what the
1591 // states mean and how we handle them:
1593 // - (mDBConn && asyncThread): The expected case where we are either an
1594 // async connection or a sync connection that has been used asynchronously.
1595 // Either way the caller must call us and not Close(). Nothing surprising
1596 // about this. We'll dispatch AsyncCloseConnection to the already-existing
1599 // - (mDBConn && !asyncThread): A somewhat unusual case where the caller
1600 // opened the connection synchronously and was planning to use it
1601 // asynchronously, but never got around to using it asynchronously before
1602 // needing to shutdown. This has been observed to happen for the cookie
1603 // service in a case where Firefox shuts itself down almost immediately
1604 // after startup (for unknown reasons). In the Firefox shutdown case,
1605 // we may also fail to create a new async execution thread if one does not
1606 // already exist. (nsThreadManager will refuse to create new threads when
1607 // it has already been told to shutdown.) As such, we need to handle a
1608 // failure to create the async execution thread by falling back to
1609 // synchronous Close() and also dispatching the completion callback because
1610 // at least Places likes to spin a nested event loop that depends on the
1611 // callback being invoked.
1613 // Note that we have considered not trying to spin up the async execution
1614 // thread in this case if it does not already exist, but the overhead of
1615 // thread startup (if successful) is significantly less expensive than the
1616 // worst-case potential I/O hit of synchronously closing a database when we
1617 // could close it asynchronously.
1619 // - (!mDBConn && asyncThread): This happens in some but not all cases where
1620 // OpenAsyncDatabase encountered a problem opening the database. If it
1621 // happened in all cases AsyncInitDatabase would just shut down the thread
1622 // directly and we would avoid this case. But it doesn't, so for simplicity
1623 // and consistency AsyncCloseConnection knows how to handle this and we
1624 // act like this was the (mDBConn && asyncThread) case in this method.
1626 // - (!mDBConn && !asyncThread): The database was never successfully opened or
1627 // Close() or AsyncClose() has already been called (at least) once. This is
1628 // undeniably a misuse case by the caller. We could optimize for this
1629 // case by adding an additional check of mAsyncExecutionThread without using
1630 // getAsyncExecutionTarget() to avoid wastefully creating a thread just to
1631 // shut it down. But this complicates the method for broken caller code
1632 // whereas we're still correct and safe without the special-case.
1633 nsIEventTarget
* asyncThread
= getAsyncExecutionTarget();
1635 // Create our callback event if we were given a callback. This will
1636 // eventually be dispatched in all cases, even if we fall back to Close() and
1637 // the database wasn't open and we return an error. The rationale is that
1638 // no existing consumer checks our return value and several of them like to
1639 // spin nested event loops until the callback fires. Given that, it seems
1640 // preferable for us to dispatch the callback in all cases. (Except the
1641 // wrong thread misuse case we bailed on up above. But that's okay because
1642 // that is statically wrong whereas these edge cases are dynamic.)
1643 nsCOMPtr
<nsIRunnable
> completeEvent
;
1645 completeEvent
= newCompletionEvent(aCallback
);
1649 // We were unable to create an async thread, so we need to fall back to
1650 // using normal Close(). Since there is no async thread, Close() will
1651 // not complain about that. (Close() may, however, complain if the
1652 // connection is closed, but that's okay.)
1653 if (completeEvent
) {
1654 // Closing the database is more important than returning an error code
1655 // about a failure to dispatch, especially because all existing native
1656 // callers ignore our return value.
1657 Unused
<< NS_DispatchToMainThread(completeEvent
.forget());
1659 MOZ_ALWAYS_SUCCEEDS(synchronousClose());
1660 // Return a success inconditionally here, since Close() is unlikely to fail
1661 // and we want to reassure the consumer that its callback will be invoked.
1665 // If we're closing the connection during shutdown, and there is an
1666 // interruptible statement running on the helper thread, issue a
1667 // sqlite3_interrupt() to avoid crashing when that statement takes a long
1668 // time (for example a vacuum).
1669 if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed
) &&
1670 mInterruptible
&& mIsStatementOnHelperThreadInterruptible
) {
1671 MOZ_ASSERT(!isClosing(), "Must not be closing, see Interrupt()");
1672 DebugOnly
<nsresult
> rv2
= Interrupt();
1673 MOZ_ASSERT(NS_SUCCEEDED(rv2
));
1676 // setClosedState nullifies our connection pointer, so we take a raw pointer
1677 // off it, to pass it through the close procedure.
1678 sqlite3
* nativeConn
= mDBConn
;
1679 rv
= setClosedState();
1680 NS_ENSURE_SUCCESS(rv
, rv
);
1682 // Create and dispatch our close event to the background thread.
1683 nsCOMPtr
<nsIRunnable
> closeEvent
=
1684 new AsyncCloseConnection(this, nativeConn
, completeEvent
);
1685 rv
= asyncThread
->Dispatch(closeEvent
, NS_DISPATCH_NORMAL
);
1686 NS_ENSURE_SUCCESS(rv
, rv
);
1692 Connection::AsyncClone(bool aReadOnly
,
1693 mozIStorageCompletionCallback
* aCallback
) {
1694 AUTO_PROFILER_LABEL("Connection::AsyncClone", OTHER
);
1696 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1697 if (!connectionReady()) {
1698 return NS_ERROR_NOT_INITIALIZED
;
1700 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1701 if (NS_FAILED(rv
)) {
1704 if (!mDatabaseFile
) return NS_ERROR_UNEXPECTED
;
1708 // Turn off SQLITE_OPEN_READWRITE, and set SQLITE_OPEN_READONLY.
1709 flags
= (~SQLITE_OPEN_READWRITE
& flags
) | SQLITE_OPEN_READONLY
;
1710 // Turn off SQLITE_OPEN_CREATE.
1711 flags
= (~SQLITE_OPEN_CREATE
& flags
);
1714 // The cloned connection will still implement the synchronous API, but throw
1715 // if any synchronous methods are called on the main thread.
1716 RefPtr
<Connection
> clone
=
1717 new Connection(mStorageService
, flags
, ASYNCHRONOUS
);
1719 RefPtr
<AsyncInitializeClone
> initEvent
=
1720 new AsyncInitializeClone(this, clone
, aReadOnly
, aCallback
);
1721 // Dispatch to our async thread, since the originating connection must remain
1722 // valid and open for the whole cloning process. This also ensures we are
1723 // properly serialized with a `close` operation, rather than race with it.
1724 nsCOMPtr
<nsIEventTarget
> target
= getAsyncExecutionTarget();
1726 return NS_ERROR_UNEXPECTED
;
1728 return target
->Dispatch(initEvent
, NS_DISPATCH_NORMAL
);
1731 nsresult
Connection::initializeClone(Connection
* aClone
, bool aReadOnly
) {
1733 if (!mStorageKey
.IsEmpty()) {
1734 rv
= aClone
->initialize(mStorageKey
, mName
);
1735 } else if (mFileURL
) {
1736 rv
= aClone
->initialize(mFileURL
, mTelemetryFilename
);
1738 rv
= aClone
->initialize(mDatabaseFile
);
1740 if (NS_FAILED(rv
)) {
1744 auto guard
= MakeScopeExit([&]() { aClone
->initializeFailed(); });
1746 rv
= aClone
->SetDefaultTransactionType(mDefaultTransactionType
);
1747 NS_ENSURE_SUCCESS(rv
, rv
);
1749 // Re-attach on-disk databases that were attached to the original connection.
1751 nsCOMPtr
<mozIStorageStatement
> stmt
;
1752 rv
= CreateStatement("PRAGMA database_list"_ns
, getter_AddRefs(stmt
));
1753 NS_ENSURE_SUCCESS(rv
, rv
);
1754 bool hasResult
= false;
1755 while (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1757 rv
= stmt
->GetUTF8String(1, name
);
1758 if (NS_SUCCEEDED(rv
) && !name
.EqualsLiteral("main") &&
1759 !name
.EqualsLiteral("temp")) {
1761 rv
= stmt
->GetUTF8String(2, path
);
1762 if (NS_SUCCEEDED(rv
) && !path
.IsEmpty()) {
1763 nsCOMPtr
<mozIStorageStatement
> attachStmt
;
1764 rv
= aClone
->CreateStatement("ATTACH DATABASE :path AS "_ns
+ name
,
1765 getter_AddRefs(attachStmt
));
1766 NS_ENSURE_SUCCESS(rv
, rv
);
1767 rv
= attachStmt
->BindUTF8StringByName("path"_ns
, path
);
1768 NS_ENSURE_SUCCESS(rv
, rv
);
1769 rv
= attachStmt
->Execute();
1770 NS_ENSURE_SUCCESS(rv
, rv
);
1776 // Copy over pragmas from the original connection.
1777 // LIMITATION WARNING! Many of these pragmas are actually scoped to the
1778 // schema ("main" and any other attached databases), and this implmentation
1779 // fails to propagate them. This is being addressed on trunk.
1780 static const char* pragmas
[] = {
1781 "cache_size", "temp_store", "foreign_keys", "journal_size_limit",
1782 "synchronous", "wal_autocheckpoint", "busy_timeout"};
1783 for (auto& pragma
: pragmas
) {
1784 // Read-only connections just need cache_size and temp_store pragmas.
1785 if (aReadOnly
&& ::strcmp(pragma
, "cache_size") != 0 &&
1786 ::strcmp(pragma
, "temp_store") != 0) {
1790 nsAutoCString
pragmaQuery("PRAGMA ");
1791 pragmaQuery
.Append(pragma
);
1792 nsCOMPtr
<mozIStorageStatement
> stmt
;
1793 rv
= CreateStatement(pragmaQuery
, getter_AddRefs(stmt
));
1794 NS_ENSURE_SUCCESS(rv
, rv
);
1795 bool hasResult
= false;
1796 if (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1797 pragmaQuery
.AppendLiteral(" = ");
1798 pragmaQuery
.AppendInt(stmt
->AsInt32(0));
1799 rv
= aClone
->ExecuteSimpleSQL(pragmaQuery
);
1800 NS_ENSURE_SUCCESS(rv
, rv
);
1804 // Copy over temporary tables, triggers, and views from the original
1805 // connections. Entities in `sqlite_temp_master` are only visible to the
1806 // connection that created them.
1808 rv
= aClone
->ExecuteSimpleSQL("BEGIN TRANSACTION"_ns
);
1809 NS_ENSURE_SUCCESS(rv
, rv
);
1811 nsCOMPtr
<mozIStorageStatement
> stmt
;
1812 rv
= CreateStatement(nsLiteralCString("SELECT sql FROM sqlite_temp_master "
1813 "WHERE type IN ('table', 'view', "
1814 "'index', 'trigger')"),
1815 getter_AddRefs(stmt
));
1816 // Propagate errors, because failing to copy triggers might cause schema
1817 // coherency issues when writing to the database from the cloned connection.
1818 NS_ENSURE_SUCCESS(rv
, rv
);
1819 bool hasResult
= false;
1820 while (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1821 nsAutoCString query
;
1822 rv
= stmt
->GetUTF8String(0, query
);
1823 NS_ENSURE_SUCCESS(rv
, rv
);
1825 // The `CREATE` SQL statements in `sqlite_temp_master` omit the `TEMP`
1826 // keyword. We need to add it back, or we'll recreate temporary entities
1827 // as persistent ones. `sqlite_temp_master` also holds `CREATE INDEX`
1828 // statements, but those don't need `TEMP` keywords.
1829 if (StringBeginsWith(query
, "CREATE TABLE "_ns
) ||
1830 StringBeginsWith(query
, "CREATE TRIGGER "_ns
) ||
1831 StringBeginsWith(query
, "CREATE VIEW "_ns
)) {
1832 query
.Replace(0, 6, "CREATE TEMP");
1835 rv
= aClone
->ExecuteSimpleSQL(query
);
1836 NS_ENSURE_SUCCESS(rv
, rv
);
1839 rv
= aClone
->ExecuteSimpleSQL("COMMIT"_ns
);
1840 NS_ENSURE_SUCCESS(rv
, rv
);
1843 // Copy any functions that have been added to this connection.
1844 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1845 for (const auto& entry
: mFunctions
) {
1846 const nsACString
& key
= entry
.GetKey();
1847 Connection::FunctionInfo data
= entry
.GetData();
1849 rv
= aClone
->CreateFunction(key
, data
.numArgs
, data
.function
);
1850 if (NS_FAILED(rv
)) {
1851 NS_WARNING("Failed to copy function to cloned connection");
1860 Connection::Clone(bool aReadOnly
, mozIStorageConnection
** _connection
) {
1861 MOZ_ASSERT(IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1863 AUTO_PROFILER_LABEL("Connection::Clone", OTHER
);
1865 if (!connectionReady()) {
1866 return NS_ERROR_NOT_INITIALIZED
;
1868 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1869 if (NS_FAILED(rv
)) {
1875 // Turn off SQLITE_OPEN_READWRITE, and set SQLITE_OPEN_READONLY.
1876 flags
= (~SQLITE_OPEN_READWRITE
& flags
) | SQLITE_OPEN_READONLY
;
1877 // Turn off SQLITE_OPEN_CREATE.
1878 flags
= (~SQLITE_OPEN_CREATE
& flags
);
1881 RefPtr
<Connection
> clone
= new Connection(
1882 mStorageService
, flags
, mSupportedOperations
, mInterruptible
);
1884 rv
= initializeClone(clone
, aReadOnly
);
1885 if (NS_FAILED(rv
)) {
1889 NS_IF_ADDREF(*_connection
= clone
);
1894 Connection::Interrupt() {
1895 MOZ_ASSERT(mInterruptible
, "Interrupt method not allowed");
1896 MOZ_ASSERT_IF(SYNCHRONOUS
== mSupportedOperations
,
1897 !IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1898 MOZ_ASSERT_IF(ASYNCHRONOUS
== mSupportedOperations
,
1899 IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1901 if (!connectionReady()) {
1902 return NS_ERROR_NOT_INITIALIZED
;
1905 if (isClosing()) { // Closing already in asynchronous case
1910 // As stated on https://www.sqlite.org/c3ref/interrupt.html,
1911 // it is not safe to call sqlite3_interrupt() when
1912 // database connection is closed or might close before
1913 // sqlite3_interrupt() returns.
1914 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1915 if (!isClosed(lockedScope
)) {
1916 MOZ_ASSERT(mDBConn
);
1917 ::sqlite3_interrupt(mDBConn
);
1925 Connection::AsyncVacuum(mozIStorageCompletionCallback
* aCallback
,
1926 bool aUseIncremental
, int32_t aSetPageSize
) {
1927 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1928 // Abort if we're shutting down.
1929 if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed
)) {
1930 return NS_ERROR_ABORT
;
1932 // Check if AsyncClose or Close were already invoked.
1933 if (!connectionReady()) {
1934 return NS_ERROR_NOT_INITIALIZED
;
1936 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1937 if (NS_FAILED(rv
)) {
1940 nsIEventTarget
* asyncThread
= getAsyncExecutionTarget();
1942 return NS_ERROR_NOT_INITIALIZED
;
1945 // Create and dispatch our vacuum event to the background thread.
1946 nsCOMPtr
<nsIRunnable
> vacuumEvent
=
1947 new AsyncVacuumEvent(this, aCallback
, aUseIncremental
, aSetPageSize
);
1948 rv
= asyncThread
->Dispatch(vacuumEvent
, NS_DISPATCH_NORMAL
);
1949 NS_ENSURE_SUCCESS(rv
, rv
);
1955 Connection::GetDefaultPageSize(int32_t* _defaultPageSize
) {
1956 *_defaultPageSize
= Service::kDefaultPageSize
;
1961 Connection::GetConnectionReady(bool* _ready
) {
1962 MOZ_ASSERT(IsOnCurrentSerialEventTarget(eventTargetOpenedOn
));
1963 *_ready
= connectionReady();
1968 Connection::GetDatabaseFile(nsIFile
** _dbFile
) {
1969 if (!connectionReady()) {
1970 return NS_ERROR_NOT_INITIALIZED
;
1972 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1973 if (NS_FAILED(rv
)) {
1977 NS_IF_ADDREF(*_dbFile
= mDatabaseFile
);
1983 Connection::GetLastInsertRowID(int64_t* _id
) {
1984 if (!connectionReady()) {
1985 return NS_ERROR_NOT_INITIALIZED
;
1987 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1988 if (NS_FAILED(rv
)) {
1992 sqlite_int64 id
= ::sqlite3_last_insert_rowid(mDBConn
);
1999 Connection::GetAffectedRows(int32_t* _rows
) {
2000 if (!connectionReady()) {
2001 return NS_ERROR_NOT_INITIALIZED
;
2003 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2004 if (NS_FAILED(rv
)) {
2008 *_rows
= ::sqlite3_changes(mDBConn
);
2014 Connection::GetLastError(int32_t* _error
) {
2015 if (!connectionReady()) {
2016 return NS_ERROR_NOT_INITIALIZED
;
2018 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2019 if (NS_FAILED(rv
)) {
2023 *_error
= ::sqlite3_errcode(mDBConn
);
2029 Connection::GetLastErrorString(nsACString
& _errorString
) {
2030 if (!connectionReady()) {
2031 return NS_ERROR_NOT_INITIALIZED
;
2033 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2034 if (NS_FAILED(rv
)) {
2038 const char* serr
= ::sqlite3_errmsg(mDBConn
);
2039 _errorString
.Assign(serr
);
2045 Connection::GetSchemaVersion(int32_t* _version
) {
2046 if (!connectionReady()) {
2047 return NS_ERROR_NOT_INITIALIZED
;
2049 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2050 if (NS_FAILED(rv
)) {
2054 nsCOMPtr
<mozIStorageStatement
> stmt
;
2055 (void)CreateStatement("PRAGMA user_version"_ns
, getter_AddRefs(stmt
));
2056 NS_ENSURE_TRUE(stmt
, NS_ERROR_OUT_OF_MEMORY
);
2060 if (NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
)
2061 *_version
= stmt
->AsInt32(0);
2067 Connection::SetSchemaVersion(int32_t aVersion
) {
2068 if (!connectionReady()) {
2069 return NS_ERROR_NOT_INITIALIZED
;
2071 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2072 if (NS_FAILED(rv
)) {
2076 nsAutoCString
stmt("PRAGMA user_version = "_ns
);
2077 stmt
.AppendInt(aVersion
);
2079 return ExecuteSimpleSQL(stmt
);
2083 Connection::CreateStatement(const nsACString
& aSQLStatement
,
2084 mozIStorageStatement
** _stmt
) {
2085 NS_ENSURE_ARG_POINTER(_stmt
);
2086 if (!connectionReady()) {
2087 return NS_ERROR_NOT_INITIALIZED
;
2089 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2090 if (NS_FAILED(rv
)) {
2094 RefPtr
<Statement
> statement(new Statement());
2095 NS_ENSURE_TRUE(statement
, NS_ERROR_OUT_OF_MEMORY
);
2097 rv
= statement
->initialize(this, mDBConn
, aSQLStatement
);
2098 NS_ENSURE_SUCCESS(rv
, rv
);
2101 statement
.forget(&rawPtr
);
2107 Connection::CreateAsyncStatement(const nsACString
& aSQLStatement
,
2108 mozIStorageAsyncStatement
** _stmt
) {
2109 NS_ENSURE_ARG_POINTER(_stmt
);
2110 if (!connectionReady()) {
2111 return NS_ERROR_NOT_INITIALIZED
;
2113 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2114 if (NS_FAILED(rv
)) {
2118 RefPtr
<AsyncStatement
> statement(new AsyncStatement());
2119 NS_ENSURE_TRUE(statement
, NS_ERROR_OUT_OF_MEMORY
);
2121 rv
= statement
->initialize(this, mDBConn
, aSQLStatement
);
2122 NS_ENSURE_SUCCESS(rv
, rv
);
2124 AsyncStatement
* rawPtr
;
2125 statement
.forget(&rawPtr
);
2131 Connection::ExecuteSimpleSQL(const nsACString
& aSQLStatement
) {
2132 CHECK_MAINTHREAD_ABUSE();
2133 if (!connectionReady()) {
2134 return NS_ERROR_NOT_INITIALIZED
;
2136 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2137 if (NS_FAILED(rv
)) {
2141 int srv
= executeSql(mDBConn
, PromiseFlatCString(aSQLStatement
).get());
2142 return convertResultCode(srv
);
2146 Connection::ExecuteAsync(
2147 const nsTArray
<RefPtr
<mozIStorageBaseStatement
>>& aStatements
,
2148 mozIStorageStatementCallback
* aCallback
,
2149 mozIStoragePendingStatement
** _handle
) {
2150 nsTArray
<StatementData
> stmts(aStatements
.Length());
2151 for (uint32_t i
= 0; i
< aStatements
.Length(); i
++) {
2152 nsCOMPtr
<StorageBaseStatementInternal
> stmt
=
2153 do_QueryInterface(aStatements
[i
]);
2154 NS_ENSURE_STATE(stmt
);
2156 // Obtain our StatementData.
2158 nsresult rv
= stmt
->getAsynchronousStatementData(data
);
2159 NS_ENSURE_SUCCESS(rv
, rv
);
2161 NS_ASSERTION(stmt
->getOwner() == this,
2162 "Statement must be from this database connection!");
2164 // Now append it to our array.
2165 stmts
.AppendElement(data
);
2168 // Dispatch to the background
2169 return AsyncExecuteStatements::execute(std::move(stmts
), this, mDBConn
,
2170 aCallback
, _handle
);
2174 Connection::ExecuteSimpleSQLAsync(const nsACString
& aSQLStatement
,
2175 mozIStorageStatementCallback
* aCallback
,
2176 mozIStoragePendingStatement
** _handle
) {
2177 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
2179 nsCOMPtr
<mozIStorageAsyncStatement
> stmt
;
2180 nsresult rv
= CreateAsyncStatement(aSQLStatement
, getter_AddRefs(stmt
));
2181 if (NS_FAILED(rv
)) {
2185 nsCOMPtr
<mozIStoragePendingStatement
> pendingStatement
;
2186 rv
= stmt
->ExecuteAsync(aCallback
, getter_AddRefs(pendingStatement
));
2187 if (NS_FAILED(rv
)) {
2191 pendingStatement
.forget(_handle
);
2196 Connection::TableExists(const nsACString
& aTableName
, bool* _exists
) {
2197 return databaseElementExists(TABLE
, aTableName
, _exists
);
2201 Connection::IndexExists(const nsACString
& aIndexName
, bool* _exists
) {
2202 return databaseElementExists(INDEX
, aIndexName
, _exists
);
2206 Connection::GetTransactionInProgress(bool* _inProgress
) {
2207 if (!connectionReady()) {
2208 return NS_ERROR_NOT_INITIALIZED
;
2210 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2211 if (NS_FAILED(rv
)) {
2215 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2216 *_inProgress
= transactionInProgress(lockedScope
);
2221 Connection::GetDefaultTransactionType(int32_t* _type
) {
2222 *_type
= mDefaultTransactionType
;
2227 Connection::SetDefaultTransactionType(int32_t aType
) {
2228 NS_ENSURE_ARG_RANGE(aType
, TRANSACTION_DEFERRED
, TRANSACTION_EXCLUSIVE
);
2229 mDefaultTransactionType
= aType
;
2234 Connection::GetVariableLimit(int32_t* _limit
) {
2235 if (!connectionReady()) {
2236 return NS_ERROR_NOT_INITIALIZED
;
2238 int limit
= ::sqlite3_limit(mDBConn
, SQLITE_LIMIT_VARIABLE_NUMBER
, -1);
2240 return NS_ERROR_UNEXPECTED
;
2247 Connection::BeginTransaction() {
2248 if (!connectionReady()) {
2249 return NS_ERROR_NOT_INITIALIZED
;
2251 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2252 if (NS_FAILED(rv
)) {
2256 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2257 return beginTransactionInternal(lockedScope
, mDBConn
,
2258 mDefaultTransactionType
);
2261 nsresult
Connection::beginTransactionInternal(
2262 const SQLiteMutexAutoLock
& aProofOfLock
, sqlite3
* aNativeConnection
,
2263 int32_t aTransactionType
) {
2264 if (transactionInProgress(aProofOfLock
)) {
2265 return NS_ERROR_FAILURE
;
2268 switch (aTransactionType
) {
2269 case TRANSACTION_DEFERRED
:
2270 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN DEFERRED"));
2272 case TRANSACTION_IMMEDIATE
:
2273 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN IMMEDIATE"));
2275 case TRANSACTION_EXCLUSIVE
:
2276 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN EXCLUSIVE"));
2279 return NS_ERROR_ILLEGAL_VALUE
;
2285 Connection::CommitTransaction() {
2286 if (!connectionReady()) {
2287 return NS_ERROR_NOT_INITIALIZED
;
2289 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2290 if (NS_FAILED(rv
)) {
2294 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2295 return commitTransactionInternal(lockedScope
, mDBConn
);
2298 nsresult
Connection::commitTransactionInternal(
2299 const SQLiteMutexAutoLock
& aProofOfLock
, sqlite3
* aNativeConnection
) {
2300 if (!transactionInProgress(aProofOfLock
)) {
2301 return NS_ERROR_UNEXPECTED
;
2304 convertResultCode(executeSql(aNativeConnection
, "COMMIT TRANSACTION"));
2309 Connection::RollbackTransaction() {
2310 if (!connectionReady()) {
2311 return NS_ERROR_NOT_INITIALIZED
;
2313 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2314 if (NS_FAILED(rv
)) {
2318 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2319 return rollbackTransactionInternal(lockedScope
, mDBConn
);
2322 nsresult
Connection::rollbackTransactionInternal(
2323 const SQLiteMutexAutoLock
& aProofOfLock
, sqlite3
* aNativeConnection
) {
2324 if (!transactionInProgress(aProofOfLock
)) {
2325 return NS_ERROR_UNEXPECTED
;
2329 convertResultCode(executeSql(aNativeConnection
, "ROLLBACK TRANSACTION"));
2334 Connection::CreateTable(const char* aTableName
, const char* aTableSchema
) {
2335 if (!connectionReady()) {
2336 return NS_ERROR_NOT_INITIALIZED
;
2338 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2339 if (NS_FAILED(rv
)) {
2343 SmprintfPointer buf
=
2344 ::mozilla::Smprintf("CREATE TABLE %s (%s)", aTableName
, aTableSchema
);
2345 if (!buf
) return NS_ERROR_OUT_OF_MEMORY
;
2347 int srv
= executeSql(mDBConn
, buf
.get());
2349 return convertResultCode(srv
);
2353 Connection::CreateFunction(const nsACString
& aFunctionName
,
2354 int32_t aNumArguments
,
2355 mozIStorageFunction
* aFunction
) {
2356 if (!connectionReady()) {
2357 return NS_ERROR_NOT_INITIALIZED
;
2359 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2360 if (NS_FAILED(rv
)) {
2364 // Check to see if this function is already defined. We only check the name
2365 // because a function can be defined with the same body but different names.
2366 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2367 NS_ENSURE_FALSE(mFunctions
.Contains(aFunctionName
), NS_ERROR_FAILURE
);
2369 int srv
= ::sqlite3_create_function(
2370 mDBConn
, nsPromiseFlatCString(aFunctionName
).get(), aNumArguments
,
2371 SQLITE_ANY
, aFunction
, basicFunctionHelper
, nullptr, nullptr);
2372 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2374 FunctionInfo info
= {aFunction
, aNumArguments
};
2375 mFunctions
.InsertOrUpdate(aFunctionName
, info
);
2381 Connection::RemoveFunction(const nsACString
& aFunctionName
) {
2382 if (!connectionReady()) {
2383 return NS_ERROR_NOT_INITIALIZED
;
2385 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2386 if (NS_FAILED(rv
)) {
2390 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2391 NS_ENSURE_TRUE(mFunctions
.Get(aFunctionName
, nullptr), NS_ERROR_FAILURE
);
2393 int srv
= ::sqlite3_create_function(
2394 mDBConn
, nsPromiseFlatCString(aFunctionName
).get(), 0, SQLITE_ANY
,
2395 nullptr, nullptr, nullptr, nullptr);
2396 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2398 mFunctions
.Remove(aFunctionName
);
2404 Connection::SetProgressHandler(int32_t aGranularity
,
2405 mozIStorageProgressHandler
* aHandler
,
2406 mozIStorageProgressHandler
** _oldHandler
) {
2407 if (!connectionReady()) {
2408 return NS_ERROR_NOT_INITIALIZED
;
2410 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2411 if (NS_FAILED(rv
)) {
2415 // Return previous one
2416 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2417 NS_IF_ADDREF(*_oldHandler
= mProgressHandler
);
2419 if (!aHandler
|| aGranularity
<= 0) {
2423 mProgressHandler
= aHandler
;
2424 ::sqlite3_progress_handler(mDBConn
, aGranularity
, sProgressHelper
, this);
2430 Connection::RemoveProgressHandler(mozIStorageProgressHandler
** _oldHandler
) {
2431 if (!connectionReady()) {
2432 return NS_ERROR_NOT_INITIALIZED
;
2434 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2435 if (NS_FAILED(rv
)) {
2439 // Return previous one
2440 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2441 NS_IF_ADDREF(*_oldHandler
= mProgressHandler
);
2443 mProgressHandler
= nullptr;
2444 ::sqlite3_progress_handler(mDBConn
, 0, nullptr, nullptr);
2450 Connection::SetGrowthIncrement(int32_t aChunkSize
,
2451 const nsACString
& aDatabaseName
) {
2452 if (!connectionReady()) {
2453 return NS_ERROR_NOT_INITIALIZED
;
2455 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2456 if (NS_FAILED(rv
)) {
2460 // Bug 597215: Disk space is extremely limited on Android
2461 // so don't preallocate space. This is also not effective
2462 // on log structured file systems used by Android devices
2463 #if !defined(ANDROID) && !defined(MOZ_PLATFORM_MAEMO)
2464 // Don't preallocate if less than 500MiB is available.
2465 int64_t bytesAvailable
;
2466 rv
= mDatabaseFile
->GetDiskSpaceAvailable(&bytesAvailable
);
2467 NS_ENSURE_SUCCESS(rv
, rv
);
2468 if (bytesAvailable
< MIN_AVAILABLE_BYTES_PER_CHUNKED_GROWTH
) {
2469 return NS_ERROR_FILE_TOO_BIG
;
2472 int srv
= ::sqlite3_file_control(
2474 aDatabaseName
.Length() ? nsPromiseFlatCString(aDatabaseName
).get()
2476 SQLITE_FCNTL_CHUNK_SIZE
, &aChunkSize
);
2477 if (srv
== SQLITE_OK
) {
2478 mGrowthChunkSize
= aChunkSize
;
2484 int32_t Connection::RemovablePagesInFreeList(const nsACString
& aSchemaName
) {
2485 int32_t freeListPagesCount
= 0;
2486 if (!isConnectionReadyOnThisThread()) {
2487 MOZ_ASSERT(false, "Database connection is not ready");
2488 return freeListPagesCount
;
2491 nsAutoCString
query(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA ");
2492 query
.Append(aSchemaName
);
2493 query
.AppendLiteral(".freelist_count");
2494 nsCOMPtr
<mozIStorageStatement
> stmt
;
2495 DebugOnly
<nsresult
> rv
= CreateStatement(query
, getter_AddRefs(stmt
));
2496 MOZ_ASSERT(NS_SUCCEEDED(rv
));
2497 bool hasResult
= false;
2498 if (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
2499 freeListPagesCount
= stmt
->AsInt32(0);
2502 // If there's no chunk size set, any page is good to be removed.
2503 if (mGrowthChunkSize
== 0 || freeListPagesCount
== 0) {
2504 return freeListPagesCount
;
2508 nsAutoCString
query(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA ");
2509 query
.Append(aSchemaName
);
2510 query
.AppendLiteral(".page_size");
2511 nsCOMPtr
<mozIStorageStatement
> stmt
;
2512 DebugOnly
<nsresult
> rv
= CreateStatement(query
, getter_AddRefs(stmt
));
2513 MOZ_ASSERT(NS_SUCCEEDED(rv
));
2514 bool hasResult
= false;
2515 if (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
2516 pageSize
= stmt
->AsInt32(0);
2518 MOZ_ASSERT(false, "Couldn't get page_size");
2522 return std::max(0, freeListPagesCount
- (mGrowthChunkSize
/ pageSize
));
2526 Connection::EnableModule(const nsACString
& aModuleName
) {
2527 if (!connectionReady()) {
2528 return NS_ERROR_NOT_INITIALIZED
;
2530 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2531 if (NS_FAILED(rv
)) {
2535 for (auto& gModule
: gModules
) {
2536 struct Module
* m
= &gModule
;
2537 if (aModuleName
.Equals(m
->name
)) {
2538 int srv
= m
->registerFunc(mDBConn
, m
->name
);
2539 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2545 return NS_ERROR_FAILURE
;
2548 // Implemented in TelemetryVFS.cpp
2549 already_AddRefed
<QuotaObject
> GetQuotaObjectForFile(sqlite3_file
* pFile
);
2552 Connection::GetQuotaObjects(QuotaObject
** aDatabaseQuotaObject
,
2553 QuotaObject
** aJournalQuotaObject
) {
2554 MOZ_ASSERT(aDatabaseQuotaObject
);
2555 MOZ_ASSERT(aJournalQuotaObject
);
2557 if (!connectionReady()) {
2558 return NS_ERROR_NOT_INITIALIZED
;
2560 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2561 if (NS_FAILED(rv
)) {
2566 int srv
= ::sqlite3_file_control(mDBConn
, nullptr, SQLITE_FCNTL_FILE_POINTER
,
2568 if (srv
!= SQLITE_OK
) {
2569 return convertResultCode(srv
);
2572 RefPtr
<QuotaObject
> databaseQuotaObject
= GetQuotaObjectForFile(file
);
2573 if (NS_WARN_IF(!databaseQuotaObject
)) {
2574 return NS_ERROR_FAILURE
;
2577 srv
= ::sqlite3_file_control(mDBConn
, nullptr, SQLITE_FCNTL_JOURNAL_POINTER
,
2579 if (srv
!= SQLITE_OK
) {
2580 return convertResultCode(srv
);
2583 RefPtr
<QuotaObject
> journalQuotaObject
= GetQuotaObjectForFile(file
);
2584 if (NS_WARN_IF(!journalQuotaObject
)) {
2585 return NS_ERROR_FAILURE
;
2588 databaseQuotaObject
.forget(aDatabaseQuotaObject
);
2589 journalQuotaObject
.forget(aJournalQuotaObject
);
2593 SQLiteMutex
& Connection::GetSharedDBMutex() { return sharedDBMutex
; }
2595 uint32_t Connection::GetTransactionNestingLevel(
2596 const mozilla::storage::SQLiteMutexAutoLock
& aProofOfLock
) {
2597 return mTransactionNestingLevel
;
2600 uint32_t Connection::IncreaseTransactionNestingLevel(
2601 const mozilla::storage::SQLiteMutexAutoLock
& aProofOfLock
) {
2602 return ++mTransactionNestingLevel
;
2605 uint32_t Connection::DecreaseTransactionNestingLevel(
2606 const mozilla::storage::SQLiteMutexAutoLock
& aProofOfLock
) {
2607 return --mTransactionNestingLevel
;
2610 } // namespace mozilla::storage