Bug 539076 - Part1: better error checking in bookmarks service and introduce lazy statements code, r=dietrich
☠☠ backed out by 040c4002e58e ☠ ☠
authorMarco Bonardo <mbonardo@mozilla.com>
Sat, 16 Jan 2010 12:37:57 +0100
changeset 37245 14c20441c8d81e34eeebc160ad1d870c59719267
parent 37244 96dd0b76a3e1557d6d213c25ccbac9a7262e1f2e
child 37246 09058ef6478cd2e700739493fad8e769b49dce6c
child 37259 040c4002e58e4aa767ca09b76cb2f63672316bdf
push idunknown
push userunknown
push dateunknown
reviewersdietrich
bugs539076
milestone1.9.3a1pre
Bug 539076 - Part1: better error checking in bookmarks service and introduce lazy statements code, r=dietrich
toolkit/components/places/src/nsNavBookmarks.cpp
toolkit/components/places/src/nsNavBookmarks.h
--- a/toolkit/components/places/src/nsNavBookmarks.cpp
+++ b/toolkit/components/places/src/nsNavBookmarks.cpp
@@ -103,39 +103,43 @@ nsNavBookmarks::nsNavBookmarks() : mItem
                                  , mRoot(0)
                                  , mBookmarksRoot(0)
                                  , mTagRoot(0)
                                  , mToolbarFolder(0)
                                  , mBatchLevel(0)
                                  , mBatchHasTransaction(PR_FALSE)
                                  , mCanNotify(false)
                                  , mCacheObservers("bookmark-observers")
+                                 , mShuttingDown(false)
 {
   NS_ASSERTION(!gBookmarksService,
                "Attempting to create two instances of the service!");
   gBookmarksService = this;
 }
 
+
 nsNavBookmarks::~nsNavBookmarks()
 {
   NS_ASSERTION(gBookmarksService == this,
                "Deleting a non-singleton instance of the service");
   if (gBookmarksService == this)
     gBookmarksService = nsnull;
 }
 
+
 NS_IMPL_ISUPPORTS3(nsNavBookmarks,
                    nsINavBookmarksService,
                    nsINavHistoryObserver,
                    nsIAnnotationObserver)
 
+
 nsresult
 nsNavBookmarks::Init()
 {
-  nsNavHistory *history = nsNavHistory::GetHistoryService();
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
   mDBConn = history->GetStorageConnection();
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
   nsresult rv = InitStatements();
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = InitRoots();
@@ -156,16 +160,17 @@ nsNavBookmarks::Init()
   // us and we won't go away.
   history->AddObserver(this, PR_FALSE);
 
   // DO NOT PUT STUFF HERE that can fail. See observer comment above.
 
   return NS_OK;
 }
 
+
 // nsNavBookmarks::InitTables
 //
 //    All commands that initialize the schema of the DB go in here. This is
 //    called from history init before the dummy DB connection is started that
 //    will prevent us from modifying the schema.
 
 nsresult // static
 nsNavBookmarks::InitTables(mozIStorageConnection* aDBConn)
@@ -454,18 +459,63 @@ nsNavBookmarks::InitStatements()
       "WHERE k.keyword = ?1 "
       "LIMIT 1"),
     getter_AddRefs(mDBGetURIForKeyword));
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
+
+mozIStorageStatement*
+nsNavBookmarks::GetStatement(const nsCOMPtr<mozIStorageStatement>& aStmt)
+{
+#define RETURN_IF_STMT(_stmt, _sql)                                        \
+  PR_BEGIN_MACRO                                                           \
+  if (address_of(_stmt) == address_of(aStmt)) {                            \
+    if (!_stmt) {                                                          \
+      nsresult rv = mDBConn->CreateStatement(_sql, getter_AddRefs(_stmt)); \
+      NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && _stmt, nsnull);                   \
+    }                                                                      \
+    return _stmt.get();                                                    \
+  }                                                                        \
+  PR_END_MACRO
+
+  if (mShuttingDown)
+    return nsnull;
+
+  RETURN_IF_STMT(mDBAdjustPosition, NS_LITERAL_CSTRING(
+    "UPDATE moz_bookmarks SET position = position + ?1 "
+    "WHERE parent = ?2 AND position >= ?3 AND position <= ?4"));
+
+  RETURN_IF_STMT(mDBRemoveItem, NS_LITERAL_CSTRING(
+    "DELETE FROM moz_bookmarks WHERE id = ?1"));
+
+  RETURN_IF_STMT(mDBGetLastChildId, NS_LITERAL_CSTRING(
+    "SELECT id FROM moz_bookmarks WHERE parent = ?1 "
+    "ORDER BY position DESC LIMIT 1"));
+
+  RETURN_IF_STMT(mDBMoveItem, NS_LITERAL_CSTRING(
+    "UPDATE moz_bookmarks SET parent = ?1, position = ?2 WHERE id = ?3 "));
+
+  RETURN_IF_STMT(mDBSetItemTitle, NS_LITERAL_CSTRING(
+    "UPDATE moz_bookmarks SET title = ?1, lastModified = ?2 WHERE id = ?3 "));
+
+  RETURN_IF_STMT(mDBChangeBookmarkURI, NS_LITERAL_CSTRING(
+    "UPDATE moz_bookmarks SET fk = ?1, lastModified = ?2 WHERE id = ?3 "));
+
+  return nsnull;
+#undef RETURN_IF_STMT
+}
+
+
 nsresult
 nsNavBookmarks::FinalizeStatements() {
+  mShuttingDown = true;
+
   mozIStorageStatement* stmts[] = {
     mDBGetChildren,
     mDBFindURIBookmarks,
     mDBFolderCount,
     mDBGetItemIndex,
     mDBGetChildAt,
     mDBGetItemProperties,
     mDBGetItemIdForGUID,
@@ -474,27 +524,34 @@ nsNavBookmarks::FinalizeStatements() {
     mDBIsBookmarkedInDatabase,
     mDBIsRealBookmark,
     mDBGetLastBookmarkID,
     mDBSetItemDateAdded,
     mDBSetItemLastModified,
     mDBSetItemIndex,
     mDBGetKeywordForURI,
     mDBGetKeywordForBookmark,
-    mDBGetURIForKeyword
+    mDBGetURIForKeyword,
+    mDBAdjustPosition,
+    mDBRemoveItem,
+    mDBGetLastChildId,
+    mDBMoveItem,
+    mDBSetItemTitle,
+    mDBChangeBookmarkURI,
   };
 
   for (PRUint32 i = 0; i < NS_ARRAY_LENGTH(stmts); i++) {
     nsresult rv = nsNavHistory::FinalizeStatement(stmts[i]);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
 }
 
+
 // nsNavBookmarks::InitRoots
 //
 //    This locates and creates if necessary the root items in the bookmarks
 //    folder hierarchy. These items are stored in a special roots table that
 //    maps short predefined names to folder IDs.
 //
 //    Normally, these folders will exist already and we will save their IDs
 //    which are exposed through the bookmark service interface.
@@ -516,138 +573,148 @@ nsNavBookmarks::InitRoots()
 {
   nsCOMPtr<mozIStorageStatement> getRootStatement;
   nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
       "SELECT folder_id FROM moz_bookmarks_roots WHERE root_name = ?1"),
     getter_AddRefs(getRootStatement));
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool createdPlacesRoot = PR_FALSE;
-  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("places"), &mRoot, 0, &createdPlacesRoot);
+  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("places"),
+                  &mRoot, 0, &createdPlacesRoot);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  getRootStatement->Reset();
-  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("menu"), &mBookmarksRoot, mRoot, nsnull);
+  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("menu"),
+                  &mBookmarksRoot, mRoot, nsnull);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool createdToolbarFolder;
-  getRootStatement->Reset();
-  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("toolbar"), &mToolbarFolder, mRoot, &createdToolbarFolder);
+  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("toolbar"),
+                  &mToolbarFolder, mRoot, &createdToolbarFolder);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Once toolbar was not a root, we may need to move over the items and
   // delete the custom folder
   if (!createdPlacesRoot && createdToolbarFolder) {
     nsAnnotationService* annosvc = nsAnnotationService::GetAnnotationService();
     NS_ENSURE_TRUE(annosvc, NS_ERROR_OUT_OF_MEMORY);
 
     nsTArray<PRInt64> folders;
-    annosvc->GetItemsWithAnnotationTArray(BOOKMARKS_TOOLBAR_FOLDER_ANNO,
-                                          &folders);
+    rv = annosvc->GetItemsWithAnnotationTArray(BOOKMARKS_TOOLBAR_FOLDER_ANNO,
+                                               &folders);
+    NS_ENSURE_SUCCESS(rv, rv);
     if (folders.Length() > 0) {
       nsCOMPtr<mozIStorageStatement> moveItems;
       rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
           "UPDATE moz_bookmarks SET parent = ?1 WHERE parent=?2"),
         getter_AddRefs(moveItems));
+      NS_ENSURE_SUCCESS(rv, rv);
       rv = moveItems->BindInt64Parameter(0, mToolbarFolder);
       NS_ENSURE_SUCCESS(rv, rv);
       rv = moveItems->BindInt64Parameter(1, folders[0]);
       NS_ENSURE_SUCCESS(rv, rv);
       rv = moveItems->Execute();
       NS_ENSURE_SUCCESS(rv, rv);
       rv = RemoveFolder(folders[0]);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
-  getRootStatement->Reset();
-  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("tags"), &mTagRoot, mRoot, nsnull);
+  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("tags"),
+                  &mTagRoot, mRoot, nsnull);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  getRootStatement->Reset();
-  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("unfiled"), &mUnfiledRoot, mRoot, nsnull);
+  rv = CreateRoot(getRootStatement, NS_LITERAL_CSTRING("unfiled"),
+                  &mUnfiledRoot, mRoot, nsnull);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Set titles for special folders
   // We cannot rely on createdPlacesRoot due to Fx3beta->final migration path
   PRUint16 databaseStatus = nsINavHistoryService::DATABASE_STATUS_OK;
-  nsNavHistory *history = nsNavHistory::GetHistoryService();
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
   rv = history->GetDatabaseStatus(&databaseStatus);
   if (NS_FAILED(rv) ||
       databaseStatus != nsINavHistoryService::DATABASE_STATUS_OK) {
     rv = InitDefaults();
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
 }
 
+
 // nsNavBookmarks::InitDefaults
 //
 // Initializes default bookmarks and containers.
 // Pulls from places.propertes for l10n.
 // Replaces the old default_places.html file.
 nsresult
 nsNavBookmarks::InitDefaults()
 {
-  nsNavHistory *history = nsNavHistory::GetHistoryService();
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
-  nsIStringBundle *bundle = history->GetBundle();
+  nsIStringBundle* bundle = history->GetBundle();
   NS_ENSURE_TRUE(bundle, NS_ERROR_OUT_OF_MEMORY);
 
   // Bookmarks Menu
   nsXPIDLString bookmarksTitle;
-  nsresult rv = bundle->GetStringFromName(NS_LITERAL_STRING("BookmarksMenuFolderTitle").get(),
-                                          getter_Copies(bookmarksTitle));
+  nsresult rv = bundle->GetStringFromName(
+    NS_LITERAL_STRING("BookmarksMenuFolderTitle").get(),
+    getter_Copies(bookmarksTitle));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = SetItemTitle(mBookmarksRoot, NS_ConvertUTF16toUTF8(bookmarksTitle));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Bookmarks Toolbar
   nsXPIDLString toolbarTitle;
-  rv = bundle->GetStringFromName(NS_LITERAL_STRING("BookmarksToolbarFolderTitle").get(),
-                                 getter_Copies(toolbarTitle));
+  rv = bundle->GetStringFromName(
+    NS_LITERAL_STRING("BookmarksToolbarFolderTitle").get(),
+    getter_Copies(toolbarTitle));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = SetItemTitle(mToolbarFolder, NS_ConvertUTF16toUTF8(toolbarTitle));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Unsorted Bookmarks
   nsXPIDLString unfiledTitle;
-  rv = bundle->GetStringFromName(NS_LITERAL_STRING("UnsortedBookmarksFolderTitle").get(),
-                                 getter_Copies(unfiledTitle));
+  rv = bundle->GetStringFromName(
+    NS_LITERAL_STRING("UnsortedBookmarksFolderTitle").get(),
+    getter_Copies(unfiledTitle));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = SetItemTitle(mUnfiledRoot, NS_ConvertUTF16toUTF8(unfiledTitle));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Tags
   nsXPIDLString tagsTitle;
-  rv = bundle->GetStringFromName(NS_LITERAL_STRING("TagsFolderTitle").get(),
-                                 getter_Copies(tagsTitle));
+  rv = bundle->GetStringFromName(
+    NS_LITERAL_STRING("TagsFolderTitle").get(),
+    getter_Copies(tagsTitle));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = SetItemTitle(mTagRoot, NS_ConvertUTF16toUTF8(tagsTitle));
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
+
 // nsNavBookmarks::CreateRoot
 //
 //    This gets or creates a root folder of the given type. aWasCreated
 //    (optional) is true if the folder had to be created, false if we just used
 //    an old one. The statement that gets a folder ID from a root name is
 //    passed in so the DB only needs to parse the statement once, and we don't
 //    have to have a global for this. Creation is less optimized because it
 //    happens rarely.
 
 nsresult
 nsNavBookmarks::CreateRoot(mozIStorageStatement* aGetRootStatement,
                            const nsCString& name, PRInt64* aID,
                            PRInt64 aParentID, PRBool* aWasCreated)
 {
+  mozStorageStatementScoper scoper(aGetRootStatement);
   PRBool hasResult = PR_FALSE;
   nsresult rv = aGetRootStatement->BindUTF8StringParameter(0, name);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = aGetRootStatement->ExecuteStep(&hasResult);
   NS_ENSURE_SUCCESS(rv, rv);
   if (hasResult) {
     if (aWasCreated)
       *aWasCreated = PR_FALSE;
@@ -674,32 +741,34 @@ nsNavBookmarks::CreateRoot(mozIStorageSt
   rv = insertStatement->BindInt64Parameter(1, *aID);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = insertStatement->Execute();
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
+
 // nsNavBookmarks::GetBookmarksHash
 //
 //    Getter and lazy initializer of the bookmarks redirect hash.
 //    See FillBookmarksHash for more information.
 
 nsDataHashtable<nsTrimInt64HashKey, PRInt64>*
 nsNavBookmarks::GetBookmarksHash()
 {
   if (!mBookmarksHash.IsInitialized()) {
     nsresult rv = FillBookmarksHash();
     NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "FillBookmarksHash() failed!");
   }
 
   return &mBookmarksHash;
 }
 
+
 // nsNavBookmarks::FillBookmarksHash
 //
 //    This initializes the bookmarks hashtable that tells us which bookmark
 //    a given URI redirects to. This hashtable includes all URIs that
 //    redirect to bookmarks.
 
 nsresult
 nsNavBookmarks::FillBookmarksHash()
@@ -718,16 +787,17 @@ nsNavBookmarks::FillBookmarksHash()
       "AND b.fk NOTNULL"),
     getter_AddRefs(statement));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = statement->BindInt32Parameter(0, TYPE_BOOKMARK);
   NS_ENSURE_SUCCESS(rv, rv);
   while (NS_SUCCEEDED(statement->ExecuteStep(&hasMore)) && hasMore) {
     PRInt64 pageID;
     rv = statement->GetInt64(0, &pageID);
+    NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(mBookmarksHash.Put(pageID, pageID), NS_ERROR_OUT_OF_MEMORY);
   }
 
   // Find all pages h2 that have been redirected to from a bookmarked URI:
   //    bookmarked -> url (h1)         url (h2)
   //                    |                 ^
   //                    .                 |
   //                 visit (v1) -> destination visit (v2)
@@ -774,23 +844,24 @@ nsNavBookmarks::FillBookmarksHash()
         "WHERE b.fk IS NOT NULL AND b.type = ?1 "
         "AND v2.visit_type IN (") +
         nsPrintfCString("%d,%d",
                         nsINavHistoryService::TRANSITION_REDIRECT_PERMANENT,
                         nsINavHistoryService::TRANSITION_REDIRECT_TEMPORARY) +
         NS_LITERAL_CSTRING(") GROUP BY v2.place_id "),
     getter_AddRefs(statement));
   NS_ENSURE_SUCCESS(rv, rv);
