Bug 599969 - Add a statement cache helper object that is exported by storage.

This adds a templated StatementCache helper object (with tests!) that allows
consumers of storage to easily cache and reuse statements.  Consumers only need
to pass in the query string, and the rest is handled for them.
r=asuth
sr=rs
This commit is contained in:
Shawn Wilsher 2010-11-08 11:42:29 -08:00
Родитель b1d1ca5412
Коммит e9f0fde783
6 изменённых файлов: 404 добавлений и 3 удалений

Просмотреть файл

@ -74,7 +74,7 @@ XPIDLSRCS = \
$(NULL)
# SEE ABOVE NOTE!
EXPORTS_NAMESPACES = mozilla
EXPORTS_NAMESPACES = mozilla mozilla/storage
EXPORTS = \
mozStorageHelper.h \
@ -83,4 +83,11 @@ EXPORTS = \
EXPORTS_mozilla = storage.h
# NOTE When adding something to this list, you probably need to add it to the
# storage.h file too.
EXPORTS_mozilla/storage = \
StatementCache.h \
$(NULL)
# SEE ABOVE NOTE!
include $(topsrcdir)/config/rules.mk

Просмотреть файл

@ -0,0 +1,187 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the mozStorage statement cache.
*
* The Initial Developer of the Original Code is
* the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shawn Wilsher <me@shawnwilsher.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef mozilla_storage_StatementCache_h
#define mozilla_storage_StatementCache_h
#include "mozIStorageConnection.h"
#include "mozIStorageStatement.h"
#include "mozIStorageAsyncStatement.h"
#include "nsAutoPtr.h"
#include "nsHashKeys.h"
#include "nsInterfaceHashtable.h"
namespace mozilla {
namespace storage {
/**
* Class used to cache statements (mozIStorageStatement or
* mozIStorageAsyncStatement).
*/
template<typename StatementType>
class StatementCache {
public:
/**
* Constructor for the cache.
*
* @note a connection can have more than one cache.
*
* @param aConnection
* A reference to the nsCOMPtr for the connection this cache is to be
* used for. This nsCOMPtr must at least live as long as this class,
* otherwise crashes will happen.
*/
StatementCache(nsCOMPtr<mozIStorageConnection>& aConnection)
: mConnection(aConnection)
{
if (!mCachedStatements.Init()) {
NS_ERROR("Out of memory!?");
}
}
/**
* Obtains a cached statement. If this statement is not yet created, it will
* be created and stored for later use.
*
* @param aQuery
* The SQL string (either a const char [] or nsACString) to get a
* cached query for.
* @return the cached statement, or null upon error.
*/
inline
already_AddRefed<StatementType>
GetCachedStatement(const nsACString& aQuery)
{
nsCOMPtr<StatementType> stmt;
if (!mCachedStatements.Get(aQuery, getter_AddRefs(stmt))) {
stmt = CreateStatement(aQuery);
NS_ENSURE_TRUE(stmt, nsnull);
if (!mCachedStatements.Put(aQuery, stmt)) {
NS_ERROR("Out of memory!?");
}
}
return stmt.forget();
}
template<int N>
NS_ALWAYS_INLINE already_AddRefed<StatementType>
GetCachedStatement(const char (&aQuery)[N])
{
nsDependentCString query(aQuery, N - 1);
return GetCachedStatement(query);
}
/**
* Finalizes all cached statements so the database can be safely closed. The
* behavior of this cache is unspecified after this method is called.
*/
inline
void
FinalizeStatements()
{
(void)mCachedStatements.Enumerate(FinalizeCachedStatements, NULL);
// Clear the cache at this time too!
(void)mCachedStatements.Clear();
}
private:
inline
already_AddRefed<StatementType>
CreateStatement(const nsACString& aQuery);
static
PLDHashOperator
FinalizeCachedStatements(const nsACString& aKey,
nsCOMPtr<StatementType>& aStatement,
void*)
{
nsresult rv = aStatement->Finalize();
NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Finalizing statement failed!");
return PL_DHASH_NEXT;
}
nsInterfaceHashtable<nsCStringHashKey, StatementType> mCachedStatements;
nsCOMPtr<mozIStorageConnection>& mConnection;
};
template< >
inline
already_AddRefed<mozIStorageStatement>
StatementCache<mozIStorageStatement>::CreateStatement(const nsACString& aQuery)
{
NS_ENSURE_TRUE(mConnection, nsnull);
nsCOMPtr<mozIStorageStatement> stmt;
nsresult rv = mConnection->CreateStatement(aQuery, getter_AddRefs(stmt));
if (NS_FAILED(rv)) {
nsCString error;
error.AppendLiteral("The statement '");
error.Append(aQuery);
error.AppendLiteral("' failed to compile with the error message '");
nsCString msg;
(void)mConnection->GetLastErrorString(msg);
error.Append(msg);
error.AppendLiteral("'.");
NS_ERROR(error.get());
}
NS_ENSURE_SUCCESS(rv, nsnull);
return stmt.forget();
}
template< >
inline
already_AddRefed<mozIStorageAsyncStatement>
StatementCache<mozIStorageAsyncStatement>::CreateStatement(const nsACString& aQuery)
{
NS_ENSURE_TRUE(mConnection, nsnull);
nsCOMPtr<mozIStorageAsyncStatement> stmt;
nsresult rv = mConnection->CreateAsyncStatement(aQuery, getter_AddRefs(stmt));
NS_ENSURE_SUCCESS(rv, nsnull);
return stmt.forget();
}
} // namespace storage
} // namespace mozilla
#endif // mozilla_storage_StatementCache_h

