~ubuntu-branches/ubuntu/wily/openms/wily

« back to all changes in this revision

Viewing changes to source/FORMAT/DB/DBConnection.C

  • Committer: Package Import Robot
  • Author(s): Filippo Rusconi
  • Date: 2012-11-12 15:58:12 UTC
  • Revision ID: package-import@ubuntu.com-20121112155812-vr15wtg9b50cuesg
Tags: upstream-1.9.0
ImportĀ upstreamĀ versionĀ 1.9.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// -*- mode: C++; tab-width: 2; -*-
 
2
// vi: set ts=2:
 
3
//
 
4
// --------------------------------------------------------------------------
 
5
//                   OpenMS Mass Spectrometry Framework 
 
6
// --------------------------------------------------------------------------
 
7
//  Copyright (C) 2003-2011 -- Oliver Kohlbacher, Knut Reinert
 
8
//
 
9
//  This library is free software; you can redistribute it and/or
 
10
//  modify it under the terms of the GNU Lesser General Public
 
11
//  License as published by the Free Software Foundation; either
 
12
//  version 2.1 of the License, or (at your option) any later version.
 
13
//
 
14
//  This library is distributed in the hope that it will be useful,
 
15
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
16
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
17
//  Lesser General Public License for more details.
 
18
//
 
19
//  You should have received a copy of the GNU Lesser General Public
 
20
//  License along with this library; if not, write to the Free Software
 
21
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
22
//
 
23
// --------------------------------------------------------------------------
 
24
// $Maintainer: $
 
25
// $Authors: Marc Sturm $
 
26
// --------------------------------------------------------------------------
 
27
 
 
28
 
 
29
//OpenMS includes
 
30
#include <OpenMS/FORMAT/DB/DBConnection.h>
 
31
 
 
32
//QT
 
33
#include <QtSql/QSqlQuery>
 
34
#include <QtSql/QSqlError>
 
35
#include <QtCore/QVariant>
 
36
#include <QtSql/QSqlRecord>
 
37
 
 
38
using namespace std;
 
39
 
 
40
namespace OpenMS
 