-  rv = statement->BindInt64Parameter(0, TYPE_BOOKMARK);
+  rv = statement->BindInt32Parameter(0, TYPE_BOOKMARK);
   NS_ENSURE_SUCCESS(rv, rv);
   while (NS_SUCCEEDED(statement->ExecuteStep(&hasMore)) && hasMore) {
     PRInt64 fromId, toId;
-    statement->GetInt64(0, &fromId);
-    statement->GetInt64(1, &toId);
-
+    rv = statement->GetInt64(0, &fromId);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = statement->GetInt64(1, &toId);
+    NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(mBookmarksHash.Put(toId, fromId), NS_ERROR_OUT_OF_MEMORY);
 
     // handle redirects deeper than one level
     rv = RecursiveAddBookmarkHash(fromId, toId, 0);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
@@ -808,17 +879,19 @@ nsNavBookmarks::FillBookmarksHash()
 //
 //    @see RecursiveAddBookmarkHash
 
 nsresult
 nsNavBookmarks::AddBookmarkToHash(PRInt64 aPlaceId, PRTime aMinTime)
 {
   if (!GetBookmarksHash()->Put(aPlaceId, aPlaceId))
     return NS_ERROR_OUT_OF_MEMORY;
-  return RecursiveAddBookmarkHash(aPlaceId, aPlaceId, aMinTime);
+  nsresult rv = RecursiveAddBookmarkHash(aPlaceId, aPlaceId, aMinTime);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
 
 // nsNavBookmkars::RecursiveAddBookmarkHash
 //
 //    Used to add a new level of redirect information to the bookmark hash.
 //    Given a source bookmark 'aBookmark' and 'aCurrentSource' that has already
 //    been added to the hashtable, this will add all redirect destinations of
@@ -904,148 +977,155 @@ RemoveBookmarkHashCallback(nsTrimInt64Ha
 nsresult
 nsNavBookmarks::UpdateBookmarkHashOnRemove(PRInt64 aPlaceId)
 {
   // note we have to use the DB version here since the hashtable may be
   // out-of-date
   PRBool inDB;
   nsresult rv = IsBookmarkedInDatabase(aPlaceId, &inDB);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (inDB)
-    return NS_OK; // bookmark still exists, don't need to update hashtable
-
-  // remove it
-  GetBookmarksHash()->Enumerate(RemoveBookmarkHashCallback,
-                                reinterpret_cast<void*>(&aPlaceId));
+  if (!inDB) {
+    // Bookmark does not exist anymore, remove it from hashtable
+    GetBookmarksHash()->Enumerate(RemoveBookmarkHashCallback,
+                                  reinterpret_cast<void*>(&aPlaceId));
+  }
   return NS_OK;
 }
 
 
 PRBool
 nsNavBookmarks::IsRealBookmark(PRInt64 aPlaceId)
 {
   // Fast path is to check the hash table first.  If it is in the hash table,
   // then verify that it is a real bookmark.
   PRInt64 bookmarkId;
   PRBool isBookmark = GetBookmarksHash()->Get(aPlaceId, &bookmarkId);
-  if (!isBookmark)
-    return PR_FALSE;
-
-  {
+  if (isBookmark) {
     mozStorageStatementScoper scope(mDBIsRealBookmark);
 
-    (void)mDBIsRealBookmark->BindInt64Parameter(0, aPlaceId);
-    (void)mDBIsRealBookmark->BindInt32Parameter(1, TYPE_BOOKMARK);
-    (void)mDBIsRealBookmark->BindUTF8StringParameter(
-      2, NS_LITERAL_CSTRING(LMANNO_FEEDURI)
-    );
+    nsresult rv = mDBIsRealBookmark->BindInt64Parameter(0, aPlaceId);
+    NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Binding failed");
+    rv = mDBIsRealBookmark->BindInt32Parameter(1, TYPE_BOOKMARK);
+    NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Binding failed");
+    rv = mDBIsRealBookmark->BindUTF8StringParameter(
+      2, NS_LITERAL_CSTRING(LMANNO_FEEDURI));
+    NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Binding failed");
 
     // If we get any rows, then there exists at least one bookmark corresponding
     // to aPlaceId that is not a livemark item.
-    if (NS_SUCCEEDED(mDBIsRealBookmark->ExecuteStep(&isBookmark)))
+    rv = mDBIsRealBookmark->ExecuteStep(&isBookmark);
+    NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "ExecuteStep failed");
+    if (NS_SUCCEEDED(rv))
       return isBookmark;
   }
 
   return PR_FALSE;
 }
 
+
 // nsNavBookmarks::IsBookmarkedInDatabase
 //
 //    This checks to see if the specified place_id is actually bookmarked.
 //    This does not check for redirects in the hashtable.
 
 nsresult
 nsNavBookmarks::IsBookmarkedInDatabase(PRInt64 aPlaceId,
-                                       PRBool *aIsBookmarked)
+                                       PRBool* aIsBookmarked)
 {
   mozStorageStatementScoper scope(mDBIsBookmarkedInDatabase);
   nsresult rv = mDBIsBookmarkedInDatabase->BindInt64Parameter(0, aPlaceId);
   NS_ENSURE_SUCCESS(rv, rv);
-
   rv = mDBIsBookmarkedInDatabase->BindInt32Parameter(1, TYPE_BOOKMARK);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  return mDBIsBookmarkedInDatabase->ExecuteStep(aIsBookmarked);
+  rv = mDBIsBookmarkedInDatabase->ExecuteStep(aIsBookmarked);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
 
 nsresult
-nsNavBookmarks::AdjustIndices(PRInt64 aFolder,
-                              PRInt32 aStartIndex, PRInt32 aEndIndex,
+nsNavBookmarks::AdjustIndices(PRInt64 aFolderId,
+                              PRInt32 aStartIndex,
+                              PRInt32 aEndIndex,
                               PRInt32 aDelta)
 {
-  NS_ASSERTION(aStartIndex <= aEndIndex, "start index must be <= end index");
-
-  nsCAutoString buffer;
-  buffer.AssignLiteral("UPDATE moz_bookmarks SET position = position + ");
-  buffer.AppendInt(aDelta);
-  buffer.AppendLiteral(" WHERE parent = ");
-  buffer.AppendInt(aFolder);
-
-  if (aStartIndex != 0) {
-    buffer.AppendLiteral(" AND position >= ");
-    buffer.AppendInt(aStartIndex);
-  }
-  if (aEndIndex != PR_INT32_MAX) {
-    buffer.AppendLiteral(" AND position <= ");
-    buffer.AppendInt(aEndIndex);
-  }
-
-  nsresult rv = mDBConn->ExecuteSimpleSQL(buffer);
+  NS_ASSERTION(aStartIndex >= 0 && aEndIndex <= PR_INT32_MAX &&
+               aStartIndex <= aEndIndex, "Bad indices");
+
+  mozIStorageStatement* stmt = GetStatement(mDBAdjustPosition);
+  NS_ENSURE_STATE(stmt);
+  mozStorageStatementScoper scoper(stmt);
+
+  nsresult rv = stmt->BindInt32Parameter(0, aDelta);
+  NS_ENSURE_SUCCESS(rv, rv);
+  rv = stmt->BindInt64Parameter(1, aFolderId);
+  NS_ENSURE_SUCCESS(rv, rv);
+  rv = stmt->BindInt32Parameter(2, aStartIndex);
+  NS_ENSURE_SUCCESS(rv, rv);
+  rv = stmt->BindInt32Parameter(3, aEndIndex);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  rv = stmt->Execute();
   NS_ENSURE_SUCCESS(rv, rv);
  
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetPlacesRoot(PRInt64 *aRoot)
+nsNavBookmarks::GetPlacesRoot(PRInt64* aRoot)
 {
   *aRoot = mRoot;
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetBookmarksMenuFolder(PRInt64 *aRoot)
+nsNavBookmarks::GetBookmarksMenuFolder(PRInt64* aRoot)
 {
   *aRoot = mBookmarksRoot;
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetToolbarFolder(PRInt64 *aFolderId)
+nsNavBookmarks::GetToolbarFolder(PRInt64* aFolderId)
 {
   *aFolderId = mToolbarFolder;
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetTagsFolder(PRInt64 *aRoot)
+nsNavBookmarks::GetTagsFolder(PRInt64* aRoot)
 {
   *aRoot = mTagRoot;
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetUnfiledBookmarksFolder(PRInt64 *aRoot)
+nsNavBookmarks::GetUnfiledBookmarksFolder(PRInt64* aRoot)
 {
   *aRoot = mUnfiledRoot;
   return NS_OK;
 }
 
+
 nsresult
 nsNavBookmarks::InsertBookmarkInDB(PRInt64 aItemId,
                                    PRInt64 aPlaceId,
                                    enum ItemType aItemType,
                                    PRInt64 aParentId,
                                    PRInt32 aIndex,
-                                   const nsACString &aTitle,
+                                   const nsACString& aTitle,
                                    PRTime aDateAdded,
                                    PRTime aLastModified,
-                                   const nsAString &aServiceContractId,
-                                   PRInt64 *_newItemId)
+                                   const nsAString& aServiceContractId,
+                                   PRInt64* _newItemId)
 {
   NS_ASSERTION(_newItemId, "Null pointer passed to InsertBookmarkInDB!");
 
   mozStorageStatementScoper scope(mDBInsertBookmark);
 
   nsresult rv;
   if (aItemId && aItemId != -1)
     rv = mDBInsertBookmark->BindInt64Parameter(kInsertBookmarkIndex_Id, aItemId);
@@ -1093,47 +1173,50 @@ nsNavBookmarks::InsertBookmarkInDB(PRInt
 
   if (!aItemId || aItemId == -1) {
     // Get the new inserted item id.
     mozStorageStatementScoper scoper(mDBGetLastBookmarkID);
     PRBool hasResult;
     rv = mDBGetLastBookmarkID->ExecuteStep(&hasResult);
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(hasResult, NS_ERROR_UNEXPECTED);
-    *_newItemId = mDBGetLastBookmarkID->AsInt64(0);
+    rv = mDBGetLastBookmarkID->GetInt64(0, _newItemId);
+    NS_ENSURE_SUCCESS(rv, rv);
   }
-  else
+  else {
     *_newItemId = aItemId;
+  }
 
   // Update last modified date of the parent folder.
   // XXX TODO: This should be done recursively for all ancestors, that would
   //           be slow without a nested tree though.  See bug 408991.
   rv = SetItemDateInternal(mDBSetItemLastModified, aParentId, aDateAdded);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::InsertBookmark(PRInt64 aFolder,
-                               nsIURI *aURI,
+                               nsIURI* aURI,
                                PRInt32 aIndex,
                                const nsACString& aTitle,
-                               PRInt64 *aNewBookmarkId)
+                               PRInt64* aNewBookmarkId)
 {
   NS_ENSURE_ARG(aURI);
   NS_ENSURE_ARG_POINTER(aNewBookmarkId);
 
   // You can pass -1 to indicate append, but no other negative number is allowed
   if (aIndex < nsINavBookmarksService::DEFAULT_INDEX)
     return NS_ERROR_INVALID_ARG;
 
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
-  nsNavHistory *history = nsNavHistory::GetHistoryService();
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
 
   // This is really a place ID
   PRInt64 childID;
   nsresult rv = history->GetUrlIdFor(aURI, &childID, PR_TRUE);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRInt32 index;
@@ -1145,18 +1228,16 @@ nsNavBookmarks::InsertBookmark(PRInt64 a
     index = folderCount;
   }
   else {
     index = aIndex;
     rv = AdjustIndices(aFolder, index, PR_INT32_MAX, 1);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  nsString voidString;
-  voidString.SetIsVoid(PR_TRUE);
   rv = InsertBookmarkInDB(-1, childID, BOOKMARK, aFolder, index,
                           aTitle, PR_Now(), nsnull, EmptyString(),
                           aNewBookmarkId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // XXX
   // 0n import / fx 2 migration, is the frecency work going to slow us down?
   // We might want to skip this stuff, as well as the frecency work
@@ -1192,31 +1273,31 @@ nsNavBookmarks::InsertBookmark(PRInt64 a
   // (a side effect of calling GetUrlIdFor()) frecency -1;
   // now we re-calculate the frecency for this moz_place entry. 
   rv = history->UpdateFrecency(childID, isBookmark);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = transaction.Commit();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  AddBookmarkToHash(childID, 0);
+  rv = AddBookmarkToHash(childID, 0);
+  NS_ENSURE_SUCCESS(rv, rv);
 
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnItemAdded(*aNewBookmarkId, aFolder, index, TYPE_BOOKMARK));
 
   // If the bookmark has been added to a tag container, notify all
   // bookmark-folder result nodes which contain a bookmark for the new
   // bookmark's url
   PRInt64 grandParentId;
   rv = GetFolderIdForItem(aFolder, &grandParentId);
   NS_ENSURE_SUCCESS(rv, rv);
   if (grandParentId == mTagRoot) {
     // query for all bookmarks for that URI, notify for each
     nsTArray<PRInt64> bookmarks;
-
     rv = GetBookmarkIdsForURITArray(aURI, bookmarks);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (bookmarks.Length()) {
       for (PRUint32 i = 0; i < bookmarks.Length(); i++) {
         ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                             OnItemChanged(bookmarks[i],
                                           NS_LITERAL_CSTRING("tags"),
@@ -1225,16 +1306,17 @@ nsNavBookmarks::InsertBookmark(PRInt64 a
                                           0,
                                           TYPE_BOOKMARK));
       }
     }
   }
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::RemoveItem(PRInt64 aItemId)
 {
   NS_ENSURE_TRUE(aItemId != mRoot, NS_ERROR_INVALID_ARG);
 
   nsresult rv;
   PRInt32 childIndex;
   PRInt64 placeId, folderId;
@@ -1248,20 +1330,28 @@ nsNavBookmarks::RemoveItem(PRInt64 aItem
 
     PRBool results;
     rv = mDBGetItemProperties->ExecuteStep(&results);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!results)
       return NS_ERROR_INVALID_ARG; // invalid bookmark id
 
-    childIndex = mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Position);
-    placeId = mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_PlaceID);
-    folderId = mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_Parent);
-    itemType = (PRUint16) mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Position,
+                                        &childIndex);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_PlaceID,
+                                        &placeId);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent,
+                                        &folderId);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                        (PRInt32*)&itemType);
+    NS_ENSURE_SUCCESS(rv, rv);
     if (itemType == TYPE_BOOKMARK) {
       rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_URI, spec);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   if (itemType == TYPE_FOLDER) {
     rv = RemoveFolder(aItemId);
@@ -1275,21 +1365,25 @@ nsNavBookmarks::RemoveItem(PRInt64 aItem
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
   // First, remove item annotations
   nsAnnotationService* annosvc = nsAnnotationService::GetAnnotationService();
   NS_ENSURE_TRUE(annosvc, NS_ERROR_OUT_OF_MEMORY);
   rv = annosvc->RemoveItemAnnotations(aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  buffer.AssignLiteral("DELETE FROM moz_bookmarks WHERE id = ");
-  buffer.AppendInt(aItemId);
-
-  rv = mDBConn->ExecuteSimpleSQL(buffer);
-  NS_ENSURE_SUCCESS(rv, rv);
+  {
+    mozIStorageStatement* stmt = GetStatement(mDBRemoveItem);
+    NS_ENSURE_STATE(stmt);
+    mozStorageStatementScoper scoper(stmt);
+    rv = stmt->BindInt64Parameter(0, aItemId);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = stmt->Execute();
+    NS_ENSURE_SUCCESS(rv, rv);
+  }
 
   if (childIndex != -1) {
     rv = AdjustIndices(folderId, childIndex + 1, PR_INT32_MAX, -1);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   rv = SetItemDateInternal(mDBSetItemLastModified, folderId, PR_Now());
   NS_ENSURE_SUCCESS(rv, rv);
@@ -1299,17 +1393,17 @@ nsNavBookmarks::RemoveItem(PRInt64 aItem
 
   rv = UpdateBookmarkHashOnRemove(placeId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (itemType == TYPE_BOOKMARK) {
     // UpdateFrecency needs to know whether placeId is still bookmarked.
     // Although we removed aItemId, placeId may still be bookmarked elsewhere;
     // IsRealBookmark will know.
-    nsNavHistory *history = nsNavHistory::GetHistoryService();
+    nsNavHistory* history = nsNavHistory::GetHistoryService();
     NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
     rv = history->UpdateFrecency(placeId, IsRealBookmark(placeId));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnItemRemoved(aItemId, folderId, childIndex, itemType));
 
@@ -1342,85 +1436,98 @@ nsNavBookmarks::RemoveItem(PRInt64 aItem
       }
     }
   }
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
-nsNavBookmarks::CreateFolder(PRInt64 aParent, const nsACString &aName,
-                             PRInt32 aIndex, PRInt64 *aNewFolder)
+nsNavBookmarks::CreateFolder(PRInt64 aParent, const nsACString& aName,
+                             PRInt32 aIndex, PRInt64* aNewFolder)
 {
   // NOTE: aParent can be null for root creation, so not checked
   NS_ENSURE_ARG_POINTER(aNewFolder);
 
   // CreateContainerWithID returns the index of the new folder, but that's not
   // used here.  To avoid any risk of corrupting data should this function
   // be changed, we'll use a local variable to hold it.  The PR_TRUE argument
   // will cause notifications to be sent to bookmark observers.
   PRInt32 localIndex = aIndex;
-  nsString voidString;
-  voidString.SetIsVoid(PR_TRUE);
-  return CreateContainerWithID(-1, aParent, aName, voidString, PR_TRUE,
-                               &localIndex, aNewFolder);
+  nsresult rv = CreateContainerWithID(-1, aParent, aName, EmptyString(),
+                                      PR_TRUE, &localIndex, aNewFolder);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::CreateDynamicContainer(PRInt64 aParent, const nsACString &aName,
-                                       const nsAString &aContractId,
+nsNavBookmarks::CreateDynamicContainer(PRInt64 aParent,
+                                       const nsACString& aName,
+                                       const nsAString& aContractId,
                                        PRInt32 aIndex,
-                                       PRInt64 *aNewFolder)
+                                       PRInt64* aNewFolder)
 {
-  if (aContractId.IsEmpty())
-    return NS_ERROR_INVALID_ARG;
-
-  return CreateContainerWithID(-1, aParent, aName, aContractId, PR_FALSE,
-                               &aIndex, aNewFolder);
+  NS_ENSURE_FALSE(aContractId.IsEmpty(), NS_ERROR_INVALID_ARG);
+
+  nsresult rv = CreateContainerWithID(-1, aParent, aName, aContractId,
+                                      PR_FALSE, &aIndex, aNewFolder);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetFolderReadonly(PRInt64 aFolder, PRBool *aResult)
+nsNavBookmarks::GetFolderReadonly(PRInt64 aFolder, PRBool* aResult)
 {
   NS_ENSURE_ARG_MIN(aFolder, 1);
   NS_ENSURE_ARG_POINTER(aResult);
 
   nsAnnotationService* annosvc = nsAnnotationService::GetAnnotationService();
   NS_ENSURE_TRUE(annosvc, NS_ERROR_OUT_OF_MEMORY);
-  return annosvc->ItemHasAnnotation(aFolder, READ_ONLY_ANNO, aResult);
+  nsresult rv = annosvc->ItemHasAnnotation(aFolder, READ_ONLY_ANNO, aResult);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::SetFolderReadonly(PRInt64 aFolder, PRBool aReadOnly)
 {
   NS_ENSURE_ARG_MIN(aFolder, 1);
 
   nsAnnotationService* annosvc = nsAnnotationService::GetAnnotationService();
   NS_ENSURE_TRUE(annosvc, NS_ERROR_OUT_OF_MEMORY);
+  nsresult rv;
   if (aReadOnly) {
-    return annosvc->SetItemAnnotationInt32(aFolder, READ_ONLY_ANNO, 1,
-                                           0,
-                                           nsAnnotationService::EXPIRE_NEVER);
+    rv = annosvc->SetItemAnnotationInt32(aFolder, READ_ONLY_ANNO, 1, 0,
+                                         nsAnnotationService::EXPIRE_NEVER);
+    NS_ENSURE_SUCCESS(rv, rv);
   }
   else {
     PRBool hasAnno;
-    nsresult rv = annosvc->ItemHasAnnotation(aFolder, READ_ONLY_ANNO, &hasAnno);
+    rv = annosvc->ItemHasAnnotation(aFolder, READ_ONLY_ANNO, &hasAnno);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (hasAnno)
-      return annosvc->RemoveItemAnnotation(aFolder, READ_ONLY_ANNO);
+    if (hasAnno) {
+      rv = annosvc->RemoveItemAnnotation(aFolder, READ_ONLY_ANNO);
+      NS_ENSURE_SUCCESS(rv, rv);
+    }
   }
   return NS_OK;
 }
 
+
 nsresult
-nsNavBookmarks::CreateContainerWithID(PRInt64 aItemId, PRInt64 aParent,
+nsNavBookmarks::CreateContainerWithID(PRInt64 aItemId,
+                                      PRInt64 aParent,
                                       const nsACString& aName,
                                       const nsAString& aContractId,
                                       PRBool aIsBookmarkFolder,
-                                      PRInt32* aIndex, PRInt64* aNewFolder)
+                                      PRInt32* aIndex,
+                                      PRInt64* aNewFolder)
 {
   // You can pass -1 to indicate append, but no other negative number is allowed
   if (*aIndex < -1)
     return NS_ERROR_INVALID_ARG;
 
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
   PRInt32 index;
@@ -1447,18 +1554,20 @@ nsNavBookmarks::CreateContainerWithID(PR
 
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnItemAdded(*aNewFolder, aParent, index, containerType));
 
   *aIndex = index;
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::InsertSeparator(PRInt64 aParent, PRInt32 aIndex,
+nsNavBookmarks::InsertSeparator(PRInt64 aParent,
+                                PRInt32 aIndex,
                                 PRInt64* aNewItemId)
 {
   NS_ENSURE_ARG_MIN(aParent, 1);
   // -1 means "append", but no other negative value is allowed.
   NS_ENSURE_ARG_MIN(aIndex, -1);
   NS_ENSURE_ARG_POINTER(aNewItemId);
 
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
@@ -1472,58 +1581,61 @@ nsNavBookmarks::InsertSeparator(PRInt64 
     index = folderCount;
   }
   else {
     index = aIndex;
     rv = AdjustIndices(aParent, index, PR_INT32_MAX, 1);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
+  // Set a NULL title, not an empty title.
   nsCString voidString;
   voidString.SetIsVoid(PR_TRUE);
   rv = InsertBookmarkInDB(-1, nsnull, SEPARATOR, aParent, index,
                           voidString, PR_Now(), nsnull, EmptyString(),
                           aNewItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = transaction.Commit();
   NS_ENSURE_SUCCESS(rv, rv);
 
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnItemAdded(*aNewItemId, aParent, index, TYPE_SEPARATOR));
 
   return NS_OK;
 }
 
+
 nsresult
-nsNavBookmarks::GetLastChildId(PRInt64 aFolder, PRInt64* aItemId)
+nsNavBookmarks::GetLastChildId(PRInt64 aFolderId, PRInt64* aItemId)
 {
+  NS_ASSERTION(aFolderId > 0, "Invalid folder id");
   *aItemId = -1;
 
-  nsCOMPtr<mozIStorageStatement> statement;
-  nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "SELECT id FROM moz_bookmarks WHERE parent = ?1 "
-      "ORDER BY position DESC LIMIT 1"),
-    getter_AddRefs(statement));
+  mozIStorageStatement* stmt = GetStatement(mDBGetLastChildId);
+  NS_ENSURE_STATE(stmt);
+  mozStorageStatementScoper scoper(stmt);
+  nsresult rv = stmt->BindInt64Parameter(0, aFolderId);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = statement->BindInt64Parameter(0, aFolder);
+  PRBool found;
+  rv = stmt->ExecuteStep(&found);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  PRBool found;
-  rv = statement->ExecuteStep(&found);
-  NS_ENSURE_SUCCESS(rv, rv);
-  if (found)
-    *aItemId = statement->AsInt64(0);
+  if (found) {
+    rv = stmt->GetInt64(0, aItemId);
+    NS_ENSURE_SUCCESS(rv, rv);
+  }
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetIdForItemAt(PRInt64 aFolder, PRInt32 aIndex, PRInt64* aItemId)
+nsNavBookmarks::GetIdForItemAt(PRInt64 aFolder,
+                               PRInt32 aIndex,
+                               PRInt64* aItemId)
 {
   NS_ENSURE_ARG_MIN(aFolder, 1);
   NS_ENSURE_ARG_POINTER(aItemId);
 
   *aItemId = -1;
 
   nsresult rv;
   if (aIndex == nsINavBookmarksService::DEFAULT_INDEX) {
@@ -1538,47 +1650,49 @@ nsNavBookmarks::GetIdForItemAt(PRInt64 a
     rv = mDBGetChildAt->BindInt64Parameter(0, aFolder);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = mDBGetChildAt->BindInt32Parameter(1, aIndex);
     NS_ENSURE_SUCCESS(rv, rv);
 
     PRBool found;
     rv = mDBGetChildAt->ExecuteStep(&found);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (found)
-      *aItemId = mDBGetChildAt->AsInt64(0);
+    if (found) {
+      rv = mDBGetChildAt->GetInt64(0, aItemId);
+      NS_ENSURE_SUCCESS(rv, rv);
+    }
   }
   return NS_OK;
 }
 
+
 nsresult 
-nsNavBookmarks::GetParentAndIndexOfFolder(PRInt64 aFolder, PRInt64* aParent, 
-                                          PRInt32* aIndex)
+nsNavBookmarks::GetParentAndIndexOfFolder(PRInt64 aFolderId,
+                                          PRInt64* _aParent,
+                                          PRInt32* _aIndex)
 {
-  nsCOMPtr<mozIStorageStatement> statement;
-  nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "SELECT parent, position FROM moz_bookmarks WHERE id = ?1"),
-    getter_AddRefs(statement));
+  mozStorageStatementScoper scope(mDBGetItemProperties);
+  nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aFolderId);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  rv = statement->BindInt64Parameter(0, aFolder);
+  PRBool hasResult;
+  rv = mDBGetItemProperties->ExecuteStep(&hasResult);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  PRBool found;
-  rv = statement->ExecuteStep(&found);
+  NS_ENSURE_TRUE(hasResult, NS_ERROR_INVALID_ARG);
+
+  rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent, _aParent);
   NS_ENSURE_SUCCESS(rv, rv);
-  NS_ENSURE_TRUE(found, NS_ERROR_INVALID_ARG); // Folder does not exist.
-
-  *aParent = statement->AsInt64(0);
-  *aIndex = statement->AsInt32(1);
+  rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Position, _aIndex);
+  NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
-NS_HIDDEN_(nsresult)
+
+nsresult
 nsNavBookmarks::RemoveFolder(PRInt64 aFolderId)
 {
   NS_ENSURE_TRUE(aFolderId != mRoot, NS_ERROR_INVALID_ARG);
 
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnBeforeItemRemoved(aFolderId, TYPE_FOLDER));
 
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
@@ -1587,62 +1701,71 @@ nsNavBookmarks::RemoveFolder(PRInt64 aFo
   PRInt64 parent;
   PRInt32 index, type;
   nsCAutoString folderType;
   {
     mozStorageStatementScoper scope(mDBGetItemProperties);
     rv = mDBGetItemProperties->BindInt64Parameter(0, aFolderId);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    PRBool results;
-    rv = mDBGetItemProperties->ExecuteStep(&results);
+    PRBool hasResult;
+    rv = mDBGetItemProperties->ExecuteStep(&hasResult);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (!results) {
+    if (!hasResult) {
       return NS_ERROR_INVALID_ARG; // folder is not in the hierarchy
     }
 
-    type = mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
-    parent = mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_Parent);
-    index = mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Position);
-    rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_ServiceContractId, folderType);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                        (PRInt32*)&type);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent,
+                                        &parent);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Position,
+                                        &index);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_ServiceContractId,
+                                             folderType);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  if (type != TYPE_FOLDER) {
-    NS_WARNING("RemoveFolder(): aFolderId is not a folder!");
-    return NS_ERROR_INVALID_ARG; // aFolderId is not a folder!
-  }
+  // Ensure this is really a folder.
+  NS_ENSURE_TRUE(type == TYPE_FOLDER, NS_ERROR_INVALID_ARG);
 
   // First, remove item annotations
   nsAnnotationService* annosvc = nsAnnotationService::GetAnnotationService();
   NS_ENSURE_TRUE(annosvc, NS_ERROR_OUT_OF_MEMORY);
   rv = annosvc->RemoveItemAnnotations(aFolderId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // If this is a container bookmark, try to notify its service.
   if (folderType.Length() > 0) {
     // There is a type associated with this folder.
     nsCOMPtr<nsIDynamicContainer> bmcServ = do_GetService(folderType.get());
     if (bmcServ) {
       rv = bmcServ->OnContainerRemoving(aFolderId);
-      if (NS_FAILED(rv))
-        NS_WARNING("Remove folder container notification failed.");
+      NS_WARN_IF_FALSE(NS_SUCCEEDED(rv),
+                       "Remove folder container notification failed.");
     }
   }
 
   // Remove all of the folder's children
   rv = RemoveFolderChildren(aFolderId);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // Remove the folder from its parent
-  nsCAutoString buffer;
-  buffer.AssignLiteral("DELETE FROM moz_bookmarks WHERE id = ");
-  buffer.AppendInt(aFolderId);
-  rv = mDBConn->ExecuteSimpleSQL(buffer);
-  NS_ENSURE_SUCCESS(rv, rv);
+  {
+    // Remove the folder from its parent.
+    mozIStorageStatement* stmt = GetStatement(mDBRemoveItem);
+    NS_ENSURE_STATE(stmt);
+    mozStorageStatementScoper scoper(stmt);
+    rv = stmt->BindInt64Parameter(0, aFolderId);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = stmt->Execute();
+    NS_ENSURE_SUCCESS(rv, rv);
+  }
 
   rv = AdjustIndices(parent, index + 1, PR_INT32_MAX, -1);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetItemDateInternal(mDBSetItemLastModified, parent, PR_Now());
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = transaction.Commit();
@@ -1653,16 +1776,17 @@ nsNavBookmarks::RemoveFolder(PRInt64 aFo
   }
 
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnItemRemoved(aFolderId, parent, index, TYPE_FOLDER));
 
   return NS_OK;
 }
 
+
 NS_IMPL_ISUPPORTS1(nsNavBookmarks::RemoveFolderTransaction, nsITransaction)
 
 NS_IMETHODIMP
 nsNavBookmarks::GetRemoveFolderTransaction(PRInt64 aFolderId, nsITransaction** aResult)
 {
   NS_ENSURE_ARG_MIN(aFolderId, 1);
   NS_ENSURE_ARG_POINTER(aResult);
 
@@ -1673,38 +1797,45 @@ nsNavBookmarks::GetRemoveFolderTransacti
     new RemoveFolderTransaction(aFolderId);
   if (!rft)
     return NS_ERROR_OUT_OF_MEMORY;
 
   NS_ADDREF(*aResult = rft);
   return NS_OK;
 }
 
+
 nsresult
 nsNavBookmarks::GetDescendantChildren(PRInt64 aFolderId,
                                       PRInt64 aGrandParentId,
                                       nsTArray<folderChildrenInfo>& aFolderChildrenArray) {
   // New children will be added from this index on.
   PRUint32 startIndex = aFolderChildrenArray.Length();
   nsresult rv;
   {
     // Collect children informations.
     mozStorageStatementScoper scope(mDBGetChildren);
     rv = mDBGetChildren->BindInt64Parameter(0, aFolderId);
     NS_ENSURE_SUCCESS(rv, rv);
 
     PRBool hasMore;
     while (NS_SUCCEEDED(mDBGetChildren->ExecuteStep(&hasMore)) && hasMore) {
       folderChildrenInfo child;
-      child.itemId = mDBGetChildren->AsInt64(nsNavHistory::kGetInfoIndex_ItemId);
+      rv = mDBGetChildren->GetInt64(nsNavHistory::kGetInfoIndex_ItemId,
+                                    &child.itemId);
+      NS_ENSURE_SUCCESS(rv, rv);
       child.parentId = aFolderId;
       child.grandParentId = aGrandParentId;
-      child.itemType = (PRUint16) mDBGetChildren->AsInt32(kGetChildrenIndex_Type);
-      child.placeId = mDBGetChildren->AsInt64(kGetChildrenIndex_PlaceID);
-      child.index = mDBGetChildren->AsInt32(kGetChildrenIndex_Position);
+      rv = mDBGetChildren->GetInt32(kGetChildrenIndex_Type,
+                                    (PRInt32*)&child.itemType);
+      NS_ENSURE_SUCCESS(rv, rv);
+      rv = mDBGetChildren->GetInt64(kGetChildrenIndex_PlaceID, &child.placeId);
+      NS_ENSURE_SUCCESS(rv, rv);
+      rv = mDBGetChildren->GetInt32(kGetChildrenIndex_Position, &child.index);
+      NS_ENSURE_SUCCESS(rv, rv);
 
       if (child.itemType == TYPE_BOOKMARK) {
         nsCAutoString URIString;
         rv = mDBGetChildren->GetUTF8String(nsNavHistory::kGetInfoIndex_URL,
                                            URIString);
         NS_ENSURE_SUCCESS(rv, rv);
         child.url = URIString;
       }
@@ -1730,41 +1861,48 @@ nsNavBookmarks::GetDescendantChildren(PR
                             aFolderId,
                             aFolderChildrenArray);
     }
   }
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::RemoveFolderChildren(PRInt64 aFolderId)
 {
+  NS_ENSURE_ARG_MIN(aFolderId, 1);
+
   nsresult rv;
   PRUint16 itemType;
   PRInt64 grandParentId;
   {
     mozStorageStatementScoper scope(mDBGetItemProperties);
     rv = mDBGetItemProperties->BindInt64Parameter(0, aFolderId);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Sanity check: ensure that item exists.
     PRBool folderExists;
     if (NS_FAILED(mDBGetItemProperties->ExecuteStep(&folderExists)) || !folderExists)
       return NS_ERROR_INVALID_ARG;
 
     // Sanity check: ensure that this is a folder.
-    itemType = (PRUint16) mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                        (PRInt32*)&itemType);
+    NS_ENSURE_SUCCESS(rv, rv);
     if (itemType != TYPE_FOLDER)
       return NS_ERROR_INVALID_ARG;
 
     // Get the grandParent.
     // We have to do this only once since recursion will give us other
     // grandParents without the need of additional queries.
-    grandParentId = mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_Parent);
+    rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent,
+                                        &grandParentId);
+    NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Fill folder children array recursively.
   nsTArray<folderChildrenInfo> folderChildrenArray;
   rv = GetDescendantChildren(aFolderId, grandParentId, folderChildrenArray);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Build a string of folders whose children will be removed.
@@ -1829,17 +1967,17 @@ nsNavBookmarks::RemoveFolderChildren(PRI
     folderChildrenInfo child = folderChildrenArray[i];
     if (child.itemType == TYPE_BOOKMARK) {
       PRInt64 placeId = child.placeId;
       UpdateBookmarkHashOnRemove(placeId);
 
       // UpdateFrecency needs to know whether placeId is still bookmarked.
       // Although we removed a child of aFolderId that bookmarked it, it may
       // still be bookmarked elsewhere; IsRealBookmark will know.
-      nsNavHistory *history = nsNavHistory::GetHistoryService();
+      nsNavHistory* history = nsNavHistory::GetHistoryService();
       NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
       rv = history->UpdateFrecency(placeId, IsRealBookmark(placeId));
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   rv = transaction.Commit();
   NS_ENSURE_SUCCESS(rv, rv);
@@ -1881,28 +2019,27 @@ nsNavBookmarks::RemoveFolderChildren(PRI
         }
       }
     }
   }
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::MoveItem(PRInt64 aItemId, PRInt64 aNewParent, PRInt32 aIndex)
 {
   NS_ENSURE_TRUE(aItemId != mRoot, NS_ERROR_INVALID_ARG);
-
-  // You can pass -1 to indicate append, but no other negative number is allowed
-  if (aIndex < -1)
-    return NS_ERROR_INVALID_ARG;
-
+  NS_ENSURE_ARG_MIN(aItemId, 1);
+  NS_ENSURE_ARG_MIN(aNewParent, 1);
+  // -1 is append, but no other negative number is allowed.
+  NS_ENSURE_ARG_MIN(aIndex, -1);
   // Disallow making an item its own parent.
-  if (aItemId == aNewParent)
-    return NS_ERROR_INVALID_ARG;
+  NS_ENSURE_TRUE(aItemId != aNewParent, NS_ERROR_INVALID_ARG);
 
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
   // get item properties
   nsresult rv;
   PRInt64 oldParent;
   PRInt32 oldIndex;
   PRUint16 itemType;
@@ -1914,47 +2051,60 @@ nsNavBookmarks::MoveItem(PRInt64 aItemId
 
     PRBool results;
     rv = mDBGetItemProperties->ExecuteStep(&results);
     NS_ENSURE_SUCCESS(rv, rv);
     if (!results) {
       return NS_ERROR_INVALID_ARG; // folder is not in the hierarchy
     }
 
-    oldParent = mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_Parent);
-    oldIndex = mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Position);
-    itemType = (PRUint16) mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
+    rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent,
+                                        &oldParent);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Position,
+                                        &oldIndex);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                        (PRInt32*)&itemType);
+    NS_ENSURE_SUCCESS(rv, rv);
     if (itemType == TYPE_FOLDER) {
       rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_ServiceContractId,
                                                folderType);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   // if parent and index are the same, nothing to do
   if (oldParent == aNewParent && oldIndex == aIndex)
     return NS_OK;
 
   // Make sure aNewParent is not aFolder or a subfolder of aFolder
   if (itemType == TYPE_FOLDER) {
-    PRInt64 p = aNewParent;
-
-    while (p) {
+    PRInt64 ancestorId = aNewParent;
+
+    while (ancestorId) {
       mozStorageStatementScoper scope(mDBGetItemProperties);
-      if (p == aItemId) {
+      if (ancestorId == aItemId) {
         return NS_ERROR_INVALID_ARG;
       }
 
-      rv = mDBGetItemProperties->BindInt64Parameter(0, p);
+      rv = mDBGetItemProperties->BindInt64Parameter(0, ancestorId);
+      NS_ENSURE_SUCCESS(rv, rv);
+
+      PRBool hasResult;
+      rv = mDBGetItemProperties->ExecuteStep(&hasResult);
       NS_ENSURE_SUCCESS(rv, rv);
-
-      PRBool results;
-      rv = mDBGetItemProperties->ExecuteStep(&results);
-      NS_ENSURE_SUCCESS(rv, rv);
-      p = results ? mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_Parent) : 0;
+      if (hasResult) {
+        rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent,
+                                            &ancestorId);
+        NS_ENSURE_SUCCESS(rv, rv);
+      }
+      else {
+        break;
+      }
     }
   }
 
   // calculate new index
   PRInt32 newIndex;
   PRInt32 folderCount;
   rv = FolderCount(aNewParent, &folderCount);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -1989,46 +2139,46 @@ nsNavBookmarks::MoveItem(PRInt64 aItemId
   // do this before we update the parent/index fields
   // or we'll re-adjust the index for the item we are moving
   if (oldParent == aNewParent) {
     // We can optimize the updates if moving within the same container.
     // We only shift the items between the old and new positions, since the
     // insertion will offset the deletion.
     if (oldIndex > newIndex) {
       rv = AdjustIndices(oldParent, newIndex, oldIndex - 1, 1);
-    } else {
+    }
+    else {
       rv = AdjustIndices(oldParent, oldIndex + 1, newIndex, -1);
     }
-  } else {
+    NS_ENSURE_SUCCESS(rv, rv);
+  }
+  else {
     // We're moving between containers, so this happens in two steps.
     // First, fill the hole from the removal from the old parent.
     rv = AdjustIndices(oldParent, oldIndex + 1, PR_INT32_MAX, -1);
     NS_ENSURE_SUCCESS(rv, rv);
     // Now, make room in the new parent for the insertion.
     rv = AdjustIndices(aNewParent, newIndex, PR_INT32_MAX, 1);
-  }
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // update parent/index fields
-  nsCAutoString buffer;
-  buffer.AssignLiteral("UPDATE moz_bookmarks SET ");
-  if (aNewParent != oldParent) {
-    buffer.AppendLiteral(" parent = ");
-    buffer.AppendInt(aNewParent);
+    NS_ENSURE_SUCCESS(rv, rv);
   }
-  if (newIndex != oldIndex) {
-    if (aNewParent != oldParent)
-      buffer.AppendLiteral(", ");
-    buffer.AppendLiteral(" position = ");
-    buffer.AppendInt(newIndex);
+
+  {
+    // Update parent and position.
+    mozIStorageStatement* stmt = GetStatement(mDBMoveItem);
+    NS_ENSURE_STATE(stmt);
+    mozStorageStatementScoper scoper(stmt);
+    rv = stmt->BindInt64Parameter(0, aNewParent);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = stmt->BindInt32Parameter(1, newIndex);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = stmt->BindInt64Parameter(2, aItemId);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = stmt->Execute();
+    NS_ENSURE_SUCCESS(rv, rv);
   }
-  buffer.AppendLiteral(" WHERE id = ");
-  buffer.AppendInt(aItemId);
-  rv = mDBConn->ExecuteSimpleSQL(buffer);
-  NS_ENSURE_SUCCESS(rv, rv);
 
   PRTime now = PR_Now();
   rv = SetItemDateInternal(mDBSetItemLastModified, oldParent, now);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = SetItemDateInternal(mDBSetItemLastModified, aNewParent, now);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = transaction.Commit();
@@ -2046,34 +2196,38 @@ nsNavBookmarks::MoveItem(PRInt64 aItemId
     if (NS_SUCCEEDED(rv)) {
       rv = container->OnContainerMoved(aItemId, aNewParent, newIndex);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
   return NS_OK;
 }
 
+
 nsresult
-nsNavBookmarks::SetItemDateInternal(mozIStorageStatement* aStatement, PRInt64 aItemId, PRTime aValue)
+nsNavBookmarks::SetItemDateInternal(mozIStorageStatement* aStatement,
+                                    PRInt64 aItemId,
+                                    PRTime aValue)
 {
   mozStorageStatementScoper scope(aStatement);
   nsresult rv = aStatement->BindInt64Parameter(0, aValue);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = aStatement->BindInt64Parameter(1, aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = aStatement->Execute();
   NS_ENSURE_SUCCESS(rv, rv);
 
   // note, we are not notifying the observers
   // that the item has changed.
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::SetItemDateAdded(PRInt64 aItemId, PRTime aDateAdded)
 {
   // GetItemType also ensures that aItemId points to a valid item.
   PRUint16 itemType;
   nsresult rv = GetItemType(aItemId, &itemType);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -2085,36 +2239,40 @@ nsNavBookmarks::SetItemDateAdded(PRInt64
                       OnItemChanged(aItemId, NS_LITERAL_CSTRING("dateAdded"),
                                     PR_FALSE,
                                     nsPrintfCString(16, "%lld", aDateAdded),
                                     aDateAdded,
                                     itemType));
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetItemDateAdded(PRInt64 aItemId, PRTime *aDateAdded)
+nsNavBookmarks::GetItemDateAdded(PRInt64 aItemId, PRTime* _dateAdded)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
-  NS_ENSURE_ARG_POINTER(aDateAdded);
+  NS_ENSURE_ARG_POINTER(_dateAdded);
 
   mozStorageStatementScoper scope(mDBGetItemProperties);
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  PRBool results;
-  rv = mDBGetItemProperties->ExecuteStep(&results);
+  PRBool hasResult;
+  rv = mDBGetItemProperties->ExecuteStep(&hasResult);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  if (!results)
-    return NS_ERROR_INVALID_ARG; // invalid item id
-
-  return mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_DateAdded, aDateAdded);
+  NS_ENSURE_TRUE(hasResult, NS_ERROR_INVALID_ARG); // Invalid itemId.
+
+  rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_DateAdded,
+                                      _dateAdded);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::SetItemLastModified(PRInt64 aItemId, PRTime aLastModified)
 {
   // GetItemType also ensures that aItemId points to a valid item.
   PRUint16 itemType;
   nsresult rv = GetItemType(aItemId, &itemType);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -2126,18 +2284,19 @@ nsNavBookmarks::SetItemLastModified(PRIn
                                     NS_LITERAL_CSTRING("lastModified"),
                                     PR_FALSE,
                                     nsPrintfCString(16, "%lld", aLastModified),
                                     aLastModified,
                                     itemType));
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetItemLastModified(PRInt64 aItemId, PRTime *aLastModified)
+nsNavBookmarks::GetItemLastModified(PRInt64 aItemId, PRTime* aLastModified)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
   NS_ENSURE_ARG_POINTER(aLastModified);
 
   mozStorageStatementScoper scope(mDBGetItemProperties);
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -2146,16 +2305,17 @@ nsNavBookmarks::GetItemLastModified(PRIn
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!results)
     return NS_ERROR_INVALID_ARG; // invalid item id
 
   return mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_LastModified, aLastModified);
 }
 
+
 nsresult
 nsNavBookmarks::GetGUIDBase(nsAString &aGUIDBase)
 {
   if (!mGUIDBase.IsEmpty()) {
     aGUIDBase = mGUIDBase;
     return NS_OK;
   }
 
@@ -2168,89 +2328,97 @@ nsNavBookmarks::GetGUIDBase(nsAString &a
   NS_ENSURE_SUCCESS(rv, rv);
   char GUIDChars[NSID_LENGTH];
   GUID.ToProvidedString(GUIDChars);
   CopyASCIItoUTF16(GUIDChars, mGUIDBase);
   aGUIDBase = mGUIDBase;
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetItemGUID(PRInt64 aItemId, nsAString &aGUID)
+nsNavBookmarks::GetItemGUID(PRInt64 aItemId, nsAString& aGUID)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
 
   nsAnnotationService* annosvc = nsAnnotationService::GetAnnotationService();
   NS_ENSURE_TRUE(annosvc, NS_ERROR_OUT_OF_MEMORY);
   nsresult rv = annosvc->GetItemAnnotationString(aItemId, GUID_ANNO, aGUID);
-
   if (NS_SUCCEEDED(rv) || rv != NS_ERROR_NOT_AVAILABLE)
     return rv;
 
   nsAutoString tmp;
   tmp.AppendInt(mItemCount++);
   aGUID.SetCapacity(NSID_LENGTH - 1 + tmp.Length());
   nsString GUIDBase;
   rv = GetGUIDBase(GUIDBase);
   NS_ENSURE_SUCCESS(rv, rv);
   aGUID.Assign(GUIDBase);
   aGUID.Append(tmp);
 
-  return SetItemGUID(aItemId, aGUID);
+  rv = SetItemGUID(aItemId, aGUID);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::SetItemGUID(PRInt64 aItemId, const nsAString &aGUID)
+nsNavBookmarks::SetItemGUID(PRInt64 aItemId, const nsAString& aGUID)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
 
   PRInt64 checkId;
   GetItemIdForGUID(aGUID, &checkId);
   if (checkId != -1)
     return NS_ERROR_INVALID_ARG; // invalid GUID, already exists
 
   nsAnnotationService* annosvc = nsAnnotationService::GetAnnotationService();
   NS_ENSURE_TRUE(annosvc, NS_ERROR_OUT_OF_MEMORY);
-  return annosvc->SetItemAnnotationString(aItemId, GUID_ANNO, aGUID, 0,
-                                          nsIAnnotationService::EXPIRE_NEVER);
+  nsresult rv = annosvc->SetItemAnnotationString(aItemId, GUID_ANNO, aGUID, 0,
+                                                 nsIAnnotationService::EXPIRE_NEVER);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetItemIdForGUID(const nsAString &aGUID, PRInt64 *aItemId)
+nsNavBookmarks::GetItemIdForGUID(const nsAString& aGUID, PRInt64* aItemId)
 {
   NS_ENSURE_ARG_POINTER(aItemId);
 
   mozStorageStatementScoper scoper(mDBGetItemIdForGUID);
   nsresult rv = mDBGetItemIdForGUID->BindStringParameter(0, aGUID);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool hasMore = PR_FALSE;
   rv = mDBGetItemIdForGUID->ExecuteStep(&hasMore);
   if (NS_FAILED(rv) || ! hasMore) {
     *aItemId = -1;
     return NS_OK; // not found: return -1
   }
 
   // found, get the itemId
-  return mDBGetItemIdForGUID->GetInt64(0, aItemId);
+  rv = mDBGetItemIdForGUID->GetInt64(0, aItemId);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::SetItemTitle(PRInt64 aItemId, const nsACString &aTitle)
+nsNavBookmarks::SetItemTitle(PRInt64 aItemId, const nsACString& aTitle)
 {
   // GetItemType also ensures that aItemId points to a valid item.
   PRUint16 itemType;
   nsresult rv = GetItemType(aItemId, &itemType);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<mozIStorageStatement> statement;
-  rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "UPDATE moz_bookmarks SET title = ?1, lastModified = ?2 WHERE id = ?3"),
-    getter_AddRefs(statement));
-  NS_ENSURE_SUCCESS(rv, rv);
+  mozIStorageStatement* statement = GetStatement(mDBSetItemTitle);
+  NS_ENSURE_STATE(statement);
+  mozStorageStatementScoper scoper(statement);
+
   // Support setting a null title, we support this in insertBookmark.
   if (aTitle.IsVoid())
     rv = statement->BindNullParameter(0);
   else
     rv = statement->BindUTF8StringParameter(0, aTitle);
   NS_ENSURE_SUCCESS(rv, rv);
   PRTime lastModified = PR_Now();
   rv = statement->BindInt64Parameter(1, lastModified);
@@ -2266,157 +2434,179 @@ nsNavBookmarks::SetItemTitle(PRInt64 aIt
                                     NS_LITERAL_CSTRING("title"),
                                     PR_FALSE,
                                     aTitle,
                                     lastModified,
                                     itemType));
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetItemTitle(PRInt64 aItemId, nsACString &aTitle)
+nsNavBookmarks::GetItemTitle(PRInt64 aItemId, nsACString& aTitle)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
 
   mozStorageStatementScoper scope(mDBGetItemProperties);
 
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool results;
   rv = mDBGetItemProperties->ExecuteStep(&results);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!results)
     return NS_ERROR_INVALID_ARG; // invalid bookmark id
 
-  return mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_Title, aTitle);
+  rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_Title,
+                                           aTitle);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetBookmarkURI(PRInt64 aItemId, nsIURI **aURI)
+nsNavBookmarks::GetBookmarkURI(PRInt64 aItemId, nsIURI** aURI)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
   NS_ENSURE_ARG_POINTER(aURI);
 
   mozStorageStatementScoper scope(mDBGetItemProperties);
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool results;
   rv = mDBGetItemProperties->ExecuteStep(&results);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!results)
     return NS_ERROR_INVALID_ARG; // invalid bookmark id
 
-  PRInt32 type = mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
-  if (type != TYPE_BOOKMARK)
-    return NS_ERROR_INVALID_ARG; // invalid type (only for bookmarks)
+  PRInt32 type;
+  rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                      (PRInt32*)&type);
+  NS_ENSURE_SUCCESS(rv, rv);
+  // Ensure this is a bookmark.
+  NS_ENSURE_TRUE(type == TYPE_BOOKMARK, NS_ERROR_INVALID_ARG);
 
   nsCAutoString spec;
   rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_URI, spec);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = NS_NewURI(aURI, spec);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetItemType(PRInt64 aItemId, PRUint16 *aType)