Просмотреть файл

@ -66,7 +66,7 @@
//// Native Language Helpers
#include "mozStorageHelper.h"
#include "mozilla/storage/StatementCache.h"
#include "mozilla/storage/Variant.h"
#endif // mozilla_storage_h_

Просмотреть файл

@ -58,6 +58,7 @@ CPP_UNIT_TESTS = \
test_unlock_notify.cpp \
test_service_init_background_thread.cpp \
test_AsXXX_helpers.cpp \
test_StatementCache.cpp \
$(NULL)
ifdef MOZ_DEBUG

Просмотреть файл

@ -51,6 +51,7 @@
#include "mozIStorageStatement.h"
#include "mozIStoragePendingStatement.h"
#include "nsThreadUtils.h"
#include <sstream>
static int gTotalTests = 0;
static int gPassedTests = 0;
@ -79,7 +80,17 @@ static int gPassedTests = 0;
do_check_true(NS_SUCCEEDED(aResult))
#define do_check_eq(aFirst, aSecond) \
do_check_true(aFirst == aSecond)
PR_BEGIN_MACRO \
gTotalTests++; \
if (aFirst == aSecond) { \
gPassedTests++; \
} else { \
std::ostringstream temp; \
temp << "Expected '" << aFirst << "', got '" << aSecond <<"' at "; \
temp << __FILE__ << ":" << __LINE__ << "!"; \
fail(temp.str().c_str()); \
} \
PR_END_MACRO
already_AddRefed<mozIStorageService>
getService()

Просмотреть файл

