QxOrm  1.2.4
C++ Object Relational Mapping library
QxSqlRelation_ManyToMany.h
Go to the documentation of this file.
00001 /****************************************************************************
00002 **
00003 ** http://www.qxorm.com/
00004 ** http://sourceforge.net/projects/qxorm/
00005 ** Original file by Lionel Marty
00006 **
00007 ** This file is part of the QxOrm library
00008 **
00009 ** This software is provided 'as-is', without any express or implied
00010 ** warranty. In no event will the authors be held liable for any
00011 ** damages arising from the use of this software.
00012 **
00013 ** GNU Lesser General Public License Usage
00014 ** This file must be used under the terms of the GNU Lesser
00015 ** General Public License version 2.1 as published by the Free Software
00016 ** Foundation and appearing in the file 'license.lgpl.txt' included in the
00017 ** packaging of this file.  Please review the following information to
00018 ** ensure the GNU Lesser General Public License version 2.1 requirements
00019 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
00020 **
00021 ** If you have questions regarding the use of this file, please contact :
00022 ** contact@qxorm.com
00023 **
00024 ****************************************************************************/
00025 
00026 #ifndef _QX_SQL_RELATION_MANY_TO_MANY_H_
00027 #define _QX_SQL_RELATION_MANY_TO_MANY_H_
00028 
00029 #ifdef _MSC_VER
00030 #pragma once
00031 #endif
00032 
00040 #include <QxDao/QxSqlRelation.h>
00041 
00042 namespace qx {
00043 
00048 template <class DataType, class Owner>
00049 class QxSqlRelation_ManyToMany : public QxSqlRelation<DataType, Owner>
00050 {
00051 
00052 private:
00053 
00054    typedef typename QxSqlRelation<DataType, Owner>::type_owner type_owner;
00055    typedef typename QxSqlRelation<DataType, Owner>::type_data type_data;
00056    typedef typename QxSqlRelation<DataType, Owner>::type_container type_container;
00057    typedef typename QxSqlRelation<DataType, Owner>::type_generic_container type_generic_container;
00058    typedef typename QxSqlRelation<DataType, Owner>::type_item type_item;
00059    typedef typename type_generic_container::type_iterator type_iterator;
00060 
00061    enum { is_data_container = QxSqlRelation<DataType, Owner>::is_data_container };
00062 
00063 protected:
00064 
00065    QString m_sExtraTable;           
00066    QString m_sForeignKeyOwner;      
00067    QString m_sForeignKeyDataType;   
00068 
00069 public:
00070 
00071    QxSqlRelation_ManyToMany(IxDataMember * p, const QString & sExtraTable, const QString & sForeignKeyOwner, const QString & sForeignKeyDataType) : QxSqlRelation<DataType, Owner>(p), m_sExtraTable(sExtraTable), m_sForeignKeyOwner(sForeignKeyOwner), m_sForeignKeyDataType(sForeignKeyDataType) { this->m_eRelationType = qx::IxSqlRelation::many_to_many; this->verifyParameters(); }
00072    virtual ~QxSqlRelation_ManyToMany() { BOOST_STATIC_ASSERT(is_data_container); }
00073 
00074    virtual QString getDescription() const                                     { return "relation many-to-many"; }
00075    virtual QString getExtraTable() const                                      { return m_sExtraTable; }
00076    virtual bool getCartesianProduct() const                                   { return true; }
00077    virtual void createTable(QxSqlRelationParams & params) const               { Q_UNUSED(params); }
00078    virtual void lazySelect(QxSqlRelationParams & params) const                { Q_UNUSED(params); }
00079    virtual void lazyFrom(QxSqlRelationParams & params) const                  { Q_UNUSED(params); }
00080    virtual void eagerFrom(QxSqlRelationParams & params) const                 { Q_UNUSED(params); }
00081    virtual void lazyJoin(QxSqlRelationParams & params) const                  { Q_UNUSED(params); }
00082    virtual void lazyWhere(QxSqlRelationParams & params) const                 { Q_UNUSED(params); }
00083    virtual void eagerWhere(QxSqlRelationParams & params) const                { Q_UNUSED(params); }
00084    virtual void lazyWhereSoftDelete(QxSqlRelationParams & params) const       { Q_UNUSED(params); }
00085    virtual void lazyFetch_ResolveInput(QxSqlRelationParams & params) const    { Q_UNUSED(params); }
00086    virtual void eagerFetch_ResolveInput(QxSqlRelationParams & params) const   { Q_UNUSED(params); }
00087    virtual void lazyFetch_ResolveOutput(QxSqlRelationParams & params) const   { Q_UNUSED(params); }
00088    virtual void lazyInsert(QxSqlRelationParams & params) const                { Q_UNUSED(params); }
00089    virtual void lazyInsert_Values(QxSqlRelationParams & params) const         { Q_UNUSED(params); }
00090    virtual void lazyUpdate(QxSqlRelationParams & params) const                { Q_UNUSED(params); }
00091    virtual void lazyInsert_ResolveInput(QxSqlRelationParams & params) const   { Q_UNUSED(params); }
00092    virtual void lazyUpdate_ResolveInput(QxSqlRelationParams & params) const   { Q_UNUSED(params); }
00093    virtual QSqlError onBeforeSave(QxSqlRelationParams & params) const         { Q_UNUSED(params); return QSqlError(); }
00094 
00095    virtual QVariant getIdFromQuery(bool bEager, QxSqlRelationParams & params) const
00096    {
00097       QString sId; IxDataMember * pId = this->getDataId(); if (! bEager || ! pId) { return QVariant(); }
00098       for (int i = 0; i < pId->getNameCount(); i++) { sId += params.query().value(params.offset() + i).toString() + "|"; }
00099       return QVariant(sId);
00100    }
00101 
00102    virtual void updateOffset(bool bEager, QxSqlRelationParams & params) const
00103    {
00104       if (! bEager) { return; }
00105       long lOffsetNew = params.offset() + this->getDataCount();
00106       lOffsetNew += (this->getDataId() ? this->getDataId()->getNameCount() : 0);
00107       lOffsetNew += (this->m_oSoftDelete.isEmpty() ? 0 : 1);
00108       params.setOffset(lOffsetNew);
00109    }
00110 
00111    virtual void eagerSelect(QxSqlRelationParams & params) const
00112    {
00113       long l1(0);
00114       QString & sql = params.sql();
00115       IxDataMember * p = NULL; IxDataMember * pId = this->getDataId(); qAssert(pId);
00116       QString tableAlias = this->tableAlias(params);
00117       if (pId) { sql += (pId->getSqlTablePointNameAsAlias(tableAlias) + ", "); }
00118       while ((p = this->nextData(l1))) { sql += (p->getSqlTablePointNameAsAlias(tableAlias) + ", "); }
00119       if (! this->m_oSoftDelete.isEmpty()) { sql += (this->m_oSoftDelete.buildSqlTablePointName(tableAlias) + ", "); }
00120    }
00121 
00122    virtual void eagerJoin(QxSqlRelationParams & params) const
00123    {
00124       QString & sql = params.sql();
00125       IxDataMember * pIdOwner = this->getDataIdOwner(); qAssert(pIdOwner);
00126       IxDataMember * pIdData = this->getDataId(); qAssert(pIdData);
00127       QString table = this->table(); QString tableAlias = this->tableAlias(params);
00128       QString tableOwner = this->tableAliasOwner(params);
00129       if (! pIdOwner || ! pIdData) { return; }
00130       QStringList lstForeignKeyOwner = m_sForeignKeyOwner.split("|");
00131       QStringList lstForeignKeyDataType = m_sForeignKeyDataType.split("|");
00132       qAssert(pIdOwner->getNameCount() == lstForeignKeyOwner.count());
00133       qAssert(pIdData->getNameCount() == lstForeignKeyDataType.count());
00134       QString sExtraTableAlias = m_sExtraTable + "_" + QString::number(params.index());
00135       sql += this->getSqlJoin(params.joinType()) + m_sExtraTable + " " + sExtraTableAlias + " ON ";
00136       for (int i = 0; i < pIdOwner->getNameCount(); i++)
00137       { sql += pIdOwner->getSqlAlias(tableOwner, true, i) + " = " + sExtraTableAlias + "." + lstForeignKeyOwner.at(i) + " AND "; }
00138       sql = sql.left(sql.count() - 5); // Remove last " AND "
00139       sql += this->getSqlJoin(params.joinType()) + table + " " + tableAlias + " ON ";
00140       params.builder().addSqlQueryAlias(table, tableAlias);
00141       for (int i = 0; i < pIdData->getNameCount(); i++)
00142       { sql += sExtraTableAlias + "." + lstForeignKeyDataType.at(i) + " = " + pIdData->getSqlAlias(tableAlias, true, i) + " AND "; }
00143       sql = sql.left(sql.count() - 5); // Remove last " AND "
00144    }
00145 
00146    virtual void eagerWhereSoftDelete(QxSqlRelationParams & params) const
00147    {
00148       if (this->m_oSoftDelete.isEmpty()) { return; }
00149       QString & sql = params.sql();
00150       QString tableAlias = this->tableAlias(params);
00151       sql += qx::IxSqlQueryBuilder::addSqlCondition(sql);
00152       sql += this->m_oSoftDelete.buildSqlQueryToFetch(tableAlias);
00153    }
00154 
00155    virtual void * eagerFetch_ResolveOutput(QxSqlRelationParams & params) const
00156    {
00157       if (! this->verifyOffset(params, true)) { return NULL; }
00158       QSqlQuery & query = params.query();
00159       IxDataMember * p = NULL; IxDataMember * pId = this->getDataId(); qAssert(pId);
00160       long lIndex = 0; long lOffsetId = (pId ? pId->getNameCount() : 0); bool bValidId(false);
00161       long lOffsetOld = params.offset(); this->updateOffset(true, params);
00162       for (int i = 0; i < pId->getNameCount(); i++)
00163       { QVariant v = query.value(lOffsetOld + i); bValidId = (bValidId || qx::trait::is_valid_primary_key(v)); }
00164       if (! bValidId) { return NULL; }
00165       type_item item = this->createItem();
00166       type_data & item_val = item.value_qx();
00167       for (int i = 0; i < pId->getNameCount(); i++)
00168       { QVariant v = query.value(lOffsetOld + i); qx::cvt::from_variant(v, item.key(), "", i); }
00169       for (int i = 0; i < pId->getNameCount(); i++)
00170       { QVariant v = query.value(lOffsetOld + i); pId->fromVariant((& item_val), v, "", i); }
00171       while ((p = this->nextData(lIndex)))
00172       { p->fromVariant((& item_val), query.value(lIndex + lOffsetOld + lOffsetId - 1)); }
00173       type_generic_container::insertItem(this->getContainer(params), item);
00174       return (& item_val);
00175    }
00176 
00177    virtual QSqlError onAfterSave(QxSqlRelationParams & params) const
00178    {
00179       if (this->isNullData(params)) { return this->deleteFromExtraTable(params); }
00180       QSqlError daoError = qx::dao::save(this->getContainer(params), (& params.database()));
00181       if (daoError.isValid()) { return daoError; }
00182       daoError = this->deleteFromExtraTable(params);
00183       if (daoError.isValid()) { return daoError; }
00184       daoError = this->insertIntoExtraTable(params);
00185       if (daoError.isValid()) { return daoError; }
00186       return QSqlError();
00187    }
00188 
00189    virtual QString createExtraTable() const
00190    {
00191       IxDataMember * pIdOwner = this->getDataIdOwner(); qAssert(pIdOwner);
00192       IxDataMember * pIdData = this->getDataId(); qAssert(pIdData);
00193       if (! pIdOwner || ! pIdData) { return ""; }
00194 
00195       bool bOldPKOwner = pIdOwner->getIsPrimaryKey(); pIdOwner->setIsPrimaryKey(false);
00196       bool bOldPKData = ((pIdOwner == pIdData) ? bOldPKOwner : pIdData->getIsPrimaryKey()); pIdData->setIsPrimaryKey(false);
00197       bool bOldAIOwner = pIdOwner->getAutoIncrement(); pIdOwner->setAutoIncrement(false);
00198       bool bOldAIData = ((pIdOwner == pIdData) ? bOldAIOwner : pIdData->getAutoIncrement()); pIdData->setAutoIncrement(false);
00199 
00200       QString sql = "CREATE TABLE IF NOT EXISTS " + m_sExtraTable + " (";
00201       sql += pIdOwner->getSqlNameAndTypeAndParams(", ", m_sForeignKeyOwner) + ", "; qAssert(! pIdOwner->getSqlType().isEmpty());
00202       sql += pIdData->getSqlNameAndTypeAndParams(", ", m_sForeignKeyDataType) + ", "; qAssert(! pIdData->getSqlType().isEmpty());
00203       sql = sql.left(sql.count() - 2); // Remove last ", "
00204       sql += ")";
00205 
00206       pIdOwner->setIsPrimaryKey(bOldPKOwner); pIdData->setIsPrimaryKey(bOldPKData);
00207       pIdOwner->setAutoIncrement(bOldAIOwner); pIdData->setAutoIncrement(bOldAIData);
00208       if (this->traceSqlQuery()) { qDebug("[QxOrm] create extra-table (relation many-to-many) : %s", qPrintable(sql)); }
00209       return sql;
00210    }
00211 
00212 private:
00213 
00214    inline void verifyParameters()
00215    { qAssert(! m_sExtraTable.isEmpty() && ! m_sForeignKeyOwner.isEmpty() && ! m_sForeignKeyDataType.isEmpty() && (m_sForeignKeyOwner != m_sForeignKeyDataType)); }
00216 
00217    QSqlError deleteFromExtraTable(QxSqlRelationParams & params) const
00218    {
00219       IxDataMember * pIdOwner = this->getDataIdOwner(); qAssert(pIdOwner);
00220       QString sql = "DELETE FROM " + m_sExtraTable + " WHERE ";
00221       QStringList lstForeignKeyOwner = m_sForeignKeyOwner.split("|");
00222       qAssert(pIdOwner->getNameCount() == lstForeignKeyOwner.count());
00223       for (int i = 0; i < pIdOwner->getNameCount(); i++)
00224       { sql += m_sExtraTable + "." + lstForeignKeyOwner.at(i) + " = " + pIdOwner->getSqlPlaceHolder("", i) + " AND "; }
00225       sql = sql.left(sql.count() - 5); // Remove last " AND "
00226       if (this->traceSqlQuery()) { qDebug("[QxOrm] sql query (extra-table) : %s", qPrintable(sql)); }
00227 
00228       QSqlQuery queryDelete(params.database());
00229       queryDelete.prepare(sql);
00230       pIdOwner->setSqlPlaceHolder(queryDelete, params.owner());
00231       if (! queryDelete.exec()) { return queryDelete.lastError(); }
00232       return QSqlError();
00233    }
00234 
00235    QSqlError insertIntoExtraTable(QxSqlRelationParams & params) const
00236    {
00237       IxDataMember * pIdOwner = this->getDataIdOwner(); qAssert(pIdOwner);
00238       IxDataMember * pIdData = this->getDataId(); qAssert(pIdData);
00239       if (! pIdOwner || ! pIdData) { return QSqlError(); }
00240       QStringList lstForeignKeyOwner = m_sForeignKeyOwner.split("|");
00241       QStringList lstForeignKeyDataType = m_sForeignKeyDataType.split("|");
00242       qAssert(pIdOwner->getNameCount() == lstForeignKeyOwner.count());
00243       qAssert(pIdData->getNameCount() == lstForeignKeyDataType.count());
00244 
00245       QString sql = "INSERT INTO " + m_sExtraTable + " (";
00246       sql += pIdOwner->getSqlName(", ", m_sForeignKeyOwner) + ", " + pIdData->getSqlName(", ", m_sForeignKeyDataType);
00247       sql += ") VALUES (";
00248       sql += pIdOwner->getSqlPlaceHolder("", -1, ", ", m_sForeignKeyOwner) + ", " + pIdData->getSqlPlaceHolder("", -1, ", ", m_sForeignKeyDataType) + ")";
00249       if (this->traceSqlQuery()) { qDebug("[QxOrm] sql query (extra-table) : %s", qPrintable(sql)); }
00250 
00251       type_item item;
00252       type_container & container = this->getContainer(params);
00253       type_iterator itr = type_generic_container::begin(container, item);
00254       type_iterator itr_end = type_generic_container::end(container);
00255       QSqlQuery queryInsert(params.database());
00256       queryInsert.prepare(sql);
00257 
00258       while (itr != itr_end)
00259       {
00260          pIdOwner->setSqlPlaceHolder(queryInsert, params.owner(), "", m_sForeignKeyOwner);
00261          pIdData->setSqlPlaceHolder(queryInsert, (& item.value_qx()), "", m_sForeignKeyDataType);
00262          if (! queryInsert.exec()) { return queryInsert.lastError(); }
00263          itr = type_generic_container::next(container, itr, item);
00264       }
00265 
00266       return QSqlError();
00267    }
00268 
00269 };
00270 
00271 } // namespace qx
00272 
00273 #endif // _QX_SQL_RELATION_MANY_TO_MANY_H_