Bug 520165 - Part6: generic constants and comments cleanup, r=mano
authorMarco Bonardo <mbonardo@mozilla.com>
Tue, 22 Dec 2009 13:05:14 +0100
changeset 36541 85c3437867aed3a3336035e583c85c1dd3b0301f
parent 36540 44d046507cf9c78aa94d2dc206bca016ca20f1ca
child 36542 195db4224a601cda5f8a07d23b0175c647759766
push idunknown
push userunknown
push dateunknown
reviewersmano
bugs520165
milestone1.9.3a1pre
Bug 520165 - Part6: generic constants and comments cleanup, r=mano
toolkit/components/places/src/nsNavHistory.cpp
toolkit/components/places/src/nsNavHistory.h
toolkit/components/places/src/nsNavHistoryResult.cpp
--- a/toolkit/components/places/src/nsNavHistory.cpp
+++ b/toolkit/components/places/src/nsNavHistory.cpp
@@ -83,31 +83,32 @@
 #include "nsIAutoCompletePopup.h"
 #endif
 
 using namespace mozilla::places;
 
 // Microsecond timeout for "recent" events such as typed and bookmark following.
 // If you typed it more than this time ago, it's not recent.
 // This is 15 minutes           m    s/m  us/s
-#define RECENT_EVENT_THRESHOLD (15 * 60 * PR_USEC_PER_SEC)
+#define RECENT_EVENT_THRESHOLD ((PRInt64)15 * 60 * PR_USEC_PER_SEC)
 
 // Microseconds ago to look for redirects when updating bookmarks. Used to
 // compute the threshold for nsNavBookmarks::AddBookmarkToHash
-#define BOOKMARK_REDIRECT_TIME_THRESHOLD (2 * 60 * PR_USEC_PER_SEC)
+#define BOOKMARK_REDIRECT_TIME_THRESHOLD ((PRInt64)2 * 60 * PR_USEC_PER_SEC)
 
 // The maximum number of things that we will store in the recent events list
 // before calling ExpireNonrecentEvents. This number should be big enough so it
 // is very difficult to get that many unconsumed events (for example, typed but
 // never visited) in the RECENT_EVENT_THRESHOLD. Otherwise, we'll start
 // checking each one for every page visit, which will be somewhat slower.
 #define RECENT_EVENT_QUEUE_MAX_LENGTH 128
 
 // preference ID strings
 #define PREF_BRANCH_BASE                        "browser."
+
 #define PREF_BROWSER_HISTORY_EXPIRE_DAYS_MIN    "history_expire_days_min"
 #define PREF_BROWSER_HISTORY_EXPIRE_DAYS_MAX    "history_expire_days"
 #define PREF_BROWSER_HISTORY_EXPIRE_SITES       "history_expire_sites"
 
 #define PREF_FRECENCY_NUM_VISITS                "places.frecency.numVisits"
 #define PREF_FRECENCY_FIRST_BUCKET_CUTOFF       "places.frecency.firstBucketCutoff"
 #define PREF_FRECENCY_SECOND_BUCKET_CUTOFF      "places.frecency.secondBucketCutoff"
 #define PREF_FRECENCY_THIRD_BUCKET_CUTOFF       "places.frecency.thirdBucketCutoff"
@@ -132,43 +133,54 @@ using namespace mozilla::places;
 
 #define PREF_CACHE_TO_MEMORY_PERCENTAGE         "places.database.cache_to_memory_percentage"
 
 // Default integer value for PREF_CACHE_TO_MEMORY_PERCENTAGE.
 // This is 6% of machine memory, giving 15MB for a user with 256MB of memory.
 // Out of this cache, SQLite will use at most the size of the database file.
 #define DATABASE_DEFAULT_CACHE_TO_MEMORY_PERCENTAGE 6
 
+// This is the schema version, update it at any schema change and add a
+// corresponding migrateVxx method below.
+#define DATABASE_SCHEMA_VERSION 10
+
 // We set the default database page size to be larger. sqlite's default is 1K.
 // This gives good performance when many small parts of the file have to be
 // loaded for each statement. Because we try to keep large chunks of the file
 // in memory, a larger page size should give better I/O performance. 32K is
 // sqlite's default max page size.
-#define DEFAULT_DB_PAGE_SIZE 4096
+#define DATABASE_PAGE_SIZE 4096
+
+// Filename of the database.
+#define DATABASE_FILENAME NS_LITERAL_STRING("places.sqlite")
+
+// Filename used to backup corrupt databases.
+#define DATABASE_CORRUPT_FILENAME NS_LITERAL_STRING("places.sqlite.corrupt")
+
+// We use the TRUNCATE journal mode to reduce the number of fsyncs.  Without
+// this setting we had a Ts hit on Linux.  See bug 460315 for details.
+#define DATABASE_JOURNAL_MODE "TRUNCATE"
+
+// Fraction of free pages in the database to force a vacuum between
+// DATABASE_MAX_TIME_BEFORE_VACUUM and DATABASE_MIN_TIME_BEFORE_VACUUM.
+#define DATABASE_VACUUM_FREEPAGES_THRESHOLD 0.1
+// This is the maximum time (in microseconds) that can pass between 2 VACUUM
+// operations.
+#define DATABASE_MAX_TIME_BEFORE_VACUUM (PRInt64)60 * 24 * 60 * 60 * 1000 * 1000
+// This is the minimum time (in microseconds) that should pass between 2 VACUUM
+// operations.
+#define DATABASE_MIN_TIME_BEFORE_VACUUM (PRInt64)30 * 24 * 60 * 60 * 1000 * 1000
 
 // In order to avoid calling PR_now() too often we use a cached "now" value
 // for repeating stuff.  These are milliseconds between "now" cache refreshes.
 #define RENEW_CACHED_NOW_TIMEOUT ((PRInt32)3 * PR_MSEC_PER_SEC)
 
 // USECS_PER_DAY == PR_USEC_PER_SEC * 60 * 60 * 24;
 static const PRInt64 USECS_PER_DAY = LL_INIT(20, 500654080);
 
-// see bug #319004 -- clamp title and URL to generously-large but not too large
-// length
-#define HISTORY_URI_LENGTH_MAX 65536
-#define HISTORY_TITLE_LENGTH_MAX 4096
-
-// db file name
-#define DB_FILENAME NS_LITERAL_STRING("places.sqlite")
-
-// db backup file name
-#define DB_CORRUPT_FILENAME NS_LITERAL_STRING("places.sqlite.corrupt")
-
-// Lazy adding
-
 #ifdef LAZY_ADD
 
 // time that we'll wait before committing messages
 #define LAZY_MESSAGE_TIMEOUT (3 * PR_MSEC_PER_SEC)
 
 // the maximum number of times we'll postpone a lazy timer before committing
 // See StartLazyTimer()
 #define MAX_LAZY_TIMER_DEFERMENTS 2
@@ -176,41 +188,27 @@ static const PRInt64 USECS_PER_DAY = LL_
 #endif // LAZY_ADD
 
 // Limit the number of items in the history for performance reasons
 #define EXPIRATION_CAP_SITES 40000
 
 // character-set annotation
 #define CHARSET_ANNO NS_LITERAL_CSTRING("URIProperties/characterSet")
 