@ -0,0 +1,195 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is storage test code.
*
* The Initial Developer of the Original Code is
* the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shawn Wilsher <me@shawnwilsher.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "storage_test_harness.h"
#include "mozilla/storage/StatementCache.h"
using namespace mozilla::storage;
/**
* This file test our statement cache in StatementCache.h.
*/
////////////////////////////////////////////////////////////////////////////////
//// Helpers
class SyncCache : public StatementCache<mozIStorageStatement>
{
public:
SyncCache(nsCOMPtr<mozIStorageConnection>& aConnection)
: StatementCache<mozIStorageStatement>(aConnection)
{
}
};
class AsyncCache : public StatementCache<mozIStorageAsyncStatement>
{
public:
AsyncCache(nsCOMPtr<mozIStorageConnection>& aConnection)
: StatementCache<mozIStorageAsyncStatement>(aConnection)
{
}
};
/**
* Wraps nsCString so we can not implement the same functions twice for each
* type.
*/
class StringWrapper : public nsCString
{
public:
StringWrapper(const char* aOther)
{
this->Assign(aOther);
}
};
////////////////////////////////////////////////////////////////////////////////
//// Test Functions
template<typename StringType>
void
test_GetCachedStatement()
{
nsCOMPtr<mozIStorageConnection> db(getMemoryDatabase());
SyncCache cache(db);
StringType sql = "SELECT * FROM sqlite_master";
// Make sure we get a statement back with the right state.
nsCOMPtr<mozIStorageStatement> stmt = cache.GetCachedStatement(sql);
do_check_true(stmt);
PRInt32 state;
do_check_success(stmt->GetState(&state));
do_check_eq(mozIStorageBaseStatement::MOZ_STORAGE_STATEMENT_READY, state);
// Check to make sure we get the same copy the second time we ask.
nsCOMPtr<mozIStorageStatement> stmt2 = cache.GetCachedStatement(sql);
do_check_true(stmt2);
do_check_eq(stmt.get(), stmt2.get());
}
template <typename StringType>
void
test_FinalizeStatements()
{
nsCOMPtr<mozIStorageConnection> db(getMemoryDatabase());
SyncCache cache(db);
StringType sql = "SELECT * FROM sqlite_master";
// Get a statement, and then tell the cache to finalize.
nsCOMPtr<mozIStorageStatement> stmt = cache.GetCachedStatement(sql);
do_check_true(stmt);
cache.FinalizeStatements();
// We should be in an invalid state at this point.
PRInt32 state;
do_check_success(stmt->GetState(&state));
do_check_eq(mozIStorageBaseStatement::MOZ_STORAGE_STATEMENT_INVALID, state);
// Should be able to close the database now too.
do_check_success(db->Close());
}
template<typename StringType>
void
test_GetCachedAsyncStatement()
{
nsCOMPtr<mozIStorageConnection> db(getMemoryDatabase());
AsyncCache cache(db);
StringType sql = "SELECT * FROM sqlite_master";
// Make sure we get a statement back with the right state.
nsCOMPtr<mozIStorageAsyncStatement> stmt = cache.GetCachedStatement(sql);
do_check_true(stmt);
PRInt32 state;
do_check_success(stmt->GetState(&state));
do_check_eq(mozIStorageBaseStatement::MOZ_STORAGE_STATEMENT_READY, state);
// Check to make sure we get the same copy the second time we ask.
nsCOMPtr<mozIStorageAsyncStatement> stmt2 = cache.GetCachedStatement(sql);
do_check_true(stmt2);
do_check_eq(stmt.get(), stmt2.get());
}
template <typename StringType>
void
test_FinalizeAsyncStatements()
{
nsCOMPtr<mozIStorageConnection> db(getMemoryDatabase());
AsyncCache cache(db);
StringType sql = "SELECT * FROM sqlite_master";
// Get a statement, and then tell the cache to finalize.
nsCOMPtr<mozIStorageAsyncStatement> stmt = cache.GetCachedStatement(sql);
do_check_true(stmt);
cache.FinalizeStatements();
// We should be in an invalid state at this point.
PRInt32 state;
do_check_success(stmt->GetState(&state));
do_check_eq(mozIStorageBaseStatement::MOZ_STORAGE_STATEMENT_INVALID, state);
// Should be able to close the database now too.
do_check_success(db->AsyncClose(nsnull));
}
////////////////////////////////////////////////////////////////////////////////
//// Test Harness Stuff
void (*gTests[])(void) = {
test_GetCachedStatement<const char []>,
test_GetCachedStatement<StringWrapper>,
test_FinalizeStatements<const char []>,
test_FinalizeStatements<StringWrapper>,
test_GetCachedAsyncStatement<const char []>,
test_GetCachedAsyncStatement<StringWrapper>,
test_FinalizeAsyncStatements<const char []>,
test_FinalizeAsyncStatements<StringWrapper>,
};
const char *file = __FILE__;
#define TEST_NAME "StatementCache"
#define TEST_FILE file
#include "storage_test_harness_tail.h"