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