summaryrefslogtreecommitdiffstats
path: root/kexi/kexidb/drivers/pqxx/pqxxconnection.cpp
blob: 76684483aaa510ed4339f25b85cf50c8dc23ae09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/* This file is part of the KDE project
   Copyright (C) 2003 Adam Pigg <adam@piggz.co.uk>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this program; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "pqxxconnection.h"
#include <tqvariant.h>
#include <tqfile.h>
#include <kdebug.h>
#include <kexidb/error.h>
#include <kexidb/global.h>
#include <tdelocale.h>
#include <string>
#include "pqxxpreparedstatement.h"
#include "pqxxconnection_p.h"
using namespace KexiDB;

pqxxTransactionData::pqxxTransactionData(Connection *conn, bool nontransaction)
 : TransactionData(conn)
{
	if (nontransaction)
		data = new pqxx::nontransaction(*static_cast<pqxxSqlConnection*>(conn)->d->pqxxsql /* todo: add name? */);
	else
		data = new pqxx::transaction<>(*static_cast<pqxxSqlConnection*>(conn)->d->pqxxsql /* todo: add name? */);
	if (!static_cast<pqxxSqlConnection*>(conn)->m_trans) {
		static_cast<pqxxSqlConnection*>(conn)->m_trans = this;
	}
}

pqxxTransactionData::~pqxxTransactionData()
{
	if (static_cast<pqxxSqlConnection*>(m_conn)->m_trans == this) {
		static_cast<pqxxSqlConnection*>(m_conn)->m_trans = 0;
	}
	delete data;
	data = 0;
}

//==================================================================================

pqxxSqlConnection::pqxxSqlConnection(Driver *driver, ConnectionData &conn_data)
 : Connection(driver,conn_data)
 , d( new pqxxSqlConnectionInternal(this) )
 , m_trans(0)
{
}

//==================================================================================
//Do any tidying up before the object is deleted
pqxxSqlConnection::~pqxxSqlConnection()
{
	//delete m_trans;
	destroy();
	delete d;
}

//==================================================================================
//Return a new query based on a query statment
Cursor* pqxxSqlConnection::prepareQuery( const TQString& statement,  uint cursor_options)
{
	Q_UNUSED(cursor_options);
	return new pqxxSqlCursor(this, statement, 1); //Always used buffered cursor
}

//==================================================================================
//Return a new query based on a query object
Cursor* pqxxSqlConnection::prepareQuery( QuerySchema& query, uint cursor_options)
{
	Q_UNUSED(cursor_options);
	return new pqxxSqlCursor(this, query, 1);//Always used buffered cursor
}

//==================================================================================
//Properly escaped a database object name
TQString pqxxSqlConnection::escapeName(const TQString &name) const
{
	return TQString("\"" + name + "\"");
}

//==================================================================================
//Made this a noop
//We tell kexi we are connected, but we wont actually connect until we use a database!
bool pqxxSqlConnection::drv_connect(KexiDB::ServerVersionInfo& version)
{
	KexiDBDrvDbg << "pqxxSqlConnection::drv_connect" << endl;
	version.clear();
	d->version = &version; //remember for later...
#ifdef __GNUC__
#warning pqxxSqlConnection::drv_connect implement setting version info when we drop libpqxx for libpq
#endif
	return true;
}

//==================================================================================
//Made this a noop
//We tell kexi wehave disconnected, but it is actually handled by closeDatabse
bool pqxxSqlConnection::drv_disconnect()
{
	KexiDBDrvDbg << "pqxxSqlConnection::drv_disconnect: " << endl;
	return true;
}

//==================================================================================
//Return a list of database names
bool pqxxSqlConnection::drv_getDatabasesList( TQStringList &list )
{
//	KexiDBDrvDbg << "pqxxSqlConnection::drv_getDatabaseList" << endl;

	if (executeSQL("SELECT datname FROM pg_database WHERE datallowconn = TRUE"))
	{
		std::string N;
		for (pqxx::result::const_iterator c = d->res->begin(); c != d->res->end(); ++c)
		{
			// Read value of column 0 into a string N
			c[0].to(N);
			// Copy the result into the return list
			list << TQString::fromLatin1 (N.c_str());
		}
		return true;
	}

	return false;
}

//==================================================================================
//Create a new database
bool pqxxSqlConnection::drv_createDatabase( const TQString &dbName )
{
	KexiDBDrvDbg << "pqxxSqlConnection::drv_createDatabase: " << dbName << endl;

	if (executeSQL("CREATE DATABASE " + escapeName(dbName)))
		return true;

	return false;
}

