From 76418628f14ff555242d7819e6cbcc6191c44360 Mon Sep 17 00:00:00 2001 From: Mark Brand Date: Thu, 9 Feb 2012 15:33:43 +0100 Subject: [PATCH] QSqlTableModel: deduplicate and optimize counting of inserts Reading STL iteration code is painful enough if you only have to do it once. Thiago suggested remembering the end iterator for performance. Change-Id: Ic2cdc480f591932ea420e692a4d2796d49f05313 Reviewed-by: Yunqiao Yin --- src/sql/models/qsqltablemodel.cpp | 31 +++++++++++++++++-------------- src/sql/models/qsqltablemodel_p.h | 1 + 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/sql/models/qsqltablemodel.cpp b/src/sql/models/qsqltablemodel.cpp index ab87397..51c7170 100644 --- a/src/sql/models/qsqltablemodel.cpp +++ b/src/sql/models/qsqltablemodel.cpp @@ -79,6 +79,21 @@ QString QSqlTableModelPrivate::strippedFieldName(const QString &name) const return fieldname; } +int QSqlTableModelPrivate::insertCount(int maxRow) const +{ + int cnt = 0; + CacheMap::ConstIterator i = cache.constBegin(); + const CacheMap::ConstIterator e = cache.constEnd(); + for (; + i != e && (maxRow < 0 || i.key() <= maxRow); + ++i) { + if (i.value().op() == Insert) + ++cnt; + } + + return cnt; +} + void QSqlTableModelPrivate::initRecordAndPrimaryIndex() { rec = db.record(tableName); @@ -1091,13 +1106,7 @@ int QSqlTableModel::rowCount(const QModelIndex &parent) const if (parent.isValid()) return 0; - int rc = QSqlQueryModel::rowCount(); - for (QSqlTableModelPrivate::CacheMap::ConstIterator it = d->cache.constBegin(); - it != d->cache.constEnd(); ++it) { - if (it.value().op() == QSqlTableModelPrivate::Insert) - ++rc; - } - return rc; + return QSqlQueryModel::rowCount() + d->insertCount(); } /*! @@ -1115,13 +1124,7 @@ int QSqlTableModel::rowCount(const QModelIndex &parent) const QModelIndex QSqlTableModel::indexInQuery(const QModelIndex &item) const { Q_D(const QSqlTableModel); - int rowOffset = 0; - QSqlTableModelPrivate::CacheMap::ConstIterator i = d->cache.constBegin(); - while (i != d->cache.constEnd() && i.key() <= item.row()) { - if (i.value().op() == QSqlTableModelPrivate::Insert) - ++rowOffset; - ++i; - } + const int rowOffset = d->insertCount(item.row()); return QSqlQueryModel::indexInQuery(createIndex(item.row() - rowOffset, item.column(), item.internalPointer())); } diff --git a/src/sql/models/qsqltablemodel_p.h b/src/sql/models/qsqltablemodel_p.h index 8649a91..c2e4442 100644 --- a/src/sql/models/qsqltablemodel_p.h +++ b/src/sql/models/qsqltablemodel_p.h @@ -79,6 +79,7 @@ public: virtual void revertCachedRow(int row); virtual int nameToIndex(const QString &name) const; QString strippedFieldName(const QString &name) const; + int insertCount(int maxRow = -1) const; void initRecordAndPrimaryIndex(); QSqlDatabase db; -- 2.7.4