aboutsummaryrefslogtreecommitdiff
path: root/src/interfaces/ecpg/ecpglib/prepare.c
blob: 1afa63c9339be935e79c85590202b95ada0d6499 (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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/* $PostgreSQL: pgsql/src/interfaces/ecpg/ecpglib/prepare.c,v 1.21 2007/09/30 11:38:48 meskes Exp $ */

#define POSTGRES_ECPG_INTERNAL
#include "postgres_fe.h"

#include <ctype.h>

#include "ecpgtype.h"
#include "ecpglib.h"
#include "ecpgerrno.h"
#include "extern.h"
#include "sqlca.h"

struct prepared_statement
{
	char					   *name;
	bool						prepared;
	struct statement		   *stmt;
	struct prepared_statement  *next;
};

#define STMTID_SIZE 32

typedef struct 
{
    int         lineno;
    char        stmtID[STMTID_SIZE];
    char        *ecpgQuery;
    long        execs;                  /* # of executions      */
    char        *connection;            /* connection for the statement     */
} stmtCacheEntry;

static int             nextStmtID               = 1;
const static int       stmtCacheNBuckets        = 2039;     /* # buckets - a prime # */
const static int       stmtCacheEntPerBucket    = 8;        /* # entries/bucket     */
static stmtCacheEntry  stmtCacheEntries[16384] = {{0,{0},0,0,0}};

static struct prepared_statement *find_prepared_statement(const char *name,
	struct connection *con, struct prepared_statement **prev);
static bool	deallocate_one(int lineno, enum COMPAT_MODE c, struct connection *con,
	struct prepared_statement *prev, struct prepared_statement *this);

static bool
isvarchar(unsigned char c)
{
	if (isalnum(c))
		return true;

	if (c == '_' || c == '>' || c == '-' || c == '.')
		return true;

	if (c >= 128)
		return true;

	return (false);
}

static bool
replace_variables(char **text, int lineno, bool questionmarks)
{
	bool	string = false;
	int 	counter = 1, ptr = 0;

	for (; (*text)[ptr] != '\0'; ptr++)
	{
		if ((*text)[ptr] == '\'')
			string = string ? false : true;

		if (string || (((*text)[ptr] != ':') && ((*text)[ptr] != '?')))
			continue;

		if (((*text)[ptr] == ':') && ((*text)[ptr+1] == ':')) 
			ptr += 2;		/* skip  '::' */
		else
		{
			int len;
			int buffersize = sizeof(int) * CHAR_BIT * 10 / 3; /* a rough guess of the size we need */
			char *buffer, *newcopy;

			if (!(buffer = (char *) ECPGalloc(buffersize, lineno)))
				return false;

			snprintf(buffer, buffersize, "$%d", counter++);

			for (len=1; (*text)[ptr+len] && isvarchar((*text)[ptr+len]); len++);
			if (!(newcopy = (char *) ECPGalloc(strlen(*text) - len + strlen(buffer) + 1, lineno)))
			{
				ECPGfree(buffer);
				return false;
			}

			strncpy(newcopy, *text, ptr);
			strcpy(newcopy + ptr, buffer);
			strcat(newcopy, (*text) + ptr + len);

			ECPGfree(*text);
			ECPGfree(buffer);

			*text = newcopy;

			if ((*text)[ptr] == '\0')		/* we reached the end */
				ptr--;		/* since we will (*text)[ptr]++ in the top level for
							 * loop */
		}
	}
	return true;
}

/* handle the EXEC SQL PREPARE statement */
bool
ECPGprepare(int lineno, const char *connection_name, const int questionmarks, const char *name, const char *variable)
{
	struct connection		   *con;
	struct statement		   *stmt;
	struct prepared_statement  *this,
							   *prev;
	struct sqlca_t *sqlca = ECPGget_sqlca();
	PGresult   *query;

	ECPGinit_sqlca(sqlca);

	con = ECPGget_connection(connection_name);

	/* check if we already have prepared this statement */
	this = find_prepared_statement(name, con, &prev);
	if (this && !deallocate_one(lineno, ECPG_COMPAT_PGSQL, con, prev, this))
		return false;

	/* allocate new statement */
	this = (struct prepared_statement *) ECPGalloc(sizeof(struct prepared_statement), lineno);
	if (!this)
		return false;

	stmt = (struct statement *) ECPGalloc(sizeof(struct statement), lineno);
	if (!stmt)
	{
		ECPGfree(this);
		return false;
	}

	/* create statement */
	stmt->lineno = lineno;
	stmt->connection = con;
	stmt->command = ECPGstrdup(variable, lineno);
	stmt->inlist = stmt->outlist = NULL;

	/* if we have C variables in our statment replace them with '?' */
	replace_variables(&(stmt->command), lineno, questionmarks);

	/* add prepared statement to our list */
	this->name = (char *) name;
	this->stmt = stmt;

	/* and finally really prepare the statement */
	query = PQprepare(stmt->connection->connection, name, stmt->command, 0, NULL);
	if (!ECPGcheck_PQresult(query, stmt->lineno, stmt->connection->connection, stmt->compat))
	{
		ECPGfree(stmt->command);
		ECPGfree(this);
		ECPGfree(stmt);
		return false;
	}

	ECPGlog("ECPGprepare line %d: NAME: %s QUERY: %s\n", stmt->lineno, name, stmt->command);
	PQclear(query);
	this->prepared = true;

	if (con->prep_stmts == NULL)
		this->next = NULL;
	else
		this->next = con->prep_stmts;

	con->prep_stmts = this;
	return true;
}

static struct prepared_statement *find_prepared_statement(const char *name,
	struct connection *con, struct prepared_statement **prev_)
{
	struct prepared_statement  *this,
							   *prev;

	for (this = con->prep_stmts, prev = NULL; this != NULL; prev = this, this = this->next)
	{
		if (strcmp(this->name, name) == 0)
		{
			if (prev_)
				*prev_ = prev;
			return this;
		}
	}
	return NULL;
}

static bool
deallocate_one(int lineno, enum COMPAT_MODE c, struct connection *con, struct prepared_statement *prev, struct prepared_statement *this)
{
	bool	r = false;

	ECPGlog("ECPGdeallocate line %d: NAME: %s\n", lineno, this->name);

	/* first deallocate the statement in the backend */
	if (this->prepared)
	{
		char *text;
		PGresult *query;
		
		text = (char *) ECPGalloc(strlen("deallocate \"\" ") + strlen(this->name), this->stmt->lineno);
		if (text)
		{
			sprintf(text, "deallocate \"%s\"", this->name);
			query = PQexec(this->stmt->connection->connection, text);
			ECPGfree(text);
			if (ECPGcheck_PQresult(query, lineno, this->stmt->connection->connection, this->stmt->compat))
			{
				PQclear(query);
				r = true;
			}
		}
	}

	/*
	 * Just ignore all errors since we do not know the list of cursors we
	 * are allowed to free. We have to trust the software.
	 */
	if (!r && !INFORMIX_MODE(c))
	{
		ECPGraise(lineno, ECPG_INVALID_STMT, ECPG_SQLSTATE_INVALID_SQL_STATEMENT_NAME, this->name);
		return false;
	}
	
	/* okay, free all the resources */
	ECPGfree(this->stmt->command);
	ECPGfree(this->stmt);
	if (prev != NULL)
		prev->next = this->next;
	else
		con->prep_stmts = this->next;

	ECPGfree(this);
	return true;
}

/* handle the EXEC SQL DEALLOCATE PREPARE statement */
bool
ECPGdeallocate(int lineno, int c, const char *connection_name, const char *name)
{
	struct connection		   *con;
	struct prepared_statement  *this,
							   *prev;

	con = ECPGget_connection(connection_name);

	this = find_prepared_statement(name, con, &prev);
	if (this)
		return deallocate_one(lineno, c, con, prev, this);

	/* prepared statement is not found */
	if (INFORMIX_MODE(c))
		return true;
	ECPGraise(lineno, ECPG_INVALID_STMT, ECPG_SQLSTATE_INVALID_SQL_STATEMENT_NAME, name);
	return false;
}

bool
ECPGdeallocate_all_conn(int lineno, enum COMPAT_MODE c, struct connection *con)
{
	/* deallocate all prepared statements */
	while (con->prep_stmts)
	{
		if (!deallocate_one(lineno, c, con, NULL, con->prep_stmts))
			return false;
	}

	return true;
}

bool
ECPGdeallocate_all(int lineno, int compat, const char *connection_name)
{
	return ECPGdeallocate_all_conn(lineno, compat, ECPGget_connection(connection_name));
}

char *
ECPGprepared(const char *name, struct connection *con, int lineno)
{
	struct prepared_statement  *this;
	this = find_prepared_statement(name, con, NULL);
	return this ? this->stmt->command : NULL;
}

/* return the prepared statement */
char *
ECPGprepared_statement(const char *connection_name, const char *name, int lineno)
{
	return ECPGprepared(name, ECPGget_connection(connection_name), lineno);
}

/*
 * hash a SQL statement -  returns entry # of first entry in the bucket
 */
static int
HashStmt(const char *ecpgQuery)
{
    int             stmtIx, bucketNo, hashLeng, stmtLeng;
    long long       hashVal, rotVal;

    stmtLeng = strlen(ecpgQuery);
    hashLeng = 50;                          /* use 1st 50 characters of statement       */
    if(hashLeng > stmtLeng)                 /* if the statement isn't that long         */
        hashLeng = stmtLeng;                /*      use its actual length               */

    hashVal = 0;
    for(stmtIx = 0; stmtIx < hashLeng; ++stmtIx)
    {
        hashVal = hashVal +  (int) ecpgQuery[stmtIx];
        hashVal = hashVal << 13;
        rotVal  = (hashVal & 0x1fff00000000LL) >> 32;
        hashVal = (hashVal & 0xffffffffLL) | rotVal;
    }

    bucketNo  = hashVal % stmtCacheNBuckets;
    bucketNo += 1;                                      /* don't use bucket # 0         */

    return (bucketNo * stmtCacheEntPerBucket);
}

/*
 * search the statement cache - search for entry with matching ECPG-format query
 * Returns entry # in cache if found
 *   OR  zero if not present (zero'th entry isn't used)
 */
static int
SearchStmtCache(const char *ecpgQuery)
{
    int             entNo, entIx;

/* hash the statement           */
    entNo = HashStmt(ecpgQuery);

/* search the cache     */
    for(entIx = 0; entIx < stmtCacheEntPerBucket; ++entIx)
    {
        if(stmtCacheEntries[entNo].stmtID[0])   /* check if entry is in use     */
        {
		if(!strcmp(ecpgQuery, stmtCacheEntries[entNo].ecpgQuery))
                	break;                          /* found it     */
        }
        ++entNo;                                /* incr entry #     */
    }

/* if entry wasn't found - set entry # to zero  */
    if(entIx >= stmtCacheEntPerBucket)
        entNo = 0;

    return(entNo);
}

/*
 * free an entry in the statement cache
 * Returns entry # in cache used
 *   OR  negative error code
 */
static int
ECPGfreeStmtCacheEntry(int      entNo)          /* entry # to free          */
{
    stmtCacheEntry  *entry;
    PGresult        *results;
    char            deallocText[100];
    struct connection *con;

    entry = &stmtCacheEntries[entNo];
    if(!entry->stmtID[0])                       /* return if the entry isn't in use     */
        return(0);

    con = ECPGget_connection(entry->connection);
/* free the server resources for the statement                                          */
    ECPGlog("ECPGfreeStmtCacheEntry line %d: deallocate %s, cache entry #%d\n", entry->lineno, entry->stmtID, entNo);
    sprintf(deallocText, "DEALLOCATE PREPARE %s", entry->stmtID);
    results = PQexec(con->connection, deallocText);

    if (!ECPGcheck_PQresult(results, entry->lineno, con->connection, ECPG_COMPAT_PGSQL))
    	return(-1);
    PQclear(results);

    entry->stmtID[0] = '\0';

/* free the memory used by the cache entry      */
    if(entry->ecpgQuery)
    {
	ECPGfree(entry->ecpgQuery);
        entry->ecpgQuery = 0;
    }

    return(entNo);
}

/*
 * add an entry to the statement cache
 * returns entry # in cache used  OR  negative error code
 */
static int
AddStmtToCache(int      	lineno,         /* line # of statement      */
               char		*stmtID,        /* statement ID             */
               const char	*connection,    /* connection               */
               const char	*ecpgQuery)     /* query                    */
{
    int             ix, initEntNo, luEntNo, entNo;
    stmtCacheEntry  *entry;

/* hash the statement                                                                   */
    initEntNo = HashStmt(ecpgQuery);

/* search for an unused entry                                                           */
    entNo   = initEntNo;            /* start with the initial entry # for the bucket    */
    luEntNo = initEntNo;            /* use it as the initial 'least used' entry         */
    for(ix = 0; ix < stmtCacheEntPerBucket; ++ix)
    {
        entry = &stmtCacheEntries[entNo];
        if(!entry->stmtID[0])                       /* unused entry  -  use it          */
            break;
        if(entry->execs < stmtCacheEntries[luEntNo].execs)
            luEntNo = entNo;                        /* save new 'least used' entry      */
        ++entNo;                                    /* increment entry #                */
    }

/* if no unused entries were found - use the 'least used' entry found in the bucket     */
    if(ix >= stmtCacheEntPerBucket)                 /* if no unused entries were found  */
        entNo = luEntNo;                            /* re-use the 'least used' entry    */

/* 'entNo' is the entry to use - make sure its free                                     */
    if (ECPGfreeStmtCacheEntry(entNo) < 0)
    	return (-1);

/* add the query to the entry                                                           */
    entry = &stmtCacheEntries[entNo];
    entry->lineno = lineno;
    entry->ecpgQuery = ECPGstrdup(ecpgQuery, lineno);
    entry->connection = (char *)connection;
    entry->execs = 0;
    memcpy(entry->stmtID, stmtID, sizeof(entry->stmtID));

    return(entNo);
}

/* handle cache and preparation of statments in auto-prepare mode */
bool
ECPGauto_prepare(int lineno, const char *connection_name, const int questionmarks, char **name, const char *query)
{
	int entNo;

	/* search the statement cache for this statement    */
	entNo = SearchStmtCache(query);

	/* if not found - add the statement to the cache    */
	if(entNo)
	{
		ECPGlog("ECPGauto_prepare line %d: stmt found in cache, entry %d\n", lineno, entNo);
		*name = ECPGstrdup(stmtCacheEntries[entNo].stmtID, lineno); 
	}
	else
	{
		ECPGlog("ECPGauto_prepare line %d: stmt not in cache; inserting\n", lineno);

		/* generate a statement ID */
		*name = (char *) ECPGalloc(STMTID_SIZE, lineno);
		sprintf(*name, "ecpg%d", nextStmtID++);

		if (!ECPGprepare(lineno, connection_name, questionmarks, ECPGstrdup(*name, lineno), query))
			return(false);
		if (AddStmtToCache(lineno, *name, connection_name, query) < 0)
			return(false);
	}

	/* increase usage counter */
	stmtCacheEntries[entNo].execs++;

	return(true);
}