Logo
  • Main Page
  • Related Pages
  • Modules
  • Classes
  • Files

mmsdbmysql.cpp

Go to the documentation of this file.
00001 /***************************************************************************
00002  *   Copyright (C) 2005-2007 Stefan Schwarzer, Jens Schneider,             *
00003  *                           Matthias Hardt, Guido Madaus                  *
00004  *                                                                         *
00005  *   Copyright (C) 2007-2008 BerLinux Solutions GbR                        *
00006  *                           Stefan Schwarzer & Guido Madaus               *
00007  *                                                                         *
00008  *   Copyright (C) 2009-2013 BerLinux Solutions GmbH                       *
00009  *                                                                         *
00010  *   Authors:                                                              *
00011  *      Stefan Schwarzer   <stefan.schwarzer@diskohq.org>,                 *
00012  *      Matthias Hardt     <matthias.hardt@diskohq.org>,                   *
00013  *      Jens Schneider     <jens.schneider@diskohq.org>,                   *
00014  *      Guido Madaus       <guido.madaus@diskohq.org>,                     *
00015  *      Patrick Helterhoff <patrick.helterhoff@diskohq.org>,               *
00016  *      René Bählkow       <rene.baehlkow@diskohq.org>                     *
00017  *                                                                         *
00018  *   This library is free software; you can redistribute it and/or         *
00019  *   modify it under the terms of the GNU Lesser General Public            *
00020  *   License version 2.1 as published by the Free Software Foundation.     *
00021  *                                                                         *
00022  *   This library is distributed in the hope that it will be useful,       *
00023  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
00024  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
00025  *   Lesser General Public License for more details.                       *
00026  *                                                                         *
00027  *   You should have received a copy of the GNU Lesser General Public      *
00028  *   License along with this library; if not, write to the                 *
00029  *   Free Software Foundation, Inc.,                                       *
00030  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
00031  **************************************************************************/
00032 
00033 /**
00034  * @file  mmsdbmysql.cpp
00035  *
00036  * @brief Source file for mysql database functions.
00037  *
00038  * @author Stefan Schwarzer <stefan.schwarzer@diskohq.org>
00039  * @author Guido Madaus     <guido.madaus@diskohq.org>
00040  * @author Jens Schneider   <pupeider@gmx.de>
00041  * @author Matthias Hardt   <matthias.hardt@diskohq.org>
00042  *
00043  * @ingroup mmstools
00044  */
00045 #ifdef __ENABLE_MYSQL__
00046 
00047 #include <stdlib.h>
00048 #include "mmstools/mmsdbmysql.h"
00049 #include "mmstools/mmslogger.h"
00050 
00051 /**
00052  * Constructor
00053  *
00054  * It just sets the datasource and the reconnect parameters
00055  * for later use in the connect() method.
00056  *
00057  * @param   _datasource     [in]    datasource object containing definitions for database connection
00058  * @param   autoreconnect   [in]    if set to true, connection to the database server will be reestablished, if lost (needs mysql >= 5.0.13)
00059  *
00060  * @exception MMSError  No datasource given (Look at the exception message).
00061  *
00062  * @see MMSDBMySQL::~MMSDBMySQL()
00063  * @see MMSError::getMessage()
00064  */
00065 MMSDBMySQL::MMSDBMySQL(DataSource *_datasource, bool autoreconnect) :
00066     IMMSDB(_datasource),
00067     autoreconnect(autoreconnect) {
00068     if(!this->datasource)
00069         throw MMSError(0, "Cannot instantiate MMSDBMySQL without datasource");
00070 };
00071 
00072 /**
00073  * Destructor
00074  *
00075  * Handles disconnection from the mysql database.
00076  *
00077  * @see MMSDBMySQL::MMSDBMySQL()
00078  */
00079 MMSDBMySQL::~MMSDBMySQL() {
00080     this->disconnect();
00081 }
00082 
00083 /**
00084  * Starts a transaction.
00085  *
00086  * If you are using transaction based queries, call
00087  * this method to start a transaction. To commit it,
00088  * call commitTransaction().
00089  *
00090  * @see MMSDBMySQL::commitTransaction()
00091  * @see MMSError::getMessage()
00092  *
00093  * @exception MMSError  Error while trying to start transaction (Look at the exception message).
00094  */
00095 void MMSDBMySQL::startTransaction() {
00096     if(mysql_query(&this->dbhandle, "START TRANSACTION") != 0)
00097         throw MMSError(0, mysql_error(&this->dbhandle));
00098 }
00099 
00100 /**
00101  * Commits a transaction.
00102  *
00103  * If you are using transaction based queries, call
00104  * this method to commit a transaction. To start it,
00105  * call startTransaction().
00106  *
00107  * @see MMSDBMySQL::startTransaction()
00108  * @see MMSError::getMessage()
00109  *
00110  * @exception MMSError  Error while trying to commit transaction (Look at the exception message).
00111  */
00112 void MMSDBMySQL::commitTransaction() {
00113 #if MYSQL_VERSION_ID >= 40100
00114     if(mysql_commit(&this->dbhandle) != 0)
00115 #else
00116     if(mysql_query(&this->dbhandle, "COMMIT") != 0)
00117 #endif
00118         throw MMSError(0, mysql_error(&this->dbhandle));
00119 }
00120 
00121 /**
00122  * Does a rollback on the current transaction.
00123  *
00124  * If you are using transaction based queries, call
00125  * this method to rollback a transaction.
00126  *
00127  * @see MMSDBMySQL::startTransaction()
00128  * @see MMSDBMySQL::commitTransaction()
00129  * @see MMSError::getMessage()
00130  *
00131  * @exception MMSError  Error while trying to rollback the transaction (Look at the exception message).
00132  */
00133 void MMSDBMySQL::rollbackTransaction() {
00134 #if MYSQL_VERSION_ID >= 40100
00135     if(mysql_rollback(&this->dbhandle) != 0)
00136 #else
00137     if(mysql_query(&this->dbhandle, "ROLLBACK") != 0)
00138 #endif
00139         throw MMSError(0, mysql_error(&this->dbhandle));
00140 }
00141 
00142 /**
00143  * Connects to the mysql database.
00144  *
00145  * @see MMSDBMySQL::disconnect()
00146  * @see MMSError::getMessage()
00147  *
00148  * @exception MMSError  Error while trying to connect (Look at the exception message).
00149  */
00150 void MMSDBMySQL::connect() {
00151     mysql_init(&this->dbhandle);
00152 
00153 #ifdef MYSQL_OPT_RECONNECT
00154 #  if defined(MYSQL_VERSION_ID) && (MYSQL_VERSION_ID >= 50013)
00155     // reconnect?
00156     if(this->autoreconnect) {
00157         my_bool r = 1;
00158         mysql_options(&this->dbhandle, MYSQL_OPT_RECONNECT, &r);
00159     }
00160 #  endif
00161 #endif
00162 
00163     if(!mysql_real_connect(&this->dbhandle,
00164                            this->datasource->getAddress().c_str(),
00165                            this->datasource->getUser().c_str(),
00166                            this->datasource->getPassword().c_str(),
00167                            this->datasource->getDatabaseName().c_str(),
00168                            this->datasource->getPort(),
00169                            NULL, 0)) {
00170            string err = mysql_error(&this->dbhandle);
00171            mysql_close(&this->dbhandle);
00172            throw MMSError(0, err);
00173     }
00174 
00175    this->connected = true;
00176 }
00177 
00178 /**
00179  * Disconnects from a mysql database.
00180  *
00181  * @see MMSDBMySQL::connect()
00182  */
00183 void MMSDBMySQL::disconnect() {
00184     if(this->connected) {
00185         mysql_close(&this->dbhandle);
00186         this->connected = false;
00187     }
00188 
00189     this->dbname = "";
00190 
00191     return;
00192 }
00193 
00194 /**
00195  * @brief This function executes given database query and puts the results in MMSRecordSet.
00196  *        This method is used for select statements
00197  *
00198  * @param statement [in]    buffer with database query
00199  * @param rs        [out]   MMSRecordSet that holds the results
00200  *
00201  * @see MMSRecordSet
00202  * @see MMSError::getMessage()
00203  *
00204  * @return Returns the number of affected rows
00205  *
00206  * @exception   MMSError    Query couldn't be executed (Look at the exception message).
00207  */
00208 int MMSDBMySQL::query(string statement, MMSRecordSet *rs) {
00209     int     numRows = 0;
00210     string  message;
00211 
00212     rs->reset();
00213 
00214     if(!this->connected) {
00215         message = "Query called but no connection established." + string(" [query was: ") + statement + string("]");
00216         throw MMSError(0, message);
00217     }
00218 
00219     if(mysql_query(&this->dbhandle, statement.c_str()) != 0) {
00220         message = mysql_error(&this->dbhandle) + string(" [query was: ") + statement + string("]");
00221         throw MMSError(0, message);
00222     }
00223 
00224     // get results
00225     MYSQL_RES *results = mysql_use_result(&this->dbhandle);
00226     if(results) {
00227         unsigned int count = mysql_num_fields(results);
00228         if(count > 0) {
00229             MYSQL_FIELD *fields = mysql_fetch_fields(results);
00230             MYSQL_ROW row;
00231             while((row = mysql_fetch_row(results))) {
00232                 rs->addRow();
00233                 for(unsigned int i = 0; i < count; i++) {
00234                     if(row[i])
00235                         (*rs)[fields[i].name] = row[i];
00236                 }
00237             }
00238         }
00239         numRows = mysql_num_rows(results);
00240         mysql_free_result(results);
00241     }
00242 
00243     //rewind
00244     rs->setRecordNum(0);
00245 
00246     return numRows;
00247 }
00248 
00249 /**
00250  * @brief This function executes given database query.
00251  *        This method is used for insert, update and delete statements
00252  *
00253  * @param statement buffer with database query
00254  *
00255  * @see MMSError::getMessage()
00256  *
00257  * @return Returns the number of affected rows
00258  *
00259  * @exception   MMSError    Query couldn't be executed (Look at the exception message).
00260  */
00261 int MMSDBMySQL::query(string statement) {
00262     int     numRows = 0;
00263     string  message;
00264 
00265     if(!this->connected) {
00266         message = "Query called but no connection established." + string(" [query was: ") + statement + string("]");
00267         throw MMSError(0, message);
00268     }
00269 
00270     if(mysql_query(&this->dbhandle, statement.c_str()) != 0) {
00271         message = mysql_error(&this->dbhandle) + string(" [query was: ") + statement + string("]");
00272         throw MMSError(0, message);
00273     }
00274 
00275     // fetch results if there are some
00276     MYSQL_RES *results = mysql_store_result(&this->dbhandle);
00277     if(results) {
00278         numRows = mysql_num_rows(results);
00279         mysql_free_result(results);
00280     }
00281 
00282     // return the number of affected rows
00283     return numRows;
00284 }
00285 
00286 /**
00287  * @brief Returns the ID of the last inserted record
00288  *
00289  * @return Returns the ID of the last inserted record
00290  *
00291  * @exception   MMSError    Couldn't fetch last ID (Look at the exception message).
00292  */
00293 int MMSDBMySQL::getLastInsertedID() {
00294     int ret = 0;
00295 
00296     if(!this->connected)
00297         throw MMSError(0, "No connection established. Cannot fetch last inserted id.");
00298 
00299     if(mysql_query(&this->dbhandle, "SELECT LAST_INSERT_ID();") != 0) {
00300         string message = mysql_error(&this->dbhandle) + string(" [query was: SELECT LAST_INSERT_ID();]");
00301         throw MMSError(0, message);
00302     }
00303 
00304     // fetch results if there are some
00305     MYSQL_RES *results = mysql_store_result(&this->dbhandle);
00306     if(results) {
00307         MYSQL_ROW row = mysql_fetch_row(results);
00308         if(row)
00309             ret = atoi(row[0]);
00310         mysql_free_result(results);
00311     }
00312 
00313     return ret;
00314 }
00315 
00316 #endif /*__ENABLE_MYSQL__*/

Generated by doxygen