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 "nsThreadUtils.h"
12 #include "nsIFileURL.h"
13 #include "nsIXPConnect.h"
14 #include "mozilla/Telemetry.h"
15 #include "mozilla/Mutex.h"
16 #include "mozilla/CondVar.h"
17 #include "mozilla/Attributes.h"
18 #include "mozilla/ErrorNames.h"
19 #include "mozilla/Unused.h"
20 #include "mozilla/dom/quota/QuotaObject.h"
21 #include "mozilla/ScopeExit.h"
22 #include "mozilla/SpinEventLoopUntil.h"
23 #include "mozilla/StaticPrefs_storage.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"
42 #include "mozilla/Logging.h"
43 #include "mozilla/Printf.h"
44 #include "mozilla/ProfilerLabels.h"
45 #include "nsProxyRelease.h"
46 #include "nsURLHelper.h"
50 #define MIN_AVAILABLE_BYTES_PER_CHUNKED_GROWTH 524288000 // 500 MiB
52 // Maximum size of the pages cache per connection.
53 #define MAX_CACHE_SIZE_KIBIBYTES 2048 // 2 MiB
55 mozilla::LazyLogModule
gStorageLog("mozStorage");
57 // Checks that the protected code is running on the main-thread only if the
58 // connection was also opened on it.
60 # define CHECK_MAINTHREAD_ABUSE() \
62 nsCOMPtr<nsIThread> mainThread = do_GetMainThread(); \
63 NS_WARNING_ASSERTION( \
64 threadOpenedOn == mainThread || !NS_IsMainThread(), \
65 "Using Storage synchronous API on main-thread, but " \
66 "the connection was " \
67 "opened on another thread."); \
70 # define CHECK_MAINTHREAD_ABUSE() \
75 namespace mozilla::storage
{
77 using mozilla::dom::quota::QuotaObject
;
78 using mozilla::Telemetry::AccumulateCategoricalKeyed
;
79 using mozilla::Telemetry::LABELS_SQLITE_STORE_OPEN
;
80 using mozilla::Telemetry::LABELS_SQLITE_STORE_QUERY
;
82 const char* GetTelemetryVFSName(bool);
83 const char* GetObfuscatingVFSName();
87 int nsresultToSQLiteResult(nsresult aXPCOMResultCode
) {
88 if (NS_SUCCEEDED(aXPCOMResultCode
)) {
92 switch (aXPCOMResultCode
) {
93 case NS_ERROR_FILE_CORRUPTED
:
94 return SQLITE_CORRUPT
;
95 case NS_ERROR_FILE_ACCESS_DENIED
:
96 return SQLITE_CANTOPEN
;
97 case NS_ERROR_STORAGE_BUSY
:
99 case NS_ERROR_FILE_IS_LOCKED
:
100 return SQLITE_LOCKED
;
101 case NS_ERROR_FILE_READ_ONLY
:
102 return SQLITE_READONLY
;
103 case NS_ERROR_STORAGE_IOERR
:
105 case NS_ERROR_FILE_NO_DEVICE_SPACE
:
107 case NS_ERROR_OUT_OF_MEMORY
:
109 case NS_ERROR_UNEXPECTED
:
110 return SQLITE_MISUSE
;
113 case NS_ERROR_STORAGE_CONSTRAINT
:
114 return SQLITE_CONSTRAINT
;
119 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Must return in switch above!");
122 ////////////////////////////////////////////////////////////////////////////////
123 //// Variant Specialization Functions (variantToSQLiteT)
125 int sqlite3_T_int(sqlite3_context
* aCtx
, int aValue
) {
126 ::sqlite3_result_int(aCtx
, aValue
);
130 int sqlite3_T_int64(sqlite3_context
* aCtx
, sqlite3_int64 aValue
) {
131 ::sqlite3_result_int64(aCtx
, aValue
);
135 int sqlite3_T_double(sqlite3_context
* aCtx
, double aValue
) {
136 ::sqlite3_result_double(aCtx
, aValue
);
140 int sqlite3_T_text(sqlite3_context
* aCtx
, const nsCString
& aValue
) {
141 ::sqlite3_result_text(aCtx
, aValue
.get(), aValue
.Length(), SQLITE_TRANSIENT
);
145 int sqlite3_T_text16(sqlite3_context
* aCtx
, const nsString
& aValue
) {
146 ::sqlite3_result_text16(
148 aValue
.Length() * sizeof(char16_t
), // Number of bytes.
153 int sqlite3_T_null(sqlite3_context
* aCtx
) {
154 ::sqlite3_result_null(aCtx
);
158 int sqlite3_T_blob(sqlite3_context
* aCtx
, const void* aData
, int aSize
) {
159 ::sqlite3_result_blob(aCtx
, aData
, aSize
, free
);
163 #include "variantToSQLiteT_impl.h"
165 ////////////////////////////////////////////////////////////////////////////////
170 int (*registerFunc
)(sqlite3
*, const char*);
173 Module gModules
[] = {{"filesystem", RegisterFileSystemModule
}};
175 ////////////////////////////////////////////////////////////////////////////////
178 int tracefunc(unsigned aReason
, void* aClosure
, void* aP
, void* aX
) {
180 case SQLITE_TRACE_STMT
: {
181 // aP is a pointer to the prepared statement.
182 sqlite3_stmt
* stmt
= static_cast<sqlite3_stmt
*>(aP
);
183 // aX is a pointer to a string containing the unexpanded SQL or a comment,
184 // starting with "--"" in case of a trigger.
185 char* expanded
= static_cast<char*>(aX
);
186 // Simulate what sqlite_trace was doing.
187 if (!::strncmp(expanded
, "--", 2)) {
188 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
189 ("TRACE_STMT on %p: '%s'", aClosure
, expanded
));
191 char* sql
= ::sqlite3_expanded_sql(stmt
);
192 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
193 ("TRACE_STMT on %p: '%s'", aClosure
, sql
));
198 case SQLITE_TRACE_PROFILE
: {
199 // aX is pointer to a 64bit integer containing nanoseconds it took to
200 // execute the last command.
201 sqlite_int64 time
= *(static_cast<sqlite_int64
*>(aX
)) / 1000000;
203 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
204 ("TRACE_TIME on %p: %lldms", aClosure
, time
));
212 void basicFunctionHelper(sqlite3_context
* aCtx
, int aArgc
,
213 sqlite3_value
** aArgv
) {
214 void* userData
= ::sqlite3_user_data(aCtx
);
216 mozIStorageFunction
* func
= static_cast<mozIStorageFunction
*>(userData
);
218 RefPtr
<ArgValueArray
> arguments(new ArgValueArray(aArgc
, aArgv
));
219 if (!arguments
) return;
221 nsCOMPtr
<nsIVariant
> result
;
222 nsresult rv
= func
->OnFunctionCall(arguments
, getter_AddRefs(result
));
224 nsAutoCString errorMessage
;
225 GetErrorName(rv
, errorMessage
);
226 errorMessage
.InsertLiteral("User function returned ", 0);
227 errorMessage
.Append('!');
229 NS_WARNING(errorMessage
.get());
231 ::sqlite3_result_error(aCtx
, errorMessage
.get(), -1);
232 ::sqlite3_result_error_code(aCtx
, nsresultToSQLiteResult(rv
));
235 int retcode
= variantToSQLiteT(aCtx
, result
);
236 if (retcode
!= SQLITE_OK
) {
237 NS_WARNING("User function returned invalid data type!");
238 ::sqlite3_result_error(aCtx
, "User function returned invalid data type",
244 * This code is heavily based on the sample at:
245 * http://www.sqlite.org/unlock_notify.html
247 class UnlockNotification
{
250 : mMutex("UnlockNotification mMutex"),
251 mCondVar(mMutex
, "UnlockNotification condVar"),
255 MutexAutoLock
lock(mMutex
);
257 (void)mCondVar
.Wait();
262 MutexAutoLock
lock(mMutex
);
264 (void)mCondVar
.Notify();
273 void UnlockNotifyCallback(void** aArgs
, int aArgsSize
) {
274 for (int i
= 0; i
< aArgsSize
; i
++) {
275 UnlockNotification
* notification
=
276 static_cast<UnlockNotification
*>(aArgs
[i
]);
277 notification
->Signal();
281 int WaitForUnlockNotify(sqlite3
* aDatabase
) {
282 UnlockNotification notification
;
284 ::sqlite3_unlock_notify(aDatabase
, UnlockNotifyCallback
, ¬ification
);
285 MOZ_ASSERT(srv
== SQLITE_LOCKED
|| srv
== SQLITE_OK
);
286 if (srv
== SQLITE_OK
) {
293 ////////////////////////////////////////////////////////////////////////////////
296 class AsyncCloseConnection final
: public Runnable
{
298 AsyncCloseConnection(Connection
* aConnection
, sqlite3
* aNativeConnection
,
299 nsIRunnable
* aCallbackEvent
)
300 : Runnable("storage::AsyncCloseConnection"),
301 mConnection(aConnection
),
302 mNativeConnection(aNativeConnection
),
303 mCallbackEvent(aCallbackEvent
) {}
305 NS_IMETHOD
Run() override
{
306 // This code is executed on the background thread
307 MOZ_ASSERT(NS_GetCurrentThread() != mConnection
->threadOpenedOn
);
309 nsCOMPtr
<nsIRunnable
> event
=
310 NewRunnableMethod("storage::Connection::shutdownAsyncThread",
311 mConnection
, &Connection::shutdownAsyncThread
);
312 MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(event
));
315 (void)mConnection
->internalClose(mNativeConnection
);
318 if (mCallbackEvent
) {
319 nsCOMPtr
<nsIThread
> thread
;
320 (void)NS_GetMainThread(getter_AddRefs(thread
));
321 (void)thread
->Dispatch(mCallbackEvent
, NS_DISPATCH_NORMAL
);
327 ~AsyncCloseConnection() override
{
328 NS_ReleaseOnMainThread("AsyncCloseConnection::mConnection",
329 mConnection
.forget());
330 NS_ReleaseOnMainThread("AsyncCloseConnection::mCallbackEvent",
331 mCallbackEvent
.forget());
335 RefPtr
<Connection
> mConnection
;
336 sqlite3
* mNativeConnection
;
337 nsCOMPtr
<nsIRunnable
> mCallbackEvent
;
341 * An event used to initialize the clone of a connection.
343 * Must be executed on the clone's async execution thread.
345 class AsyncInitializeClone final
: public Runnable
{
348 * @param aConnection The connection being cloned.
349 * @param aClone The clone.
350 * @param aReadOnly If |true|, the clone is read only.
351 * @param aCallback A callback to trigger once initialization
352 * is complete. This event will be called on
353 * aClone->threadOpenedOn.
355 AsyncInitializeClone(Connection
* aConnection
, Connection
* aClone
,
356 const bool aReadOnly
,
357 mozIStorageCompletionCallback
* aCallback
)
358 : Runnable("storage::AsyncInitializeClone"),
359 mConnection(aConnection
),
361 mReadOnly(aReadOnly
),
362 mCallback(aCallback
) {
363 MOZ_ASSERT(NS_IsMainThread());
366 NS_IMETHOD
Run() override
{
367 MOZ_ASSERT(!NS_IsMainThread());
368 nsresult rv
= mConnection
->initializeClone(mClone
, mReadOnly
);
370 return Dispatch(rv
, nullptr);
372 return Dispatch(NS_OK
,
373 NS_ISUPPORTS_CAST(mozIStorageAsyncConnection
*, mClone
));
377 nsresult
Dispatch(nsresult aResult
, nsISupports
* aValue
) {
378 RefPtr
<CallbackComplete
> event
=
379 new CallbackComplete(aResult
, aValue
, mCallback
.forget());
380 return mClone
->threadOpenedOn
->Dispatch(event
, NS_DISPATCH_NORMAL
);
383 ~AsyncInitializeClone() override
{
384 nsCOMPtr
<nsIThread
> thread
;
385 DebugOnly
<nsresult
> rv
= NS_GetMainThread(getter_AddRefs(thread
));
386 MOZ_ASSERT(NS_SUCCEEDED(rv
));
388 // Handle ambiguous nsISupports inheritance.
389 NS_ProxyRelease("AsyncInitializeClone::mConnection", thread
,
390 mConnection
.forget());
391 NS_ProxyRelease("AsyncInitializeClone::mClone", thread
, mClone
.forget());
393 // Generally, the callback will be released by CallbackComplete.
394 // However, if for some reason Run() is not executed, we still
395 // need to ensure that it is released here.
396 NS_ProxyRelease("AsyncInitializeClone::mCallback", thread
,
400 RefPtr
<Connection
> mConnection
;
401 RefPtr
<Connection
> mClone
;
402 const bool mReadOnly
;
403 nsCOMPtr
<mozIStorageCompletionCallback
> mCallback
;
407 * A listener for async connection closing.
409 class CloseListener final
: public mozIStorageCompletionCallback
{
412 CloseListener() : mClosed(false) {}
414 NS_IMETHOD
Complete(nsresult
, nsISupports
*) override
{
422 ~CloseListener() = default;
425 NS_IMPL_ISUPPORTS(CloseListener
, mozIStorageCompletionCallback
)
429 ////////////////////////////////////////////////////////////////////////////////
432 Connection::Connection(Service
* aService
, int aFlags
,
433 ConnectionOperation aSupportedOperations
,
434 bool aIgnoreLockingMode
)
435 : sharedAsyncExecutionMutex("Connection::sharedAsyncExecutionMutex"),
436 sharedDBMutex("Connection::sharedDBMutex"),
437 threadOpenedOn(do_GetCurrentThread()),
439 mAsyncExecutionThreadShuttingDown(false),
440 mConnectionClosed(false),
441 mDefaultTransactionType(mozIStorageConnection::TRANSACTION_DEFERRED
),
443 mProgressHandler(nullptr),
445 mIgnoreLockingMode(aIgnoreLockingMode
),
446 mStorageService(aService
),
447 mSupportedOperations(aSupportedOperations
),
448 mTransactionNestingLevel(0) {
449 MOZ_ASSERT(!mIgnoreLockingMode
|| mFlags
& SQLITE_OPEN_READONLY
,
450 "Can't ignore locking for a non-readonly connection!");
451 mStorageService
->registerConnection(this);
454 Connection::~Connection() {
455 // Failsafe Close() occurs in our custom Release method because of
456 // complications related to Close() potentially invoking AsyncClose() which
457 // will increment our refcount.
458 MOZ_ASSERT(!mAsyncExecutionThread
,
459 "The async thread has not been shutdown properly!");
462 NS_IMPL_ADDREF(Connection
)
464 NS_INTERFACE_MAP_BEGIN(Connection
)
465 NS_INTERFACE_MAP_ENTRY(mozIStorageAsyncConnection
)
466 NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor
)
467 NS_INTERFACE_MAP_ENTRY(mozIStorageConnection
)
468 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports
, mozIStorageConnection
)
471 // This is identical to what NS_IMPL_RELEASE provides, but with the
472 // extra |1 == count| case.
473 NS_IMETHODIMP_(MozExternalRefCountType
) Connection::Release(void) {
474 MOZ_ASSERT(0 != mRefCnt
, "dup release");
475 nsrefcnt count
= --mRefCnt
;
476 NS_LOG_RELEASE(this, count
, "Connection");
478 // If the refcount went to 1, the single reference must be from
479 // gService->mConnections (in class |Service|). And the code calling
480 // Release is either:
481 // - The "user" code that had created the connection, releasing on any
483 // - One of Service's getConnections() callers had acquired a strong
484 // reference to the Connection that out-lived the last "user" reference,
485 // and now that just got dropped. Note that this reference could be
486 // getting dropped on the main thread or Connection->threadOpenedOn
487 // (because of the NewRunnableMethod used by minimizeMemory).
489 // Either way, we should now perform our failsafe Close() and unregister.
490 // However, we only want to do this once, and the reality is that our
491 // refcount could go back up above 1 and down again at any time if we are
492 // off the main thread and getConnections() gets called on the main thread,
493 // so we use an atomic here to do this exactly once.
494 if (mDestroying
.compareExchange(false, true)) {
495 // Close the connection, dispatching to the opening thread if we're not
496 // on that thread already and that thread is still accepting runnables.
497 // We do this because it's possible we're on the main thread because of
498 // getConnections(), and we REALLY don't want to transfer I/O to the main
499 // thread if we can avoid it.
500 if (threadOpenedOn
->IsOnCurrentThread()) {
501 // This could cause SpinningSynchronousClose() to be invoked and AddRef
502 // triggered for AsyncCloseConnection's strong ref if the conn was ever
503 // use for async purposes. (Main-thread only, though.)
504 Unused
<< synchronousClose();
506 nsCOMPtr
<nsIRunnable
> event
=
507 NewRunnableMethod("storage::Connection::synchronousClose", this,
508 &Connection::synchronousClose
);
510 threadOpenedOn
->Dispatch(event
.forget(), NS_DISPATCH_NORMAL
))) {
511 // The target thread was dead and so we've just leaked our runnable.
512 // This should not happen because our non-main-thread consumers should
513 // be explicitly closing their connections, not relying on us to close
514 // them for them. (It's okay to let a statement go out of scope for
515 // automatic cleanup, but not a Connection.)
517 "Leaked Connection::synchronousClose(), ownership fail.");
518 Unused
<< synchronousClose();
522 // This will drop its strong reference right here, right now.
523 mStorageService
->unregisterConnection(this);
525 } else if (0 == count
) {
526 mRefCnt
= 1; /* stabilize */
527 #if 0 /* enable this to find non-threadsafe destructors: */
528 NS_ASSERT_OWNINGTHREAD(Connection
);
536 int32_t Connection::getSqliteRuntimeStatus(int32_t aStatusOption
,
537 int32_t* aMaxValue
) {
538 MOZ_ASSERT(connectionReady(), "A connection must exist at this point");
539 int curr
= 0, max
= 0;
541 ::sqlite3_db_status(mDBConn
, aStatusOption
, &curr
, &max
, 0);
542 MOZ_ASSERT(NS_SUCCEEDED(convertResultCode(rc
)));
543 if (aMaxValue
) *aMaxValue
= max
;
547 nsIEventTarget
* Connection::getAsyncExecutionTarget() {
548 NS_ENSURE_TRUE(threadOpenedOn
== NS_GetCurrentThread(), nullptr);
550 // Don't return the asynchronous thread if we are shutting down.
551 if (mAsyncExecutionThreadShuttingDown
) {
555 // Create the async thread if there's none yet.
556 if (!mAsyncExecutionThread
) {
557 static nsThreadPoolNaming naming
;
558 nsresult rv
= NS_NewNamedThread(naming
.GetNextThreadName("mozStorage"),
559 getter_AddRefs(mAsyncExecutionThread
));
561 NS_WARNING("Failed to create async thread.");
564 mAsyncExecutionThread
->SetNameForWakeupTelemetry("mozStorage (all)"_ns
);
567 return mAsyncExecutionThread
;
570 void Connection::RecordOpenStatus(nsresult rv
) {
571 nsCString histogramKey
= mTelemetryFilename
;
573 if (histogramKey
.IsEmpty()) {
574 histogramKey
.AssignLiteral("unknown");
577 if (NS_SUCCEEDED(rv
)) {
578 AccumulateCategoricalKeyed(histogramKey
, LABELS_SQLITE_STORE_OPEN::success
);
583 case NS_ERROR_FILE_CORRUPTED
:
584 AccumulateCategoricalKeyed(histogramKey
,
585 LABELS_SQLITE_STORE_OPEN::corrupt
);
587 case NS_ERROR_STORAGE_IOERR
:
588 AccumulateCategoricalKeyed(histogramKey
,
589 LABELS_SQLITE_STORE_OPEN::diskio
);
591 case NS_ERROR_FILE_ACCESS_DENIED
:
592 case NS_ERROR_FILE_IS_LOCKED
:
593 case NS_ERROR_FILE_READ_ONLY
:
594 AccumulateCategoricalKeyed(histogramKey
,
595 LABELS_SQLITE_STORE_OPEN::access
);
597 case NS_ERROR_FILE_NO_DEVICE_SPACE
:
598 AccumulateCategoricalKeyed(histogramKey
,
599 LABELS_SQLITE_STORE_OPEN::diskspace
);
602 AccumulateCategoricalKeyed(histogramKey
,
603 LABELS_SQLITE_STORE_OPEN::failure
);
607 void Connection::RecordQueryStatus(int srv
) {
608 nsCString histogramKey
= mTelemetryFilename
;
610 if (histogramKey
.IsEmpty()) {
611 histogramKey
.AssignLiteral("unknown");
619 // Note that these are returned when we intentionally cancel a statement so
620 // they aren't indicating a failure.
622 case SQLITE_INTERRUPT
:
623 AccumulateCategoricalKeyed(histogramKey
,
624 LABELS_SQLITE_STORE_QUERY::success
);
628 AccumulateCategoricalKeyed(histogramKey
,
629 LABELS_SQLITE_STORE_QUERY::corrupt
);
632 case SQLITE_CANTOPEN
:
634 case SQLITE_READONLY
:
635 AccumulateCategoricalKeyed(histogramKey
,
636 LABELS_SQLITE_STORE_QUERY::access
);
640 AccumulateCategoricalKeyed(histogramKey
,
641 LABELS_SQLITE_STORE_QUERY::diskio
);
645 AccumulateCategoricalKeyed(histogramKey
,
646 LABELS_SQLITE_STORE_OPEN::diskspace
);
648 case SQLITE_CONSTRAINT
:
650 case SQLITE_MISMATCH
:
652 AccumulateCategoricalKeyed(histogramKey
,
653 LABELS_SQLITE_STORE_OPEN::misuse
);
656 AccumulateCategoricalKeyed(histogramKey
, LABELS_SQLITE_STORE_OPEN::busy
);
659 AccumulateCategoricalKeyed(histogramKey
,
660 LABELS_SQLITE_STORE_QUERY::failure
);
664 nsresult
Connection::initialize(const nsACString
& aStorageKey
,
665 const nsACString
& aName
) {
666 MOZ_ASSERT(aStorageKey
.Equals(kMozStorageMemoryStorageKey
));
667 NS_ASSERTION(!connectionReady(),
668 "Initialize called on already opened database!");
669 MOZ_ASSERT(!mIgnoreLockingMode
, "Can't ignore locking on an in-memory db.");
670 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
672 mStorageKey
= aStorageKey
;
675 // in memory database requested, sqlite uses a magic file name
677 const nsAutoCString path
=
678 mName
.IsEmpty() ? nsAutoCString(":memory:"_ns
)
679 : "file:"_ns
+ mName
+ "?mode=memory&cache=shared"_ns
;
681 mTelemetryFilename
.AssignLiteral(":memory:");
683 int srv
= ::sqlite3_open_v2(path
.get(), &mDBConn
, mFlags
,
684 GetTelemetryVFSName(true));
685 if (srv
!= SQLITE_OK
) {
687 nsresult rv
= convertResultCode(srv
);
688 RecordOpenStatus(rv
);
692 #ifdef MOZ_SQLITE_FTS3_TOKENIZER
694 ::sqlite3_db_config(mDBConn
, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, 1, 0);
695 MOZ_ASSERT(srv
== SQLITE_OK
,
696 "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
699 // Do not set mDatabaseFile or mFileURL here since this is a "memory"
702 nsresult rv
= initializeInternal();
703 RecordOpenStatus(rv
);
704 NS_ENSURE_SUCCESS(rv
, rv
);
709 nsresult
Connection::initialize(nsIFile
* aDatabaseFile
) {
710 NS_ASSERTION(aDatabaseFile
, "Passed null file!");
711 NS_ASSERTION(!connectionReady(),
712 "Initialize called on already opened database!");
713 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
715 // Do not set mFileURL here since this is database does not have an associated
717 mDatabaseFile
= aDatabaseFile
;
718 aDatabaseFile
->GetNativeLeafName(mTelemetryFilename
);
721 nsresult rv
= aDatabaseFile
->GetPath(path
);
722 NS_ENSURE_SUCCESS(rv
, rv
);
725 static const char* sIgnoreLockingVFS
= "win32-none";
727 static const char* sIgnoreLockingVFS
= "unix-none";
730 bool exclusive
= StaticPrefs::storage_sqlite_exclusiveLock_enabled();
732 if (mIgnoreLockingMode
) {
734 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
, mFlags
,
737 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
, mFlags
,
738 GetTelemetryVFSName(exclusive
));
739 if (exclusive
&& (srv
== SQLITE_LOCKED
|| srv
== SQLITE_BUSY
)) {
740 // Retry without trying to get an exclusive lock.
742 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
,
743 mFlags
, GetTelemetryVFSName(false));
746 if (srv
!= SQLITE_OK
) {
748 rv
= convertResultCode(srv
);
749 RecordOpenStatus(rv
);
753 rv
= initializeInternal();
755 (rv
== NS_ERROR_STORAGE_BUSY
|| rv
== NS_ERROR_FILE_IS_LOCKED
)) {
756 // Usually SQLite will fail to acquire an exclusive lock on opening, but in
757 // some cases it may successfully open the database and then lock on the
758 // first query execution. When initializeInternal fails it closes the
759 // connection, so we can try to restart it in non-exclusive mode.
760 srv
= ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path
).get(), &mDBConn
, mFlags
,
761 GetTelemetryVFSName(false));
762 if (srv
== SQLITE_OK
) {
763 rv
= initializeInternal();
767 RecordOpenStatus(rv
);
768 NS_ENSURE_SUCCESS(rv
, rv
);
773 nsresult
Connection::initialize(nsIFileURL
* aFileURL
,
774 const nsACString
& aTelemetryFilename
) {
775 NS_ASSERTION(aFileURL
, "Passed null file URL!");
776 NS_ASSERTION(!connectionReady(),
777 "Initialize called on already opened database!");
778 AUTO_PROFILER_LABEL("Connection::initialize", OTHER
);
780 nsCOMPtr
<nsIFile
> databaseFile
;
781 nsresult rv
= aFileURL
->GetFile(getter_AddRefs(databaseFile
));
782 NS_ENSURE_SUCCESS(rv
, rv
);
784 // Set both mDatabaseFile and mFileURL here.
786 mDatabaseFile
= databaseFile
;
788 if (!aTelemetryFilename
.IsEmpty()) {
789 mTelemetryFilename
= aTelemetryFilename
;
791 databaseFile
->GetNativeLeafName(mTelemetryFilename
);
795 rv
= aFileURL
->GetSpec(spec
);
796 NS_ENSURE_SUCCESS(rv
, rv
);
798 bool exclusive
= StaticPrefs::storage_sqlite_exclusiveLock_enabled();
800 // If there is a key specified, we need to use the obfuscating VFS.
802 rv
= aFileURL
->GetQuery(query
);
803 NS_ENSURE_SUCCESS(rv
, rv
);
804 const char* const vfs
=
805 URLParams::Parse(query
,
806 [](const nsAString
& aName
, const nsAString
& aValue
) {
807 return aName
.EqualsLiteral("key");
809 ? GetObfuscatingVFSName()
810 : GetTelemetryVFSName(exclusive
);
811 int srv
= ::sqlite3_open_v2(spec
.get(), &mDBConn
, mFlags
, vfs
);
812 if (srv
!= SQLITE_OK
) {
814 rv
= convertResultCode(srv
);
815 RecordOpenStatus(rv
);
819 rv
= initializeInternal();
820 RecordOpenStatus(rv
);
821 NS_ENSURE_SUCCESS(rv
, rv
);
826 nsresult
Connection::initializeInternal() {
828 auto guard
= MakeScopeExit([&]() { initializeFailed(); });
830 mConnectionClosed
= false;
832 #ifdef MOZ_SQLITE_FTS3_TOKENIZER
833 DebugOnly
<int> srv2
=
834 ::sqlite3_db_config(mDBConn
, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
, 1, 0);
835 MOZ_ASSERT(srv2
== SQLITE_OK
,
836 "SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
839 MOZ_ASSERT(!mTelemetryFilename
.IsEmpty(),
840 "A telemetry filename should have been set by now.");
842 // Properly wrap the database handle's mutex.
843 sharedDBMutex
.initWithMutex(sqlite3_db_mutex(mDBConn
));
845 // SQLite tracing can slow down queries (especially long queries)
846 // significantly. Don't trace unless the user is actively monitoring SQLite.
847 if (MOZ_LOG_TEST(gStorageLog
, LogLevel::Debug
)) {
848 ::sqlite3_trace_v2(mDBConn
, SQLITE_TRACE_STMT
| SQLITE_TRACE_PROFILE
,
852 gStorageLog
, LogLevel::Debug
,
853 ("Opening connection to '%s' (%p)", mTelemetryFilename
.get(), this));
856 int64_t pageSize
= Service::kDefaultPageSize
;
858 // Set page_size to the preferred default value. This is effective only if
859 // the database has just been created, otherwise, if the database does not
860 // use WAL journal mode, a VACUUM operation will updated its page_size.
861 nsAutoCString
pageSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
862 "PRAGMA page_size = ");
863 pageSizeQuery
.AppendInt(pageSize
);
864 int srv
= executeSql(mDBConn
, pageSizeQuery
.get());
865 if (srv
!= SQLITE_OK
) {
866 return convertResultCode(srv
);
869 // Setting the cache_size forces the database open, verifying if it is valid
870 // or corrupt. So this is executed regardless it being actually needed.
871 // The cache_size is calculated from the actual page_size, to save memory.
872 nsAutoCString
cacheSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
873 "PRAGMA cache_size = ");
874 cacheSizeQuery
.AppendInt(-MAX_CACHE_SIZE_KIBIBYTES
);
875 srv
= executeSql(mDBConn
, cacheSizeQuery
.get());
876 if (srv
!= SQLITE_OK
) {
877 return convertResultCode(srv
);
880 // Register our built-in SQL functions.
881 srv
= registerFunctions(mDBConn
);
882 if (srv
!= SQLITE_OK
) {
883 return convertResultCode(srv
);
886 // Register our built-in SQL collating sequences.
887 srv
= registerCollations(mDBConn
, mStorageService
);
888 if (srv
!= SQLITE_OK
) {
889 return convertResultCode(srv
);
892 // Set the default synchronous value. Each consumer can switch this
893 // accordingly to their needs.
895 // Android prefers synchronous = OFF for performance reasons.
896 Unused
<< ExecuteSimpleSQL("PRAGMA synchronous = OFF;"_ns
);
898 // Normal is the suggested value for WAL journals.
899 Unused
<< ExecuteSimpleSQL("PRAGMA synchronous = NORMAL;"_ns
);
902 // Initialization succeeded, we can stop guarding for failures.
907 nsresult
Connection::initializeOnAsyncThread(nsIFile
* aStorageFile
) {
908 MOZ_ASSERT(threadOpenedOn
!= NS_GetCurrentThread());
909 nsresult rv
= aStorageFile
910 ? initialize(aStorageFile
)
911 : initialize(kMozStorageMemoryStorageKey
, VoidCString());
913 // Shutdown the async thread, since initialization failed.
914 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
915 mAsyncExecutionThreadShuttingDown
= true;
916 nsCOMPtr
<nsIRunnable
> event
=
917 NewRunnableMethod("Connection::shutdownAsyncThread", this,
918 &Connection::shutdownAsyncThread
);
919 Unused
<< NS_DispatchToMainThread(event
);
924 void Connection::initializeFailed() {
926 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
927 mConnectionClosed
= true;
929 MOZ_ALWAYS_TRUE(::sqlite3_close(mDBConn
) == SQLITE_OK
);
931 sharedDBMutex
.destroy();
934 nsresult
Connection::databaseElementExists(
935 enum DatabaseElementType aElementType
, const nsACString
& aElementName
,
937 if (!connectionReady()) {
938 return NS_ERROR_NOT_AVAILABLE
;
940 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
945 // When constructing the query, make sure to SELECT the correct db's
946 // sqlite_master if the user is prefixing the element with a specific db. ex:
948 nsCString
query("SELECT name FROM (SELECT * FROM ");
949 nsDependentCSubstring element
;
950 int32_t ind
= aElementName
.FindChar('.');
951 if (ind
== kNotFound
) {
952 element
.Assign(aElementName
);
954 nsDependentCSubstring
db(Substring(aElementName
, 0, ind
+ 1));
955 element
.Assign(Substring(aElementName
, ind
+ 1, aElementName
.Length()));
959 "sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = "
962 switch (aElementType
) {
964 query
.AppendLiteral("index");
967 query
.AppendLiteral("table");
970 query
.AppendLiteral("' AND name ='");
971 query
.Append(element
);
975 int srv
= prepareStatement(mDBConn
, query
, &stmt
);
976 if (srv
!= SQLITE_OK
) {
977 RecordQueryStatus(srv
);
978 return convertResultCode(srv
);
981 srv
= stepStatement(mDBConn
, stmt
);
982 // we just care about the return value from step
983 (void)::sqlite3_finalize(stmt
);
985 RecordQueryStatus(srv
);
987 if (srv
== SQLITE_ROW
) {
991 if (srv
== SQLITE_DONE
) {
996 return convertResultCode(srv
);
999 bool Connection::findFunctionByInstance(mozIStorageFunction
* aInstance
) {
1000 sharedDBMutex
.assertCurrentThreadOwns();
1002 for (const auto& data
: mFunctions
.Values()) {
1003 if (data
.function
== aInstance
) {
1011 int Connection::sProgressHelper(void* aArg
) {
1012 Connection
* _this
= static_cast<Connection
*>(aArg
);
1013 return _this
->progressHandler();
1016 int Connection::progressHandler() {
1017 sharedDBMutex
.assertCurrentThreadOwns();
1018 if (mProgressHandler
) {
1020 nsresult rv
= mProgressHandler
->OnProgress(this, &result
);
1021 if (NS_FAILED(rv
)) return 0; // Don't break request
1022 return result
? 1 : 0;
1027 nsresult
Connection::setClosedState() {
1028 // Ensure that we are on the correct thread to close the database.
1029 bool onOpenedThread
;
1030 nsresult rv
= threadOpenedOn
->IsOnCurrentThread(&onOpenedThread
);
1031 NS_ENSURE_SUCCESS(rv
, rv
);
1032 if (!onOpenedThread
) {
1033 NS_ERROR("Must close the database on the thread that you opened it with!");
1034 return NS_ERROR_UNEXPECTED
;
1037 // Flag that we are shutting down the async thread, so that
1038 // getAsyncExecutionTarget knows not to expose/create the async thread.
1040 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1041 NS_ENSURE_FALSE(mAsyncExecutionThreadShuttingDown
, NS_ERROR_UNEXPECTED
);
1042 mAsyncExecutionThreadShuttingDown
= true;
1044 // Set the property to null before closing the connection, otherwise the
1045 // other functions in the module may try to use the connection after it is
1052 bool Connection::operationSupported(ConnectionOperation aOperationType
) {
1053 if (aOperationType
== ASYNCHRONOUS
) {
1054 // Async operations are supported for all connections, on any thread.
1057 // Sync operations are supported for sync connections (on any thread), and
1058 // async connections on a background thread.
1059 MOZ_ASSERT(aOperationType
== SYNCHRONOUS
);
1060 return mSupportedOperations
== SYNCHRONOUS
|| !NS_IsMainThread();
1063 nsresult
Connection::ensureOperationSupported(
1064 ConnectionOperation aOperationType
) {
1065 if (NS_WARN_IF(!operationSupported(aOperationType
))) {
1067 if (NS_IsMainThread()) {
1068 nsCOMPtr
<nsIXPConnect
> xpc
= nsIXPConnect::XPConnect();
1069 Unused
<< xpc
->DebugDumpJSStack(false, false, false);
1073 "Don't use async connections synchronously on the main thread");
1074 return NS_ERROR_NOT_AVAILABLE
;
1079 bool Connection::isConnectionReadyOnThisThread() {
1080 MOZ_ASSERT_IF(connectionReady(), !mConnectionClosed
);
1081 if (mAsyncExecutionThread
&& mAsyncExecutionThread
->IsOnCurrentThread()) {
1084 return connectionReady();
1087 bool Connection::isClosing() {
1088 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1089 return mAsyncExecutionThreadShuttingDown
&& !mConnectionClosed
;
1092 bool Connection::isClosed() {
1093 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1094 return mConnectionClosed
;
1097 bool Connection::isClosed(MutexAutoLock
& lock
) { return mConnectionClosed
; }
1099 bool Connection::isAsyncExecutionThreadAvailable() {
1100 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1101 return mAsyncExecutionThread
&& !mAsyncExecutionThreadShuttingDown
;
1104 void Connection::shutdownAsyncThread() {
1105 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1106 MOZ_ASSERT(mAsyncExecutionThread
);
1107 MOZ_ASSERT(mAsyncExecutionThreadShuttingDown
);
1109 MOZ_ALWAYS_SUCCEEDS(mAsyncExecutionThread
->Shutdown());
1110 mAsyncExecutionThread
= nullptr;
1113 nsresult
Connection::internalClose(sqlite3
* aNativeConnection
) {
1115 { // Make sure we have marked our async thread as shutting down.
1116 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1117 MOZ_ASSERT(mAsyncExecutionThreadShuttingDown
,
1118 "Did not call setClosedState!");
1119 MOZ_ASSERT(!isClosed(lockedScope
), "Unexpected closed state");
1123 if (MOZ_LOG_TEST(gStorageLog
, LogLevel::Debug
)) {
1124 nsAutoCString
leafName(":memory");
1125 if (mDatabaseFile
) (void)mDatabaseFile
->GetNativeLeafName(leafName
);
1126 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
1127 ("Closing connection to '%s'", leafName
.get()));
1130 // At this stage, we may still have statements that need to be
1131 // finalized. Attempt to close the database connection. This will
1132 // always disconnect any virtual tables and cleanly finalize their
1133 // internal statements. Once this is done, closing may fail due to
1134 // unfinalized client statements, in which case we need to finalize
1135 // these statements and close again.
1137 MutexAutoLock
lockedScope(sharedAsyncExecutionMutex
);
1138 mConnectionClosed
= true;
1141 // Nothing else needs to be done if we don't have a connection here.
1142 if (!aNativeConnection
) return NS_OK
;
1144 int srv
= ::sqlite3_close(aNativeConnection
);
1146 if (srv
== SQLITE_BUSY
) {
1148 // Nothing else should change the connection or statements status until we
1150 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1151 // We still have non-finalized statements. Finalize them.
1152 sqlite3_stmt
* stmt
= nullptr;
1153 while ((stmt
= ::sqlite3_next_stmt(aNativeConnection
, stmt
))) {
1154 MOZ_LOG(gStorageLog
, LogLevel::Debug
,
1155 ("Auto-finalizing SQL statement '%s' (%p)", ::sqlite3_sql(stmt
),
1159 SmprintfPointer msg
= ::mozilla::Smprintf(
1160 "SQL statement '%s' (%p) should have been finalized before closing "
1162 ::sqlite3_sql(stmt
), stmt
);
1163 NS_WARNING(msg
.get());
1166 srv
= ::sqlite3_finalize(stmt
);
1169 if (srv
!= SQLITE_OK
) {
1170 SmprintfPointer msg
= ::mozilla::Smprintf(
1171 "Could not finalize SQL statement (%p)", stmt
);
1172 NS_WARNING(msg
.get());
1176 // Ensure that the loop continues properly, whether closing has
1177 // succeeded or not.
1178 if (srv
== SQLITE_OK
) {
1182 // Scope exiting will unlock the mutex before we invoke sqlite3_close()
1183 // again, since Sqlite will try to acquire it.
1186 // Now that all statements have been finalized, we
1187 // should be able to close.
1188 srv
= ::sqlite3_close(aNativeConnection
);
1190 "Had to forcibly close the database connection because not all "
1191 "the statements have been finalized.");
1194 if (srv
== SQLITE_OK
) {
1195 sharedDBMutex
.destroy();
1198 "sqlite3_close failed. There are probably outstanding "
1199 "statements that are listed above!");
1202 return convertResultCode(srv
);
1205 nsCString
Connection::getFilename() { return mTelemetryFilename
; }
1207 int Connection::stepStatement(sqlite3
* aNativeConnection
,
1208 sqlite3_stmt
* aStatement
) {
1209 MOZ_ASSERT(aStatement
);
1211 AUTO_PROFILER_LABEL_DYNAMIC_CSTR("Connection::stepStatement", OTHER
,
1212 ::sqlite3_sql(aStatement
));
1214 bool checkedMainThread
= false;
1215 TimeStamp startTime
= TimeStamp::Now();
1217 // The connection may have been closed if the executing statement has been
1218 // created and cached after a call to asyncClose() but before the actual
1219 // sqlite3_close(). This usually happens when other tasks using cached
1220 // statements are asynchronously scheduled for execution and any of them ends
1221 // up after asyncClose. See bug 728653 for details.
1222 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1224 (void)::sqlite3_extended_result_codes(aNativeConnection
, 1);
1227 while ((srv
= ::sqlite3_step(aStatement
)) == SQLITE_LOCKED_SHAREDCACHE
) {
1228 if (!checkedMainThread
) {
1229 checkedMainThread
= true;
1230 if (::NS_IsMainThread()) {
1231 NS_WARNING("We won't allow blocking on the main thread!");
1236 srv
= WaitForUnlockNotify(aNativeConnection
);
1237 if (srv
!= SQLITE_OK
) {
1241 ::sqlite3_reset(aStatement
);
1244 // Report very slow SQL statements to Telemetry
1245 TimeDuration duration
= TimeStamp::Now() - startTime
;
1246 const uint32_t threshold
= NS_IsMainThread()
1247 ? Telemetry::kSlowSQLThresholdForMainThread
1248 : Telemetry::kSlowSQLThresholdForHelperThreads
;
1249 if (duration
.ToMilliseconds() >= threshold
) {
1250 nsDependentCString
statementString(::sqlite3_sql(aStatement
));
1251 Telemetry::RecordSlowSQLStatement(statementString
, mTelemetryFilename
,
1252 duration
.ToMilliseconds());
1255 (void)::sqlite3_extended_result_codes(aNativeConnection
, 0);
1256 // Drop off the extended result bits of the result code.
1260 int Connection::prepareStatement(sqlite3
* aNativeConnection
,
1261 const nsCString
& aSQL
, sqlite3_stmt
** _stmt
) {
1262 // We should not even try to prepare statements after the connection has
1264 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1266 bool checkedMainThread
= false;
1268 (void)::sqlite3_extended_result_codes(aNativeConnection
, 1);
1271 while ((srv
= ::sqlite3_prepare_v2(aNativeConnection
, aSQL
.get(), -1, _stmt
,
1272 nullptr)) == SQLITE_LOCKED_SHAREDCACHE
) {
1273 if (!checkedMainThread
) {
1274 checkedMainThread
= true;
1275 if (::NS_IsMainThread()) {
1276 NS_WARNING("We won't allow blocking on the main thread!");
1281 srv
= WaitForUnlockNotify(aNativeConnection
);
1282 if (srv
!= SQLITE_OK
) {
1287 if (srv
!= SQLITE_OK
) {
1289 warnMsg
.AppendLiteral("The SQL statement '");
1290 warnMsg
.Append(aSQL
);
1291 warnMsg
.AppendLiteral("' could not be compiled due to an error: ");
1292 warnMsg
.Append(::sqlite3_errmsg(aNativeConnection
));
1295 NS_WARNING(warnMsg
.get());
1297 MOZ_LOG(gStorageLog
, LogLevel::Error
, ("%s", warnMsg
.get()));
1300 (void)::sqlite3_extended_result_codes(aNativeConnection
, 0);
1301 // Drop off the extended result bits of the result code.
1302 int rc
= srv
& 0xFF;
1303 // sqlite will return OK on a comment only string and set _stmt to nullptr.
1304 // The callers of this function are used to only checking the return value,
1305 // so it is safer to return an error code.
1306 if (rc
== SQLITE_OK
&& *_stmt
== nullptr) {
1307 return SQLITE_MISUSE
;
1313 int Connection::executeSql(sqlite3
* aNativeConnection
, const char* aSqlString
) {
1314 if (!isConnectionReadyOnThisThread()) return SQLITE_MISUSE
;
1316 AUTO_PROFILER_LABEL_DYNAMIC_CSTR("Connection::executeSql", OTHER
, aSqlString
);
1318 TimeStamp startTime
= TimeStamp::Now();
1320 ::sqlite3_exec(aNativeConnection
, aSqlString
, nullptr, nullptr, nullptr);
1321 RecordQueryStatus(srv
);
1323 // Report very slow SQL statements to Telemetry
1324 TimeDuration duration
= TimeStamp::Now() - startTime
;
1325 const uint32_t threshold
= NS_IsMainThread()
1326 ? Telemetry::kSlowSQLThresholdForMainThread
1327 : Telemetry::kSlowSQLThresholdForHelperThreads
;
1328 if (duration
.ToMilliseconds() >= threshold
) {
1329 nsDependentCString
statementString(aSqlString
);
1330 Telemetry::RecordSlowSQLStatement(statementString
, mTelemetryFilename
,
1331 duration
.ToMilliseconds());
1337 ////////////////////////////////////////////////////////////////////////////////
1338 //// nsIInterfaceRequestor
1341 Connection::GetInterface(const nsIID
& aIID
, void** _result
) {
1342 if (aIID
.Equals(NS_GET_IID(nsIEventTarget
))) {
1343 nsIEventTarget
* background
= getAsyncExecutionTarget();
1344 NS_IF_ADDREF(background
);
1345 *_result
= background
;
1348 return NS_ERROR_NO_INTERFACE
;
1351 ////////////////////////////////////////////////////////////////////////////////
1352 //// mozIStorageConnection
1355 Connection::Close() {
1356 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1357 if (NS_FAILED(rv
)) {
1360 return synchronousClose();
1363 nsresult
Connection::synchronousClose() {
1364 if (!connectionReady()) {
1365 return NS_ERROR_NOT_INITIALIZED
;
1369 // Since we're accessing mAsyncExecutionThread, we need to be on the opener
1370 // thread. We make this check outside of debug code below in setClosedState,
1371 // but this is here to be explicit.
1372 bool onOpenerThread
= false;
1373 (void)threadOpenedOn
->IsOnCurrentThread(&onOpenerThread
);
1374 MOZ_ASSERT(onOpenerThread
);
1377 // Make sure we have not executed any asynchronous statements.
1378 // If this fails, the mDBConn may be left open, resulting in a leak.
1379 // We'll try to finalize the pending statements and close the connection.
1380 if (isAsyncExecutionThreadAvailable()) {
1382 if (NS_IsMainThread()) {
1383 nsCOMPtr
<nsIXPConnect
> xpc
= nsIXPConnect::XPConnect();
1384 Unused
<< xpc
->DebugDumpJSStack(false, false, false);
1388 "Close() was invoked on a connection that executed asynchronous "
1390 "Should have used asyncClose().");
1391 // Try to close the database regardless, to free up resources.
1392 Unused
<< SpinningSynchronousClose();
1393 return NS_ERROR_UNEXPECTED
;
1396 // setClosedState nullifies our connection pointer, so we take a raw pointer
1397 // off it, to pass it through the close procedure.
1398 sqlite3
* nativeConn
= mDBConn
;
1399 nsresult rv
= setClosedState();
1400 NS_ENSURE_SUCCESS(rv
, rv
);
1402 return internalClose(nativeConn
);
1406 Connection::SpinningSynchronousClose() {
1407 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1408 if (NS_FAILED(rv
)) {
1411 if (threadOpenedOn
!= NS_GetCurrentThread()) {
1412 return NS_ERROR_NOT_SAME_THREAD
;
1415 // As currently implemented, we can't spin to wait for an existing AsyncClose.
1416 // Our only existing caller will never have called close; assert if misused
1417 // so that no new callers assume this works after an AsyncClose.
1418 MOZ_DIAGNOSTIC_ASSERT(connectionReady());
1419 if (!connectionReady()) {
1420 return NS_ERROR_UNEXPECTED
;
1423 RefPtr
<CloseListener
> listener
= new CloseListener();
1424 rv
= AsyncClose(listener
);
1425 NS_ENSURE_SUCCESS(rv
, rv
);
1427 SpinEventLoopUntil("storage::Connection::SpinningSynchronousClose"_ns
,
1428 [&]() { return listener
->mClosed
; }));
1429 MOZ_ASSERT(isClosed(), "The connection should be closed at this point");
1435 Connection::AsyncClose(mozIStorageCompletionCallback
* aCallback
) {
1436 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1437 // Check if AsyncClose or Close were already invoked.
1438 if (!connectionReady()) {
1439 return NS_ERROR_NOT_INITIALIZED
;
1441 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1442 if (NS_FAILED(rv
)) {
1446 // The two relevant factors at this point are whether we have a database
1447 // connection and whether we have an async execution thread. Here's what the
1448 // states mean and how we handle them:
1450 // - (mDBConn && asyncThread): The expected case where we are either an
1451 // async connection or a sync connection that has been used asynchronously.
1452 // Either way the caller must call us and not Close(). Nothing surprising
1453 // about this. We'll dispatch AsyncCloseConnection to the already-existing
1456 // - (mDBConn && !asyncThread): A somewhat unusual case where the caller
1457 // opened the connection synchronously and was planning to use it
1458 // asynchronously, but never got around to using it asynchronously before
1459 // needing to shutdown. This has been observed to happen for the cookie
1460 // service in a case where Firefox shuts itself down almost immediately
1461 // after startup (for unknown reasons). In the Firefox shutdown case,
1462 // we may also fail to create a new async execution thread if one does not
1463 // already exist. (nsThreadManager will refuse to create new threads when
1464 // it has already been told to shutdown.) As such, we need to handle a
1465 // failure to create the async execution thread by falling back to
1466 // synchronous Close() and also dispatching the completion callback because
1467 // at least Places likes to spin a nested event loop that depends on the
1468 // callback being invoked.
1470 // Note that we have considered not trying to spin up the async execution
1471 // thread in this case if it does not already exist, but the overhead of
1472 // thread startup (if successful) is significantly less expensive than the
1473 // worst-case potential I/O hit of synchronously closing a database when we
1474 // could close it asynchronously.
1476 // - (!mDBConn && asyncThread): This happens in some but not all cases where
1477 // OpenAsyncDatabase encountered a problem opening the database. If it
1478 // happened in all cases AsyncInitDatabase would just shut down the thread
1479 // directly and we would avoid this case. But it doesn't, so for simplicity
1480 // and consistency AsyncCloseConnection knows how to handle this and we
1481 // act like this was the (mDBConn && asyncThread) case in this method.
1483 // - (!mDBConn && !asyncThread): The database was never successfully opened or
1484 // Close() or AsyncClose() has already been called (at least) once. This is
1485 // undeniably a misuse case by the caller. We could optimize for this
1486 // case by adding an additional check of mAsyncExecutionThread without using
1487 // getAsyncExecutionTarget() to avoid wastefully creating a thread just to
1488 // shut it down. But this complicates the method for broken caller code
1489 // whereas we're still correct and safe without the special-case.
1490 nsIEventTarget
* asyncThread
= getAsyncExecutionTarget();
1492 // Create our callback event if we were given a callback. This will
1493 // eventually be dispatched in all cases, even if we fall back to Close() and
1494 // the database wasn't open and we return an error. The rationale is that
1495 // no existing consumer checks our return value and several of them like to
1496 // spin nested event loops until the callback fires. Given that, it seems
1497 // preferable for us to dispatch the callback in all cases. (Except the
1498 // wrong thread misuse case we bailed on up above. But that's okay because
1499 // that is statically wrong whereas these edge cases are dynamic.)
1500 nsCOMPtr
<nsIRunnable
> completeEvent
;
1502 completeEvent
= newCompletionEvent(aCallback
);
1506 // We were unable to create an async thread, so we need to fall back to
1507 // using normal Close(). Since there is no async thread, Close() will
1508 // not complain about that. (Close() may, however, complain if the
1509 // connection is closed, but that's okay.)
1510 if (completeEvent
) {
1511 // Closing the database is more important than returning an error code
1512 // about a failure to dispatch, especially because all existing native
1513 // callers ignore our return value.
1514 Unused
<< NS_DispatchToMainThread(completeEvent
.forget());
1516 MOZ_ALWAYS_SUCCEEDS(synchronousClose());
1517 // Return a success inconditionally here, since Close() is unlikely to fail
1518 // and we want to reassure the consumer that its callback will be invoked.
1522 // setClosedState nullifies our connection pointer, so we take a raw pointer
1523 // off it, to pass it through the close procedure.
1524 sqlite3
* nativeConn
= mDBConn
;
1525 rv
= setClosedState();
1526 NS_ENSURE_SUCCESS(rv
, rv
);
1528 // Create and dispatch our close event to the background thread.
1529 nsCOMPtr
<nsIRunnable
> closeEvent
=
1530 new AsyncCloseConnection(this, nativeConn
, completeEvent
);
1531 rv
= asyncThread
->Dispatch(closeEvent
, NS_DISPATCH_NORMAL
);
1532 NS_ENSURE_SUCCESS(rv
, rv
);
1538 Connection::AsyncClone(bool aReadOnly
,
1539 mozIStorageCompletionCallback
* aCallback
) {
1540 AUTO_PROFILER_LABEL("Connection::AsyncClone", OTHER
);
1542 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1543 if (!connectionReady()) {
1544 return NS_ERROR_NOT_INITIALIZED
;
1546 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1547 if (NS_FAILED(rv
)) {
1550 if (!mDatabaseFile
) return NS_ERROR_UNEXPECTED
;
1554 // Turn off SQLITE_OPEN_READWRITE, and set SQLITE_OPEN_READONLY.
1555 flags
= (~SQLITE_OPEN_READWRITE
& flags
) | SQLITE_OPEN_READONLY
;
1556 // Turn off SQLITE_OPEN_CREATE.
1557 flags
= (~SQLITE_OPEN_CREATE
& flags
);
1560 // The cloned connection will still implement the synchronous API, but throw
1561 // if any synchronous methods are called on the main thread.
1562 RefPtr
<Connection
> clone
=
1563 new Connection(mStorageService
, flags
, ASYNCHRONOUS
);
1565 RefPtr
<AsyncInitializeClone
> initEvent
=
1566 new AsyncInitializeClone(this, clone
, aReadOnly
, aCallback
);
1567 // Dispatch to our async thread, since the originating connection must remain
1568 // valid and open for the whole cloning process. This also ensures we are
1569 // properly serialized with a `close` operation, rather than race with it.
1570 nsCOMPtr
<nsIEventTarget
> target
= getAsyncExecutionTarget();
1572 return NS_ERROR_UNEXPECTED
;
1574 return target
->Dispatch(initEvent
, NS_DISPATCH_NORMAL
);
1577 nsresult
Connection::initializeClone(Connection
* aClone
, bool aReadOnly
) {
1579 if (!mStorageKey
.IsEmpty()) {
1580 rv
= aClone
->initialize(mStorageKey
, mName
);
1581 } else if (mFileURL
) {
1582 rv
= aClone
->initialize(mFileURL
, mTelemetryFilename
);
1584 rv
= aClone
->initialize(mDatabaseFile
);
1586 if (NS_FAILED(rv
)) {
1590 auto guard
= MakeScopeExit([&]() { aClone
->initializeFailed(); });
1592 rv
= aClone
->SetDefaultTransactionType(mDefaultTransactionType
);
1593 NS_ENSURE_SUCCESS(rv
, rv
);
1595 // Re-attach on-disk databases that were attached to the original connection.
1597 nsCOMPtr
<mozIStorageStatement
> stmt
;
1598 rv
= CreateStatement("PRAGMA database_list"_ns
, getter_AddRefs(stmt
));
1599 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1600 bool hasResult
= false;
1601 while (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1603 rv
= stmt
->GetUTF8String(1, name
);
1604 if (NS_SUCCEEDED(rv
) && !name
.EqualsLiteral("main") &&
1605 !name
.EqualsLiteral("temp")) {
1607 rv
= stmt
->GetUTF8String(2, path
);
1608 if (NS_SUCCEEDED(rv
) && !path
.IsEmpty()) {
1609 nsCOMPtr
<mozIStorageStatement
> attachStmt
;
1610 rv
= aClone
->CreateStatement("ATTACH DATABASE :path AS "_ns
+ name
,
1611 getter_AddRefs(attachStmt
));
1612 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1613 rv
= attachStmt
->BindUTF8StringByName("path"_ns
, path
);
1614 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1615 rv
= attachStmt
->Execute();
1616 MOZ_ASSERT(NS_SUCCEEDED(rv
),
1617 "couldn't re-attach database to cloned connection");
1623 // Copy over pragmas from the original connection.
1624 // LIMITATION WARNING! Many of these pragmas are actually scoped to the
1625 // schema ("main" and any other attached databases), and this implmentation
1626 // fails to propagate them. This is being addressed on trunk.
1627 static const char* pragmas
[] = {
1628 "cache_size", "temp_store", "foreign_keys", "journal_size_limit",
1629 "synchronous", "wal_autocheckpoint", "busy_timeout"};
1630 for (auto& pragma
: pragmas
) {
1631 // Read-only connections just need cache_size and temp_store pragmas.
1632 if (aReadOnly
&& ::strcmp(pragma
, "cache_size") != 0 &&
1633 ::strcmp(pragma
, "temp_store") != 0) {
1637 nsAutoCString
pragmaQuery("PRAGMA ");
1638 pragmaQuery
.Append(pragma
);
1639 nsCOMPtr
<mozIStorageStatement
> stmt
;
1640 rv
= CreateStatement(pragmaQuery
, getter_AddRefs(stmt
));
1641 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1642 bool hasResult
= false;
1643 if (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1644 pragmaQuery
.AppendLiteral(" = ");
1645 pragmaQuery
.AppendInt(stmt
->AsInt32(0));
1646 rv
= aClone
->ExecuteSimpleSQL(pragmaQuery
);
1647 MOZ_ASSERT(NS_SUCCEEDED(rv
));
1651 // Copy over temporary tables, triggers, and views from the original
1652 // connections. Entities in `sqlite_temp_master` are only visible to the
1653 // connection that created them.
1655 rv
= aClone
->ExecuteSimpleSQL("BEGIN TRANSACTION"_ns
);
1656 NS_ENSURE_SUCCESS(rv
, rv
);
1658 nsCOMPtr
<mozIStorageStatement
> stmt
;
1659 rv
= CreateStatement(nsLiteralCString("SELECT sql FROM sqlite_temp_master "
1660 "WHERE type IN ('table', 'view', "
1661 "'index', 'trigger')"),
1662 getter_AddRefs(stmt
));
1663 // Propagate errors, because failing to copy triggers might cause schema
1664 // coherency issues when writing to the database from the cloned connection.
1665 NS_ENSURE_SUCCESS(rv
, rv
);
1666 bool hasResult
= false;
1667 while (stmt
&& NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
) {
1668 nsAutoCString query
;
1669 rv
= stmt
->GetUTF8String(0, query
);
1670 NS_ENSURE_SUCCESS(rv
, rv
);
1672 // The `CREATE` SQL statements in `sqlite_temp_master` omit the `TEMP`
1673 // keyword. We need to add it back, or we'll recreate temporary entities
1674 // as persistent ones. `sqlite_temp_master` also holds `CREATE INDEX`
1675 // statements, but those don't need `TEMP` keywords.
1676 if (StringBeginsWith(query
, "CREATE TABLE "_ns
) ||
1677 StringBeginsWith(query
, "CREATE TRIGGER "_ns
) ||
1678 StringBeginsWith(query
, "CREATE VIEW "_ns
)) {
1679 query
.Replace(0, 6, "CREATE TEMP");
1682 rv
= aClone
->ExecuteSimpleSQL(query
);
1683 NS_ENSURE_SUCCESS(rv
, rv
);
1686 rv
= aClone
->ExecuteSimpleSQL("COMMIT"_ns
);
1687 NS_ENSURE_SUCCESS(rv
, rv
);
1690 // Copy any functions that have been added to this connection.
1691 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
1692 for (const auto& entry
: mFunctions
) {
1693 const nsACString
& key
= entry
.GetKey();
1694 Connection::FunctionInfo data
= entry
.GetData();
1696 rv
= aClone
->CreateFunction(key
, data
.numArgs
, data
.function
);
1697 if (NS_FAILED(rv
)) {
1698 NS_WARNING("Failed to copy function to cloned connection");
1707 Connection::Clone(bool aReadOnly
, mozIStorageConnection
** _connection
) {
1708 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1710 AUTO_PROFILER_LABEL("Connection::Clone", OTHER
);
1712 if (!connectionReady()) {
1713 return NS_ERROR_NOT_INITIALIZED
;
1715 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1716 if (NS_FAILED(rv
)) {
1722 // Turn off SQLITE_OPEN_READWRITE, and set SQLITE_OPEN_READONLY.
1723 flags
= (~SQLITE_OPEN_READWRITE
& flags
) | SQLITE_OPEN_READONLY
;
1724 // Turn off SQLITE_OPEN_CREATE.
1725 flags
= (~SQLITE_OPEN_CREATE
& flags
);
1728 RefPtr
<Connection
> clone
=
1729 new Connection(mStorageService
, flags
, mSupportedOperations
);
1731 rv
= initializeClone(clone
, aReadOnly
);
1732 if (NS_FAILED(rv
)) {
1736 NS_IF_ADDREF(*_connection
= clone
);
1741 Connection::Interrupt() {
1742 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1743 if (!connectionReady()) {
1744 return NS_ERROR_NOT_INITIALIZED
;
1746 if (operationSupported(SYNCHRONOUS
) || !(mFlags
& SQLITE_OPEN_READONLY
)) {
1747 // Interrupting a synchronous connection from the same thread doesn't make
1748 // sense, and read-write connections aren't safe to interrupt.
1749 return NS_ERROR_INVALID_ARG
;
1751 ::sqlite3_interrupt(mDBConn
);
1756 Connection::GetDefaultPageSize(int32_t* _defaultPageSize
) {
1757 *_defaultPageSize
= Service::kDefaultPageSize
;
1762 Connection::GetConnectionReady(bool* _ready
) {
1763 MOZ_ASSERT(threadOpenedOn
== NS_GetCurrentThread());
1764 *_ready
= connectionReady();
1769 Connection::GetDatabaseFile(nsIFile
** _dbFile
) {
1770 if (!connectionReady()) {
1771 return NS_ERROR_NOT_INITIALIZED
;
1773 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1774 if (NS_FAILED(rv
)) {
1778 NS_IF_ADDREF(*_dbFile
= mDatabaseFile
);
1784 Connection::GetLastInsertRowID(int64_t* _id
) {
1785 if (!connectionReady()) {
1786 return NS_ERROR_NOT_INITIALIZED
;
1788 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1789 if (NS_FAILED(rv
)) {
1793 sqlite_int64 id
= ::sqlite3_last_insert_rowid(mDBConn
);
1800 Connection::GetAffectedRows(int32_t* _rows
) {
1801 if (!connectionReady()) {
1802 return NS_ERROR_NOT_INITIALIZED
;
1804 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1805 if (NS_FAILED(rv
)) {
1809 *_rows
= ::sqlite3_changes(mDBConn
);
1815 Connection::GetLastError(int32_t* _error
) {
1816 if (!connectionReady()) {
1817 return NS_ERROR_NOT_INITIALIZED
;
1819 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1820 if (NS_FAILED(rv
)) {
1824 *_error
= ::sqlite3_errcode(mDBConn
);
1830 Connection::GetLastErrorString(nsACString
& _errorString
) {
1831 if (!connectionReady()) {
1832 return NS_ERROR_NOT_INITIALIZED
;
1834 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1835 if (NS_FAILED(rv
)) {
1839 const char* serr
= ::sqlite3_errmsg(mDBConn
);
1840 _errorString
.Assign(serr
);
1846 Connection::GetSchemaVersion(int32_t* _version
) {
1847 if (!connectionReady()) {
1848 return NS_ERROR_NOT_INITIALIZED
;
1850 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1851 if (NS_FAILED(rv
)) {
1855 nsCOMPtr
<mozIStorageStatement
> stmt
;
1856 (void)CreateStatement("PRAGMA user_version"_ns
, getter_AddRefs(stmt
));
1857 NS_ENSURE_TRUE(stmt
, NS_ERROR_OUT_OF_MEMORY
);
1861 if (NS_SUCCEEDED(stmt
->ExecuteStep(&hasResult
)) && hasResult
)
1862 *_version
= stmt
->AsInt32(0);
1868 Connection::SetSchemaVersion(int32_t aVersion
) {
1869 if (!connectionReady()) {
1870 return NS_ERROR_NOT_INITIALIZED
;
1872 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1873 if (NS_FAILED(rv
)) {
1877 nsAutoCString
stmt("PRAGMA user_version = "_ns
);
1878 stmt
.AppendInt(aVersion
);
1880 return ExecuteSimpleSQL(stmt
);
1884 Connection::CreateStatement(const nsACString
& aSQLStatement
,
1885 mozIStorageStatement
** _stmt
) {
1886 NS_ENSURE_ARG_POINTER(_stmt
);
1887 if (!connectionReady()) {
1888 return NS_ERROR_NOT_INITIALIZED
;
1890 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1891 if (NS_FAILED(rv
)) {
1895 RefPtr
<Statement
> statement(new Statement());
1896 NS_ENSURE_TRUE(statement
, NS_ERROR_OUT_OF_MEMORY
);
1898 rv
= statement
->initialize(this, mDBConn
, aSQLStatement
);
1899 NS_ENSURE_SUCCESS(rv
, rv
);
1902 statement
.forget(&rawPtr
);
1908 Connection::CreateAsyncStatement(const nsACString
& aSQLStatement
,
1909 mozIStorageAsyncStatement
** _stmt
) {
1910 NS_ENSURE_ARG_POINTER(_stmt
);
1911 if (!connectionReady()) {
1912 return NS_ERROR_NOT_INITIALIZED
;
1914 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
1915 if (NS_FAILED(rv
)) {
1919 RefPtr
<AsyncStatement
> statement(new AsyncStatement());
1920 NS_ENSURE_TRUE(statement
, NS_ERROR_OUT_OF_MEMORY
);
1922 rv
= statement
->initialize(this, mDBConn
, aSQLStatement
);
1923 NS_ENSURE_SUCCESS(rv
, rv
);
1925 AsyncStatement
* rawPtr
;
1926 statement
.forget(&rawPtr
);
1932 Connection::ExecuteSimpleSQL(const nsACString
& aSQLStatement
) {
1933 CHECK_MAINTHREAD_ABUSE();
1934 if (!connectionReady()) {
1935 return NS_ERROR_NOT_INITIALIZED
;
1937 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
1938 if (NS_FAILED(rv
)) {
1942 int srv
= executeSql(mDBConn
, PromiseFlatCString(aSQLStatement
).get());
1943 return convertResultCode(srv
);
1947 Connection::ExecuteAsync(
1948 const nsTArray
<RefPtr
<mozIStorageBaseStatement
>>& aStatements
,
1949 mozIStorageStatementCallback
* aCallback
,
1950 mozIStoragePendingStatement
** _handle
) {
1951 nsTArray
<StatementData
> stmts(aStatements
.Length());
1952 for (uint32_t i
= 0; i
< aStatements
.Length(); i
++) {
1953 nsCOMPtr
<StorageBaseStatementInternal
> stmt
=
1954 do_QueryInterface(aStatements
[i
]);
1955 NS_ENSURE_STATE(stmt
);
1957 // Obtain our StatementData.
1959 nsresult rv
= stmt
->getAsynchronousStatementData(data
);
1960 NS_ENSURE_SUCCESS(rv
, rv
);
1962 NS_ASSERTION(stmt
->getOwner() == this,
1963 "Statement must be from this database connection!");
1965 // Now append it to our array.
1966 stmts
.AppendElement(data
);
1969 // Dispatch to the background
1970 return AsyncExecuteStatements::execute(std::move(stmts
), this, mDBConn
,
1971 aCallback
, _handle
);
1975 Connection::ExecuteSimpleSQLAsync(const nsACString
& aSQLStatement
,
1976 mozIStorageStatementCallback
* aCallback
,
1977 mozIStoragePendingStatement
** _handle
) {
1978 NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_SAME_THREAD
);
1980 nsCOMPtr
<mozIStorageAsyncStatement
> stmt
;
1981 nsresult rv
= CreateAsyncStatement(aSQLStatement
, getter_AddRefs(stmt
));
1982 if (NS_FAILED(rv
)) {
1986 nsCOMPtr
<mozIStoragePendingStatement
> pendingStatement
;
1987 rv
= stmt
->ExecuteAsync(aCallback
, getter_AddRefs(pendingStatement
));
1988 if (NS_FAILED(rv
)) {
1992 pendingStatement
.forget(_handle
);
1997 Connection::TableExists(const nsACString
& aTableName
, bool* _exists
) {
1998 return databaseElementExists(TABLE
, aTableName
, _exists
);
2002 Connection::IndexExists(const nsACString
& aIndexName
, bool* _exists
) {
2003 return databaseElementExists(INDEX
, aIndexName
, _exists
);
2007 Connection::GetTransactionInProgress(bool* _inProgress
) {
2008 if (!connectionReady()) {
2009 return NS_ERROR_NOT_INITIALIZED
;
2011 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2012 if (NS_FAILED(rv
)) {
2016 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2017 *_inProgress
= transactionInProgress(lockedScope
);
2022 Connection::GetDefaultTransactionType(int32_t* _type
) {
2023 *_type
= mDefaultTransactionType
;
2028 Connection::SetDefaultTransactionType(int32_t aType
) {
2029 NS_ENSURE_ARG_RANGE(aType
, TRANSACTION_DEFERRED
, TRANSACTION_EXCLUSIVE
);
2030 mDefaultTransactionType
= aType
;
2035 Connection::GetVariableLimit(int32_t* _limit
) {
2036 if (!connectionReady()) {
2037 return NS_ERROR_NOT_INITIALIZED
;
2039 int limit
= ::sqlite3_limit(mDBConn
, SQLITE_LIMIT_VARIABLE_NUMBER
, -1);
2041 return NS_ERROR_UNEXPECTED
;
2048 Connection::BeginTransaction() {
2049 if (!connectionReady()) {
2050 return NS_ERROR_NOT_INITIALIZED
;
2052 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2053 if (NS_FAILED(rv
)) {
2057 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2058 return beginTransactionInternal(lockedScope
, mDBConn
,
2059 mDefaultTransactionType
);
2062 nsresult
Connection::beginTransactionInternal(
2063 const SQLiteMutexAutoLock
& aProofOfLock
, sqlite3
* aNativeConnection
,
2064 int32_t aTransactionType
) {
2065 if (transactionInProgress(aProofOfLock
)) {
2066 return NS_ERROR_FAILURE
;
2069 switch (aTransactionType
) {
2070 case TRANSACTION_DEFERRED
:
2071 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN DEFERRED"));
2073 case TRANSACTION_IMMEDIATE
:
2074 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN IMMEDIATE"));
2076 case TRANSACTION_EXCLUSIVE
:
2077 rv
= convertResultCode(executeSql(aNativeConnection
, "BEGIN EXCLUSIVE"));
2080 return NS_ERROR_ILLEGAL_VALUE
;
2086 Connection::CommitTransaction() {
2087 if (!connectionReady()) {
2088 return NS_ERROR_NOT_INITIALIZED
;
2090 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2091 if (NS_FAILED(rv
)) {
2095 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2096 return commitTransactionInternal(lockedScope
, mDBConn
);
2099 nsresult
Connection::commitTransactionInternal(
2100 const SQLiteMutexAutoLock
& aProofOfLock
, sqlite3
* aNativeConnection
) {
2101 if (!transactionInProgress(aProofOfLock
)) {
2102 return NS_ERROR_UNEXPECTED
;
2105 convertResultCode(executeSql(aNativeConnection
, "COMMIT TRANSACTION"));
2110 Connection::RollbackTransaction() {
2111 if (!connectionReady()) {
2112 return NS_ERROR_NOT_INITIALIZED
;
2114 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2115 if (NS_FAILED(rv
)) {
2119 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2120 return rollbackTransactionInternal(lockedScope
, mDBConn
);
2123 nsresult
Connection::rollbackTransactionInternal(
2124 const SQLiteMutexAutoLock
& aProofOfLock
, sqlite3
* aNativeConnection
) {
2125 if (!transactionInProgress(aProofOfLock
)) {
2126 return NS_ERROR_UNEXPECTED
;
2130 convertResultCode(executeSql(aNativeConnection
, "ROLLBACK TRANSACTION"));
2135 Connection::CreateTable(const char* aTableName
, const char* aTableSchema
) {
2136 if (!connectionReady()) {
2137 return NS_ERROR_NOT_INITIALIZED
;
2139 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2140 if (NS_FAILED(rv
)) {
2144 SmprintfPointer buf
=
2145 ::mozilla::Smprintf("CREATE TABLE %s (%s)", aTableName
, aTableSchema
);
2146 if (!buf
) return NS_ERROR_OUT_OF_MEMORY
;
2148 int srv
= executeSql(mDBConn
, buf
.get());
2150 return convertResultCode(srv
);
2154 Connection::CreateFunction(const nsACString
& aFunctionName
,
2155 int32_t aNumArguments
,
2156 mozIStorageFunction
* aFunction
) {
2157 if (!connectionReady()) {
2158 return NS_ERROR_NOT_INITIALIZED
;
2160 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2161 if (NS_FAILED(rv
)) {
2165 // Check to see if this function is already defined. We only check the name
2166 // because a function can be defined with the same body but different names.
2167 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2168 NS_ENSURE_FALSE(mFunctions
.Contains(aFunctionName
), NS_ERROR_FAILURE
);
2170 int srv
= ::sqlite3_create_function(
2171 mDBConn
, nsPromiseFlatCString(aFunctionName
).get(), aNumArguments
,
2172 SQLITE_ANY
, aFunction
, basicFunctionHelper
, nullptr, nullptr);
2173 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2175 FunctionInfo info
= {aFunction
, aNumArguments
};
2176 mFunctions
.InsertOrUpdate(aFunctionName
, info
);
2182 Connection::RemoveFunction(const nsACString
& aFunctionName
) {
2183 if (!connectionReady()) {
2184 return NS_ERROR_NOT_INITIALIZED
;
2186 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2187 if (NS_FAILED(rv
)) {
2191 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2192 NS_ENSURE_TRUE(mFunctions
.Get(aFunctionName
, nullptr), NS_ERROR_FAILURE
);
2194 int srv
= ::sqlite3_create_function(
2195 mDBConn
, nsPromiseFlatCString(aFunctionName
).get(), 0, SQLITE_ANY
,
2196 nullptr, nullptr, nullptr, nullptr);
2197 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2199 mFunctions
.Remove(aFunctionName
);
2205 Connection::SetProgressHandler(int32_t aGranularity
,
2206 mozIStorageProgressHandler
* aHandler
,
2207 mozIStorageProgressHandler
** _oldHandler
) {
2208 if (!connectionReady()) {
2209 return NS_ERROR_NOT_INITIALIZED
;
2211 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2212 if (NS_FAILED(rv
)) {
2216 // Return previous one
2217 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2218 NS_IF_ADDREF(*_oldHandler
= mProgressHandler
);
2220 if (!aHandler
|| aGranularity
<= 0) {
2224 mProgressHandler
= aHandler
;
2225 ::sqlite3_progress_handler(mDBConn
, aGranularity
, sProgressHelper
, this);
2231 Connection::RemoveProgressHandler(mozIStorageProgressHandler
** _oldHandler
) {
2232 if (!connectionReady()) {
2233 return NS_ERROR_NOT_INITIALIZED
;
2235 nsresult rv
= ensureOperationSupported(ASYNCHRONOUS
);
2236 if (NS_FAILED(rv
)) {
2240 // Return previous one
2241 SQLiteMutexAutoLock
lockedScope(sharedDBMutex
);
2242 NS_IF_ADDREF(*_oldHandler
= mProgressHandler
);
2244 mProgressHandler
= nullptr;
2245 ::sqlite3_progress_handler(mDBConn
, 0, nullptr, nullptr);
2251 Connection::SetGrowthIncrement(int32_t aChunkSize
,
2252 const nsACString
& aDatabaseName
) {
2253 if (!connectionReady()) {
2254 return NS_ERROR_NOT_INITIALIZED
;
2256 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2257 if (NS_FAILED(rv
)) {
2261 // Bug 597215: Disk space is extremely limited on Android
2262 // so don't preallocate space. This is also not effective
2263 // on log structured file systems used by Android devices
2264 #if !defined(ANDROID) && !defined(MOZ_PLATFORM_MAEMO)
2265 // Don't preallocate if less than 500MiB is available.
2266 int64_t bytesAvailable
;
2267 rv
= mDatabaseFile
->GetDiskSpaceAvailable(&bytesAvailable
);
2268 NS_ENSURE_SUCCESS(rv
, rv
);
2269 if (bytesAvailable
< MIN_AVAILABLE_BYTES_PER_CHUNKED_GROWTH
) {
2270 return NS_ERROR_FILE_TOO_BIG
;
2273 (void)::sqlite3_file_control(mDBConn
,
2274 aDatabaseName
.Length()
2275 ? nsPromiseFlatCString(aDatabaseName
).get()
2277 SQLITE_FCNTL_CHUNK_SIZE
, &aChunkSize
);
2283 Connection::EnableModule(const nsACString
& aModuleName
) {
2284 if (!connectionReady()) {
2285 return NS_ERROR_NOT_INITIALIZED
;
2287 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2288 if (NS_FAILED(rv
)) {
2292 for (auto& gModule
: gModules
) {
2293 struct Module
* m
= &gModule
;
2294 if (aModuleName
.Equals(m
->name
)) {
2295 int srv
= m
->registerFunc(mDBConn
, m
->name
);
2296 if (srv
!= SQLITE_OK
) return convertResultCode(srv
);
2302 return NS_ERROR_FAILURE
;
2305 // Implemented in TelemetryVFS.cpp
2306 already_AddRefed
<QuotaObject
> GetQuotaObjectForFile(sqlite3_file
* pFile
);
2309 Connection::GetQuotaObjects(QuotaObject
** aDatabaseQuotaObject
,
2310 QuotaObject
** aJournalQuotaObject
) {
2311 MOZ_ASSERT(aDatabaseQuotaObject
);
2312 MOZ_ASSERT(aJournalQuotaObject
);
2314 if (!connectionReady()) {
2315 return NS_ERROR_NOT_INITIALIZED
;
2317 nsresult rv
= ensureOperationSupported(SYNCHRONOUS
);
2318 if (NS_FAILED(rv
)) {
2323 int srv
= ::sqlite3_file_control(mDBConn
, nullptr, SQLITE_FCNTL_FILE_POINTER
,
2325 if (srv
!= SQLITE_OK
) {
2326 return convertResultCode(srv
);
2329 RefPtr
<QuotaObject
> databaseQuotaObject
= GetQuotaObjectForFile(file
);
2330 if (NS_WARN_IF(!databaseQuotaObject
)) {
2331 return NS_ERROR_FAILURE
;
2334 srv
= ::sqlite3_file_control(mDBConn
, nullptr, SQLITE_FCNTL_JOURNAL_POINTER
,
2336 if (srv
!= SQLITE_OK
) {
2337 return convertResultCode(srv
);
2340 RefPtr
<QuotaObject
> journalQuotaObject
= GetQuotaObjectForFile(file
);
2341 if (NS_WARN_IF(!journalQuotaObject
)) {
2342 return NS_ERROR_FAILURE
;
2345 databaseQuotaObject
.forget(aDatabaseQuotaObject
);
2346 journalQuotaObject
.forget(aJournalQuotaObject
);
2350 SQLiteMutex
& Connection::GetSharedDBMutex() { return sharedDBMutex
; }
2352 uint32_t Connection::GetTransactionNestingLevel(
2353 const mozilla::storage::SQLiteMutexAutoLock
& aProofOfLock
) {
2354 return mTransactionNestingLevel
;
2357 uint32_t Connection::IncreaseTransactionNestingLevel(
2358 const mozilla::storage::SQLiteMutexAutoLock
& aProofOfLock
) {
2359 return ++mTransactionNestingLevel
;
2362 uint32_t Connection::DecreaseTransactionNestingLevel(
2363 const mozilla::storage::SQLiteMutexAutoLock
& aProofOfLock
) {
2364 return --mTransactionNestingLevel
;
2367 } // namespace mozilla::storage