-// We use the TRUNCATE journal mode to reduce the number of fsyncs.  Without
-// this setting we had a Ts hit on Linux.  See bug 460315 for details.
-#define DEFAULT_JOURNAL_MODE "TRUNCATE"
-
 // These macros are used when splitting history by date.
 // These are the day containers and catch-all final container.
 #define HISTORY_ADDITIONAL_DATE_CONT_NUM 3
 // We use a guess of the number of months considering all of them 30 days
 // long, but we split only the last 6 months.
 #define HISTORY_DATE_CONT_NUM(_daysFromOldestVisit) \
   (HISTORY_ADDITIONAL_DATE_CONT_NUM + \
    NS_MIN(6, (PRInt32)NS_ceilf((float)_daysFromOldestVisit/30)))
 // Max number of containers, used to initialize the params hash.
 #define HISTORY_DATE_CONT_MAX 10
 
-// fraction of free pages in the database to force a vacuum between
-// MAX_TIME_BEFORE_VACUUM and MIN_TIME_BEFORE_VACUUM.
-#define VACUUM_FREEPAGES_THRESHOLD 0.1
-// This is the maximum time (in microseconds) that can pass between 2 VACUUM
-// operations.
-#define MAX_TIME_BEFORE_VACUUM (PRInt64)60 * 24 * 60 * 60 * 1000 * 1000
-// This is the minimum time (in microseconds) that should pass between 2 VACUUM
-// operations.
-#define MIN_TIME_BEFORE_VACUUM (PRInt64)30 * 24 * 60 * 60 * 1000 * 1000
-
 #ifdef MOZ_XUL
 #define TOPIC_AUTOCOMPLETE_FEEDBACK_INCOMING "autocomplete-will-enter-text"
 #define TOPIC_AUTOCOMPLETE_FEEDBACK_UPDATED "places-autocomplete-feedback-updated"
 #endif
 #define TOPIC_XPCOM_SHUTDOWN "xpcom-shutdown"
 #define TOPIC_IDLE_DAILY "idle-daily"
 #define TOPIC_DATABASE_VACUUM_STARTING "places-vacuum-starting"
 #define TOPIC_DATABASE_LOCKED "places-database-locked"
@@ -241,31 +239,35 @@ NS_IMPL_CI_INTERFACE_GETTER5(
   nsNavHistory
 , nsINavHistoryService
 , nsIGlobalHistory3
 , nsIGlobalHistory2
 , nsIDownloadHistory
 , nsIBrowserHistory
 )
 
+namespace {
+
 static nsresult GetReversedHostname(nsIURI* aURI, nsAString& host);
 static void GetReversedHostname(const nsString& aForward, nsAString& aReversed);
 static PRInt64 GetSimpleBookmarksQueryFolder(
     const nsCOMArray<nsNavHistoryQuery>& aQueries,
     nsNavHistoryQueryOptions* aOptions);
 static void ParseSearchTermsFromQueries(const nsCOMArray<nsNavHistoryQuery>& aQueries,
                                         nsTArray<nsTArray<nsString>*>* aTerms);
 
 inline void ReverseString(const nsString& aInput, nsAString& aReversed)
 {
   aReversed.Truncate(0);
   for (PRInt32 i = aInput.Length() - 1; i >= 0; i --)
     aReversed.Append(aInput[i]);
 }
 
+} // anonymous namespace
+
 namespace mozilla {
   namespace places {
 
     bool hasRecentCorruptDB()
     {
       nsCOMPtr<nsIFile> profDir;
       nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
                                            getter_AddRefs(profDir));
@@ -279,18 +281,18 @@ namespace mozilla {
         rv = entries->GetNext(getter_AddRefs(next));
         NS_ENSURE_SUCCESS(rv, false);
         nsCOMPtr<nsIFile> currFile = do_QueryInterface(next, &rv);
         NS_ENSURE_SUCCESS(rv, false);
 
         nsAutoString leafName;
         rv = currFile->GetLeafName(leafName);
         NS_ENSURE_SUCCESS(rv, false);
-        if (leafName.Length() >= DB_CORRUPT_FILENAME.Length() &&
-            leafName.Find(".corrupt", DB_FILENAME.Length()) != -1) {
+        if (leafName.Length() >= DATABASE_CORRUPT_FILENAME.Length() &&
+            leafName.Find(".corrupt", DATABASE_FILENAME.Length()) != -1) {
           PRInt64 lastMod;
           rv = currFile->GetLastModifiedTime(&lastMod);
           NS_ENSURE_SUCCESS(rv, false);
           if (PR_Now() - lastMod > (PRInt64)24 * 60 * 60 * 1000 * 1000)
            return true;
         }
       }
       return false;
@@ -317,24 +319,26 @@ namespace mozilla {
                 "ORDER BY t_t.title COLLATE NOCASE ASC "
               ") "
              ")"));
       }
 
       _sqlFragment.AppendLiteral(" AS tags ");
     }
 
-  }
-}
-
-// UpdateBatchScoper
-//
-//    This just sets begin/end of batch updates to correspond to C++ scopes so
-//    we can be sure end always gets called.
-
+  } // namespace places
+} // namespace mozilla
+
+
+namespace {
+
+/**
+ * This class sets begin/end of batch updates to correspond to C++ scopes so
+ * we can be sure end always gets called.
+ */
 class UpdateBatchScoper
 {
 public:
   UpdateBatchScoper(nsNavHistory& aNavHistory) : mNavHistory(aNavHistory)
   {
     mNavHistory.BeginUpdateBatch();
   }
   ~UpdateBatchScoper()
@@ -358,16 +362,19 @@ class PlacesEvent : public nsRunnable {
       (void)observerService->NotifyObservers(nsnull, mTopic, nsnull);
 
     return NS_OK;
   }
   protected:
   const char* mTopic;
 };
 
+} // anonymouse namespace
+
+
 // Queries rows indexes to bind or get values, if adding a new one, be sure to
 // update nsNavBookmarks statements and its kGetChildrenIndex_* constants
 const PRInt32 nsNavHistory::kGetInfoIndex_PageID = 0;
 const PRInt32 nsNavHistory::kGetInfoIndex_URL = 1;
 const PRInt32 nsNavHistory::kGetInfoIndex_Title = 2;
 const PRInt32 nsNavHistory::kGetInfoIndex_RevHost = 3;
 const PRInt32 nsNavHistory::kGetInfoIndex_VisitCount = 4;
 const PRInt32 nsNavHistory::kGetInfoIndex_VisitDate = 5;