41
{
 
42
 
 
43
        DBConnection::DBConnection()
 
44
                : connection_name_()
 
45
        {
 
46
                
 
47
        }
 
48
        
 
49
        DBConnection::~DBConnection()
 
50
        {
 
51
                disconnect();
 
52
        }
 
53
        
 
54
        void DBConnection::connect(const String& db, const String& user, const String& password, const String& host,UInt port,const String& QTDBDriver, const String& connection_name)
 
55
        {
 
56
                connection_name_ = connection_name.toQString();
 
57
 
 
58
                QSqlDatabase::addDatabase(QTDBDriver.c_str(), connection_name_);
 
59
                
 
60
                getDB_().setHostName(host.c_str());
 
61
                getDB_().setUserName(user.c_str());
 
62
                getDB_().setDatabaseName(db.c_str());
 
63
                getDB_().setPassword(password.c_str());
 
64
                getDB_().setPort(port);
 
65
                if (!getDB_().open())
 
66
                {
 
67
                        //construct query
 
68
                        String query = String("Connecting to DB '") + db + "' ( host: '"+host+"', port: '"+String(port)+"', user: '"+user+"', password: '"+password+"')";
 
69
                        //sore error
 
70
                        String error = getDB_().lastError().databaseText();
 
71
                        //close connection
 
72
                        disconnect();
 
73
                                                
 
74
                        throw InvalidQuery(__FILE__, __LINE__, __PRETTY_FUNCTION__,query,error);
 
75
                }
 
76
        }
 
77
        
 
78
        bool DBConnection::isConnected() const
 
79
        {
 
80
                return getDB_().isOpen();
 
81
        }
 
82
        
 
83
        void DBConnection::disconnect()
 
84
        {
 
85
                getDB_().close();
 
86
                QSqlDatabase::removeDatabase(connection_name_);
 
87
        }
 
88
 
 
89
        QSqlQuery DBConnection::executeQuery(const String& query, bool first)
 
90
        {
 
91
                QSqlDatabase db_handle = getDB_();
 
92
                
 
93
                if (!db_handle.isOpen())
 
94
                {
 
95
                        throw NotConnected(__FILE__, __LINE__, __PRETTY_FUNCTION__);
 
96
                }
 
97
                
 
98
                QSqlQuery result(db_handle);
 
99
                
 
100
                //execute the query
 
101
                if (!result.exec(query.c_str()))
 
102
                {
 
103
            throw InvalidQuery(__FILE__, __LINE__, __PRETTY_FUNCTION__,query,db_handle.lastError().text() );
 
104
                }
 
105
                if (first) result.first();
 
106
                
 
107
                return result;
 
108
        }
 
109
        
 
110
        UInt DBConnection::getId(const String& table, const String& column, const String& value)
 
111
        {
 
112
                String query = String("SELECT id FROM ") + table + " WHERE " + column + "='" + value + "' LIMIT 1";
 
113
                return executeQuery(query, true).value(0).toInt();
 
114
        }
 
115
        
 
116
        String DBConnection::DBName() const 
 
117
        { 
 
118
                QSqlDatabase db_handle = getDB_();
 
119
                if (!db_handle.isOpen()) return "";
 
120
                return db_handle.databaseName();
 
121
        }
 
122
        
 
123
        void DBConnection::render(QSqlQuery& result, ostream& out, const String& separator, const String& line_begin, const String& line_end)
 
124
        {
 
125
                
 
126
                //if res is still empty, do nothing
 
127
                if (result.size()!=0)
 
128
                {
 
129
                        Int col_count = result.record().count();
 
130
                        
 
131
                        out << line_begin;
 
132
                        
 
133
                        //render field names
 
134
                        for (Int i = 0; i < col_count; i++) 
 
135
                        {
 
136
                if (i!=0)
 
137
                {
 
138
                        out << separator;
 
139
                } 
 
140
        
 
141
              out << result.record().fieldName(i).toStdString();
 
142
            } 
 
143
            out << line_end;
 
144
                        
 
145
                        //set back internal pointer
 
146
                        result.first();
 
147
                        
 
148
                        //render lines
 
149
                        while(result.isValid())
 
150
                        {
 
151
                                out << line_begin;
 
152
                                for (Int j = 0; j < col_count; j++) 
 
153
                                { 
 
154
                      if (j!=0)
 
155
                        {
 
156
                                out << separator;
 
157
                        }
 
158
                      out << result.value(j).toString().toAscii().data();
 
159
                    }                   
 
160
                                out << line_end;
 
161
                                result.next();  
 
162
                        }
 
163
                }
 
164
        }
 
165
 
 
166
        Int DBConnection::getIntValue(const String& table, const String& column, const String& id)
 
167
        {
 
168
                String query = String("SELECT ") + column + " FROM " + table + " WHERE id='" + id + "'";
 
169
 
 
170
                QSqlQuery result = executeQuery(query, true);
 
171
 
 
172
                if (!result.value(0).canConvert(QVariant::Int))
 
173
                {
 
174
                        throw Exception::ConversionError(__FILE__, __LINE__, __PRETTY_FUNCTION__,"Conversion of QVariant to int failed!");
 
175
                }
 
176
                return result.value(0).toInt();
 
177
        }
 
178
 
 
179
        double DBConnection::getDoubleValue(const String& table, const String& column, const String& id)
 
180
        {
 
181
                String query = String("SELECT ") + column + " FROM " + table + " WHERE id='" + id + "'";
 
182
 
 
183
                QSqlQuery result = executeQuery(query, true);
 
184
 
 
185
                if (!result.value(0).canConvert(QVariant::Double))
 
186
                {
 
187
                        throw Exception::ConversionError(__FILE__, __LINE__, __PRETTY_FUNCTION__,"Conversion of QVariant to double failed!");
 
188
                }
 
189
                return result.value(0).toDouble();
 
190
        }
 
191
 
 
192
        String DBConnection::getStringValue(const String& table, const String& column, const String& id)
 
193
        {
 
194
                String query = String("SELECT ") + column + " FROM " + table + " WHERE id='" + id + "'";
 
195
 
 
196
                QSqlQuery result = executeQuery(query, true);
 
197
 
 
198
                if (!result.value(0).canConvert(QVariant::String))
 
199
                {
 
200
                        throw Exception::ConversionError(__FILE__, __LINE__, __PRETTY_FUNCTION__,"Conversion of QVariant to double failed!");
 
201
                }
 
202
                return result.value(0).toString();
 
203
        }
 
204
        
 
205
        UInt DBConnection::getAutoId()
 
206
        {
 
207
                QSqlQuery result = executeQuery("SELECT LAST_INSERT_ID()", true);
 
208
                if (!result.value(0).canConvert(QVariant::Int))
 
209
                {
 
210
                        throw Exception::ConversionError(__FILE__, __LINE__, __PRETTY_FUNCTION__,"Conversion of QVariant to int failed in DBConnection::getAutoId()!");
 
211
                }
 
212
                return result.value(0).toInt();
 
213
        }
 
214
        
 
215
        
 
216
        // ---------------------------------------------------------------
 
217
        //
 
218
        // Excpetions
 
219
        //
 
220
        // ---------------------------------------------------------------
 
221
        
 
222
        DBConnection::InvalidQuery::InvalidQuery(const char* file, Int line, const char* function, const String& sql_query, const String& sql_error) 
 
223
                :       BaseException(file, line, function, "Invalid Query", "an SQL query failed")
 
224
        {
 
225
                what_ = String("Query '")+sql_query +"' failed: '"+sql_error+"'";
 
226
                Exception::globalHandler.setMessage(what_);
 
227
        }
 
228
        
 
229
        DBConnection::InvalidQuery::~InvalidQuery() throw()
 
230
        {
 
231
        }
 
232
        
 
233
        DBConnection::NotConnected::NotConnected(const char* file, Int line, const char* function) 
 
234
                :       BaseException(file, line, function, "Not Connected", "the DBConnection was accessed but it is not connected to a SQL database")
 
235
        {
 
236
        }
 
237
        
 
238
        DBConnection::NotConnected::~NotConnected() throw()
 
239
        {
 
240
        }
 
241
        
 
242
}
 
243