-rw-r--r-- | libopie2/opiepim/backend/ocontactaccessbackend_sql.cpp | 154 | ||||
-rw-r--r-- | libopie2/opiepim/backend/ocontactaccessbackend_sql.h | 5 | ||||
-rw-r--r-- | libopie2/opiepim/backend/opimaccessbackend.h | 28 | ||||
-rw-r--r-- | libopie2/opiepim/core/opimaccesstemplate.h | 40 | ||||
-rw-r--r-- | libopie2/opiepim/core/opimtemplatebase.h | 16 |
5 files changed, 196 insertions, 47 deletions
diff --git a/libopie2/opiepim/backend/ocontactaccessbackend_sql.cpp b/libopie2/opiepim/backend/ocontactaccessbackend_sql.cpp index dda23cc..abfd944 100644 --- a/libopie2/opiepim/backend/ocontactaccessbackend_sql.cpp +++ b/libopie2/opiepim/backend/ocontactaccessbackend_sql.cpp @@ -239,150 +239,151 @@ namespace { if ( day.isValid() ){ qu += QString(",\"%1-%2-%3\"") .arg( QString::number( day.year() ).rightJustify( 4, '0' ) ) .arg( QString::number( day.month() ).rightJustify( 2, '0' ) ) .arg( QString::number( day.day() ).rightJustify( 2, '0' ) ); } else { qu += ",\"\""; } } break; default: qu += QString( ",\"%1\"" ).arg( contactMap[id] ); } } qu += " );"; // Now add custom data.. int id = 0; id = 0; QMap<QString, QString> customMap = m_contact.toExtraMap(); for( QMap<QString, QString>::Iterator it = customMap.begin(); it != customMap.end(); ++it ){ qu += "insert into custom_data VALUES(" + QString::number( m_contact.uid() ) + "," + QString::number( id++ ) + ",'" + it.key() + "'," + "0" // Priority for future enhancements + ",'" + it.data() + "');"; } // qu += "commit;"; odebug << "add " << qu << "" << oendl; return qu; } RemoveQuery::RemoveQuery(int uid ) : OSQLQuery(), m_uid( uid ) {} RemoveQuery::~RemoveQuery() {} QString RemoveQuery::query()const { QString qu = "DELETE from addressbook where uid = " + QString::number(m_uid) + ";"; qu += "DELETE from custom_data where uid = " + QString::number(m_uid) + ";"; return qu; } FindQuery::FindQuery(int uid) : OSQLQuery(), m_uid( uid ) { } FindQuery::FindQuery(const QArray<int>& ints) : OSQLQuery(), m_uids( ints ){ } FindQuery::~FindQuery() { } QString FindQuery::query()const{ -// if ( m_uids.count() == 0 ) - return single(); + if ( m_uids.count() == 0 ) + return single(); + else + return multi(); } - /* - else - return multi(); - } - QString FindQuery::multi()const { - QString qu = "select uid, type, value from addressbook where"; - for (uint i = 0; i < m_uids.count(); i++ ) { - qu += " UID = " + QString::number( m_uids[i] ) + " OR"; - } - qu.remove( qu.length()-2, 2 ); // Hmmmm.. - return qu; + + QString FindQuery::multi()const { + QString qu = "select * from addressbook where"; + for (uint i = 0; i < m_uids.count(); i++ ) { + qu += " uid = " + QString::number( m_uids[i] ) + " OR"; + } + qu.remove( qu.length()-2, 2 ); // Hmmmm.. + + odebug << "find query: " << qu << "" << oendl; + return qu; } - */ - QString FindQuery::single()const{ - QString qu = "select *"; - qu += " from addressbook where uid = " + QString::number(m_uid); - // owarn << "find query: " << qu << "" << oendl; - return qu; + QString FindQuery::single()const{ + QString qu = "select *"; + qu += " from addressbook where uid = " + QString::number(m_uid); + + // owarn << "find query: " << qu << "" << oendl; + return qu; } FindCustomQuery::FindCustomQuery(int uid) : OSQLQuery(), m_uid( uid ) { } FindCustomQuery::FindCustomQuery(const QArray<int>& ints) : OSQLQuery(), m_uids( ints ){ } FindCustomQuery::~FindCustomQuery() { } QString FindCustomQuery::query()const{ // if ( m_uids.count() == 0 ) return single(); } QString FindCustomQuery::single()const{ QString qu = "select uid, type, value from custom_data where uid = "; qu += QString::number(m_uid); return qu; } }; /* --------------------------------------------------------------------------- */ namespace Opie { OPimContactAccessBackend_SQL::OPimContactAccessBackend_SQL ( const QString& /* appname */, const QString& filename ): OPimContactAccessBackend(), m_changed(false), m_driver( NULL ) { odebug << "C'tor OPimContactAccessBackend_SQL starts" << oendl; QTime t; t.start(); /* Expecting to access the default filename if nothing else is set */ if ( filename.isEmpty() ){ m_fileName = Global::applicationFileName( "addressbook","addressbook.db" ); } else m_fileName = filename; // Get the standart sql-driver from the OSQLManager.. OSQLManager man; m_driver = man.standard(); m_driver->setUrl( m_fileName ); load(); odebug << "C'tor OPimContactAccessBackend_SQL ends: " << t.elapsed() << " ms" << oendl; } OPimContactAccessBackend_SQL::~OPimContactAccessBackend_SQL () { if( m_driver ) delete m_driver; } bool OPimContactAccessBackend_SQL::load () { if (!m_driver->open() ) return false; // Don't expect that the database exists. @@ -412,139 +413,180 @@ void OPimContactAccessBackend_SQL::clear () { ClearQuery cle; OSQLResult res = m_driver->query( &cle ); reload(); } bool OPimContactAccessBackend_SQL::wasChangedExternally() { return false; } QArray<int> OPimContactAccessBackend_SQL::allRecords() const { // FIXME: Think about cute handling of changed tables.. // Thus, we don't have to call update here... if ( m_changed ) ((OPimContactAccessBackend_SQL*)this)->update(); return m_uids; } bool OPimContactAccessBackend_SQL::add ( const OPimContact &newcontact ) { odebug << "add in contact SQL-Backend" << oendl; InsertQuery ins( newcontact ); OSQLResult res = m_driver->query( &ins ); if ( res.state() == OSQLResult::Failure ) return false; int c = m_uids.count(); m_uids.resize( c+1 ); m_uids[c] = newcontact.uid(); return true; } bool OPimContactAccessBackend_SQL::remove ( int uid ) { RemoveQuery rem( uid ); OSQLResult res = m_driver->query(&rem ); if ( res.state() == OSQLResult::Failure ) return false; m_changed = true; return true; } bool OPimContactAccessBackend_SQL::replace ( const OPimContact &contact ) { if ( !remove( contact.uid() ) ) return false; return add( contact ); } OPimContact OPimContactAccessBackend_SQL::find ( int uid ) const { - odebug << "OPimContactAccessBackend_SQL::find()" << oendl; + odebug << "OPimContactAccessBackend_SQL::find(" << uid << ")" << oendl; QTime t; t.start(); OPimContact retContact( requestNonCustom( uid ) ); retContact.setExtraMap( requestCustom( uid ) ); odebug << "OPimContactAccessBackend_SQL::find() needed: " << t.elapsed() << " ms" << oendl; return retContact; } +OPimContact OPimContactAccessBackend_SQL::find( int uid, const QArray<int>& queryUids, uint current, Frontend::CacheDirection direction ) const +{ + odebug << "OPimContactAccessBackend_SQL::find( ..multi.. )" << oendl; + odebug << "searching for " << uid << "" << oendl; + + QTime t; + t.start(); + + uint numReadAhead = readAhead(); + QArray<int> searchList( numReadAhead ); + + uint size =0; + + // Build an array with all elements which should be requested and cached + // We will just request "numReadAhead" elements, starting from "current" position in + // the list of many uids ! + switch( direction ) { + /* forward */ + case Frontend::Forward: + for ( uint i = current; i < queryUids.count() && size < numReadAhead; i++ ) { + searchList[size] = queryUids[i]; + size++; + } + break; + /* reverse */ + case Frontend::Reverse: + for ( uint i = current; i != 0 && size < numReadAhead; i-- ) { + searchList[size] = queryUids[i]; + size++; + } + break; + } + + //Shrink to real size.. + searchList.resize( size ); + + OPimContact retContact( requestContactsAndCache( uid, searchList ) ); + + odebug << "OPimContactAccessBackend_SQL::find( ..multi.. ) needed: " << t.elapsed() << " ms" << oendl; + return retContact; +} QArray<int> OPimContactAccessBackend_SQL::queryByExample ( const OPimContact &query, int settings, const QDateTime& qd ) { QString qu = "SELECT uid FROM addressbook WHERE"; QString searchQuery =""; QDate startDate; if ( qd.isValid() ) startDate = qd.date(); else startDate = QDate::currentDate(); QMap<int, QString> queryFields = query.toMap(); QStringList fieldList = OPimContactFields::untrfields( false ); QMap<QString, int> translate = OPimContactFields::untrFieldsToId(); // Convert every filled field to a SQL-Query // bool isAnyFieldSelected = false; for ( QStringList::Iterator it = ++fieldList.begin(); it != fieldList.end(); ++it ){ int id = translate[*it]; QString queryStr = queryFields[id]; QDate* endDate = 0l; if ( !queryStr.isEmpty() ){ // If something is alredy stored in the query, add an "AND" // to the end of the string to prepare for the next .. if ( !searchQuery.isEmpty() ) searchQuery += " AND"; // isAnyFieldSelected = true; switch( id ){ case Qtopia::Birthday: endDate = new QDate( query.birthday() ); // Fall through ! case Qtopia::Anniversary: if ( endDate == 0l ) endDate = new QDate( query.anniversary() ); if ( settings & OPimContactAccess::DateDiff ) { searchQuery += QString( " (\"%1\" <= '%2-%3-%4\' AND \"%5\" >= '%6-%7-%8')" ) .arg( *it ) .arg( QString::number( endDate->year() ).rightJustify( 4, '0' ) ) .arg( QString::number( endDate->month() ).rightJustify( 2, '0' ) ) .arg( QString::number( endDate->day() ).rightJustify( 2, '0' ) ) .arg( *it ) .arg( QString::number( startDate.year() ).rightJustify( 4, '0' ) ) .arg( QString::number( startDate.month() ).rightJustify( 2, '0' ) ) .arg( QString::number( startDate.day() ).rightJustify( 2, '0' ) ) ; } if ( settings & OPimContactAccess::DateYear ){ if ( settings & OPimContactAccess::DateDiff ) searchQuery += " AND"; searchQuery += QString( " (\"%1\" LIKE '%2-%')" ) .arg( *it ) .arg( QString::number( endDate->year() ).rightJustify( 4, '0' ) ); } if ( settings & OPimContactAccess::DateMonth ){ @@ -707,150 +749,202 @@ QArray<int> OPimContactAccessBackend_SQL::sorted( bool asc, int , int , int ) // odebug << "sorted query is: " << query << "" << oendl; OSQLRawQuery raw( query ); OSQLResult res = m_driver->query( &raw ); if ( res.state() != OSQLResult::Success ){ QArray<int> empty; return empty; } QArray<int> list = extractUids( res ); odebug << "sorted needed " << t.elapsed() << " ms!" << oendl; return list; } void OPimContactAccessBackend_SQL::update() { odebug << "Update starts" << oendl; QTime t; t.start(); // Now load the database set and extract the uid's // which will be held locally LoadQuery lo; OSQLResult res = m_driver->query(&lo); if ( res.state() != OSQLResult::Success ) return; m_uids = extractUids( res ); m_changed = false; odebug << "Update ends " << t.elapsed() << " ms" << oendl; } QArray<int> OPimContactAccessBackend_SQL::extractUids( OSQLResult& res ) const { odebug << "extractUids" << oendl; QTime t; t.start(); OSQLResultItem::ValueList list = res.results(); OSQLResultItem::ValueList::Iterator it; QArray<int> ints(list.count() ); odebug << " count = " << list.count() << "" << oendl; int i = 0; for (it = list.begin(); it != list.end(); ++it ) { ints[i] = (*it).data("uid").toInt(); i++; } odebug << "extractUids ready: count2 = " << i << " needs " << t.elapsed() << " ms" << oendl; return ints; } QMap<int, QString> OPimContactAccessBackend_SQL::requestNonCustom( int uid ) const { QTime t; t.start(); - QMap<int, QString> nonCustomMap; - int t2needed = 0; int t3needed = 0; QTime t2; t2.start(); FindQuery query( uid ); OSQLResult res_noncustom = m_driver->query( &query ); t2needed = t2.elapsed(); OSQLResultItem resItem = res_noncustom.first(); + QMap<int, QString> nonCustomMap; QTime t3; t3.start(); + nonCustomMap = fillNonCustomMap( resItem ); + t3needed = t3.elapsed(); + + + // odebug << "Adding UID: " << resItem.data( "uid" ) << "" << oendl; + odebug << "RequestNonCustom needed: insg.:" << t.elapsed() << " ms, query: " << t2needed + << " ms, mapping: " << t3needed << " ms" << oendl; + + return nonCustomMap; +} + +/* Returns contact requested by uid and fills cache with contacts requested by uids in the cachelist */ +OPimContact OPimContactAccessBackend_SQL::requestContactsAndCache( int uid, const QArray<int>& uidlist )const +{ + // We want to get all contacts with one query. + // We don't have to add the given uid to the uidlist, it is expected to be there already (see opimrecordlist.h). + // All contacts will be stored in the cache, afterwards the contact with the user id "uid" will be returned + // by using the cache.. + QArray<int> cachelist = uidlist; + + odebug << "Reqest and cache" << cachelist.size() << "elements !" << oendl; + + QTime t; + t.start(); + + int t2needed = 0; + int t3needed = 0; + QTime t2; + t2.start(); + FindQuery query( cachelist ); + OSQLResult res_noncustom = m_driver->query( &query ); + t2needed = t2.elapsed(); + + QMap<int, QString> nonCustomMap; + QTime t3; + t3.start(); + OSQLResultItem resItem = res_noncustom.first(); + do { + OPimContact contact( fillNonCustomMap( resItem ) ); + contact.setExtraMap( requestCustom( contact.uid() ) ); + odebug << "Caching uid: " << contact.uid() << oendl; + cache( contact ); + resItem = res_noncustom.next(); + } while ( ! res_noncustom.atEnd() ); //atEnd() is true if we are past(!) the list !! + t3needed = t3.elapsed(); + + + // odebug << "Adding UID: " << resItem.data( "uid" ) << "" << oendl; + odebug << "RequestContactsAndCache needed: insg.:" << t.elapsed() << " ms, query: " << t2needed + << " ms, mapping: " << t3needed << " ms" << oendl; + + return cacheFind( uid ); +} + +QMap<int, QString> OPimContactAccessBackend_SQL::fillNonCustomMap( const OSQLResultItem& resultItem ) const +{ + QMap<int, QString> nonCustomMap; + // Now loop through all columns QStringList fieldList = OPimContactFields::untrfields( false ); QMap<QString, int> translate = OPimContactFields::untrFieldsToId(); for ( QStringList::Iterator it = ++fieldList.begin(); it != fieldList.end(); ++it ){ // Get data for the selected column and store it with the // corresponding id into the map.. int id = translate[*it]; - QString value = resItem.data( (*it) ); + QString value = resultItem.data( (*it) ); // odebug << "Reading " << (*it) << "... found: " << value << "" << oendl; switch( id ){ case Qtopia::Birthday: case Qtopia::Anniversary:{ // Birthday and Anniversary are encoded special ( yyyy-mm-dd ) QStringList list = QStringList::split( '-', value ); QStringList::Iterator lit = list.begin(); int year = (*lit).toInt(); int month = (*(++lit)).toInt(); int day = (*(++lit)).toInt(); if ( ( day != 0 ) && ( month != 0 ) && ( year != 0 ) ){ QDate date( year, month, day ); nonCustomMap.insert( id, OPimDateConversion::dateToString( date ) ); } } break; case Qtopia::AddressCategory: odebug << "Category is: " << value << "" << oendl; default: nonCustomMap.insert( id, value ); } } - // First insert uid - nonCustomMap.insert( Qtopia::AddressUid, resItem.data( "uid" ) ); - t3needed = t3.elapsed(); - - // odebug << "Adding UID: " << resItem.data( "uid" ) << "" << oendl; - odebug << "RequestNonCustom needed: insg.:" << t.elapsed() << " ms, query: " << t2needed - << " ms, mapping: " << t3needed << " ms" << oendl; + nonCustomMap.insert( Qtopia::AddressUid, resultItem.data( "uid" ) ); return nonCustomMap; } + QMap<QString, QString> OPimContactAccessBackend_SQL::requestCustom( int uid ) const { QTime t; t.start(); QMap<QString, QString> customMap; FindCustomQuery query( uid ); OSQLResult res_custom = m_driver->query( &query ); if ( res_custom.state() == OSQLResult::Failure ) { owarn << "OSQLResult::Failure in find query !!" << oendl; QMap<QString, QString> empty; return empty; } OSQLResultItem::ValueList list = res_custom.results(); OSQLResultItem::ValueList::Iterator it = list.begin(); for ( ; it != list.end(); ++it ) { customMap.insert( (*it).data( "type" ), (*it).data( "value" ) ); } odebug << "RequestCustom needed: " << t.elapsed() << " ms" << oendl; return customMap; } } diff --git a/libopie2/opiepim/backend/ocontactaccessbackend_sql.h b/libopie2/opiepim/backend/ocontactaccessbackend_sql.h index ba122ec..4f81735 100644 --- a/libopie2/opiepim/backend/ocontactaccessbackend_sql.h +++ b/libopie2/opiepim/backend/ocontactaccessbackend_sql.h @@ -12,102 +12,103 @@ ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * SQL Backend for the OPIE-Contact Database. */ #ifndef _OPimContactAccessBackend_SQL_ #define _OPimContactAccessBackend_SQL_ #include <opie2/ocontactaccessbackend.h> #include <opie2/ocontactaccess.h> #include <qlist.h> #include <qdict.h> /* aren't in namespace Opie yet - alwin */ namespace Opie { namespace DB { class OSQLDriver; class OSQLResult; class OSQLResultItem; } } namespace Opie { /* the default xml implementation */ /** * This class is the SQL implementation of a Contact backend * it does implement everything available for OPimContact. * @see OPimAccessBackend for more information of available methods */ class OPimContactAccessBackend_SQL : public OPimContactAccessBackend { public: OPimContactAccessBackend_SQL ( const QString& appname, const QString& filename = QString::null ); ~OPimContactAccessBackend_SQL (); bool save(); bool load (); void clear (); bool wasChangedExternally(); QArray<int> allRecords() const; OPimContact find ( int uid ) const; - // FIXME: Add lookahead-cache support ! - //OPimContact find(int uid, const QArray<int>&, uint cur, Frontend::CacheDirection )const; + OPimContact find( int uid, const QArray<int>&, uint cur, Frontend::CacheDirection ) const; QArray<int> queryByExample ( const OPimContact &query, int settings, const QDateTime& d ); QArray<int> matchRegexp( const QRegExp &r ) const; const uint querySettings(); bool hasQuerySettings (uint querySettings) const; // Currently only asc implemented.. QArray<int> sorted( bool asc, int , int , int ); bool add ( const OPimContact &newcontact ); bool replace ( const OPimContact &contact ); bool remove ( int uid ); bool reload(); private: QArray<int> extractUids( Opie::DB::OSQLResult& res ) const; QMap<int, QString> requestNonCustom( int uid ) const; QMap<QString, QString> requestCustom( int uid ) const; + QMap<int, QString> fillNonCustomMap( const Opie::DB::OSQLResultItem& resultItem ) const; + OPimContact requestContactsAndCache( int uid, const QArray<int>& cachelist ) const; void update(); protected: bool m_changed; QString m_fileName; QArray<int> m_uids; Opie::DB::OSQLDriver* m_driver; }; } #endif diff --git a/libopie2/opiepim/backend/opimaccessbackend.h b/libopie2/opiepim/backend/opimaccessbackend.h index 0682063..15a7b7f 100644 --- a/libopie2/opiepim/backend/opimaccessbackend.h +++ b/libopie2/opiepim/backend/opimaccessbackend.h @@ -35,158 +35,178 @@ #include <opie2/opimtemplatebase.h> #include <opie2/opimrecord.h> namespace Opie { class OPimAccessBackendPrivate; /** * OPimAccessBackend is the base class * for all private backends * it operates on OPimRecord as the base class * and it's responsible for fast manipulating * the resource the implementation takes care * of */ template <class T = OPimRecord> class OPimAccessBackend { public: typedef OTemplateBase<T> Frontend; /** The access hint from the frontend */ OPimAccessBackend(int access = 0); virtual ~OPimAccessBackend(); /** * load the resource */ virtual bool load() = 0; /** * reload the resource */ virtual bool reload() = 0; /** * save the resource and * all it's changes */ virtual bool save() = 0; /** * return an array of * all available uids */ virtual QArray<int> allRecords()const = 0; /** * return a List of records * that match the regex */ virtual QArray<int> matchRegexp(const QRegExp &r) const = 0; /** * queryByExample for T with the given Settings * */ virtual QArray<int> queryByExample( const T& t, int settings, const QDateTime& d = QDateTime() ) = 0; /** * find the OPimRecord with uid @param uid * returns T and T.isEmpty() if nothing was found */ virtual T find(int uid )const = 0; virtual T find(int uid, const QArray<int>& items, - uint current, typename Frontend::CacheDirection )const ; + uint current, typename Frontend::CacheDirection ) const; /** * clear the back end */ virtual void clear() = 0; /** * add T */ virtual bool add( const T& t ) = 0; /** * remove */ virtual bool remove( int uid ) = 0; /** * replace a record with T.uid() */ virtual bool replace( const T& t ) = 0; /* * setTheFrontEnd!!! */ void setFrontend( Frontend* front ); /** * set the read ahead count */ void setReadAhead( uint count ); protected: int access()const; + void cache( const T& t )const; + /** + * Returns the element with given uid out of the cache. + * Returns empty element if nothing was found. + * <b>Attention:</b> This just works if we have a frontend which contains the cache ! + */ + T cacheFind( int uid ) const; + /** * use a prime number here! */ void setSaneCacheSize( int ); uint readAhead()const; private: OPimAccessBackendPrivate *d; Frontend* m_front; uint m_read; int m_acc; }; template <class T> OPimAccessBackend<T>::OPimAccessBackend(int acc) : m_acc( acc ) { m_front = 0l; } template <class T> OPimAccessBackend<T>::~OPimAccessBackend() { } template <class T> void OPimAccessBackend<T>::setFrontend( Frontend* fr ) { m_front = fr; } template <class T> void OPimAccessBackend<T>::cache( const T& t )const { - if (m_front ) + if ( m_front ) m_front->cache( t ); } + +template <class T> +T OPimAccessBackend<T>::cacheFind( int uid )const { + if ( ! m_front ){ + qWarning ( "No frontend assigned ! Therefore we cannot access the cache to return the right element!" ); + return T(); + } + + return m_front->cacheFind( uid ); +} + template <class T> void OPimAccessBackend<T>::setSaneCacheSize( int size) { - if (m_front ) + if ( m_front ) m_front->setSaneCacheSize( size ); } template <class T> T OPimAccessBackend<T>::find( int uid, const QArray<int>&, - uint, typename Frontend::CacheDirection )const { + uint, typename Frontend::CacheDirection ) const{ + qDebug( "*** Lookahead feature not supported. Fallback to default find!" ); return find( uid ); } template <class T> void OPimAccessBackend<T>::setReadAhead( uint count ) { m_read = count; } template <class T> uint OPimAccessBackend<T>::readAhead()const { return m_read; } template <class T> int OPimAccessBackend<T>::access()const { return m_acc; } } #endif diff --git a/libopie2/opiepim/core/opimaccesstemplate.h b/libopie2/opiepim/core/opimaccesstemplate.h index 55d600a..6f01b46 100644 --- a/libopie2/opiepim/core/opimaccesstemplate.h +++ b/libopie2/opiepim/core/opimaccesstemplate.h @@ -1,360 +1,380 @@ /* This file is part of the Opie Project Copyright (C) Holger Freyther <zecke@handhelds.org> Copyright (C) Stefan Eilers <eilers.stefan@epost.de> =. Copyright (C) The Opie Team <opie-devel@handhelds.org> .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef OPIE_PIM_ACCESS_TEMPLATE_H #define OPIE_PIM_ACCESS_TEMPLATE_H /* OPIE */ #include <opie2/opimrecord.h> #include <opie2/opimaccessbackend.h> #include <opie2/opimrecordlist.h> -#include <opie2/opimcache.h> #include <opie2/opimtemplatebase.h> #include <opie2/odebug.h> /* QT */ #include <qarray.h> namespace Opie { class OPimAccessTemplatePrivate; /** * Thats the frontend to our OPIE PIM * Library. Either you want to use it's * interface or you want to implement * your own Access lib * Just create a OPimRecord and inherit from * the templates */ template <class T = OPimRecord > class OPimAccessTemplate : public OTemplateBase<T> { public: enum Access { Random = 0, SortedAccess }; typedef OPimRecordList<T> List; typedef OPimAccessBackend<T> BackEnd; typedef OPimCache<T> Cache; /** * c'tor BackEnd * enum Access a small hint on how to handle the backend */ OPimAccessTemplate( BackEnd* end); virtual ~OPimAccessTemplate(); /** * load from the backend */ bool load(); /** Reload database. * You should execute this function if the external database * was changed. * This function will load the external database and afterwards * rejoin the local changes. Therefore the local database will be set consistent. */ virtual bool reload(); /** Save contacts database. * Save is more a "commit". After calling this function, all changes are public available. * @return true if successful */ bool save(); /** * if the resource was changed externally * You should use the signal handling instead of polling possible changes ! * zecke: Do you implement a signal for otodoaccess ? */ bool wasChangedExternally()const; /** * return a List of records * you can iterate over them */ virtual List allRecords()const; /** * return a List of records * that match the regex */ virtual List matchRegexp( const QRegExp &r ) const; /** * queryByExample. * @see otodoaccess, ocontactaccess */ virtual List queryByExample( const T& t, int querySettings, const QDateTime& d = QDateTime() ); /** * find the OPimRecord uid */ virtual T find( int uid )const; /** * read ahead cache find method ;) */ virtual T find( int uid, const QArray<int>&, uint current, typename OTemplateBase<T>::CacheDirection dir = OTemplateBase<T>::Forward )const; + /* invalidate cache here */ /** * clears the backend and invalidates the backend */ void clear() ; /** * add T to the backend * @param t The item to add. * @return <i>true</i> if added successfully. */ - virtual bool add( const T& t ) ; + virtual bool add( const T& t ) ; + bool add( const OPimRecord& ); - // Needed for real generic access (eilers) - // Info: Take this if you are working with OPimRecord, which is a generic base class, and - // you need to add it into any database, you cannot generate a reference to - // it and casting may be not approriate, too. - // But take care that the accessing database is compatible to the real type of OPimRecord !! + /** + * Add an Opie PimRecord. + * Info: Take this if you are working with OPimRecords and you need to add it into any database. + * But take care that the accessing database is compatible to the real type of OPimRecord !! + * Otherwise this access will be rejected ! + */ bool add( const OPimRecord* ); /* only the uid matters */ /** * remove T from the backend * @param t The item to remove * @return <i>true</i> if successful. */ virtual bool remove( const T& t ); /** * remove the OPimRecord with uid * @param uid The ID of the item to remove * @return <i>true</i> if successful. */ bool remove( int uid ); bool remove( const OPimRecord& ); /** * replace T from backend * @param t The item to replace * @return <i>true</i> if successful. */ virtual bool replace( const T& t) ; void setReadAhead( uint count ); /** * @internal */ + virtual T cacheFind( int uid )const; void cache( const T& )const; void setSaneCacheSize( int ); QArray<int> records()const; protected: /** * invalidate the cache */ void invalidateCache(); void setBackEnd( BackEnd* end ); /** * returns the backend */ BackEnd* backEnd(); BackEnd* m_backEnd; + Cache m_cache; private: OPimAccessTemplatePrivate *d; }; template <class T> OPimAccessTemplate<T>::OPimAccessTemplate( BackEnd* end ) : OTemplateBase<T>(), m_backEnd( end ) { if (end ) end->setFrontend( this ); } template <class T> OPimAccessTemplate<T>::~OPimAccessTemplate() { owarn << "~OPimAccessTemplate<T>" << oendl; delete m_backEnd; } template <class T> bool OPimAccessTemplate<T>::load() { invalidateCache(); return m_backEnd->load(); } template <class T> bool OPimAccessTemplate<T>::reload() { - invalidateCache(); // zecke: I think this should be added (se) + invalidateCache(); return m_backEnd->reload(); } template <class T> bool OPimAccessTemplate<T>::save() { return m_backEnd->save(); } template <class T> typename OPimAccessTemplate<T>::List OPimAccessTemplate<T>::allRecords()const { QArray<int> ints = m_backEnd->allRecords(); List lis(ints, this ); return lis; } template <class T> typename OPimAccessTemplate<T>::List OPimAccessTemplate<T>::matchRegexp( const QRegExp &r )const { QArray<int> ints = m_backEnd->matchRegexp( r ); List lis(ints, this ); return lis; } template <class T> QArray<int> OPimAccessTemplate<T>::records()const { return m_backEnd->allRecords(); } template <class T> typename OPimAccessTemplate<T>::List OPimAccessTemplate<T>::queryByExample( const T& t, int settings, const QDateTime& d ) { QArray<int> ints = m_backEnd->queryByExample( t, settings, d ); List lis(ints, this ); return lis; } template <class T> T OPimAccessTemplate<T>::find( int uid ) const{ + // First search in cache.. + if ( m_cache.contains( uid ) ) + return m_cache.find( uid ); + T t = m_backEnd->find( uid ); cache( t ); + return t; } + +template <class T> +T OPimAccessTemplate<T>::cacheFind( int uid ) const +{ + return m_cache.find( uid ); +} + template <class T> T OPimAccessTemplate<T>::find( int uid, const QArray<int>& ar, uint current, typename OTemplateBase<T>::CacheDirection dir )const { /* * better do T.isEmpty() * after a find this way we would * avoid two finds in QCache... */ // owarn << "find it now " << uid << oendl; - if (m_cache.contains( uid ) ) { + if ( m_cache.contains( uid ) ) { return m_cache.find( uid ); } T t = m_backEnd->find( uid, ar, current, dir ); cache( t ); return t; } template <class T> void OPimAccessTemplate<T>::clear() { invalidateCache(); m_backEnd->clear(); } template <class T> bool OPimAccessTemplate<T>::add( const T& t ) { cache( t ); return m_backEnd->add( t ); } template <class T> -bool OPimAccessTemplate<T>::add( const OPimRecord& rec) { +bool OPimAccessTemplate<T>::add( const OPimRecord& rec ) { /* same type */ T tempInstance; if ( rec.rtti() == tempInstance.rtti() ) { const T& t = static_cast<const T&>(rec); return add(t); + } else { + owarn << "Adding not possible: Objecttype mismatch" << oendl; } return false; } template <class T> bool OPimAccessTemplate<T>::add( const OPimRecord* rec) { /* same type, but pointer */ T tempInstance; if ( rec -> rtti() == tempInstance.rtti() ) { const T* t = static_cast<const T*>(rec); return add( *t ); + } else { + owarn << "Adding not possible: Objecttype mismatch" << oendl; } return false; } template <class T> bool OPimAccessTemplate<T>::remove( const T& t ) { return remove( t.uid() ); } template <class T> bool OPimAccessTemplate<T>::remove( int uid ) { m_cache.remove( uid ); return m_backEnd->remove( uid ); } template <class T> bool OPimAccessTemplate<T>::remove( const OPimRecord& rec) { return remove( rec.uid() ); } template <class T> bool OPimAccessTemplate<T>::replace( const T& t ) { m_cache.replace( t ); return m_backEnd->replace( t ); } template <class T> void OPimAccessTemplate<T>::invalidateCache() { m_cache.invalidate(); } template <class T> typename OPimAccessTemplate<T>::BackEnd* OPimAccessTemplate<T>::backEnd() { return m_backEnd; } template <class T> bool OPimAccessTemplate<T>::wasChangedExternally()const { return false; } template <class T> void OPimAccessTemplate<T>::setBackEnd( BackEnd* end ) { m_backEnd = end; if (m_backEnd ) m_backEnd->setFrontend( this ); } template <class T> void OPimAccessTemplate<T>::cache( const T& t ) const{ /* hacky we need to work around the const*/ ((OPimAccessTemplate<T>*)this)->m_cache.add( t ); } template <class T> void OPimAccessTemplate<T>::setSaneCacheSize( int size ) { m_cache.setSize( size ); } template <class T> void OPimAccessTemplate<T>::setReadAhead( uint count ) { m_backEnd->setReadAhead( count ); } } #endif diff --git a/libopie2/opiepim/core/opimtemplatebase.h b/libopie2/opiepim/core/opimtemplatebase.h index b48dfed..ec9a94e 100644 --- a/libopie2/opiepim/core/opimtemplatebase.h +++ b/libopie2/opiepim/core/opimtemplatebase.h @@ -1,122 +1,136 @@ /* This file is part of the Opie Project Copyright (C) Holger Freyther <zecke@handhelds.org> =. Copyright (C) The Opie Team <opie-devel@handhelds.org> .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program is distributed in the hope that + . -:. = it will be useful, but WITHOUT ANY WARRANTY; : .. .:, . . . without even the implied warranty of =_ + =;=|` MERCHANTABILITY or FITNESS FOR A _.=:. : :=>`: PARTICULAR PURPOSE. See the GNU ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef OTEMPLATEBASE_H #define OTEMPLATEBASE_H /* OPIE */ #include <opie2/opimrecord.h> +#include <opie2/opimcache.h> /* QT */ #include <qarray.h> namespace Opie { /** * Templates do not have a base class, This is why * we've this class * this is here to give us the possibility * to have a common base class * You may not want to use that interface internaly * POOR mans interface */ class OPimBasePrivate; struct OPimBase { /** * return the rtti */ virtual int rtti() const = 0; virtual OPimRecord* record()const = 0; virtual OPimRecord* record(int uid)const = 0; virtual bool add( const OPimRecord& ) = 0; virtual bool add( const OPimRecord* ) = 0; virtual bool remove( int uid ) = 0; virtual bool remove( const OPimRecord& ) = 0; virtual void clear() = 0; virtual bool load() = 0; virtual bool save() = 0; virtual QArray<int> records()const = 0; /* * ADD editing here? * -zecke */ private: OPimBasePrivate* d; }; /** * internal template base - * T needs to implement the copy c'tor!!! + * Attention: T needs to implement the copy c'tor!!! */ class OTemplateBasePrivate; template <class T = OPimRecord> class OTemplateBase : public OPimBase { public: + /** Look ahead direction of cache */ enum CacheDirection { Forward=0, Reverse }; + OTemplateBase() { }; virtual ~OTemplateBase() { } virtual T find( int uid )const = 0; /** * read ahead find */ virtual T find( int uid, const QArray<int>& items, uint current, CacheDirection dir = Forward )const = 0; + + /** + * Find in Cache.. + * Returns empty object if nothing found. + */ + virtual T cacheFind( int uid )const = 0; + + /** + * Put element into Cache + */ virtual void cache( const T& )const = 0; virtual void setSaneCacheSize( int ) = 0; OPimRecord* record()const; OPimRecord* record(int uid )const; static T* rec(); + private: OTemplateBasePrivate *d; }; template <class T> OPimRecord* OTemplateBase<T>::record()const { T* t = new T; return t; } template <class T> OPimRecord* OTemplateBase<T>::record(int uid )const { T t2 = find(uid ); T* t1 = new T(t2); return t1; }; template <class T> T* OTemplateBase<T>::rec() { return new T; } } #endif |