+nsNavBookmarks::GetItemType(PRInt64 aItemId, PRUint16* _type)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
-  NS_ENSURE_ARG_POINTER(aType);
+  NS_ENSURE_ARG_POINTER(_type);
 
   mozStorageStatementScoper scope(mDBGetItemProperties);
 
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool results;
   rv = mDBGetItemProperties->ExecuteStep(&results);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!results) {
     return NS_ERROR_INVALID_ARG; // invalid bookmark id
   }
 
-  *aType = (PRUint16)mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
+  rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                      (PRInt32*)_type);
+  NS_ENSURE_SUCCESS(rv, rv);
+
   return NS_OK;
 }
 
+
 nsresult
-nsNavBookmarks::GetFolderType(PRInt64 aFolder, nsACString &aType)
+nsNavBookmarks::GetFolderType(PRInt64 aFolder, nsACString& aType)
 {
   mozStorageStatementScoper scope(mDBGetItemProperties);
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aFolder);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool results;
   rv = mDBGetItemProperties->ExecuteStep(&results);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!results) {
     return NS_ERROR_INVALID_ARG;
   }
 
   return mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_ServiceContractId, aType);
 }
 
+
 nsresult
 nsNavBookmarks::ResultNodeForContainer(PRInt64 aID,
-                                       nsNavHistoryQueryOptions *aOptions,
-                                       nsNavHistoryResultNode **aNode)
+                                       nsNavHistoryQueryOptions* aOptions,
+                                       nsNavHistoryResultNode** aNode)
 {
   mozStorageStatementScoper scope(mDBGetItemProperties);
   mDBGetItemProperties->BindInt64Parameter(0, aID);
 
   PRBool results;
   nsresult rv = mDBGetItemProperties->ExecuteStep(&results);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ASSERTION(results, "ResultNodeForContainer expects a valid item id");
 
-  // title
   nsCAutoString title;
-  rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_Title, title);
-
-  PRUint16 itemType = (PRUint16) mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
+  rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_Title,
+                                           title);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  PRUint16 itemType;
+  rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                      (PRInt32*)&itemType);
+  NS_ENSURE_SUCCESS(rv, rv);
   if (itemType == TYPE_DYNAMIC_CONTAINER) {
     // contract id
     nsCAutoString contractId;
     rv = mDBGetItemProperties->GetUTF8String(kGetItemPropertiesIndex_ServiceContractId,
                                              contractId);
     NS_ENSURE_SUCCESS(rv, rv);
     *aNode = new nsNavHistoryContainerResultNode(EmptyCString(), title, EmptyCString(),
                                                  nsINavHistoryResultNode::RESULT_TYPE_DYNAMIC_CONTAINER,
                                                  PR_TRUE,
                                                  contractId,
                                                  aOptions);
     (*aNode)->mItemId = aID;
-  } else { // TYPE_FOLDER
+  }
+  else { // TYPE_FOLDER
     *aNode = new nsNavHistoryFolderResultNode(title, aOptions, aID, EmptyCString());
   }
   if (!*aNode)
     return NS_ERROR_OUT_OF_MEMORY;
 