//==================================================================================
//Use this as our connection instead of connect
bool pqxxSqlConnection::drv_useDatabase( const TQString &dbName, bool *cancelled, 
	MessageHandler* msgHandler )
{
	Q_UNUSED(cancelled);
	Q_UNUSED(msgHandler);
	KexiDBDrvDbg << "pqxxSqlConnection::drv_useDatabase: " << dbName << endl;

	TQString conninfo;
	TQString socket;
	TQStringList sockets;

	if (data()->hostName.isEmpty() || data()->hostName == "localhost")
	{
		if (data()->localSocketFileName.isEmpty())
		{
			sockets.append("/tmp/.s.PGSQL.5432");

			for(TQStringList::ConstIterator it = sockets.constBegin(); it != sockets.constEnd(); it++)
			{
				if(TQFile(*it).exists())
				{
					socket = (*it);
					break;
				}
			}
		}
		else
		{
			socket=data()->localSocketFileName; //data()->fileName();
		}
	}
	else
	{
		conninfo = "host='" + data()->hostName + "'";
	}

	//Build up the connection string
	if (data()->port == 0)
		data()->port = 5432;

	conninfo += TQString::fromLatin1(" port='%1'").arg(data()->port);

	conninfo += TQString::fromLatin1(" dbname='%1'").arg(dbName);

	if (!data()->userName.isNull())
		conninfo += TQString::fromLatin1(" user='%1'").arg(data()->userName);

	if (!data()->password.isNull())
		conninfo += TQString::fromLatin1(" password='%1'").arg(data()->password);

	try
	{
		d->pqxxsql = new pqxx::connection( conninfo.latin1() );
		drv_executeSQL( "SET DEFAULT_WITH_OIDS TO ON" ); //Postgres 8.1 changed the default to no oids but we need them

		if (d->version) {
//! @todo set version using the connection pointer when we drop libpqxx for libpq
		}
		return true;
	}
	catch(const std::exception &e)
	{
		KexiDBDrvDbg << "pqxxSqlConnection::drv_useDatabase:exception - " << e.what() << endl;
		d->errmsg = TQString::fromUtf8( e.what() );

	}
	catch(...)
	{
		d->errmsg = i18n("Unknown error.");
	}
	return false;
}

//==================================================================================
//Here we close the database connection
bool pqxxSqlConnection::drv_closeDatabase()
{
	KexiDBDrvDbg << "pqxxSqlConnection::drv_closeDatabase" << endl;
//	if (isConnected())
//	{
	delete d->pqxxsql;
	return true;
//	}
/* js: not needed, right? 
	else
	{
		d->errmsg = "Not connected to database backend";
		d->res = ERR_NO_CONNECTION;
	}
	return false;*/
}

//==================================================================================
//Drops the given database
bool pqxxSqlConnection::drv_dropDatabase( const TQString &dbName )
{
	KexiDBDrvDbg << "pqxxSqlConnection::drv_dropDatabase: " << dbName << endl;

	//FIXME Maybe should check that dbname is no the currentdb
	if (executeSQL("DROP DATABASE " + escapeName(dbName)))
		return true;

	return false;
}

//==================================================================================
//Execute an SQL statement
bool pqxxSqlConnection::drv_executeSQL( const TQString& statement )
{
//	KexiDBDrvDbg << "pqxxSqlConnection::drv_executeSQL: " << statement << endl;
	bool ok = false;

	// Clear the last result information...
	delete d->res;
	d->res = 0;

//	KexiDBDrvDbg << "About to try" << endl;
	try
	{
		//Create a transaction
		const bool implicityStarted = !m_trans;
		if (implicityStarted)
			(void)new pqxxTransactionData(this, true);

		//		m_trans = new pqxx::nontransaction(*m_pqxxsql);
//		KexiDBDrvDbg << "About to execute" << endl;
		//Create a result object through the transaction
		d->res = new pqxx::result(m_trans->data->exec(std::string(statement.utf8())));
//		KexiDBDrvDbg << "Executed" << endl;
		//Commit the transaction
		if (implicityStarted) {
			pqxxTransactionData *t = m_trans;
			drv_commitTransaction(t);
			delete t;
//			m_trans = 0;
		}

		//If all went well then return true, errors picked up by the catch block
		ok = true;
	}
	catch(const pqxx::sql_error& sqlerr) {
		KexiDBDrvDbg << "pqxxSqlConnection::drv_executeSQL: sql_error exception - " << sqlerr.query().c_str() << endl;
	}
	catch (const pqxx::broken_connection& bcerr) {
		KexiDBDrvDbg << "pqxxSqlConnection::drv_executeSQL: broken_connection exception" << endl;
	}
	catch (const std::exception &e)
	{
		//If an error ocurred then put the error description into _dbError
		d->errmsg = TQString::fromUtf8( e.what() );
		KexiDBDrvDbg << "pqxxSqlConnection::drv_executeSQL:exception - " << e.what() << endl;
	}
	catch(...)
	{
		d->errmsg = i18n("Unknown error.");
	}
	//KexiDBDrvDbg << "EXECUTE SQL OK: OID was " << (d->res ? d->res->inserted_oid() : 0) << endl;
	return ok;
}

