File: PostgresConnection.cpp

package info (click to toggle)
cvsnt 2.5.03.2382-3.3%2Blenny1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 32,288 kB
  • ctags: 24,567
  • sloc: ansic: 136,648; cpp: 102,037; sh: 42,846; asm: 3,495; makefile: 1,763; ada: 1,681; perl: 1,352; pascal: 1,089; cs: 1,008; yacc: 805; python: 453; xml: 263; sql: 210; lisp: 7
file content (347 lines) | stat: -rw-r--r-- 8,456 bytes parent folder | download | duplicates (2)
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
/*
	CVSNT Generic API
    Copyright (C) 2005 Tony Hoyle and March-Hare Software Ltd

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

    This library 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#endif
#include <config.h>
#include "../lib/api_system.h"

#ifdef HAVE_LIBPQ_FE_H
#include <libpq-fe.h>
#else
// else what??
#endif

#include "../cvs_string.h"
#include "../FileAccess.h"
#include "../ServerIO.h"
#include "PostgresConnection.h"
#include "PostgresRecordset.h"

extern "C" CSqlConnection *Postgres_Alloc()
{
        return new CPostgresConnection;
}

CPostgresConnection::CPostgresConnection()
{
	m_pDb=NULL;
	m_lasterr=PGRES_COMMAND_OK;
}

CPostgresConnection::~CPostgresConnection()
{
	Close();
}

bool CPostgresConnection::Create(const char *host, const char *database, const char *username, const char *password)
{
	if(!Open(host,"template1",username,password))
		return false;
	Execute("create database %s",database);
	if(Error())
		return false;
	Close();
	return Open(host,database,username,password);
}

bool CPostgresConnection::Open(const char *host, const char *database, const char *username, const char *password)
{
	return __Open(host,database,username,password);
}

bool CPostgresConnection::__Open(const char *host, const char *database, const char *username, const char *password)
{
#ifdef _WIN32
	__try
	{
#endif
		char tmp[1024];
		snprintf(tmp,sizeof(tmp),"host = '%s' dbname = '%s' user = '%s' password = '%s'",host,database,username,password);

		m_pDb = PQconnectdb(tmp);
		if(!m_pDb)
			return false;

		if(PQstatus(m_pDb)==CONNECTION_BAD)
			return false;

		PQsetClientEncoding(m_pDb,"UNICODE");
#ifdef _WIN32
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		return false;
	}
#endif
	return true;
}

bool CPostgresConnection::Close()
{
	if(m_pDb)
		PQfinish(m_pDb);

	m_pDb=NULL;
	return true;
}

bool CPostgresConnection::IsOpen()
{
	if(m_pDb && PQstatus(m_pDb)!=CONNECTION_BAD)
		return true;
	return false;
}

CSqlRecordsetPtr CPostgresConnection::Execute(const char *string, ...)
{
	cvs::string str;
	va_list va;
	va_start(va,string);
	cvs::vsprintf(str,64,string,va);
	va_end(va);

	CPostgresRecordset *rs = new CPostgresRecordset();

	/* postgres doesn't support the standard questionmark operator, instead using '$n'.
	   preparse the string looking for these and replacing them.  This routine is probably
	   not very robust. */
	size_t pos = 0;
	int var = 1;
	char varstr[32];
	bool quote = false;
	while(pos<str.size())
	{
		char c=str[pos];
		if(!quote && c=='\'')
			quote=true;
		else if(quote && c=='\'')
			quote=false;
		else if(!quote && c=='?')
		{
			snprintf(varstr,sizeof(varstr),"$%d",var++);
			str.replace(pos,1,varstr);
		}
		pos++;
	}

	CServerIo::trace(3,"%s",str.c_str());

	PGresult *rslt;
	int numParams = (int)m_bindVars.size();
	Oid *paramTypes = NULL;
	char **paramValues = NULL;
	int *paramLength = NULL;
	int *paramFormats = NULL;
	// Appears to be impossible to define in VC.. Probably an MS bug.
	typedef char __dummy[16];
	__dummy *paramVars = NULL;
	if(numParams)
	{
		paramTypes = new Oid[numParams];
		paramValues = new char *[numParams];
		paramLength = new int[numParams];
		paramFormats = new int[numParams];
		paramVars = new char[numParams][16];

		int n = 0;
		for(std::map<int,CSqlVariant>::iterator i = m_bindVars.begin(); i!=m_bindVars.end(); ++i)
		{
			paramFormats[n]=1;
			switch(i->second.type())
			{
			case CSqlVariant::vtNull:
				paramTypes[n]=0; 
				paramValues[n]=0;
				paramLength[n]=0;
				break;
			case CSqlVariant::vtChar:
			case CSqlVariant::vtUChar:
				paramTypes[n]=18;
				*(char*)paramVars[n]=(char)i->second;
				paramValues[n]=paramVars[n];
				paramLength[n]=sizeof(char);
				break;
			case CSqlVariant::vtShort:
			case CSqlVariant::vtUShort:
				paramTypes[n]=21;
				*(short*)paramVars[n]=(short)i->second;
				paramValues[n]=paramVars[n];
				paramLength[n]=sizeof(short);
				break;
			case CSqlVariant::vtInt:
			case CSqlVariant::vtUInt:
			case CSqlVariant::vtLong:
			case CSqlVariant::vtULong:
				if(sizeof(int)==4)
				{
					paramTypes[n]=23; 
					*(int*)paramVars[n]=(int)i->second;
					paramValues[n]=paramVars[n];
					paramLength[n]=sizeof(int);
					break;
				}
			/* fall through (64bit systems) */
			case CSqlVariant::vtLongLong:
			case CSqlVariant::vtULongLong:
				paramTypes[n]=20;
	#ifdef _WIN32
				*(__int64*)paramVars[n]=(__int64)i->second;
				paramValues[n]=paramVars[n];
				paramLength[n]=sizeof(__int64);
	#else
				*(long long*)paramVars[n]=(long long)i->second;
				paramValues[n]=paramVars[n];
				paramLength[n]=sizeof(long long);
	#endif
				break;
			case CSqlVariant::vtString:
			case CSqlVariant::vtWString:
				{
				paramTypes[n]=25;
				const char *s = i->second;
				paramLength[n]=(int)strlen(s);
				paramValues[n]=(char*)s;
				}
				break;
			}
			n++;
		}
	}


	rslt = PQexecParams(m_pDb, str.c_str(), numParams, paramTypes, paramValues, paramLength, paramFormats, 1);

	if(paramTypes)
		delete[] paramTypes;
	if(paramValues)
		delete[] paramValues;
	if(paramLength)
		delete[] paramLength;
	if(paramFormats)
		delete[] paramFormats;
	if(paramVars)
		delete[] paramVars;

	if(!rslt)
	{
		m_lasterr = PGRES_FATAL_ERROR;
		return rs;
	}

	m_lasterr = PQresultStatus(rslt);
	if(m_lasterr == PGRES_BAD_RESPONSE || m_lasterr == PGRES_NONFATAL_ERROR || m_lasterr == PGRES_FATAL_ERROR)
	{
		if(rslt)
			m_lasterrmsg = PQresultErrorMessage(rslt);
		else
			m_lasterrmsg = "";
		if(m_lasterrmsg.size() && m_lasterrmsg[m_lasterrmsg.size()-1]=='\n')
			m_lasterrmsg.resize(m_lasterrmsg.size()-1);
		PQclear(rslt);
		return rs;
	}

	rs->Init(m_pDb,rslt);

	m_bindVars.clear();

	return rs;
}

