2016-12-12 22:33:33 +00:00
# include "notecollection.h"
using namespace jop ;
NoteCollection : : NoteCollection ( ) { }
2016-12-14 21:50:26 +00:00
NoteCollection : : NoteCollection ( Database & db , int parentId , const QString & orderBy ) {
2016-12-12 22:33:33 +00:00
db_ = db ;
parentId_ = parentId ;
orderBy_ = orderBy ;
}
2016-12-14 21:50:26 +00:00
Note NoteCollection : : at ( int index ) const {
2016-12-12 22:33:33 +00:00
if ( ! parentId_ ) return Note ( ) ;
2016-12-14 21:50:26 +00:00
if ( cache_ . isset ( index ) ) return cache_ . get ( index ) ;
2016-12-12 22:33:33 +00:00
2016-12-14 21:50:26 +00:00
std : : vector < int > indexes = cache_ . availableBufferAround ( index , 32 ) ;
if ( ! indexes . size ( ) ) {
qWarning ( ) < < " Couldn't acquire buffer " ; // "Cannot happen"
return Note ( ) ;
2016-12-12 22:33:33 +00:00
}
2016-12-14 21:50:26 +00:00
int from = indexes [ 0 ] ;
int to = indexes [ indexes . size ( ) - 1 ] ;
2016-12-12 22:33:33 +00:00
2016-12-14 21:50:26 +00:00
qDebug ( ) < < " Getting from " < < from < < " to " < < to ;
2016-12-12 22:33:33 +00:00
2016-12-14 21:50:26 +00:00
QSqlQuery q = db_ . query ( " SELECT id, title, body FROM notes WHERE parent_id = :parent_id ORDER BY " + orderBy_ + " LIMIT " + QString : : number ( to - from + 1 ) + " OFFSET " + QString : : number ( from ) ) ;
2016-12-12 22:33:33 +00:00
q . bindValue ( " :parent_id " , parentId_ ) ;
q . exec ( ) ;
int noteIndex = from ;
while ( q . next ( ) ) {
2016-12-14 21:50:26 +00:00
Note note ;
note . setId ( q . value ( 0 ) . toInt ( ) ) ;
note . setTitle ( q . value ( 1 ) . toString ( ) ) ;
note . setBody ( q . value ( 2 ) . toString ( ) ) ;
note . setIsPartial ( true ) ;
2016-12-12 22:33:33 +00:00
2016-12-14 21:50:26 +00:00
cache_ . set ( noteIndex , note ) ;
2016-12-12 22:33:33 +00:00
noteIndex + + ;
}
2016-12-14 21:50:26 +00:00
return cache_ . get ( index ) ;
2016-12-12 22:33:33 +00:00
}
// TODO: cache result
int NoteCollection : : count ( ) const {
if ( ! parentId_ ) return 0 ;
QSqlQuery q = db_ . query ( " SELECT count(*) as row_count FROM notes WHERE parent_id = :parent_id " ) ;
q . bindValue ( " :parent_id " , parentId_ ) ;
q . exec ( ) ;
q . next ( ) ;
return q . value ( 0 ) . toInt ( ) ;
}
2016-12-14 21:50:26 +00:00
Note NoteCollection : : byId ( int id ) const {
std : : vector < int > indexes = cache_ . indexes ( ) ;
for ( int i = 0 ; i < indexes . size ( ) ; i + + ) {
Note note = cache_ . get ( indexes [ i ] ) ;
if ( note . id ( ) = = id ) return note ;
}
QSqlQuery q = db_ . query ( " SELECT id, title, body FROM notes WHERE id = :id " ) ;
q . bindValue ( " :id " , id ) ;
q . exec ( ) ;
q . next ( ) ;
if ( ! q . isValid ( ) ) {
qWarning ( ) < < " Invalid note ID: " < < id ;
return Note ( ) ;
}
// TODO: refactor creation of note from SQL query object
Note note ;
note . setId ( q . value ( 0 ) . toInt ( ) ) ;
note . setTitle ( q . value ( 1 ) . toString ( ) ) ;
note . setBody ( q . value ( 2 ) . toString ( ) ) ;
return note ;
}