//==================================================================================
//Return true if currently connected to a database, ignoring the m_is_connected falg.
bool pqxxSqlConnection::drv_isDatabaseUsed() const
{
	if (d->pqxxsql->is_open())
	{
		return true;
	}
	return false;
}

//==================================================================================
//Return the oid of the last insert - only works if sql was insert of 1 row
TQ_ULLONG pqxxSqlConnection::drv_lastInsertRowID()
{
	if (d->res)
	{
		pqxx::oid theOid = d->res->inserted_oid();

		if (theOid != pqxx::oid_none)
		{
			return (TQ_ULLONG)theOid;
		}
		else
		{
			return 0;
		}
	}
	return 0;
}

//<queries taken from pqxxMigrate>
bool pqxxSqlConnection::drv_containsTable( const TQString &tableName )
{
	bool success;
	return resultExists(TQString("select 1 from pg_class where relkind='r' and relname LIKE %1")
		.arg(driver()->escapeString(tableName)), success) && success;
}

bool pqxxSqlConnection::drv_getTablesList( TQStringList &list )
{
	KexiDB::Cursor *cursor;
	m_sql = "select lower(relname) from pg_class where relkind='r'";
	if (!(cursor = executeQuery( m_sql ))) {
		KexiDBDrvWarn << "pqxxSqlConnection::drv_getTablesList(): !executeQuery()" << endl;
		return false;
	}
	list.clear();
	cursor->moveFirst();
	while (!cursor->eof() && !cursor->error()) {
		list += cursor->value(0).toString();
		cursor->moveNext();
	}
	if (cursor->error()) {
		deleteCursor(cursor);
		return false;
	}
	return deleteCursor(cursor);
}
//</taken from pqxxMigrate>

TransactionData* pqxxSqlConnection::drv_beginTransaction()
{
	return new pqxxTransactionData(this, false);
}

bool pqxxSqlConnection::drv_commitTransaction(TransactionData *tdata)
{
	bool result = true;
	try {
		static_cast<pqxxTransactionData*>(tdata)->data->commit();
	}
	catch (const std::exception &e)
	{
		//If an error ocurred then put the error description into _dbError
		d->errmsg = TQString::fromUtf8( e.what() );
		result = false;
	}
	catch (...) {
		//! @todo
		setError();
		result = false;
	}
	if (m_trans == tdata)
		m_trans = 0;
	return result;
}

bool pqxxSqlConnection::drv_rollbackTransaction(TransactionData *tdata)
{
	bool result = true;
	try {
		static_cast<pqxxTransactionData*>(tdata)->data->abort();
	}
	catch (const std::exception &e)
	{
		//If an error ocurred then put the error description into _dbError
		d->errmsg = TQString::fromUtf8( e.what() );
		
		result = false;
	}
	catch (...) {
		d->errmsg = i18n("Unknown error.");
		result = false;
	}
	if (m_trans == tdata)
		m_trans = 0;
	return result;
}

int pqxxSqlConnection::serverResult()
{
	return d->resultCode;
}

TQString pqxxSqlConnection::serverResultName()
{
	return TQString();
}

void pqxxSqlConnection::drv_clearServerResult()
{
	d->resultCode = 0;
}

TQString pqxxSqlConnection::serverErrorMsg()
{
	return d->errmsg;
}

PreparedStatement::Ptr pqxxSqlConnection::prepareStatement(PreparedStatement::StatementType type, 
	FieldList& fields)
{
	return new pqxxPreparedStatement(type, *d, fields);
}
#include "pqxxconnection.moc"