bool CPostgresConnection::Error() const
{
	if(!m_pDb) return true;
	if(PQstatus(m_pDb)==CONNECTION_BAD) return true;
	if(m_lasterr == PGRES_BAD_RESPONSE || m_lasterr == PGRES_NONFATAL_ERROR || m_lasterr == PGRES_FATAL_ERROR)
		return true;
	return false;
}

const char *CPostgresConnection::ErrorString() 
{
	if(!m_pDb)
		return "Database not created or couldn't find libpq.dll";
	if(PQstatus(m_pDb)!=CONNECTION_OK)
		return PQerrorMessage(m_pDb);
	if(m_lasterrmsg.size())
		return m_lasterrmsg.c_str();
	return PQresStatus((ExecStatusType)m_lasterr);
}

unsigned CPostgresConnection::GetInsertIdentity(const char *table_hint) 
{
	cvs::string str;
	cvs::sprintf(str,80,"select currval('%s_id_seq')",table_hint);
	PGresult *rslt = PQexec(m_pDb, str.c_str());
	if(!PQntuples(rslt) || !PQnfields(rslt))
	{
		CServerIo::trace(1,"Postgres GetInsertIdentity(%s) failed",table_hint);
		return 0;
	}

	unsigned long ident;
	if(sscanf(PQgetvalue(rslt,0,0),"%lu",&ident)!=1)
	{
		CServerIo::trace(1,"Postgres GetInsertIdentity(%s) failed (bogus value)",table_hint);
		return 0;
	}

	PQclear(rslt);

	return ident;
}

bool CPostgresConnection::BeginTrans()
{
	PGresult *rslt = PQexec(m_pDb, "BEGIN TRANSACTION");
	m_lasterr = PQresultStatus(rslt);
	PQclear(rslt);
	if(m_lasterr == PGRES_BAD_RESPONSE || m_lasterr == PGRES_NONFATAL_ERROR || m_lasterr == PGRES_FATAL_ERROR)
		return false;
	return true;
}

bool CPostgresConnection::CommitTrans()
{
	PGresult *rslt = PQexec(m_pDb, "COMMIT TRANSACTION");
	m_lasterr = PQresultStatus(rslt);
	PQclear(rslt);
	if(m_lasterr == PGRES_BAD_RESPONSE || m_lasterr == PGRES_NONFATAL_ERROR || m_lasterr == PGRES_FATAL_ERROR)
		return false;
	return true;
}

bool CPostgresConnection::RollbackTrans()
{
	PGresult *rslt = PQexec(m_pDb, "ROLLBACK TRANSACTION");
	m_lasterr = PQresultStatus(rslt);
	PQclear(rslt);
	if(m_lasterr == PGRES_BAD_RESPONSE || m_lasterr == PGRES_NONFATAL_ERROR || m_lasterr == PGRES_FATAL_ERROR)
		return false;
	return true;
}

bool CPostgresConnection::Bind(int variable, CSqlVariant value)
{
	m_bindVars[variable]=value;
	return true;
}