@@ -537,37 +544,37 @@ nsNavHistory::InitDBFile(PRBool aForceIn
 {
   if (aForceInit) {
     NS_ASSERTION(mDBConn,
                  "When forcing initialization, a database connection must exist!");
     NS_ASSERTION(mDBService,
                  "When forcing initialization, the database service must exist!");
   }
 
-  // get profile dir, file
+  // Get database file handle.
   nsCOMPtr<nsIFile> profDir;
   nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
                                        getter_AddRefs(profDir));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = profDir->Clone(getter_AddRefs(mDBFile));
   NS_ENSURE_SUCCESS(rv, rv);
-  rv = mDBFile->Append(DB_FILENAME);
+  rv = mDBFile->Append(DATABASE_FILENAME);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aForceInit) {
     // If forcing initialization, backup and remove the old file.  If we have
     // already failed in the last 24 hours avoid to create another corrupt file,
     // since doing so, in some situation, could cause us to create a new corrupt
     // file at every try to access any Places service.  That is bad because it
     // would quickly fill the user's disk space without any notice.
     if (!hasRecentCorruptDB()) {
       // backup the database
       nsCOMPtr<nsIFile> backup;
-      rv = mDBService->BackupDatabaseFile(mDBFile, DB_CORRUPT_FILENAME, profDir,
-                                          getter_AddRefs(backup));
+      rv = mDBService->BackupDatabaseFile(mDBFile, DATABASE_CORRUPT_FILENAME,
+                                          profDir, getter_AddRefs(backup));
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // Close database connection if open.
     // If there's any not finalized statement or this fails for any reason
     // we won't be able to remove the database.
     rv = mDBConn->Close();
     NS_ENSURE_SUCCESS(rv, rv);
@@ -587,47 +594,46 @@ nsNavHistory::InitDBFile(PRBool aForceIn
     }
     NS_ENSURE_SUCCESS(rv, rv);
 
     // If aForceInit is true we were unable to initialize or upgrade the current
     // database, so it was corrupt.
     mDatabaseStatus = DATABASE_STATUS_CORRUPT;
   }
   else {
-    // file exists?
+    // Check if database file exists.
     PRBool dbExists = PR_TRUE;
     rv = mDBFile->Exists(&dbExists);
     NS_ENSURE_SUCCESS(rv, rv);
     // If the database didn't previously exist, we create it.
     if (!dbExists)
       mDatabaseStatus = DATABASE_STATUS_CREATE;
   }
 
-  // open the database
+  // Open the database file.  If it does not exist a new one will be created.
   mDBService = do_GetService(MOZ_STORAGE_SERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
+  // Open un unshared connection, both for safety and speed.
   rv = mDBService->OpenUnsharedDatabase(mDBFile, getter_AddRefs(mDBConn));
   if (rv == NS_ERROR_FILE_CORRUPTED) {
-    // The database is corrupt, we create a new one.
+    // The database is corrupt, try to create a new one.
     mDatabaseStatus = DATABASE_STATUS_CORRUPT;
 
-    // backup file
+    // Backup and remove old corrupt database file.
     nsCOMPtr<nsIFile> backup;
-    rv = mDBService->BackupDatabaseFile(mDBFile, DB_CORRUPT_FILENAME, profDir,
-                                        getter_AddRefs(backup));
-    NS_ENSURE_SUCCESS(rv, rv);
- 
-    // remove existing file 
+    rv = mDBService->BackupDatabaseFile(mDBFile, DATABASE_CORRUPT_FILENAME,
+                                        profDir, getter_AddRefs(backup));
+    NS_ENSURE_SUCCESS(rv, rv);
     rv = mDBFile->Remove(PR_FALSE);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    // and try again
+    // Try again to initialize the database file.
     rv = profDir->Clone(getter_AddRefs(mDBFile));
     NS_ENSURE_SUCCESS(rv, rv);
-    rv = mDBFile->Append(DB_FILENAME);
+    rv = mDBFile->Append(DATABASE_FILENAME);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = mDBService->OpenUnsharedDatabase(mDBFile, getter_AddRefs(mDBConn));
   }
  
   if (rv != NS_OK && rv != NS_ERROR_FILE_CORRUPTED) {
     // If the database cannot be opened for any reason other than corruption,
     // send out a notification and do not continue initialization.
     // Note: We swallow errors here, since we want service init to fail anyway.
@@ -635,70 +641,61 @@ nsNavHistory::InitDBFile(PRBool aForceIn
       new PlacesEvent(TOPIC_DATABASE_LOCKED);
     (void)NS_DispatchToMainThread(lockedEvent);
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
-// nsNavHistory::InitDB
-//
-
-#define PLACES_SCHEMA_VERSION 10
 
 nsresult
 nsNavHistory::InitDB()
 {
-  PRInt32 pageSize = DEFAULT_DB_PAGE_SIZE;
-
-  // Get the places schema version, which we store in the user_version PRAGMA.
-  PRInt32 DBSchemaVersion = 0;
-  nsresult rv = mDBConn->GetSchemaVersion(&DBSchemaVersion);
-  NS_ENSURE_SUCCESS(rv, rv);
-  bool databaseInitialized = (DBSchemaVersion > 0);
+  PRInt32 pageSize = DATABASE_PAGE_SIZE;
+
+  // Get the database schema version.
+  PRInt32 currentSchemaVersion = 0;
+  nsresult rv = mDBConn->GetSchemaVersion(&currentSchemaVersion);
+  NS_ENSURE_SUCCESS(rv, rv);
+  bool databaseInitialized = (currentSchemaVersion > 0);
 
   if (!databaseInitialized) {
-    // IMPORTANT NOTE:
-    // setting page_size must happen first, see bug #401985 for details
-    //
-    // Set the database page size.
-    // This will only have any effect on empty files, so must be done before
-    // anything else. If the file already exists, we'll get that file's page
-    // size and this would have no effect.
+    // First of all we must set page_size since it will only have effect on
+    // empty files.  For existing databases we could get a different page size,
+    // trying to change it would be uneffective.
+    // See bug 401985 for details.
     nsCAutoString pageSizePragma("PRAGMA page_size = ");
     pageSizePragma.AppendInt(pageSize);
     rv = mDBConn->ExecuteSimpleSQL(pageSizePragma);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   else {
     // Get the page size.  This may be different than the default if the
     // database file already existed with a different page size.
     nsCOMPtr<mozIStorageStatement> statement;
-    rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-        "PRAGMA page_size"),
-      getter_AddRefs(statement));
+    rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA page_size"),
+                                  getter_AddRefs(statement));
     NS_ENSURE_SUCCESS(rv, rv);
 
     PRBool hasResult;
     rv = statement->ExecuteStep(&hasResult);
-    NS_ENSURE_SUCCESS(rv, rv);
-    NS_ENSURE_TRUE(hasResult, NS_ERROR_FAILURE);
+    NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && hasResult, NS_ERROR_FAILURE);
     pageSize = statement->AsInt32(0);
   }
 
   // Ensure that temp tables are held in memory, not on disk.  We use temp
   // tables mainly for fsync and I/O reduction.
   rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "PRAGMA temp_store = MEMORY"));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Set pragma synchronous to FULL to ensure maximum data integrity, even in
   // case of crashes or unclean shutdowns.
-  // The suggested setting from SQLite is FULL, but Storage defaults to NORMAL.
+  // The suggested setting for SQLite is FULL, but Storage defaults to NORMAL.
   rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "PRAGMA synchronous = FULL"));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Compute the size of the database cache using the device's memory size.
   // We don't use PRAGMA default_cache_size, since the database could be moved
   // among different devices and the value would adapt accordingly.
   nsCOMPtr<nsIPrefBranch> prefs =