-  (*aNode)->mDateAdded =
-    mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_DateAdded);
-  (*aNode)->mLastModified =
-    mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_LastModified);
+  rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_DateAdded,
+                                      &(*aNode)->mDateAdded);
+  NS_ENSURE_SUCCESS(rv, rv);
+  rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_LastModified,
+                                      &(*aNode)->mLastModified);
+  NS_ENSURE_SUCCESS(rv, rv);
 
   NS_ADDREF(*aNode);
   return NS_OK;
 }
 
+
 nsresult
 nsNavBookmarks::QueryFolderChildren(PRInt64 aFolderId,
-                                    nsNavHistoryQueryOptions *aOptions,
-                                    nsCOMArray<nsNavHistoryResultNode> *aChildren)
+                                    nsNavHistoryQueryOptions* aOptions,
+                                    nsCOMArray<nsNavHistoryResultNode>* aChildren)
 {
   mozStorageStatementScoper scope(mDBGetChildren);
 
   nsresult rv = mDBGetChildren->BindInt64Parameter(0, aFolderId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool results;
 
@@ -2427,21 +2617,26 @@ nsNavBookmarks::QueryFolderChildren(PRIn
   while (NS_SUCCEEDED(mDBGetChildren->ExecuteStep(&results)) && results) {
 
     // The results will be in order of index. Even if we don't add a node
     // because it was excluded, we need to count its index, so do that
     // before doing anything else. Index was initialized to -1 above, so
     // it will start counting at 0 the first time through the loop.
     index ++;
 
-    PRUint16 itemType = (PRUint16) mDBGetChildren->AsInt32(kGetChildrenIndex_Type);
-    PRInt64 id = mDBGetChildren->AsInt64(nsNavHistory::kGetInfoIndex_ItemId);
+    PRUint16 itemType;
+    rv = mDBGetChildren->GetInt32(kGetChildrenIndex_Type,
+                                  (PRInt32*)&itemType);
+    NS_ENSURE_SUCCESS(rv, rv);
+    PRInt64 id;
+    rv = mDBGetChildren->GetInt64(nsNavHistory::kGetInfoIndex_ItemId, &id);
+    NS_ENSURE_SUCCESS(rv, rv);
     nsRefPtr<nsNavHistoryResultNode> node;
     if (itemType == TYPE_BOOKMARK) {
-      nsNavHistory *history = nsNavHistory::GetHistoryService();
+      nsNavHistory* history = nsNavHistory::GetHistoryService();
       NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
       rv = history->RowToResult(mDBGetChildren, options, getter_AddRefs(node));
       NS_ENSURE_SUCCESS(rv, rv);
 
       PRUint32 nodeType;
       node->GetType(&nodeType);
       if ((nodeType == nsINavHistoryResultNode::RESULT_TYPE_QUERY &&
            aOptions->ExcludeQueries()) ||
@@ -2467,70 +2662,79 @@ nsNavBookmarks::QueryFolderChildren(PRIn
       if (aOptions->ExcludeItems()) {
         continue;
       }
       node = new nsNavHistorySeparatorResultNode();
       NS_ENSURE_TRUE(node, NS_ERROR_OUT_OF_MEMORY);
 
       // add the item identifier (RowToResult does so for bookmark items in
       // the next else block);
-      node->mItemId =
-        mDBGetChildren->AsInt64(nsNavHistory::kGetInfoIndex_ItemId);
-
+      rv = mDBGetChildren->GetInt64(nsNavHistory::kGetInfoIndex_ItemId,
+                                    &node->mItemId);
+      NS_ENSURE_SUCCESS(rv, rv);
       // date-added and last-modified
-      node->mDateAdded =
-        mDBGetChildren->AsInt64(nsNavHistory::kGetInfoIndex_ItemDateAdded);
-      node->mLastModified =
-        mDBGetChildren->AsInt64(nsNavHistory::kGetInfoIndex_ItemLastModified);
+      rv = mDBGetChildren->GetInt64(nsNavHistory::kGetInfoIndex_ItemDateAdded,
+                                    &node->mDateAdded);
+      NS_ENSURE_SUCCESS(rv, rv);
+      rv = mDBGetChildren->GetInt64(nsNavHistory::kGetInfoIndex_ItemLastModified,
+                                    &node->mLastModified);
+      NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // this method fills all bookmark queries, so we store the index of the
     // item in its parent
     node->mBookmarkIndex = index;
 
     NS_ENSURE_TRUE(aChildren->AppendObject(node), NS_ERROR_OUT_OF_MEMORY);
   }
   return NS_OK;
 }
 
+
 nsresult
-nsNavBookmarks::FolderCount(PRInt64 aFolderId, PRInt32 *aFolderCount)
+nsNavBookmarks::FolderCount(PRInt64 aFolderId, PRInt32* _folderCount)
 {
-  *aFolderCount = 0;
+  *_folderCount = 0;
   mozStorageStatementScoper scope(mDBFolderCount);
 
   nsresult rv = mDBFolderCount->BindInt64Parameter(0, aFolderId);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  PRBool results;
-  rv = mDBFolderCount->ExecuteStep(&results);
+  PRBool hasResult;
+  rv = mDBFolderCount->ExecuteStep(&hasResult);
   NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(hasResult, NS_ERROR_UNEXPECTED);
 
   // Ensure that the folder we are looking for exists.
-  NS_ENSURE_TRUE(mDBFolderCount->AsInt64(1) == aFolderId, NS_ERROR_INVALID_ARG);
-
-  *aFolderCount = mDBFolderCount->AsInt32(0);
+  PRInt64 confirmFolderId;
+  rv = mDBFolderCount->GetInt64(1, &confirmFolderId);
+  NS_ENSURE_SUCCESS(rv, rv);
+  NS_ENSURE_TRUE(confirmFolderId == aFolderId, NS_ERROR_INVALID_ARG);
+
+  rv = mDBFolderCount->GetInt32(0, _folderCount);
+  NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::IsBookmarked(nsIURI *aURI, PRBool *aBookmarked)
+nsNavBookmarks::IsBookmarked(nsIURI* aURI, PRBool* aBookmarked)
 {
   NS_ENSURE_ARG(aURI);
   NS_ENSURE_ARG_POINTER(aBookmarked);
 
-  nsNavHistory *history = nsNavHistory::GetHistoryService();
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
 
   // convert the URL to an ID
   PRInt64 urlID;
   nsresult rv = history->GetUrlIdFor(aURI, &urlID, PR_FALSE);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (! urlID) {
+  if (!urlID) {
     // never seen this before, not even in history
     *aBookmarked = PR_FALSE;
     return NS_OK;
   }
 
   PRInt64 bookmarkedID;
   PRBool foundOne = GetBookmarksHash()->Get(urlID, &bookmarkedID);
 
@@ -2547,32 +2751,33 @@ nsNavBookmarks::IsBookmarked(nsIURI *aUR
   rv = IsBookmarkedInDatabase(urlID, &realBookmarked);
   NS_ASSERTION(realBookmarked == *aBookmarked,
                "Bookmark hash table out-of-sync with the database");
 #endif
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::GetBookmarkedURIFor(nsIURI* aURI, nsIURI** _retval)
 {
   NS_ENSURE_ARG(aURI);
   NS_ENSURE_ARG_POINTER(_retval);
 
   *_retval = nsnull;
 
-  nsNavHistory *history = nsNavHistory::GetHistoryService();
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
 
   // convert the URL to an ID
   PRInt64 urlID;
   nsresult rv = history->GetUrlIdFor(aURI, &urlID, PR_FALSE);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (! urlID) {
+  if (!urlID) {
     // never seen this before, not even in history, leave result NULL
     return NS_OK;
   }
 
   PRInt64 bookmarkID;
   if (GetBookmarksHash()->Get(urlID, &bookmarkID)) {
     // found one, convert ID back to URL. This statement is NOT refcounted
     mozIStorageStatement* statement = history->DBGetIdPageInfo();
@@ -2587,25 +2792,26 @@ nsNavBookmarks::GetBookmarkedURIFor(nsIU
       nsCAutoString spec;
       statement->GetUTF8String(nsNavHistory::kGetInfoIndex_URL, spec);
       return NS_NewURI(_retval, spec);
     }
   }
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::ChangeBookmarkURI(PRInt64 aBookmarkId, nsIURI *aNewURI)
+nsNavBookmarks::ChangeBookmarkURI(PRInt64 aBookmarkId, nsIURI* aNewURI)
 {
   NS_ENSURE_ARG_MIN(aBookmarkId, 1);
   NS_ENSURE_ARG(aNewURI);
 
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
-  nsNavHistory *history = nsNavHistory::GetHistoryService();
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
 
   PRInt64 placeId;
   nsresult rv = history->GetUrlIdFor(aNewURI, &placeId, PR_TRUE);
   NS_ENSURE_SUCCESS(rv, rv);
   if (!placeId)
     return NS_ERROR_INVALID_ARG;
 
@@ -2613,28 +2819,27 @@ nsNavBookmarks::ChangeBookmarkURI(PRInt6
   // before we change it.  GetBookmarkURI will fail if aBookmarkId is bad.
   nsCOMPtr<nsIURI> oldURI;
   PRInt64 oldPlaceId;
   rv = GetBookmarkURI(aBookmarkId, getter_AddRefs(oldURI));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = history->GetUrlIdFor(oldURI, &oldPlaceId, PR_FALSE);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<mozIStorageStatement> statement;
-  rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "UPDATE moz_bookmarks SET fk = ?1, lastModified = ?2 WHERE id = ?3"),
-    getter_AddRefs(statement));
+  mozIStorageStatement* statement = GetStatement(mDBChangeBookmarkURI);
+  NS_ENSURE_STATE(statement);
+  mozStorageStatementScoper scoper(statement);
+
   rv = statement->BindInt64Parameter(0, placeId);
   NS_ENSURE_SUCCESS(rv, rv);
   PRTime lastModified = PR_Now();
   rv = statement->BindInt64Parameter(1, lastModified);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = statement->BindInt64Parameter(2, aBookmarkId);
   NS_ENSURE_SUCCESS(rv, rv);
-
   rv = statement->Execute();
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = transaction.Commit();
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Add new URI to bookmark hash.
   rv = AddBookmarkToHash(placeId, 0);
@@ -2667,18 +2872,19 @@ nsNavBookmarks::ChangeBookmarkURI(PRInt6
   // Pass the new URI to OnItemChanged.
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
     OnItemChanged(aBookmarkId, NS_LITERAL_CSTRING("uri"), PR_FALSE, spec,
                   lastModified, TYPE_BOOKMARK));
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetFolderIdForItem(PRInt64 aItemId, PRInt64 *aFolderId)
+nsNavBookmarks::GetFolderIdForItem(PRInt64 aItemId, PRInt64* aFolderId)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
   NS_ENSURE_ARG_POINTER(aFolderId);
 
   mozStorageStatementScoper scope(mDBGetItemProperties);
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aItemId);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -2692,91 +2898,97 @@ nsNavBookmarks::GetFolderIdForItem(PRInt
   rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent, aFolderId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // this should not happen, but see bug #400448 for details
   NS_ENSURE_TRUE(aItemId != *aFolderId, NS_ERROR_UNEXPECTED);
   return NS_OK;
 }
 
+
 nsresult
-nsNavBookmarks::GetBookmarkIdsForURITArray(nsIURI *aURI,
-                                           nsTArray<PRInt64> &aResult)
+nsNavBookmarks::GetBookmarkIdsForURITArray(nsIURI* aURI,
+                                           nsTArray<PRInt64>& aResult)
 {
-  NS_PRECONDITION(aURI, "Should not be null");
   NS_ENSURE_ARG(aURI);
 
   mozStorageStatementScoper scope(mDBFindURIBookmarks);
 
   nsresult rv = BindStatementURI(mDBFindURIBookmarks, 0, aURI);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = mDBFindURIBookmarks->BindInt32Parameter(1, TYPE_BOOKMARK);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool more;
   while (NS_SUCCEEDED((rv = mDBFindURIBookmarks->ExecuteStep(&more))) && more) {
-    if (!aResult.AppendElement(
-        mDBFindURIBookmarks->AsInt64(kFindBookmarksIndex_ID)))
-      return NS_ERROR_OUT_OF_MEMORY;
+    PRInt64 bookmarkId;
+    rv = mDBFindURIBookmarks->GetInt64(kFindBookmarksIndex_ID, &bookmarkId);
+    NS_ENSURE_SUCCESS(rv, rv);
+    NS_ENSURE_TRUE(aResult.AppendElement(bookmarkId), NS_ERROR_OUT_OF_MEMORY);
   }
-
   NS_ENSURE_SUCCESS(rv, rv);
+
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetBookmarkIdsForURI(nsIURI *aURI, PRUint32 *aCount,
-                                   PRInt64 **aBookmarks)
+nsNavBookmarks::GetBookmarkIdsForURI(nsIURI* aURI, PRUint32* aCount,
+                                     PRInt64** aBookmarks)
 {
   NS_ENSURE_ARG(aURI);
   NS_ENSURE_ARG_POINTER(aCount);
   NS_ENSURE_ARG_POINTER(aBookmarks);
 
   *aCount = 0;
   *aBookmarks = nsnull;
   nsTArray<PRInt64> bookmarks;
 
   // Get the information from the DB as a TArray
   nsresult rv = GetBookmarkIdsForURITArray(aURI, bookmarks);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Copy the results into a new array for output
   if (bookmarks.Length()) {
-    *aBookmarks = static_cast<PRInt64*>
-                             (nsMemory::Alloc(sizeof(PRInt64) * bookmarks.Length()));
-    if (! *aBookmarks)
+    *aBookmarks =
+      static_cast<PRInt64*>(nsMemory::Alloc(sizeof(PRInt64) * bookmarks.Length()));
+    if (!*aBookmarks)
       return NS_ERROR_OUT_OF_MEMORY;
     for (PRUint32 i = 0; i < bookmarks.Length(); i ++)
       (*aBookmarks)[i] = bookmarks[i];
   }
   *aCount = bookmarks.Length();
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::GetItemIndex(PRInt64 aItemId, PRInt32 *aIndex)
+nsNavBookmarks::GetItemIndex(PRInt64 aItemId, PRInt32* _index)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
-  NS_ENSURE_ARG_POINTER(aIndex);
+  NS_ENSURE_ARG_POINTER(_index);
+
+  *_index = -1;
 
   mozStorageStatementScoper scope(mDBGetItemIndex);
   mDBGetItemIndex->BindInt64Parameter(0, aItemId);
-  PRBool results;
-  nsresult rv = mDBGetItemIndex->ExecuteStep(&results);
+  PRBool hasResult;
+  nsresult rv = mDBGetItemIndex->ExecuteStep(&hasResult);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (!results) {
-    *aIndex = -1;
+  if (!hasResult)
     return NS_OK;
-  }
-
-  *aIndex = mDBGetItemIndex->AsInt32(0);
+
+  rv = mDBGetItemIndex->GetInt32(0, _index);
+  NS_ENSURE_SUCCESS(rv, rv);
+
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::SetItemIndex(PRInt64 aItemId, PRInt32 aNewIndex)
 {
   NS_ENSURE_ARG_MIN(aItemId, 1);
   NS_ENSURE_ARG_MIN(aNewIndex, 0);
 
   nsresult rv;
   PRInt32 oldIndex = 0;
@@ -2789,19 +3001,25 @@ nsNavBookmarks::SetItemIndex(PRInt64 aIt
     NS_ENSURE_SUCCESS(rv, rv);
 
     PRBool results;
     rv = mDBGetItemProperties->ExecuteStep(&results);
     NS_ENSURE_SUCCESS(rv, rv);
     if (!results)
       return NS_OK;
 
-    oldIndex = mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Position);
-    itemType = (PRUint16)mDBGetItemProperties->AsInt32(kGetItemPropertiesIndex_Type);
-    parent = mDBGetItemProperties->AsInt64(kGetItemPropertiesIndex_Parent);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Position,
+                                        &oldIndex);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt32(kGetItemPropertiesIndex_Type,
+                                        (PRInt32*)&itemType);
+    NS_ENSURE_SUCCESS(rv, rv);
+    rv = mDBGetItemProperties->GetInt64(kGetItemPropertiesIndex_Parent,
+                                        &parent);
+    NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Ensure we are not going out of range.
   PRInt32 folderCount;
   rv = FolderCount(parent, &folderCount);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(aNewIndex < folderCount, NS_ERROR_INVALID_ARG);
 
@@ -2816,49 +3034,49 @@ nsNavBookmarks::SetItemIndex(PRInt64 aIt
 
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnItemMoved(aItemId, parent, oldIndex, parent,
                                   aNewIndex, itemType));
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::SetKeywordForBookmark(PRInt64 aBookmarkId, const nsAString& aKeyword)
+nsNavBookmarks::SetKeywordForBookmark(PRInt64 aBookmarkId,
+                                      const nsAString& aKeyword)
 {
   NS_ENSURE_ARG_MIN(aBookmarkId, 1);
 
-  // Shortcuts are always lowercased internally.
-  nsAutoString kwd(aKeyword);
-  ToLowerCase(kwd);
-
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
   nsresult rv;
-  PRBool results;
   PRInt64 keywordId = 0;
-
-  if (!kwd.IsEmpty()) {
-    //  Attempt to find pre-existing keyword record
+  if (!aKeyword.IsEmpty()) {
+    // Shortcuts are always lowercased internally.
+    nsAutoString kwd(aKeyword);
+    ToLowerCase(kwd);
+
+    //  Attempt to find a pre-existing keyword record.
     nsCOMPtr<mozIStorageStatement> getKeywordStmnt;
     rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
         "SELECT id from moz_keywords WHERE keyword = ?1"),
       getter_AddRefs(getKeywordStmnt));
     NS_ENSURE_SUCCESS(rv, rv);
     rv = getKeywordStmnt->BindStringParameter(0, kwd);
     NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = getKeywordStmnt->ExecuteStep(&results);
+    PRBool hasResult;
+    rv = getKeywordStmnt->ExecuteStep(&hasResult);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (results) {
+    if (hasResult) {
       rv = getKeywordStmnt->GetInt64(0, &keywordId);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     else {
-      // If not already in the db, create new keyword record
+      // Create a new keyword record.
       nsCOMPtr<mozIStorageStatement> addKeywordStmnt;
       rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
           "INSERT INTO moz_keywords (keyword) VALUES (?1)"),
         getter_AddRefs(addKeywordStmnt));
       NS_ENSURE_SUCCESS(rv, rv);
       rv = addKeywordStmnt->BindStringParameter(0, kwd);
       NS_ENSURE_SUCCESS(rv, rv);
       rv = addKeywordStmnt->Execute();
@@ -2868,32 +3086,35 @@ nsNavBookmarks::SetKeywordForBookmark(PR
       rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
           "SELECT id "
           "FROM moz_keywords "
           "ORDER BY ROWID DESC "
           "LIMIT 1"),
         getter_AddRefs(idStmt));
       NS_ENSURE_SUCCESS(rv, rv);
 
-      PRBool hasResult;
       rv = idStmt->ExecuteStep(&hasResult);
       NS_ENSURE_SUCCESS(rv, rv);
       NS_ASSERTION(hasResult, "hasResult is false but the call succeeded?");
-      keywordId = idStmt->AsInt64(0);
+      rv = idStmt->GetInt64(0, &keywordId);
+      NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
-  // Update bookmark record w/ the keyword's id, or null
+  // Update bookmark record w/ the keyword's id or null.
   nsCOMPtr<mozIStorageStatement> updateKeywordStmnt;
   rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
       "UPDATE moz_bookmarks SET keyword_id = ?1, lastModified = ?2 "
       "WHERE id = ?3"),
     getter_AddRefs(updateKeywordStmnt));
   NS_ENSURE_SUCCESS(rv, rv);
-  rv = updateKeywordStmnt->BindInt64Parameter(0, keywordId);
+  if (keywordId > 0)
+    rv = updateKeywordStmnt->BindInt64Parameter(0, keywordId);
+  else
+    rv = updateKeywordStmnt->BindNullParameter(0);
   NS_ENSURE_SUCCESS(rv, rv);
   PRTime lastModified = PR_Now();
   rv = updateKeywordStmnt->BindInt64Parameter(1, lastModified);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = updateKeywordStmnt->BindInt64Parameter(2, aBookmarkId);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = updateKeywordStmnt->Execute();
   NS_ENSURE_SUCCESS(rv, rv);
@@ -2905,37 +3126,41 @@ nsNavBookmarks::SetKeywordForBookmark(PR
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                       OnItemChanged(aBookmarkId, NS_LITERAL_CSTRING("keyword"),
                                     PR_FALSE, NS_ConvertUTF16toUTF8(aKeyword),
                                     lastModified, TYPE_BOOKMARK));
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::GetKeywordForURI(nsIURI* aURI, nsAString& aKeyword)
 {
   NS_ENSURE_ARG(aURI);
   aKeyword.Truncate(0);
 
   mozStorageStatementScoper scoper(mDBGetKeywordForURI);
   nsresult rv = BindStatementURI(mDBGetKeywordForURI, 0, aURI);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool hasMore = PR_FALSE;
   rv = mDBGetKeywordForURI->ExecuteStep(&hasMore);
-  if (NS_FAILED(rv) || ! hasMore) {
+  if (NS_FAILED(rv) || !hasMore) {
     aKeyword.SetIsVoid(PR_TRUE);
     return NS_OK; // not found: return void keyword string
   }
 
   // found, get the keyword
-  return mDBGetKeywordForURI->GetString(0, aKeyword);
+  rv = mDBGetKeywordForURI->GetString(0, aKeyword);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::GetKeywordForBookmark(PRInt64 aBookmarkId, nsAString& aKeyword)
 {
   NS_ENSURE_ARG_MIN(aBookmarkId, 1);
   aKeyword.Truncate(0);
 
   mozStorageStatementScoper scoper(mDBGetKeywordForBookmark);
   nsresult rv = mDBGetKeywordForBookmark->BindInt64Parameter(0, aBookmarkId);
@@ -2947,23 +3172,23 @@ nsNavBookmarks::GetKeywordForBookmark(PR
     aKeyword.SetIsVoid(PR_TRUE);
     return NS_OK; // not found: return void keyword string
   }
 
   // found, get the keyword
   return mDBGetKeywordForBookmark->GetString(0, aKeyword);
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::GetURIForKeyword(const nsAString& aKeyword, nsIURI** aURI)
 {
   NS_ENSURE_ARG_POINTER(aURI);
+  NS_ENSURE_TRUE(!aKeyword.IsEmpty(), NS_ERROR_INVALID_ARG);
   *aURI = nsnull;
-  if (aKeyword.IsEmpty())
-    return NS_ERROR_INVALID_ARG;
 
   // Shortcuts are always lowercased internally.
   nsAutoString kwd(aKeyword);
   ToLowerCase(kwd);
 
   mozStorageStatementScoper scoper(mDBGetURIForKeyword);
   nsresult rv = mDBGetURIForKeyword->BindStringParameter(0, kwd);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -2972,19 +3197,22 @@ nsNavBookmarks::GetURIForKeyword(const n
   rv = mDBGetURIForKeyword->ExecuteStep(&hasMore);
   if (NS_FAILED(rv) || ! hasMore)
     return NS_OK; // not found: leave URI null
 
   // found, get the URI
   nsCAutoString spec;
   rv = mDBGetURIForKeyword->GetUTF8String(0, spec);
   NS_ENSURE_SUCCESS(rv, rv);
-  return NS_NewURI(aURI, spec);
+  rv = NS_NewURI(aURI, spec);
+  NS_ENSURE_SUCCESS(rv, rv);
+  return NS_OK;
 }
 
+
 // See RunInBatchMode
 nsresult
 nsNavBookmarks::BeginUpdateBatch()
 {
   if (mBatchLevel++ == 0) {
     mozIStorageConnection* conn = mDBConn;
     PRBool transactionInProgress = PR_TRUE; // default to no transaction on err
     conn->GetTransactionInProgress(&transactionInProgress);
@@ -2993,73 +3221,80 @@ nsNavBookmarks::BeginUpdateBatch()
       conn->BeginTransaction();
 
     ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                         OnBeginUpdateBatch());
   }
   return NS_OK;
 }
 
+
 nsresult
 nsNavBookmarks::EndUpdateBatch()
 {
   if (--mBatchLevel == 0) {
     if (mBatchHasTransaction)
       mDBConn->CommitTransaction();
     mBatchHasTransaction = PR_FALSE;
     ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                         OnEndUpdateBatch());
   }
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::RunInBatchMode(nsINavHistoryBatchCallback* aCallback,
                                nsISupports* aUserData) {
   NS_ENSURE_ARG(aCallback);
 
   BeginUpdateBatch();
   nsresult rv = aCallback->RunBatched(aUserData);
   EndUpdateBatch();
 
   return rv;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::AddObserver(nsINavBookmarkObserver *aObserver,
+nsNavBookmarks::AddObserver(nsINavBookmarkObserver* aObserver,
                             PRBool aOwnsWeak)
 {
   NS_ENSURE_ARG(aObserver);
   return mObservers.AppendWeakElement(aObserver, aOwnsWeak);
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::RemoveObserver(nsINavBookmarkObserver *aObserver)
+nsNavBookmarks::RemoveObserver(nsINavBookmarkObserver* aObserver)
 {
   return mObservers.RemoveWeakElement(aObserver);
 }
 
+
 // nsNavBookmarks::nsINavHistoryObserver
 
 NS_IMETHODIMP
 nsNavBookmarks::OnBeginUpdateBatch()
 {
   // These aren't passed through to bookmark observers currently.
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::OnEndUpdateBatch()
 {
   // These aren't passed through to bookmark observers currently.
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::OnVisit(nsIURI *aURI, PRInt64 aVisitID, PRTime aTime,
+nsNavBookmarks::OnVisit(nsIURI* aURI, PRInt64 aVisitID, PRTime aTime,
                         PRInt64 aSessionID, PRInt64 aReferringID,
                         PRUint32 aTransitionType, PRUint32* aAdded)
 {
   // If the page is bookmarked, we need to notify observers
   PRBool bookmarked = PR_FALSE;
   IsBookmarked(aURI, &bookmarked);
   if (bookmarked) {
     // query for all bookmarks for that URI, notify for each
@@ -3072,24 +3307,26 @@ nsNavBookmarks::OnVisit(nsIURI *aURI, PR
       for (PRUint32 i = 0; i < bookmarks.Length(); i++)
         ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers, nsINavBookmarkObserver,
                             OnItemVisited(bookmarks[i], aVisitID, aTime));
     }
   }
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::OnBeforeDeleteURI(nsIURI *aURI)
+nsNavBookmarks::OnBeforeDeleteURI(nsIURI* aURI)
 {
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::OnDeleteURI(nsIURI *aURI)
+nsNavBookmarks::OnDeleteURI(nsIURI* aURI)
 {
   // If the page is bookmarked, we need to notify observers
   PRBool bookmarked = PR_FALSE;
   IsBookmarked(aURI, &bookmarked);
   if (bookmarked) {
     // query for all bookmarks for that URI, notify for each 
     nsTArray<PRInt64> bookmarks;
 
@@ -3105,47 +3342,50 @@ nsNavBookmarks::OnDeleteURI(nsIURI *aURI
                                           EmptyCString(),
                                           0,
                                           TYPE_BOOKMARK));
     }
   }
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::OnClearHistory()
 {
   // TODO(bryner): we should notify on visited-time change for all URIs
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::OnTitleChanged(nsIURI* aURI, const nsAString& aPageTitle)
 {
   // NOOP. We don't consume page titles from moz_places anymore.
   // Title-change notifications are sent from SetItemTitle.
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
-nsNavBookmarks::OnPageChanged(nsIURI *aURI, PRUint32 aWhat,
-                              const nsAString &aValue)
+nsNavBookmarks::OnPageChanged(nsIURI* aURI, PRUint32 aWhat,
+                              const nsAString& aValue)
 {
   nsresult rv;
   if (aWhat == nsINavHistoryObserver::ATTRIBUTE_FAVICON) {
     // Favicons may be set to either pure URIs or to folder URIs
     PRBool isPlaceURI;
     rv = aURI->SchemeIs("place", &isPlaceURI);
     NS_ENSURE_SUCCESS(rv, rv);
     if (isPlaceURI) {
       nsCAutoString spec;
       rv = aURI->GetSpec(spec);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      nsNavHistory *history = nsNavHistory::GetHistoryService();
+      nsNavHistory* history = nsNavHistory::GetHistoryService();
       NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
   
       nsCOMArray<nsNavHistoryQuery> queries;
       nsCOMPtr<nsNavHistoryQueryOptions> options;
       rv = history->QueryStringToQueryArray(spec, &queries, getter_AddRefs(options));
       NS_ENSURE_SUCCESS(rv, rv);
 
       NS_ENSURE_STATE(queries.Count() == 1);
@@ -3175,31 +3415,34 @@ nsNavBookmarks::OnPageChanged(nsIURI *aU
                                             0,
                                             TYPE_BOOKMARK));
       }
     }
   }
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::OnDeleteVisits(nsIURI* aURI, PRTime aVisitTime)
 {
   // pages that are bookmarks shouldn't expire, so we don't need to handle it
   return NS_OK;
 }
 
+
 // nsIAnnotationObserver
 
 NS_IMETHODIMP
 nsNavBookmarks::OnPageAnnotationSet(nsIURI* aPage, const nsACString& aName)
 {
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::OnItemAnnotationSet(PRInt64 aItemId, const nsACString& aName)
 {
   // GetItemType also ensures that aItemId points to a valid item.
   PRUint16 itemType;
   nsresult rv = GetItemType(aItemId, &itemType);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -3217,16 +3460,17 @@ nsNavBookmarks::OnItemAnnotationSet(PRIn
 
 
 NS_IMETHODIMP
 nsNavBookmarks::OnPageAnnotationRemoved(nsIURI* aPage, const nsACString& aName)
 {
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavBookmarks::OnItemAnnotationRemoved(PRInt64 aItemId, const nsACString& aName)
 {
   // GetItemType also ensures that aItemId points to a valid item.
   PRUint16 itemType;
   nsresult rv = GetItemType(aItemId, &itemType);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -3237,23 +3481,21 @@ nsNavBookmarks::OnItemAnnotationRemoved(
   ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers,
                       nsINavBookmarkObserver,
                       OnItemChanged(aItemId, aName, PR_TRUE, EmptyCString(),
                                     lastModified, itemType));
 
   return NS_OK;
 }
 
+
 PRBool
 nsNavBookmarks::ItemExists(PRInt64 aItemId) {
   mozStorageStatementScoper scope(mDBGetItemProperties);
   nsresult rv = mDBGetItemProperties->BindInt64Parameter(0, aItemId);
   NS_ENSURE_SUCCESS(rv, PR_FALSE);
 
-  PRBool results;
-  rv = mDBGetItemProperties->ExecuteStep(&results);
+  PRBool hasResult;
+  rv = mDBGetItemProperties->ExecuteStep(&hasResult);
   NS_ENSURE_SUCCESS(rv, PR_FALSE);
 
-  if (!results)
-    return PR_FALSE;
-
-  return PR_TRUE;
+  return hasResult;
 }
--- a/toolkit/components/places/src/nsNavBookmarks.h
+++ b/toolkit/components/places/src/nsNavBookmarks.h
@@ -61,48 +61,49 @@ public:
   NS_DECL_NSINAVHISTORYOBSERVER
   NS_DECL_NSIANNOTATIONOBSERVER
 
   nsNavBookmarks();
 
   /**
    * Obtains the service's object.
    */
-  static nsNavBookmarks *GetSingleton();
+  static nsNavBookmarks* GetSingleton();
 
   /**
    * Initializes the service's object.  This should only be called once.
    */
   nsresult Init();
 
   // called by nsNavHistory::Init
   static nsresult InitTables(mozIStorageConnection* aDBConn);
 
-  static nsNavBookmarks * GetBookmarksService() {
+  static nsNavBookmarks* GetBookmarksService() {
     if (!gBookmarksService) {
       nsCOMPtr<nsINavBookmarksService> serv =
         do_GetService(NS_NAVBOOKMARKSSERVICE_CONTRACTID);
       NS_ENSURE_TRUE(serv, nsnull);
       NS_ASSERTION(gBookmarksService,
                    "Should have static instance pointer now");
     }
     return gBookmarksService;
   }
 
   nsresult AddBookmarkToHash(PRInt64 aBookmarkId, PRTime aMinTime);
 
-  nsresult ResultNodeForContainer(PRInt64 aID, nsNavHistoryQueryOptions *aOptions,
-                                  nsNavHistoryResultNode **aNode);
+  nsresult ResultNodeForContainer(PRInt64 aID,
+                                  nsNavHistoryQueryOptions* aOptions,
+                                  nsNavHistoryResultNode** aNode);
 
   // Find all the children of a folder, using the given query and options.
   // For each child, a ResultNode is created and added to |children|.
   // The results are ordered by folder position.
   nsresult QueryFolderChildren(PRInt64 aFolderId,
-                               nsNavHistoryQueryOptions *aOptions,
-                               nsCOMArray<nsNavHistoryResultNode> *children);
+                               nsNavHistoryQueryOptions* aOptions,
+                               nsCOMArray<nsNavHistoryResultNode>* children);
 
   // If aFolder is -1, uses the autoincrement id for folder index. Returns
   // the index of the new folder in aIndex, whether it was passed in or
   // generated by autoincrement.
   nsresult CreateContainerWithID(PRInt64 aId, PRInt64 aParent,
                                  const nsACString& aName,
                                  const nsAString& aContractId,
                                  PRBool aIsBookmarkFolder,
@@ -124,45 +125,48 @@ public:
   PRBool ItemExists(PRInt64 aItemId);
 
   /**
    * Finalize all internal statements.
    */
   nsresult FinalizeStatements();
 
 private:
-  static nsNavBookmarks *gBookmarksService;
+  static nsNavBookmarks* gBookmarksService;
 
   ~nsNavBookmarks();
 
   nsresult InitRoots();
   nsresult InitDefaults();
   nsresult InitStatements();
   nsresult CreateRoot(mozIStorageStatement* aGetRootStatement,
-                      const nsCString& name, PRInt64* aID,
-                      PRInt64 aParentID, PRBool* aWasCreated);
+                      const nsCString& name,
+                      PRInt64* aID,
+                      PRInt64 aParentID,
+                      PRBool* aWasCreated);
 
   nsresult AdjustIndices(PRInt64 aFolder,
-                         PRInt32 aStartIndex, PRInt32 aEndIndex,
+                         PRInt32 aStartIndex,
+                         PRInt32 aEndIndex,
                          PRInt32 aDelta);
 
-  NS_HIDDEN_(nsresult) RemoveFolder(PRInt64 aFolderId);
+  nsresult RemoveFolder(PRInt64 aFolderId);
 
   /**
    * Calculates number of children for the given folder.
    *
    * @param aFolderId Folder to count children for.
    *
    * @return aFolderCount The number of children in this folder.
    *
    * @throws If folder does not exist.
    */
-  nsresult FolderCount(PRInt64 aFolderId, PRInt32 *aFolderCount);
+  nsresult FolderCount(PRInt64 aFolderId, PRInt32* aFolderCount);
 
-  nsresult GetFolderType(PRInt64 aFolder, nsACString &aType);
+  nsresult GetFolderType(PRInt64 aFolder, nsACString& aType);
 
   nsresult GetLastChildId(PRInt64 aFolder, PRInt64* aItemId);
 
   nsCOMPtr<mozIStorageConnection> mDBConn;
 
   nsString mGUIDBase;
   nsresult GetGUIDBase(nsAString& aGUIDBase);
 
@@ -184,26 +188,30 @@ private:
   // be committed when our batch level reaches 0 again.
   PRBool mBatchHasTransaction;
 
   // This stores a mapping from all pages reachable by redirects from bookmarked
   // pages to the bookmarked page. Used by GetBookmarkedURIFor.
   nsDataHashtable<nsTrimInt64HashKey, PRInt64> mBookmarksHash;
   nsDataHashtable<nsTrimInt64HashKey, PRInt64>* GetBookmarksHash();
   nsresult FillBookmarksHash();
-  nsresult RecursiveAddBookmarkHash(PRInt64 aBookmarkId, PRInt64 aCurrentSource,
+  nsresult RecursiveAddBookmarkHash(PRInt64 aBookmarkId,
+                                    PRInt64 aCurrentSource,
                                     PRTime aMinTime);
   nsresult UpdateBookmarkHashOnRemove(PRInt64 aPlaceId);
 
-  nsresult GetParentAndIndexOfFolder(PRInt64 aFolder, PRInt64* aParent, 
+  nsresult GetParentAndIndexOfFolder(PRInt64 aFolder,
+                                     PRInt64* aParent,
                                      PRInt32* aIndex);
 
   nsresult IsBookmarkedInDatabase(PRInt64 aBookmarkID, PRBool* aIsBookmarked);
 
-  nsresult SetItemDateInternal(mozIStorageStatement* aStatement, PRInt64 aItemId, PRTime aValue);
+  nsresult SetItemDateInternal(mozIStorageStatement* aStatement,
+                               PRInt64 aItemId,
+                               PRTime aValue);
 
   // Structure to hold folder's children informations
   struct folderChildrenInfo
   {
     PRInt64 itemId;
     PRUint16 itemType;
     PRInt64 placeId;
     PRInt64 parentId;
@@ -255,29 +263,29 @@ private:
    *
    *  @note This will also update last modified date of the parent folder.
    */
   nsresult InsertBookmarkInDB(PRInt64 aItemId,
                               PRInt64 aPlaceId,
                               enum ItemType aItemType,
                               PRInt64 aParentId,
                               PRInt32 aIndex,
-                              const nsACString &aTitle,
+                              const nsACString& aTitle,
                               PRTime aDateAdded,
                               PRTime aLastModified,
-                              const nsAString &aServiceContractId,
-                              PRInt64 *_retval);
+                              const nsAString& aServiceContractId,
+                              PRInt64* _retval);
 
   /**
    * TArray version of getBookmarksIdForURI for ease of use in C++ code.
    * Pass in a reference to a TArray; it will get filled with the
    * resulting list of bookmark IDs.
    */
-  nsresult GetBookmarkIdsForURITArray(nsIURI *aURI,
-                                      nsTArray<PRInt64> &aResult);
+  nsresult GetBookmarkIdsForURITArray(nsIURI* aURI,
+                                      nsTArray<PRInt64>& aResult);
 
   // kGetInfoIndex_* results + kGetChildrenIndex_* results
   nsCOMPtr<mozIStorageStatement> mDBGetChildren;
   static const PRInt32 kGetChildrenIndex_Position;
   static const PRInt32 kGetChildrenIndex_Type;
   static const PRInt32 kGetChildrenIndex_PlaceID;
   static const PRInt32 kGetChildrenIndex_FolderTitle;
   static const PRInt32 kGetChildrenIndex_ServiceContractId;
@@ -328,16 +336,28 @@ private:
   nsCOMPtr<mozIStorageStatement> mDBSetItemLastModified;
   nsCOMPtr<mozIStorageStatement> mDBSetItemIndex;
 
   // keywords
   nsCOMPtr<mozIStorageStatement> mDBGetKeywordForURI;
   nsCOMPtr<mozIStorageStatement> mDBGetKeywordForBookmark;
   nsCOMPtr<mozIStorageStatement> mDBGetURIForKeyword;
 
+  /**
+   *  For the next statements you should always use this getter and never use
+   *  directly the statement nsCOMPtr.
+   */
+  mozIStorageStatement* GetStatement(const nsCOMPtr<mozIStorageStatement>& aStmt);
+  nsCOMPtr<mozIStorageStatement> mDBAdjustPosition;
+  nsCOMPtr<mozIStorageStatement> mDBRemoveItem;
+  nsCOMPtr<mozIStorageStatement> mDBGetLastChildId;
+  nsCOMPtr<mozIStorageStatement> mDBMoveItem;
+  nsCOMPtr<mozIStorageStatement> mDBSetItemTitle;
+  nsCOMPtr<mozIStorageStatement> mDBChangeBookmarkURI;
+
   class RemoveFolderTransaction : public nsITransaction {
   public:
     RemoveFolderTransaction(PRInt64 aID) : mID(aID) {}
 
     NS_DECL_ISUPPORTS
 
     NS_IMETHOD DoTransaction() {
       nsNavBookmarks* bookmarks = nsNavBookmarks::GetBookmarksService();
@@ -384,28 +404,30 @@ private:
     nsCString mTitle;
     nsString mType;
     PRInt32 mIndex;
   };
 
   // Used to enable and disable the observer notifications.
   bool mCanNotify;
   nsCategoryCache<nsINavBookmarkObserver> mCacheObservers;
+
+  bool mShuttingDown;
 };
 
 struct nsBookmarksUpdateBatcher
 {
   nsBookmarksUpdateBatcher()
   {
-    nsNavBookmarks *bookmarks = nsNavBookmarks::GetBookmarksService();
+    nsNavBookmarks* bookmarks = nsNavBookmarks::GetBookmarksService();
     if (bookmarks)
       bookmarks->BeginUpdateBatch();
   }
   ~nsBookmarksUpdateBatcher()
   {
-    nsNavBookmarks *bookmarks = nsNavBookmarks::GetBookmarksService();
+    nsNavBookmarks* bookmarks = nsNavBookmarks::GetBookmarksService();
     if (bookmarks)
       bookmarks->EndUpdateBatch();
   }
 };
 
 
 #endif // nsNavBookmarks_h_