bookmarks/BookmarksManager.cpp
changeset 9 1d51612454b5
child 12 d26902edeef5
equal deleted inserted replaced
8:6b5f25f057c2 9:1d51612454b5
       
     1 /*
       
     2 * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     3 * All rights reserved.
       
     4 *
       
     5 * This program is free software: you can redistribute it and/or modify
       
     6 * it under the terms of the GNU Lesser General Public License as published by
       
     7 * the Free Software Foundation, version 2.1 of the License.
       
     8 * 
       
     9 * This program is distributed in the hope that it will be useful,
       
    10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    12 * GNU Lesser General Public License for more details.
       
    13 *
       
    14 * You should have received a copy of the GNU Lesser General Public License
       
    15 * along with this program.  If not, 
       
    16 * see "http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html/".
       
    17 *
       
    18 * Description: This implements the bookmarks API's.
       
    19 *
       
    20 */
       
    21 
       
    22 #include<QString>
       
    23 #include<QFile>
       
    24 #include<QFileInfo>
       
    25 #include<QDebug>
       
    26 #include<QSqlDatabase>
       
    27 #include<QSqlQuery>
       
    28 #include<QSqlError>
       
    29 #include<QWidget>
       
    30 #include<QtGui>
       
    31 
       
    32 #include "bookmarksapi.h"
       
    33 #include "BookmarksManager.h"
       
    34 #include "BookmarkFav.h"
       
    35 #include "BookmarkResults.h"
       
    36 #include "TagResults.h"
       
    37 #include "xbelreader.h"
       
    38 #include "xbelwriter.h"
       
    39 #include "defaultBookmarks.xml.h"
       
    40 
       
    41 BookmarksManager::BookmarksManager(QWidget *parent) :
       
    42     QObject(parent)
       
    43 {
       
    44     setObjectName("bookmarksManager");
       
    45 
       
    46     m_db = QSqlDatabase::database(BOOKMARKS_DB_NAME);
       
    47     if (!m_db.isValid()) {
       
    48         m_db = QSqlDatabase::addDatabase("QSQLITE", BOOKMARKS_DB_NAME);
       
    49         m_db.setDatabaseName(BOOKMARKS_DB_FILE);
       
    50     }
       
    51     if (m_db.open()) {
       
    52         // TODO: Do we need a flag so that this gets called only once OR when
       
    53         // creating a database tables "IF NOT EXISTS" is good enough
       
    54         createBookmarksSchema();
       
    55     }
       
    56 }
       
    57 
       
    58 BookmarksManager::~BookmarksManager() {
       
    59     m_db.close();
       
    60     QSqlDatabase::removeDatabase(BOOKMARKS_DB_NAME);
       
    61 }
       
    62 
       
    63 /*
       
    64  * +-------------+       +----------+
       
    65  * |Bookmarks(ID)|* <-> *|Tags(BMID)|
       
    66  * +-------------+       +----------+
       
    67  */
       
    68 void BookmarksManager::createBookmarksSchema() {
       
    69     // Bookmarks
       
    70     if (!doQuery("CREATE TABLE IF NOT EXISTS bookmarks("
       
    71                     "id INTEGER PRIMARY KEY,"
       
    72                     "title text, "
       
    73                     "url text,"
       
    74                     "sortIndex int DEFAULT 0)")) {
       
    75         // TODO: do some error handling here!
       
    76         return;
       
    77     }
       
    78     // Make sorting faster
       
    79     if (!doQuery("CREATE INDEX IF NOT EXISTS bm_sort_idx ON bookmarks(sortIndex ASC)")) {
       
    80         // TODO: do some error handling here!
       
    81         return;
       
    82     }
       
    83     // We do a lot of lookups by id
       
    84     if (!doQuery("CREATE INDEX IF NOT EXISTS bm_id_idx ON bookmarks(id ASC)")) {
       
    85         // TODO: do some error handling here!
       
    86         return;
       
    87     }
       
    88 
       
    89     // Tags
       
    90     // Note: foreign key constraints are not enforced in the current version of sqlite
       
    91     // that we are using.
       
    92     if (!doQuery("CREATE TABLE IF NOT EXISTS tags("
       
    93                     "bmid INTEGER,"
       
    94                     "tag text,"
       
    95                     "FOREIGN KEY(bmid) REFERENCES bookmarks(id))")) {
       
    96         // TODO: do some error handling here!
       
    97         return;
       
    98     }
       
    99     // We do a lot of lookups, both by bookmark id and by tag
       
   100     if (!doQuery("CREATE INDEX IF NOT EXISTS tags_bmid_idx ON tags(bmid ASC)")) {
       
   101         // TODO: do some error handling here!
       
   102         return;
       
   103     }
       
   104     if (!doQuery("CREATE INDEX IF NOT EXISTS tags_tag_idx ON tags(tag ASC)")) {
       
   105         // TODO: do some error handling here!
       
   106         return;
       
   107     }
       
   108 }
       
   109 
       
   110 // TODO refactor this - nothing except the schema creation can use it as is
       
   111 bool BookmarksManager::doQuery(QString query) {
       
   112 #ifdef ENABLE_PERF_TRACE
       
   113     PERF_DEBUG() << __PRETTY_FUNCTION__ << query << "\n";
       
   114     unsigned int st = WrtPerfTracer::tracer()->startTimer();
       
   115 #endif
       
   116     QSqlQuery db_query(m_db);
       
   117     bool ok = db_query.exec(query);
       
   118     if (!ok) {
       
   119         qDebug() << "BookmarksManager::doQuery" << QString("ERR: %1 %2").arg(db_query.lastError().type()).arg(db_query.lastError().text()) << " Query: " << db_query.lastQuery();
       
   120     }
       
   121 #ifdef ENABLE_PERF_TRACE
       
   122     PERF_DEBUG() << __PRETTY_FUNCTION__ << WrtPerfTracer::tracer()->elapsedTime(st) << "\n";
       
   123 #endif
       
   124     return ok;   
       
   125 }
       
   126 
       
   127 
       
   128 /**==============================================================
       
   129  * Description: Normalize a given url, if needed.
       
   130  * It adds http:// in front, if the url is relative.
       
   131  ================================================================*/
       
   132 QString BookmarksManager::normalizeUrl(const QString& url)
       
   133 {
       
   134     // If the URL is relative, add http in front
       
   135     QString updatedUrl = url;
       
   136     
       
   137     if (!url.contains("://")) {
       
   138         updatedUrl.prepend("http://");
       
   139     }
       
   140     return updatedUrl;
       
   141 }
       
   142 
       
   143 /**==============================================================
       
   144  * Description: Adds the bookmark to the database, given title and
       
   145  * url. 
       
   146  * Returns: Returns bookmarkID ( >0)else Failure (-1 or -2)
       
   147  ================================================================*/
       
   148 int BookmarksManager::addBookmark(QString title, QString URL)
       
   149 {
       
   150     int bookmarkId = 0;
       
   151     
       
   152     if(URL.isEmpty()) {
       
   153        bookmarkId = FAILURE;
       
   154     }
       
   155     
       
   156     if(bookmarkId != FAILURE) {
       
   157         // do some checking on parameters
       
   158         QString updatedTitle = title;
       
   159         QString updatedUrl = normalizeUrl(URL);
       
   160         if (title.isEmpty()) {
       
   161             updatedTitle = "Untitled";
       
   162         }
       
   163         if (m_db.isOpen()) {
       
   164             QSqlQuery query(m_db);
       
   165             query.prepare("INSERT INTO bookmarks (title, url, sortIndex)"
       
   166                    "select :title, :url, ifnull(max(sortIndex)+1,1) from bookmarks");
       
   167             query.bindValue(":title", QVariant(updatedTitle));
       
   168             query.bindValue(":url",    QVariant(updatedUrl));
       
   169             if (!query.exec()) {
       
   170                 lastErrMsg(query);
       
   171                 return DATABASEERROR;
       
   172            }
       
   173            // Note: lastInsertId() is not thread-safe
       
   174             bookmarkId = query.lastInsertId().toInt();
       
   175         } else {
       
   176             bookmarkId = FAILURE;
       
   177         }
       
   178     }
       
   179     return bookmarkId;
       
   180 }
       
   181 
       
   182 /**==============================================================
       
   183  * Import bookmarks from an XBEL file. If no filename is 
       
   184  * passed in a set of default bookmarks will be imported.
       
   185  * The default bookmarks used can be changed by updating
       
   186  * the file "defaultBookmarks.xml.cpp".
       
   187  * @param xbelFilePath - String containing the path to the
       
   188  * file to import.
       
   189  * @return SUCCESS or FAILURE depending on whether the 
       
   190  * import process was successful.
       
   191  ==============================================================*/
       
   192 int BookmarksManager::importBookmarks(QString xbelFilePath)
       
   193 {
       
   194     XbelReader *reader = new XbelReader(this);
       
   195     bool retVal = false;
       
   196     
       
   197     if(xbelFilePath.isEmpty() || !QFile::exists(xbelFilePath)) {
       
   198         xbelFilePath = "c:\\data\\temp.xml";
       
   199         QFile file(xbelFilePath);
       
   200         if(file.exists())
       
   201             file.remove();
       
   202         if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
       
   203             return false;
       
   204         QTextStream out(&file); 
       
   205         out << defaultBookmarksList;
       
   206         out.flush();
       
   207         file.close();
       
   208     } 
       
   209     QFile file(xbelFilePath);
       
   210     if(file.exists()) {
       
   211         file.open(QIODevice::ReadOnly | QIODevice::Text);
       
   212         retVal = reader->read(&file);
       
   213         file.close();
       
   214     }
       
   215     if(reader)
       
   216         delete reader;
       
   217     return retVal ? SUCCESS : FAILURE;
       
   218 }
       
   219 
       
   220 /**==============================================================
       
   221  * Exports all bookmarks in the database to an XBEL file. This function
       
   222  * expects a valid file path to be passed in. If the path is not valid
       
   223  * a default file path will be used. If a file with that name already 
       
   224  * exists at that location,
       
   225  * @param xbelFilePath String containing the path of the file to 
       
   226  * export to.
       
   227  * @return SUCCESS or FAILURE depending on whether the 
       
   228  * export process was successful.
       
   229  ==============================================================*/
       
   230 int BookmarksManager::exportBookmarks(QString xbelFilePath)
       
   231 {
       
   232     XbelWriter *writer = new XbelWriter(this);
       
   233     bool retVal = false;
       
   234 
       
   235     if(xbelFilePath.isEmpty()) {
       
   236         xbelFilePath = "c:\\data\\myBookmarks.xml";
       
   237     }  
       
   238 
       
   239     QFile file(xbelFilePath);
       
   240     if(file.exists()) {
       
   241         file.remove(xbelFilePath);
       
   242     }
       
   243     file.open(QIODevice::WriteOnly | QIODevice::Text);
       
   244     retVal = writer->writeFile(&file);
       
   245     file.flush();
       
   246     file.close();
       
   247     
       
   248     if(writer)
       
   249         delete writer;
       
   250     return retVal ? SUCCESS : FAILURE;
       
   251     
       
   252 }
       
   253 
       
   254 /**==============================================================
       
   255  * Description: Modify the existing bookmark. Given id of the bookmark
       
   256  * and new title or url, it modifies the existing bookmark.
       
   257  * Returns : Success(0) or Failure(-1 or -2).
       
   258  ================================================================*/
       
   259 int BookmarksManager::modifyBookmark(int origBookmarkId, QString newTitle, QString newURL)
       
   260 {
       
   261     int retVal = SUCCESS;
       
   262     
       
   263     // Client has to at least pass title or url
       
   264     if(newTitle.isEmpty() && newURL.isEmpty())
       
   265        retVal = FAILURE;
       
   266      
       
   267     if(retVal == SUCCESS) {
       
   268     
       
   269         if (m_db.isOpen()) { 
       
   270               QSqlQuery query(m_db);
       
   271             
       
   272             if(newTitle.isEmpty()) {        
       
   273                 query.prepare("UPDATE bookmarks SET url=:newurl WHERE id=:bmId");
       
   274                 query.bindValue(":newurl", normalizeUrl(newURL));
       
   275                 query.bindValue(":bmId", origBookmarkId);
       
   276             } else if(newURL.isEmpty()) { 
       
   277                 query.prepare("UPDATE bookmarks SET title=:newTitle WHERE id=:bmId");
       
   278                 query.bindValue(":newTitle", newTitle);
       
   279                 query.bindValue(":bmId", origBookmarkId);
       
   280             } else {
       
   281                 query.prepare("UPDATE bookmarks SET url=:newurl, title=:newTitle WHERE id=:bmId");
       
   282                 query.bindValue(":newurl", normalizeUrl(newURL));
       
   283                 query.bindValue(":newTitle", newTitle);
       
   284                 query.bindValue(":bmId", origBookmarkId);
       
   285             }
       
   286             if (!query.exec()) {
       
   287                 lastErrMsg(query);
       
   288                 return DATABASEERROR;
       
   289             } 
       
   290             if (query.numRowsAffected() == 0) {
       
   291                 // No update happened - must be an invalid id
       
   292                 // TODO: shall we return some other status
       
   293                 retVal = FAILURE;
       
   294             }
       
   295         } else 
       
   296             retVal = FAILURE;
       
   297     }
       
   298     return retVal;
       
   299 }
       
   300 
       
   301 /**===================================================================================
       
   302  * Description: Delete the bookmark item, also delete all the tags associated with it.
       
   303  * Returns: SUCCESS(0) or Failure(-1 or -2)
       
   304  ======================================================================================*/
       
   305 int BookmarksManager::deleteBookmark(int bookmarkId)
       
   306 {
       
   307     int retVal = SUCCESS;
       
   308    
       
   309     if (m_db.isOpen()) {      
       
   310     
       
   311         QSqlQuery query(m_db);
       
   312          
       
   313         // TODO: Need to think about whether we need to get sortIndex and update all the 
       
   314         // rows after the deletion or not
       
   315 
       
   316         // TODO: check if transaction() has been supported 
       
   317         // by calling hasfeature() function first
       
   318         m_db.transaction();
       
   319         
       
   320         query.prepare("DELETE FROM bookmarks WHERE id=:bmId");
       
   321         query.bindValue(":bmId", bookmarkId);
       
   322         if (!query.exec()) {
       
   323             lastErrMsg(query);
       
   324             m_db.rollback();
       
   325             return DATABASEERROR;
       
   326         }
       
   327         
       
   328         query.prepare("DELETE FROM tags WHERE bmid=:bmId");
       
   329         query.bindValue(":bmId", bookmarkId);
       
   330         if (!query.exec()) {
       
   331             lastErrMsg(query);
       
   332             m_db.rollback();
       
   333             return DATABASEERROR;
       
   334         } 
       
   335         if (!m_db.commit()) {
       
   336             qDebug() << m_db.lastError().text();
       
   337             m_db.rollback();
       
   338             return DATABASEERROR;
       
   339         }         
       
   340     } else 
       
   341         retVal = FAILURE;
       
   342     
       
   343     return retVal;     
       
   344 }
       
   345 
       
   346 /**===================================================================================
       
   347  * Description: Delete all records from the bookmarks table as well as all the tags.
       
   348  * Returns: SUCCESS(0) or FAILURE(-1 or -2)
       
   349  ======================================================================================*/
       
   350 int BookmarksManager::clearAll()
       
   351 {
       
   352     int retVal = SUCCESS;
       
   353     
       
   354     if (m_db.isOpen()) {        
       
   355        QSqlQuery query(m_db);
       
   356            
       
   357        // TODO: check if transaction() has been supported 
       
   358        // by calling hasfeature() function first
       
   359        m_db.transaction();
       
   360        
       
   361        if(!query.exec("DELETE FROM bookmarks")) {  
       
   362             lastErrMsg(query);
       
   363             m_db.rollback();
       
   364             retVal = DATABASEERROR;
       
   365        } 
       
   366        if (retVal == SUCCESS && !query.exec("DELETE FROM tags")) {
       
   367             lastErrMsg(query);
       
   368             m_db.rollback();
       
   369             retVal = DATABASEERROR;
       
   370        } 
       
   371        if (retVal == SUCCESS && !m_db.commit()) {
       
   372            qDebug() << m_db.lastError().text();
       
   373            m_db.rollback();
       
   374            retVal = DATABASEERROR;
       
   375        }
       
   376     } else 
       
   377         retVal = FAILURE;
       
   378     
       
   379     return retVal;     
       
   380 }
       
   381 
       
   382 /**==============================================================
       
   383  * Description: Deletes a single tag associated with the bookmark
       
   384  * Returns: SUCCESS(0) or FAILURE (-1 or -2)
       
   385  ===============================================================*/
       
   386 int BookmarksManager::deleteTag(int bookmarkId, QString tagToDelete)
       
   387 {
       
   388     int retVal = SUCCESS;
       
   389  
       
   390     if(tagToDelete.isEmpty()|| bookmarkId < 0)
       
   391           retVal = FAILURE;
       
   392     
       
   393     if (retVal == SUCCESS) {
       
   394         if (m_db.isOpen()) {
       
   395             QSqlQuery query(m_db);
       
   396          
       
   397             query.prepare("DELETE FROM tags WHERE bmid=:bmId AND tag=:tag");
       
   398             query.bindValue(":bmId", bookmarkId);
       
   399             query.bindValue(":tag", tagToDelete);
       
   400             if (!query.exec()) {
       
   401                 lastErrMsg(query);
       
   402                 retVal = DATABASEERROR;
       
   403             }
       
   404         } else 
       
   405             retVal = FAILURE;
       
   406     }
       
   407     
       
   408     return retVal;     
       
   409 }
       
   410 
       
   411 /**================================================================
       
   412  * Description: Adds a single tag associated given the bookmark id
       
   413  * Returns: SUCCESS(0) or FAILURE (-1 or -2)
       
   414  ==================================================================*/
       
   415 int BookmarksManager::addTag(int bookmarkId, QString tagToAdd)
       
   416 {
       
   417     int retVal = SUCCESS;
       
   418     
       
   419     if(tagToAdd.isEmpty()|| bookmarkId < 0)
       
   420        retVal = FAILURE;
       
   421     
       
   422     if(retVal == SUCCESS) {
       
   423         if (m_db.isOpen()) {     
       
   424              QSqlQuery query(m_db);
       
   425              
       
   426             query.prepare("INSERT INTO tags (bmid, tag) "
       
   427                      "VALUES (:id, :tag)");                      
       
   428             query.bindValue(":id",   QVariant(bookmarkId));
       
   429             query.bindValue(":tag",  QVariant(tagToAdd));
       
   430             
       
   431             if (!query.exec()) {
       
   432                 lastErrMsg(query);
       
   433                 retVal = DATABASEERROR;
       
   434             } 
       
   435         } else 
       
   436             retVal = FAILURE;
       
   437     }
       
   438     
       
   439     return retVal;
       
   440 }
       
   441 
       
   442 /**==============================================================
       
   443  * Description: Finds all the bookmarks weather they have tags 
       
   444  * or not.
       
   445  * Returns: A pointer to BookmarkResults object or NULL.
       
   446  ===============================================================*/
       
   447 BookmarkResults *BookmarksManager::findAllBookmarks()
       
   448 {
       
   449     BookmarkResults * results = NULL; 
       
   450     
       
   451     QString queryStr = QString("SELECT "
       
   452                                " id, title, url, sortIndex " 
       
   453                                " FROM bookmarks ORDER BY sortIndex");
       
   454     if (m_db.isOpen()) {
       
   455         QSqlQuery *query = new QSqlQuery(m_db);
       
   456         if (query->exec(queryStr)) {
       
   457              results = new BookmarkResults(query);
       
   458         } else {
       
   459             qDebug() << query->lastError().text() << " Query: " << query->lastQuery();
       
   460             results = NULL;
       
   461         }
       
   462     }
       
   463     return results;
       
   464 }
       
   465 
       
   466 /**==============================================================
       
   467  * Description: Finds all the distinct tags.
       
   468  * Returns: A pointer to TagResults object or NULL.
       
   469  ===============================================================*/
       
   470 TagResults *BookmarksManager::findAllTags()
       
   471 {
       
   472     TagResults * results = NULL; 
       
   473     
       
   474     if (m_db.isOpen()) {
       
   475         QSqlQuery *query = new QSqlQuery(m_db);
       
   476         if (query->exec("SELECT DISTINCT tag FROM tags")) {
       
   477             // TODO: do we need javascript hack here like in findAllBookmarks API.
       
   478             results = new TagResults(query); 
       
   479         } else {
       
   480             qDebug() << query->lastError().text() << " Query: " << query->lastQuery();
       
   481             results = NULL;
       
   482         }
       
   483     }
       
   484     return results;
       
   485 }
       
   486 
       
   487 
       
   488 /**==============================================================
       
   489  * Description: Finds all the bookmarks associated with a given
       
   490  * tag. 
       
   491  * Returns: A pointer to BookmarkResults object or NULL.
       
   492  ===============================================================*/
       
   493 BookmarkResults *BookmarksManager::findBookmarksByTag(QString tag)
       
   494 {
       
   495     BookmarkResults * results = NULL; 
       
   496     
       
   497     QString queryStr = QString("SELECT "
       
   498                                " id, title, url, sortIndex " 
       
   499                                " FROM bookmarks b JOIN"
       
   500                                " tags t ON b.id=t.bmid WHERE" 
       
   501                                " t.tag=:tag");
       
   502      if (m_db.isOpen()) {
       
   503          QSqlQuery *query = new QSqlQuery(m_db);
       
   504          query->prepare(queryStr);
       
   505          query->bindValue(":tag", tag);
       
   506          if (query->exec()) {
       
   507              // TODO: do we need javascript hack here like in findAllBookmarks API.
       
   508              results = new BookmarkResults(query);
       
   509          } else {
       
   510             qDebug() << query->lastError().text() << " Query: " << query->lastQuery();
       
   511             results = NULL;
       
   512          }
       
   513      }
       
   514      return results;
       
   515 }
       
   516 
       
   517 
       
   518 /**==============================================================
       
   519  * Description: Finds all the Tags associated with a given
       
   520  * bookmarkID.
       
   521  * Returns: A pointer to TagResults object or NULL.
       
   522  ===============================================================*/
       
   523 TagResults *BookmarksManager::findTagsByBookmark(int bookmarkID)
       
   524 {
       
   525      TagResults * results = NULL; 
       
   526     
       
   527      QString queryStr = QString("SELECT DISTINCT tag "
       
   528                                  " FROM tags t JOIN"
       
   529                                  " bookmarks b ON t.bmid=b.id WHERE" 
       
   530                                  " t.bmid=:id");
       
   531      if (m_db.isOpen()) {
       
   532         QSqlQuery *query = new QSqlQuery(m_db);
       
   533         query->prepare(queryStr);
       
   534         query->bindValue(":id", bookmarkID);
       
   535         if (query->exec()) {
       
   536             // TODO: do we need javascript hack here like in findAllBookmarks API.
       
   537             results =  new TagResults(query); 
       
   538         } else {
       
   539             qDebug() << query->lastError().text() << " Query: " << query->lastQuery();
       
   540             results = NULL;
       
   541         }
       
   542      }
       
   543      return results;
       
   544 }
       
   545 
       
   546 /**==============================================================
       
   547  * Description: Finds all the Bookmarks that doesn't have any
       
   548  * tags associated with it. It is needed by export API.
       
   549  * Returns: A pointer to BookmarkResults object or NULL.
       
   550  ===============================================================*/
       
   551 BookmarkResults *BookmarksManager::findUntaggedBookmarks()
       
   552 {   
       
   553     BookmarkResults * results = NULL; 
       
   554        
       
   555     QString queryStr = QString("SELECT "
       
   556                                " id, title, url, sortIndex " 
       
   557                                " FROM bookmarks b LEFT OUTER JOIN"
       
   558                                " tags t ON b.id=t.bmid WHERE" 
       
   559                                " t.bmid IS NULL ORDER BY sortIndex");
       
   560     
       
   561     if (m_db.isOpen()) { 
       
   562        QSqlQuery *query = new QSqlQuery(m_db);
       
   563        if (query->exec(queryStr)) {
       
   564            // TODO: do we need javascript hack here like in findAllBookmarks API.
       
   565            results = new BookmarkResults(query);
       
   566        } else {
       
   567            qDebug() << query->lastError().text() << " Query: " << query->lastQuery();
       
   568            results = NULL;
       
   569        }
       
   570     }
       
   571     return results;
       
   572 }
       
   573 
       
   574 
       
   575 /**==============================================================
       
   576  * Description: Reorder bookmarks. Moves a given bookmark to a 
       
   577  * passed new index.
       
   578  * Returns: SUCCESS(0) or FAILURE (-1 or -2)
       
   579  ===============================================================*/
       
   580 int BookmarksManager::reorderBookmark(int bookmarkID, int newIndex)
       
   581 {   
       
   582     if (newIndex <= 0) 
       
   583         return FAILURE;
       
   584 
       
   585     if (!m_db.isOpen())
       
   586     	return DATABASEERROR;
       
   587 
       
   588 	QSqlQuery query(m_db);
       
   589 
       
   590 	// Make sure the bookmark exists
       
   591 	BookmarkFav *bm = findBookmark(bookmarkID);
       
   592 	if (!bm)
       
   593 		return FAILURE;
       
   594 
       
   595 	// Next, help stamp out and abolish redundancy.  If the bookmark is already at this sortIndex, do nothing.
       
   596 	if (bm->sortIndex() == newIndex)
       
   597 		return SUCCESS;
       
   598 
       
   599 	/*
       
   600 	 * Ok, the way the sortIndex works is that you can specify any sortIndex you want (it doesn't have to be consecutive).
       
   601 	 * This means there can be holes in the list of sortIndexes.  Whenever someone wants to move a bookmark to a new sort
       
   602 	 * position, we just bump everything that was in that position and further down the list by 1 and then set the sortIndex
       
   603 	 * of the bookmark to what they want.  This should work whether there is more than one bookmark or not.
       
   604 	 */
       
   605 
       
   606 	// Bump all the bookmarks from this sortIndex down by 1 first
       
   607 	m_db.transaction();
       
   608 	query.prepare("UPDATE bookmarks SET sortIndex=sortIndex+1 WHERE sortIndex >= :newIndex");
       
   609 	query.bindValue(":newIndex", newIndex);
       
   610 	if (!query.exec()) {
       
   611 		lastErrMsg(query);
       
   612 		return DATABASEERROR;
       
   613 	}
       
   614 	// Then just set this bookmark's sortIndex to the new value
       
   615 	query.prepare("UPDATE bookmarks SET sortIndex=:newIndex WHERE id=:id");
       
   616 	query.bindValue(":id", bookmarkID);
       
   617 	query.bindValue(":newIndex", newIndex);
       
   618 	if (!query.exec()) {
       
   619 		  lastErrMsg(query);
       
   620 		  m_db.rollback();
       
   621 		  return DATABASEERROR;
       
   622 	}
       
   623 	if (!m_db.commit()){
       
   624 		qDebug() << m_db.lastError().text();
       
   625 		m_db.rollback();
       
   626 		return DATABASEERROR;
       
   627 	}
       
   628     return SUCCESS;
       
   629 }
       
   630 
       
   631 /**==============================================================
       
   632  * Description: Finds a bookmark based on a given bookmarkID.
       
   633  * Returns: A pointer to BookmarkFav object or NULL.
       
   634  ===============================================================*/
       
   635 BookmarkFav* BookmarksManager::findBookmark(int bookmarkId)
       
   636 {
       
   637     BookmarkFav * results = NULL;
       
   638     
       
   639   
       
   640     if (m_db.isOpen()) { 
       
   641         QSqlQuery query(m_db);  
       
   642         query.prepare("SELECT title, url, sortIndex FROM bookmarks WHERE id=:id");
       
   643         query.bindValue(":id", bookmarkId);
       
   644         if (query.exec()) {
       
   645             if (query.next()) 
       
   646                 results = new BookmarkFav(bookmarkId, query.value(0).toString(),
       
   647                          query.value(1).toString(), query.value(2).toInt()); 
       
   648         } else {
       
   649             lastErrMsg(query);
       
   650         }
       
   651     }
       
   652     return results;
       
   653 }
       
   654 
       
   655 /**==============================================================
       
   656  * Description: Prints a last error message from the query.
       
   657  * Returns: Nothing.
       
   658  ===============================================================*/
       
   659 void BookmarksManager::lastErrMsg(QSqlQuery& query) 
       
   660 {
       
   661     qDebug() << "BookmarksManager::lastErrMsg" << QString("ERR: %1 %2").arg(query.lastError().type()).arg(query.lastError().text()) << " Query: " << query.lastQuery();
       
   662 }
       
   663