@@ -712,130 +709,126 @@ nsNavHistory::InitDB()
   if (cachePercentage > 50)
     cachePercentage = 50;
   if (cachePercentage < 0)
     cachePercentage = 0;
   PRInt64 cacheSize = PR_GetPhysicalMemorySize() * cachePercentage / 100;
 
   // Compute number of cached pages, this will be our cache size.
   PRInt64 cachePages = cacheSize / pageSize;
-
-  // Set the cache size.  We don't use default_cache_size so the database can
-  // be moved between computers and the value will change dynamically.
   nsCAutoString pageSizePragma("PRAGMA cache_size = ");
   pageSizePragma.AppendInt(cachePages);
   rv = mDBConn->ExecuteSimpleSQL(pageSizePragma);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // Lock the db file.  This is done partly to avoid third party applications
-  // to access the database while it's in use, partly for performance reasons.
-  // http://www.sqlite.org/pragma.html#pragma_locking_mode
+  // Lock the database file.  This is done partly to avoid third party
+  // applications to access it while it's in use, partly for performance.
   rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "PRAGMA locking_mode = EXCLUSIVE"));
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "PRAGMA journal_mode = " DEFAULT_JOURNAL_MODE));
+      "PRAGMA journal_mode = " DATABASE_JOURNAL_MODE));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // We are going to initialize tables, so everything from now on should be in
   // a transaction for performances.
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
-  // Initialize the other places services' database tables. We do this before
-  // creating our statements. Some of our statements depend on these external
-  // tables, such as the bookmarks or favicon tables.
+  // Initialize the other Places services' database tables before creating our
+  // statements. Some of our statements depend on these external tables, such as
+  // the bookmarks or favicon tables.
   rv = nsNavBookmarks::InitTables(mDBConn);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = nsFaviconService::InitTables(mDBConn);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = nsAnnotationService::InitTables(mDBConn);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!databaseInitialized) {
     // This is the first run, so we set schema version to the latest one, since
     // we don't need to migrate anything.  We will create tables from scratch.
     rv = UpdateSchemaVersion();
     NS_ENSURE_SUCCESS(rv, rv);
-    DBSchemaVersion = PLACES_SCHEMA_VERSION;
-  }
-
-  if (PLACES_SCHEMA_VERSION != DBSchemaVersion) {
+    currentSchemaVersion = DATABASE_SCHEMA_VERSION;
+  }
+
+  if (DATABASE_SCHEMA_VERSION != currentSchemaVersion) {
     // Migration How-to:
     //
     // 1. increment PLACES_SCHEMA_VERSION.
     // 2. implement a method that performs up/sidegrade to your version
     //    from the current version.
     //
     // NOTE: We don't support downgrading back to History-only Places.
     // If you want to go from newer schema version back to V0, you'll need to
     // blow away your sqlite file. Subsequent up/downgrades have backwards and
     // forward migration code.
     //
     // XXX Backup places.sqlite to places-{version}.sqlite when doing db migration?
     
-    if (DBSchemaVersion < PLACES_SCHEMA_VERSION) {
-      // Upgrading
+    if (currentSchemaVersion < DATABASE_SCHEMA_VERSION) {
+      // Upgrading.
       mDatabaseStatus = DATABASE_STATUS_UPGRADED;
 
       // Migrate anno tables up to V3
-      if (DBSchemaVersion < 3) {
+      if (currentSchemaVersion < 3) {
         rv = MigrateV3Up(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       // Migrate bookmarks tables up to V5
-      if (DBSchemaVersion < 5) {
+      if (currentSchemaVersion < 5) {
         rv = ForceMigrateBookmarksDB(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       // Migrate anno tables up to V6
-      if (DBSchemaVersion < 6) {
+      if (currentSchemaVersion < 6) {
         rv = MigrateV6Up(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       // Migrate historyvisits and bookmarks up to V7
-      if (DBSchemaVersion < 7) {
+      if (currentSchemaVersion < 7) {
         rv = MigrateV7Up(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       // Migrate historyvisits up to V8
-      if (DBSchemaVersion < 8) {
+      if (currentSchemaVersion < 8) {
         rv = MigrateV8Up(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       // Migrate places up to V9
-      if (DBSchemaVersion < 9) {
+      if (currentSchemaVersion < 9) {
         rv = MigrateV9Up(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       // Migrate places up to V10
-      if (DBSchemaVersion < 10) {
+      if (currentSchemaVersion < 10) {
         rv = MigrateV10Up(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       // Schema Upgrades must add migration code here.
 
     } else {
       // Downgrading
 
       // XXX Need to prompt user or otherwise notify of 
       // potential dataloss when downgrading.
 
       // XXX Downgrades from >V6 must add migration code here.
 
       // Downgrade v1,2,4,5
       // v3,6 have no backwards incompatible changes.
-      if (DBSchemaVersion > 2 && DBSchemaVersion < 6) {
+      if (currentSchemaVersion > 2 && currentSchemaVersion < 6) {
         // perform downgrade to v2
         rv = ForceMigrateBookmarksDB(mDBConn);
         NS_ENSURE_SUCCESS(rv, rv);
       }
     }
 
     // Update schema version to the current one.
     rv = UpdateSchemaVersion();
@@ -892,52 +885,55 @@ nsNavHistory::InitDB()
   // ANY FAILURE IN THIS METHOD WILL CAUSE US TO MARK THE DATABASE AS CORRUPT
   // AND TRY TO REPLACE IT.
   // DO NOT PUT HERE ANYTHING THAT IS NOT RELATED TO INITIALIZATION OR MODIFYING
   // THE DISK DATABASE.
 
   return NS_OK;
 }
 
+
 nsresult
 nsNavHistory::InitAdditionalDBItems()
 {
   nsresult rv = InitTempTables();
   NS_ENSURE_SUCCESS(rv, rv);
   rv = InitViews();
   NS_ENSURE_SUCCESS(rv, rv);
   rv = InitFunctions();
   NS_ENSURE_SUCCESS(rv, rv);
   rv = InitStatements();
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 nsNavHistory::GetDatabaseStatus(PRUint16 *aDatabaseStatus)
 {
   NS_ENSURE_ARG_POINTER(aDatabaseStatus);
   *aDatabaseStatus = mDatabaseStatus;
   return NS_OK;
 }
 
-// nsNavHistory::UpdateSchemaVersion
-//
-// Called by the individual services' InitTables()
+
+/**
+ * Called by the individual services' InitTables().
+ */
 nsresult
 nsNavHistory::UpdateSchemaVersion()
 {
-  return mDBConn->SetSchemaVersion(PLACES_SCHEMA_VERSION);
-}
-
-// nsNavHistory::InitFunctions
-//
-//    Called after InitDB, this creates our own functions
-
+  return mDBConn->SetSchemaVersion(DATABASE_SCHEMA_VERSION);
+}
+
+
+/**
+ * Called after InitDB, this creates our own functions
+ */
 class mozStorageFunctionGetUnreversedHost: public mozIStorageFunction
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_MOZISTORAGEFUNCTION
 };
 
 NS_IMPL_ISUPPORTS1(mozStorageFunctionGetUnreversedHost, mozIStorageFunction)
@@ -1059,20 +1055,20 @@ nsNavHistory::InitFunctions()
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = MatchAutoCompleteFunction::create(mDBConn);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
-// nsNavHistory::InitStatements
-//
-//    Called after InitDB, this creates our stored statements
-
+
+/**
+ * Called after InitDB, this creates our stored statements.
+ */
 nsresult
 nsNavHistory::InitStatements()
 {
   // mDBGetURLPageInfo
   // We are not checking for duplicated ids into the unified table
   // for perf reasons, LIMIT 1 will discard duplicates faster since we
   // have unique urls.
   nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
@@ -1315,24 +1311,25 @@ nsNavHistory::InitStatements()
         "(SELECT COUNT(*) FROM moz_historyvisits_temp WHERE place_id = ?1 "
             "AND id NOT IN (SELECT id FROM moz_historyvisits))"),
     getter_AddRefs(mDBFullVisitCount));
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
-// nsNavHistory::ForceMigrateBookmarksDB
-//
-//    This dumps all bookmarks-related tables, and recreates them,
-//    forcing a re-import of bookmarks.html.
-//
-//    NOTE: This may cause data-loss if downgrading!
-//    Only use this for migration if you're sure that bookmarks.html
-//    and the target version support all bookmarks fields.
+
+/**
+ * This dumps all bookmarks-related tables, and recreates them,
+ * forcing a re-import of bookmarks.html.
+ *
+ * @note This may cause data-loss if downgrading!
+ *       Only use this for migration if you're sure that bookmarks.html
+ *       and the target version support all bookmarks fields.
+ */
 nsresult
 nsNavHistory::ForceMigrateBookmarksDB(mozIStorageConnection* aDBConn) 
 {
   // drop bookmarks tables
   nsresult rv = aDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "DROP TABLE IF EXISTS moz_bookmarks"));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = aDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
@@ -1352,17 +1349,17 @@ nsNavHistory::ForceMigrateBookmarksDB(mo
   // We have done a new database init, so we mark this as if the database has
   // been created now, so the frontend can distinguish this status and import
   // if needed.
   mDatabaseStatus = DATABASE_STATUS_CREATE;
 
   return NS_OK;
 }
 
-// nsNavHistory::MigrateV3Up
+
 nsresult
 nsNavHistory::MigrateV3Up(mozIStorageConnection* aDBConn) 
 {
   // if type col is already there, then a partial update occurred.
   // return, making no changes, and allowing db version to be updated.
   nsCOMPtr<mozIStorageStatement> statement;
   nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
       "SELECT type from moz_annos"),
@@ -1380,17 +1377,17 @@ nsNavHistory::MigrateV3Up(mozIStorageCon
     NS_ENSURE_SUCCESS(rv, rv);
     rv = nsAnnotationService::InitTables(mDBConn);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   NS_ENSURE_SUCCESS(rv, rv);
   return NS_OK;
 }
 
-// nsNavHistory::MigrateV6Up
+
 nsresult
 nsNavHistory::MigrateV6Up(mozIStorageConnection* aDBConn) 
 {
   mozStorageTransaction transaction(aDBConn, PR_FALSE);
 
   // if dateAdded & lastModified cols are already there, then a partial update occurred,
   // and so we should not attempt to add these cols.
   nsCOMPtr<mozIStorageStatement> statement;
@@ -1510,17 +1507,17 @@ nsNavHistory::MigrateV6Up(mozIStorageCon
     rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
         "DROP TABLE moz_places_backup"));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return transaction.Commit();
 }
 
-// nsNavHistory::MigrateV7Up
+
 nsresult
 nsNavHistory::MigrateV7Up(mozIStorageConnection* aDBConn) 
 {
   mozStorageTransaction transaction(aDBConn, PR_FALSE);
 
   // We need an index on lastModified to catch quickly last modified bookmark
   // title for tag container's children. This will be useful for sync too.
   PRBool lastModIndexExists = PR_FALSE;
@@ -1673,16 +1670,17 @@ nsNavHistory::MigrateV7Up(mozIStorageCon
     // Now we create our trigger
     rv = aDBConn->ExecuteSimpleSQL(CREATE_KEYWORD_VALIDITY_TRIGGER);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return transaction.Commit();
 }
 
+
 nsresult
 nsNavHistory::MigrateV8Up(mozIStorageConnection *aDBConn)
 {
   mozStorageTransaction transaction(aDBConn, PR_FALSE);
 
   nsresult rv = aDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "DROP TRIGGER IF EXISTS moz_historyvisits_afterinsert_v1_trigger"));
   NS_ENSURE_SUCCESS(rv, rv);
@@ -1723,16 +1721,17 @@ nsNavHistory::MigrateV8Up(mozIStorageCon
     // create new item annos index
     rv = mDBConn->ExecuteSimpleSQL(CREATE_IDX_MOZ_ITEMSANNOS_PLACEATTRIBUTE);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return transaction.Commit();
 }
 
+
 nsresult
 nsNavHistory::MigrateV9Up(mozIStorageConnection *aDBConn)
 {
   mozStorageTransaction transaction(aDBConn, PR_FALSE);
   // Added in Bug 488966.  The last_visit_date column caches the last
   // visit date, this enhances SELECT performances when we
   // need to sort visits by visit date.
   // The cached value is synced by INSERT and DELETE triggers on
@@ -1768,23 +1767,24 @@ nsNavHistory::MigrateV9Up(mozIStorageCon
         "UPDATE moz_places SET last_visit_date = "
           "(SELECT MAX(visit_date) "
            "FROM moz_historyvisits "
            "WHERE place_id = moz_places.id)"));
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Restore the default journal mode.
     rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-        "PRAGMA journal_mode = " DEFAULT_JOURNAL_MODE));
+        "PRAGMA journal_mode = " DATABASE_JOURNAL_MODE));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return transaction.Commit();
 }
 
+
 nsresult
 nsNavHistory::MigrateV10Up(mozIStorageConnection *aDBConn)
 {
   // LastModified is set to the same value as dateAdded on item creation.
   // This way we can use lastModified index to sort.
   nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "UPDATE moz_bookmarks SET lastModified = dateAdded "
       "WHERE lastModified IS NULL"));
@@ -1857,17 +1857,17 @@ nsNavHistory::InternalAddNewPage(nsIURI*
   NS_ENSURE_SUCCESS(rv, rv);
 
   // title
   if (aTitle.IsVoid()) {
     rv = mDBAddNewPage->BindNullParameter(1);
   }
   else {
     rv = mDBAddNewPage->BindStringParameter(1,
-        StringHead(aTitle, HISTORY_TITLE_LENGTH_MAX));
+        StringHead(aTitle, TITLE_LENGTH_MAX));
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   // host (reversed with trailing period)
   nsAutoString revHost;
   rv = GetReversedHostname(aURI, revHost);
   // Not all URI types have hostnames, so this is optional.
   if (NS_SUCCEEDED(rv)) {
@@ -2025,18 +2025,16 @@ PRBool nsNavHistory::IsURIStringVisited(
 
   PRBool hasMore = PR_FALSE;
   rv = mDBIsPageVisited->ExecuteStep(&hasMore);
   NS_ENSURE_SUCCESS(rv, PR_FALSE);
   return hasMore;
 }
 
 
-// nsNavHistory::LoadPrefs
-
 nsresult
 nsNavHistory::LoadPrefs(PRBool aInitializing)
 {
   if (! mPrefBranch)
     return NS_OK;
 
   mPrefBranch->GetIntPref(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MAX, &mExpireDaysMax);
   mPrefBranch->GetIntPref(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MIN, &mExpireDaysMin);
@@ -3088,28 +3086,28 @@ private:
   nsNavHistory::StringHash& mAddParams;
 };
 
 PlacesSQLQueryBuilder::PlacesSQLQueryBuilder(
     const nsCString& aConditions, 
     nsNavHistoryQueryOptions* aOptions, 
     PRBool aUseLimit,
     nsNavHistory::StringHash& aAddParams,
-    PRBool aHasSearchTerms) :
-  mConditions(aConditions),
-  mUseLimit(aUseLimit),
-  mResultType(aOptions->ResultType()),
-  mQueryType(aOptions->QueryType()),
-  mIncludeHidden(aOptions->IncludeHidden()),
-  mRedirectsMode(aOptions->RedirectsMode()),
-  mSortingMode(aOptions->SortingMode()),
-  mMaxResults(aOptions->MaxResults()),
-  mSkipOrderBy(PR_FALSE),
-  mAddParams(aAddParams),
-  mHasSearchTerms(aHasSearchTerms)
+    PRBool aHasSearchTerms)
+: mConditions(aConditions)
+, mUseLimit(aUseLimit)
+, mHasSearchTerms(aHasSearchTerms)
+, mResultType(aOptions->ResultType())
+, mQueryType(aOptions->QueryType())
+, mIncludeHidden(aOptions->IncludeHidden())
+, mRedirectsMode(aOptions->RedirectsMode())
+, mSortingMode(aOptions->SortingMode())
+, mMaxResults(aOptions->MaxResults())
+, mSkipOrderBy(PR_FALSE)
+, mAddParams(aAddParams)
 {
   mHasDateColumns = (mQueryType == nsINavHistoryQueryOptions::QUERY_TYPE_BOOKMARKS);
 }
 
 nsresult
 PlacesSQLQueryBuilder::GetQueryString(nsCString& aQueryString)
 {
   nsresult rv = Select();
@@ -3387,19 +3385,19 @@ PlacesSQLQueryBuilder::SelectAsDay()
   // Sort child queries based on sorting mode if it's provided, otherwise
   // fallback to default sort by title ascending.
   PRUint16 sortingMode = nsINavHistoryQueryOptions::SORT_BY_TITLE_ASCENDING;
   if (mSortingMode != nsINavHistoryQueryOptions::SORT_BY_NONE &&
       mResultType == nsINavHistoryQueryOptions::RESULTS_AS_DATE_QUERY)
     sortingMode = mSortingMode;
 
   PRUint16 resultType =
-    mResultType == nsINavHistoryQueryOptions::RESULTS_AS_DATE_QUERY ?
-                   nsINavHistoryQueryOptions::RESULTS_AS_URI :
-                   nsINavHistoryQueryOptions::RESULTS_AS_SITE_QUERY;
+    (mResultType == nsINavHistoryQueryOptions::RESULTS_AS_DATE_QUERY) ?
+      nsINavHistoryQueryOptions::RESULTS_AS_URI :
+      nsINavHistoryQueryOptions::RESULTS_AS_SITE_QUERY;
 
   // beginTime will become the node's time property, we don't use endTime
   // because it could overlap, and we use time to sort containers and find
   // insert position in a result.
   mQueryString = nsPrintfCString(1024,
      "SELECT null, "
        "'place:type=%ld&sort=%ld&beginTime='||beginTime||'&endTime='||endTime, "
       "dayTitle, null, null, beginTime, null, null, null, null, null, null "
@@ -5443,17 +5441,18 @@ nsNavHistory::AddDownload(nsIURI* aSourc
 NS_IMETHODIMP
 nsNavHistory::GetDBConnection(mozIStorageConnection **_DBConnection)
 {
   NS_ENSURE_ARG_POINTER(_DBConnection);
   NS_ADDREF(*_DBConnection = mDBConn);
   return NS_OK;
 }
 
-NS_HIDDEN_(nsresult)
+
+nsresult
 nsNavHistory::FinalizeInternalStatements()
 {
   NS_ASSERTION(NS_IsMainThread(), "This can only be called on the main thread");
 
   // nsNavHistory
   nsresult rv = FinalizeStatements();
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -5645,17 +5644,18 @@ nsNavHistory::Observe(nsISupports *aSubj
     // This code is only called if we've either imported or done a migration
     // from a pre-frecency build, so we will calculate all their frecencies.
     (void)FixInvalidFrecencies();
   }
 
   return NS_OK;
 }
 
-NS_HIDDEN_(nsresult)
+
+nsresult
 nsNavHistory::VacuumDatabase()
 {
   // SQLite cannot give us a real value for fragmentation percentage,
   // we could analyze the database file page by page, and count fragmented
   // space, but that would be slow and not maintainable across different SQLite
   // versions.
   // For this reason we just take a guess using the freelist count.
   // This way we know how much pages are unused, but we don't know anything
@@ -5671,18 +5671,18 @@ nsNavHistory::VacuumDatabase()
   if (NS_SUCCEEDED(prefSvc->GetIntPref(PREF_LAST_VACUUM, &lastVacuumPref))) {
     // Value are seconds till epoch, convert it to microseconds.
     lastVacuumTime = (PRInt64)lastVacuumPref * PR_USEC_PER_SEC;
   }
 
   nsresult rv;
   float freePagesRatio = 0;
   if (!lastVacuumTime ||
-      (lastVacuumTime < (PR_Now() - MIN_TIME_BEFORE_VACUUM) &&
-       lastVacuumTime > (PR_Now() - MAX_TIME_BEFORE_VACUUM))) {
+      (lastVacuumTime < (PR_Now() - DATABASE_MIN_TIME_BEFORE_VACUUM) &&
+       lastVacuumTime > (PR_Now() - DATABASE_MAX_TIME_BEFORE_VACUUM))) {
     // This is the first vacuum, or we are in the timeframe where vacuum could
     // happen.  Calculate the vacuum ratio and vacuum if it is less then
     // threshold.
     nsCOMPtr<mozIStorageStatement> statement;
     rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA page_count"),
                                   getter_AddRefs(statement));
     NS_ENSURE_SUCCESS(rv, rv);
     PRBool hasResult = PR_FALSE;
@@ -5698,18 +5698,18 @@ nsNavHistory::VacuumDatabase()
     rv = statement->ExecuteStep(&hasResult);
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(hasResult, NS_ERROR_FAILURE);
     PRInt32 freelistCount = statement->AsInt32(0);
 
     freePagesRatio = (float)(freelistCount / pageCount);
   }
   
-  if (freePagesRatio > VACUUM_FREEPAGES_THRESHOLD ||
-      lastVacuumTime < (PR_Now() - MAX_TIME_BEFORE_VACUUM)) {
+  if (freePagesRatio > DATABASE_VACUUM_FREEPAGES_THRESHOLD ||
+      lastVacuumTime < (PR_Now() - DATABASE_MAX_TIME_BEFORE_VACUUM)) {
     // We vacuum in 2 cases:
     //  - We are in the valid vacuum timeframe and vacuum ratio is high.
     //  - Last vacuum has been executed a lot of time ago.
 
     // Notify we are about to vacuum.  This is mostly for testability.
     nsCOMPtr<nsIObserverService> observerService =
       do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
     if (observerService) {
@@ -5732,17 +5732,17 @@ nsNavHistory::VacuumDatabase()
 
     nsCOMPtr<mozIStorageStatement> vacuum;
     rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING("VACUUM"),
                                   getter_AddRefs(vacuum));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<mozIStorageStatement> journalToDefault;
     rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-        "PRAGMA journal_mode = " DEFAULT_JOURNAL_MODE),
+        "PRAGMA journal_mode = " DATABASE_JOURNAL_MODE),
       getter_AddRefs(journalToDefault));
     NS_ENSURE_SUCCESS(rv, rv);
 
     mozIStorageStatement *stmts[] = {
       journalToMemory,
       vacuum,
       journalToDefault
     };
@@ -5754,17 +5754,17 @@ nsNavHistory::VacuumDatabase()
     rv = prefSvc->SetIntPref(PREF_LAST_VACUUM,
                              (PRInt32)(PR_Now() / PR_USEC_PER_SEC));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
 }
 
-NS_HIDDEN_(nsresult)
+nsresult
 nsNavHistory::DecayFrecency()
 {
   // Update frecency values.
   nsresult rv = FixInvalidFrecencies();
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Globally decay places frecency rankings to estimate reduced frecency
   // values of pages that haven't been visited for a while, i.e., they do
@@ -5883,17 +5883,17 @@ nsNavHistory::LazyTimerCallback(nsITimer
   nsNavHistory* that = static_cast<nsNavHistory*>(aClosure);
   that->mLazyTimerSet = PR_FALSE;
   that->mLazyTimerDeferments = 0;
   that->CommitLazyMessages();
 }
 
 // nsNavHistory::CommitLazyMessages
 
-NS_HIDDEN_(void)
+void
 nsNavHistory::CommitLazyMessages(PRBool aIsShutdown)
 {
   mozStorageTransaction transaction(mDBConn, PR_TRUE);
   for (PRUint32 i = 0; i < mLazyMessages.Length(); i ++) {
     LazyMessage& message = mLazyMessages[i];
     switch (message.type) {
       case LazyMessage::Type_AddURI:
         AddURIInternal(message.uri, message.time, message.isRedirect,
@@ -6214,17 +6214,17 @@ nsNavHistory::BindQueryClauseParameters(
   // URI
   if (aQuery->Uri()) {
     BindStatementURI(statement, index.For("uri"), aQuery->Uri());
     if (aQuery->UriIsPrefix()) {
       nsCAutoString uriString;
       aQuery->Uri()->GetSpec(uriString);
       uriString.Append(char(0x7F)); // MAX_UTF8
       rv = statement->BindUTF8StringParameter(index.For("uri_upper"),
-        StringHead(uriString, HISTORY_URI_LENGTH_MAX));
+        StringHead(uriString, URI_LENGTH_MAX));
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   // annotation
   if (!aQuery->Annotation().IsEmpty()) {
     rv = statement->BindUTF8StringParameter(index.For("anno"), 
                                             aQuery->Annotation());
@@ -7032,17 +7032,17 @@ nsNavHistory::SetPageTitleInternal(nsIUR
   if ((aTitle.IsVoid() && title.IsVoid()) || aTitle == title)
     return NS_OK;
 
   mozStorageStatementScoper scoper(mDBSetPlaceTitle);
   // title
   if (aTitle.IsVoid())
     rv = mDBSetPlaceTitle->BindNullParameter(0);
   else
-    rv = mDBSetPlaceTitle->BindStringParameter(0, StringHead(aTitle, HISTORY_TITLE_LENGTH_MAX));
+    rv = mDBSetPlaceTitle->BindStringParameter(0, StringHead(aTitle, TITLE_LENGTH_MAX));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // url
   rv = BindStatementURI(mDBSetPlaceTitle, 1, aURI);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = mDBSetPlaceTitle->Execute();
   NS_ENSURE_SUCCESS(rv, rv);
@@ -7251,18 +7251,18 @@ nsNavHistory::RemoveDuplicateURIs()
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   rv = transaction.Commit();
   NS_ENSURE_SUCCESS(rv, rv);
   return NS_OK;
 }
 
-// Local function **************************************************************
-
+
+namespace {
 
 // GetReversedHostname
 //
 //    This extracts the hostname from the URI and reverses it in the
 //    form that we use (always ending with a "."). So
 //    "http://microsoft.com/" becomes "moc.tfosorcim."
 //
 //    The idea behind this is that we can create an index over the items in
@@ -7404,33 +7404,35 @@ void ParseSearchTermsFromQueries(const n
       // last word
       if (lastBegin >= 0)
         queryTerms->AppendElement(Substring(searchTerms, lastBegin));
     }
     aTerms->AppendElement(queryTerms);
   }
 }
 
-// BindStatementURI
-//
-//    Binds the specified URI as the parameter 'index' for the statment.
-//    URIs are always bound as UTF8
-
+} // anonymous namespace
+
+
+/**
+ * Binds the specified URI as the parameter 'index' for the statment.
+ * URIs are always bound as UTF8
+ */
 nsresult
 BindStatementURI(mozIStorageStatement* statement, PRInt32 index, nsIURI* aURI)
 {
   NS_ASSERTION(statement, "Must have non-null statement");
   NS_ASSERTION(aURI, "Must have non-null uri");
 
   nsCAutoString utf8URISpec;
   nsresult rv = aURI->GetSpec(utf8URISpec);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = statement->BindUTF8StringParameter(index,
-      StringHead(utf8URISpec, HISTORY_URI_LENGTH_MAX));
+      StringHead(utf8URISpec, URI_LENGTH_MAX));
   NS_ENSURE_SUCCESS(rv, rv);
   return NS_OK;
 }
 
 nsresult
 nsNavHistory::UpdateFrecency(PRInt64 aPlaceId, PRBool aIsBookmarked)
 {
   mozStorageStatementScoper statsScoper(mDBGetPlaceVisitStats);
@@ -7486,17 +7488,17 @@ nsNavHistory::UpdateFrecencyInternal(PRI
 
   // save ourselves the UPDATE if the frecency hasn't changed
   // One way this can happen is with livemarks.
   // when we added the livemark, the frecency was 0.  
   // On refresh, when we remove and then add the livemark items,
   // the frecency (for a given moz_places) will not have changed
   // (if we've never visited that place).
   // Additionally, don't bother overwriting a valid frecency with an invalid one
-  if (newFrecency == aOldFrecency || aOldFrecency && newFrecency < 0)
+  if ((newFrecency == aOldFrecency) || (aOldFrecency && newFrecency < 0))
     return NS_OK;
 
   mozStorageStatementScoper updateScoper(mDBUpdateFrecencyAndHidden);
   rv = mDBUpdateFrecencyAndHidden->BindInt64Parameter(0, aPlaceId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = mDBUpdateFrecencyAndHidden->BindInt32Parameter(1, newFrecency);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -7995,17 +7997,17 @@ nsNavHistory::GetDBBookmarkToUrlResult()
       "WHERE b.id = ?1 "
       "LIMIT 1"),
     getter_AddRefs(mDBBookmarkToUrlResult));
   NS_ENSURE_SUCCESS(rv, nsnull);
 
   return mDBBookmarkToUrlResult;
 }
 
-NS_HIDDEN_(nsresult)
+nsresult
 nsNavHistory::FinalizeStatements() {
   mozIStorageStatement* stmts[] = {
 #ifdef MOZ_XUL
     mDBFeedbackIncrease,
 #endif
     mDBGetURLPageInfo,
     mDBGetIdPageInfo,
     mDBRecentVisitOfURL,
--- a/toolkit/components/places/src/nsNavHistory.h
+++ b/toolkit/components/places/src/nsNavHistory.h
@@ -78,16 +78,21 @@
 #define QUERYUPDATE_COMPLEX 2
 #define QUERYUPDATE_COMPLEX_WITH_BOOKMARKS 3
 #define QUERYUPDATE_HOST 4
 
 // This magic number specified an uninitialized value for the
 // mInPrivateBrowsing member
 #define PRIVATEBROWSING_NOTINITED (PRBool(0xffffffff))
 
+// Clamp title and URL to generously large, but not too large, length.
+// See bug 319004 for details.
+#define URI_LENGTH_MAX 65536
+#define TITLE_LENGTH_MAX 4096
+
 
 class mozIAnnotationService;
 class nsNavHistory;
 class nsNavBookmarks;
 class QueryKeyValuePair;
 class nsIEffectiveTLDService;
 class nsIIDNService;
 class PlacesSQLQueryBuilder;
@@ -403,32 +408,32 @@ protected:
   mozIStorageStatement *GetDBVisitToVisitResult();
   nsCOMPtr<mozIStorageStatement> mDBVisitToVisitResult; // kGetInfoIndex_* results
   mozIStorageStatement *GetDBBookmarkToUrlResult();
   nsCOMPtr<mozIStorageStatement> mDBBookmarkToUrlResult; // kGetInfoIndex_* results
 
   /**
    * Finalize all internal statements.
    */
-  NS_HIDDEN_(nsresult) FinalizeStatements();
+  nsresult FinalizeStatements();
 
   /**
    * Analyzes the database and VACUUM it, if needed.
    */
-  NS_HIDDEN_(nsresult) DecayFrecency();
+  nsresult DecayFrecency();
   /**
    * Decays frecency and inputhistory values.
    */
-  NS_HIDDEN_(nsresult) VacuumDatabase();
+  nsresult VacuumDatabase();
 
   /**
    * Finalizes all Places internal statements, allowing to safely close the
    * database connection.
    */
-  NS_HIDDEN_(nsresult) FinalizeInternalStatements();
+  nsresult FinalizeInternalStatements();
 
   // nsICharsetResolver
   NS_DECL_NSICHARSETRESOLVER
 
   nsresult CalculateFrecency(PRInt64 aPageID, PRInt32 aTyped, PRInt32 aVisitCount, nsCAutoString &aURL, PRInt32 *aFrecency);
   nsresult CalculateFrecencyInternal(PRInt64 aPageID, PRInt32 aTyped, PRInt32 aVisitCount, PRBool aIsBookmarked, PRInt32 *aFrecency);
   nsCOMPtr<mozIStorageStatement> mDBVisitsForFrecency;
   nsCOMPtr<mozIStorageStatement> mDBUpdateFrecencyAndHidden;
@@ -564,17 +569,17 @@ protected:
   };
   nsTArray<LazyMessage> mLazyMessages;
   nsCOMPtr<nsITimer> mLazyTimer;
   PRBool mLazyTimerSet;
   PRUint32 mLazyTimerDeferments; // see StartLazyTimer
   nsresult StartLazyTimer();
   nsresult AddLazyMessage(const LazyMessage& aMessage);
   static void LazyTimerCallback(nsITimer* aTimer, void* aClosure);
-  NS_HIDDEN_(void) CommitLazyMessages(PRBool aIsShutdown = PR_FALSE);
+  void CommitLazyMessages(PRBool aIsShutdown = PR_FALSE);
 #endif
 
   nsresult ConstructQueryString(const nsCOMArray<nsNavHistoryQuery>& aQueries, 
                                 nsNavHistoryQueryOptions* aOptions,
                                 nsCString& queryString,
                                 PRBool& aParamsPresent,
                                 StringHash& aAddParams);
 
--- a/toolkit/components/places/src/nsNavHistoryResult.cpp
+++ b/toolkit/components/places/src/nsNavHistoryResult.cpp
@@ -3995,23 +3995,23 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsINavHistoryResult)
   NS_INTERFACE_MAP_STATIC_AMBIGUOUS(nsNavHistoryResult)
   NS_INTERFACE_MAP_ENTRY(nsINavHistoryResult)
   NS_INTERFACE_MAP_ENTRY(nsINavBookmarkObserver)
   NS_INTERFACE_MAP_ENTRY(nsINavHistoryObserver)
   NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
 NS_INTERFACE_MAP_END
 
-nsNavHistoryResult::nsNavHistoryResult(nsNavHistoryContainerResultNode* aRoot) :
-  mRootNode(aRoot),
-  mIsHistoryObserver(PR_FALSE),
-  mIsBookmarkFolderObserver(PR_FALSE),
-  mIsAllBookmarksObserver(PR_FALSE),
-  mBatchInProgress(PR_FALSE),
-  mNeedsToApplySortingMode(PR_FALSE)
+nsNavHistoryResult::nsNavHistoryResult(nsNavHistoryContainerResultNode* aRoot)
+: mRootNode(aRoot)
+, mIsHistoryObserver(PR_FALSE)
+, mIsBookmarkFolderObserver(PR_FALSE)
+, mIsAllBookmarksObserver(PR_FALSE)
+, mNeedsToApplySortingMode(PR_FALSE)
+, mBatchInProgress(PR_FALSE)
 {
   mRootNode->mResult = this;
 }
 
 nsNavHistoryResult::~nsNavHistoryResult()
 {
   // delete all bookmark folder observer arrays which are allocated on the heap
   mBookmarkFolderObservers.Enumerate(&RemoveBookmarkFolderObserversCallback, nsnull);