-
Notifications
You must be signed in to change notification settings - Fork 6
/
plphp_io.c
570 lines (493 loc) · 13.9 KB
/
plphp_io.c
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/**********************************************************************
* plphp_io.c
*
* Support functions for PL/php -- mainly functions to convert stuff
* from the PHP representation to PostgreSQL representation and vice
* versa, either text or binary representations.
*
* $Id$
*
**********************************************************************/
#include "postgres.h"
#include "plphp_io.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/memutils.h"
/*
* plphp_zval_from_tuple
* Build a PHP hash from a tuple.
*/
zval *
plphp_zval_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
{
int i;
char *attname = NULL;
zval *array;
MAKE_STD_ZVAL(array);
array_init(array);
for (i = 0; i < tupdesc->natts; i++)
{
char *attdata;
/* Get the attribute name */
attname = tupdesc->attrs[i]->attname.data;
/* and get its value */
if ((attdata = SPI_getvalue(tuple, tupdesc, i + 1)) != NULL)
{
/* "true" means strdup the string */
add_assoc_string(array, attname, attdata, true);
pfree(attdata);
}
else
add_assoc_null(array, attname);
}
return array;
}
/*
* plphp_htup_from_zval
* Build a HeapTuple from a zval (which must be an array) and a TupleDesc.
*
* The return HeapTuple is allocated in the current memory context and must
* be freed by the caller.
*
* If zval doesn't contain any of the element names from the TupleDesc,
* build a tuple from the first N elements. This allows us to accept
* arrays in form array(1,2,3) as the result of functions with OUT arguments.
* XXX -- possible optimization: keep the memory context created and only
* reset it between calls.
*/
HeapTuple
plphp_htup_from_zval(zval *val, TupleDesc tupdesc)
{
MemoryContext oldcxt;
MemoryContext tmpcxt;
HeapTuple ret;
AttInMetadata *attinmeta;
HashPosition pos;
zval **element;
char **values;
int i;
bool allempty = true;
tmpcxt = AllocSetContextCreate(TopTransactionContext,
"htup_from_zval cxt",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
oldcxt = MemoryContextSwitchTo(tmpcxt);
values = (char **) palloc(tupdesc->natts * sizeof(char *));
for (i = 0; i < tupdesc->natts; i++)
{
char *key = SPI_fname(tupdesc, i + 1);
zval *scalarval = plphp_array_get_elem(val, key);
values[i] = plphp_zval_get_cstring(scalarval, true, true);
/*
* Reset the flag is even one of the keys actually exists,
* even if it is NULL.
*/
if (scalarval != NULL)
allempty = false;
}
/* None of the names from the tuple exists,
* try to get 1st N array elements and assign them to the tuple
*/
if (allempty)
for (i = 0,
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);
(zend_hash_get_current_data_ex(Z_ARRVAL_P(val),
(void **) &element,
&pos) == SUCCESS) &&
(i < tupdesc->natts);
zend_hash_move_forward_ex(Z_ARRVAL_P(val), &pos), i++)
values[i] = plphp_zval_get_cstring(element[0], true, true);
attinmeta = TupleDescGetAttInMetadata(tupdesc);
MemoryContextSwitchTo(oldcxt);
ret = BuildTupleFromCStrings(attinmeta, values);
MemoryContextDelete(tmpcxt);
return ret;
}
/* plphp_srf_htup_from_zval
* Build a tuple from a zval and a TupleDesc, for a SRF.
*
* Like above, but we don't use the names of the array attributes;
* rather we build the tuple in order. Also, we get a MemoryContext
* from the caller and just clean it at return, rather than building it each
* time.
*/
HeapTuple
plphp_srf_htup_from_zval(zval *val, AttInMetadata *attinmeta,
MemoryContext cxt)
{
MemoryContext oldcxt;
HeapTuple ret;
HashPosition pos;
char **values;
zval **element;
int i = 0;
oldcxt = MemoryContextSwitchTo(cxt);
/*
* Use palloc0 to initialize values to NULL, just in case the user does
* not pass all needed attributes
*/
values = (char **) palloc0(attinmeta->tupdesc->natts * sizeof(char *));
/*
* If the input zval is an array, build a tuple using each element as an
* attribute. Exception: if the return tuple has a single element and
* it's an array type, use the whole array as a single value.
*
* If the input zval is a scalar, use it as an element directly.
*/
if (Z_TYPE_P(val) == IS_ARRAY)
{
if (attinmeta->tupdesc->natts == 1)
{
/* Is it an array? */
if (attinmeta->tupdesc->attrs[0]->attndims != 0 ||
!OidIsValid(get_element_type(attinmeta->tupdesc->attrs[0]->atttypid)))
{
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);
zend_hash_get_current_data_ex(Z_ARRVAL_P(val),
(void **) &element,
&pos);
values[0] = plphp_zval_get_cstring(element[0], true, true);
}
else
values[0] = plphp_zval_get_cstring(val, true, true);
}
else
{
/*
* Ok, it's an array and the return tuple has more than one
* attribute, so scan each array element.
*/
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(val), &pos);
zend_hash_get_current_data_ex(Z_ARRVAL_P(val),
(void **) &element,
&pos) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_P(val), &pos))
{
/* avoid overrunning the palloc'ed chunk */
if (i >= attinmeta->tupdesc->natts)
{
elog(WARNING, "more elements in array than attributes in return type");
break;
}
values[i++] = plphp_zval_get_cstring(element[0], true, true);
}
}
}
else
{
/* The passed zval is not an array -- use as the only attribute */
if (attinmeta->tupdesc->natts != 1)
ereport(ERROR,
(errmsg("returned array does not correspond to "
"declared return value")));
values[0] = plphp_zval_get_cstring(val, true, true);
}
MemoryContextSwitchTo(oldcxt);
ret = BuildTupleFromCStrings(attinmeta, values);
MemoryContextReset(cxt);
return ret;
}
/*
* plphp_convert_to_pg_array
* Convert a zval into a Postgres text array representation.
*
* The return value is palloc'ed in the current memory context and
* must be freed by the caller.
*/
char *
plphp_convert_to_pg_array(zval *array)
{
int arr_size;
zval **element;
int i = 0;
HashPosition pos;
StringInfoData str;
initStringInfo(&str);
arr_size = zend_hash_num_elements(Z_ARRVAL_P(array));
appendStringInfoChar(&str, '{');
if (Z_TYPE_P(array) == IS_ARRAY)
{
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos);
zend_hash_get_current_data_ex(Z_ARRVAL_P(array),
(void **) &element,
&pos) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos))
{
char *tmp;
switch (Z_TYPE_P(element[0]))
{
case IS_LONG:
appendStringInfo(&str, "%li", element[0]->value.lval);
break;
case IS_DOUBLE:
appendStringInfo(&str, "%f", element[0]->value.dval);
break;
case IS_STRING:
appendStringInfo(&str, "\"%s\"", element[0]->value.str.val);
break;
case IS_ARRAY:
tmp = plphp_convert_to_pg_array(element[0]);
appendStringInfo(&str, "%s", tmp);
pfree(tmp);
break;
default:
elog(ERROR, "unrecognized element type %d",
Z_TYPE_P(element[0]));
}
if (i != arr_size - 1)
appendStringInfoChar(&str, ',');
i++;
}
}
appendStringInfoChar(&str, '}');
return str.data;
}
/*
* plphp_convert_from_pg_array
* Convert a Postgres text array representation to a PHP array
* (zval type thing).
*
* FIXME -- does not work if there are embedded {'s in the input value.
*
* FIXME -- does not correctly quote/dequote the values
*/
zval *
plphp_convert_from_pg_array(char *input TSRMLS_DC)
{
zval *retval = NULL;
int i;
StringInfoData str;
initStringInfo(&str);
MAKE_STD_ZVAL(retval);
array_init(retval);
for (i = 0; i < strlen(input); i++)
{
if (input[i] == '{')
appendStringInfoString(&str, "array(");
else if (input[i] == '}')
appendStringInfoChar(&str, ')');
else
appendStringInfoChar(&str, input[i]);
}
appendStringInfoChar(&str, ';');
if (zend_eval_string(str.data, retval,
"plphp array input parameter" TSRMLS_CC) == FAILURE)
elog(ERROR, "plphp: convert to internal representation failure");
pfree(str.data);
return retval;
}
/*
* plphp_array_get_elem
* Return a pointer to the array element with the given key
*/
zval *
plphp_array_get_elem(zval *array, char *key)
{
zval **element;
if (!array)
elog(ERROR, "passed zval is not a valid pointer");
if (Z_TYPE_P(array) != IS_ARRAY)
elog(ERROR, "passed zval is not an array");
if (zend_symtable_find(array->value.ht,
key,
strlen(key) + 1,
(void **) &element) != SUCCESS)
return NULL;
return element[0];
}
/*
* zval_get_cstring
* Get a C-string representation of a zval.
*
* All return values, except those that are NULL, are palloc'ed in the current
* memory context and must be freed by the caller.
*
* If the do_array parameter is false, then array values will not be converted
* and an error will be raised instead.
*
* If the null_ok parameter is true, we will return NULL for a NULL zval.
* Otherwise we raise an error.
*/
char *
plphp_zval_get_cstring(zval *val, bool do_array, bool null_ok)
{
char *ret;
if (!val)
{
if (null_ok)
return NULL;
else
elog(ERROR, "invalid zval pointer");
}
switch (Z_TYPE_P(val))
{
case IS_NULL:
return NULL;
case IS_LONG:
ret = palloc(64);
snprintf(ret, 64, "%ld", Z_LVAL_P(val));
break;
case IS_DOUBLE:
ret = palloc(64);
snprintf(ret, 64, "%f", Z_DVAL_P(val));
break;
case IS_BOOL:
ret = palloc(8);
snprintf(ret, 8, "%s", Z_BVAL_P(val) ? "true": "false");
break;
case IS_STRING:
ret = palloc(Z_STRLEN_P(val) + 1);
snprintf(ret, Z_STRLEN_P(val) + 1, "%s",
Z_STRVAL_P(val));
break;
case IS_ARRAY:
if (!do_array)
elog(ERROR, "can't stringize array value");
ret = plphp_convert_to_pg_array(val);
break;
default:
/* keep compiler quiet */
ret = NULL;
elog(ERROR, "can't stringize value of type %d", val->type);
}
return ret;
}
/*
* plphp_build_tuple_argument
*
* Build a PHP array from all attributes of a given tuple
*/
zval *
plphp_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc)
{
int i;
zval *output;
Datum attr;
bool isnull;
char *attname;
char *outputstr;
HeapTuple typeTup;
Oid typoutput;
Oid typioparam;
MAKE_STD_ZVAL(output);
array_init(output);
for (i = 0; i < tupdesc->natts; i++)
{
/* Ignore dropped attributes */
if (tupdesc->attrs[i]->attisdropped)
continue;
/* Get the attribute name */
attname = tupdesc->attrs[i]->attname.data;
/* Get the attribute value */
attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
/* If it is null, set it to undef in the hash. */
if (isnull)
{
add_next_index_unset(output);
continue;
}
/*
* Lookup the attribute type in the syscache for the output function
*/
typeTup = SearchSysCache(TYPEOID,
ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),
0, 0, 0);
if (!HeapTupleIsValid(typeTup))
{
elog(ERROR, "cache lookup failed for type %u",
tupdesc->attrs[i]->atttypid);
}
typoutput = ((Form_pg_type) GETSTRUCT(typeTup))->typoutput;
typioparam = getTypeIOParam(typeTup);
ReleaseSysCache(typeTup);
/* Append the attribute name and the value to the list. */
outputstr =
DatumGetCString(OidFunctionCall3(typoutput, attr,
ObjectIdGetDatum(typioparam),
Int32GetDatum(tupdesc->attrs[i]->atttypmod)));
add_assoc_string(output, attname, outputstr, 1);
pfree(outputstr);
}
return output;
}
/*
* plphp_modify_tuple
* Return the modified NEW tuple, for use as return value in a BEFORE
* trigger. outdata must point to the $_TD variable from the PHP
* function.
*
* The tuple will be allocated in the current memory context and must be freed
* by the caller.
*
* XXX Possible optimization: make this a global context that is not deleted,
* but only reset each time this function is called. (Think about triggers
* calling other triggers though).
*/
HeapTuple
plphp_modify_tuple(zval *outdata, TriggerData *tdata)
{
TupleDesc tupdesc;
HeapTuple rettuple;
zval *newtup;
zval **element;
char **vals;
int i;
AttInMetadata *attinmeta;
MemoryContext tmpcxt,
oldcxt;
tmpcxt = AllocSetContextCreate(CurTransactionContext,
"PL/php NEW context",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
oldcxt = MemoryContextSwitchTo(tmpcxt);
/* Fetch "new" from $_TD */
if (zend_hash_find(outdata->value.ht,
"new", strlen("new") + 1,
(void **) &element) != SUCCESS)
elog(ERROR, "$_TD['new'] not found");
if (Z_TYPE_P(element[0]) != IS_ARRAY)
elog(ERROR, "$_TD['new'] must be an array");
newtup = element[0];
/* Fetch the tupledesc and metadata */
tupdesc = tdata->tg_relation->rd_att;
attinmeta = TupleDescGetAttInMetadata(tupdesc);
i = zend_hash_num_elements(Z_ARRVAL_P(newtup));
if (tupdesc->natts > i)
ereport(ERROR,
(errmsg("insufficient number of keys in $_TD['new']"),
errdetail("At least %d expected, %d found.",
tupdesc->natts, i)));
vals = (char **) palloc(tupdesc->natts * sizeof(char *));
/*
* For each attribute in the tupledesc, get its value from newtup and put
* it in an array of cstrings.
*/
for (i = 0; i < tupdesc->natts; i++)
{
zval **element;
char *attname = NameStr(tupdesc->attrs[i]->attname);
/* Fetch the attribute value from the zval */
if (zend_symtable_find(newtup->value.ht, attname, strlen(attname) + 1,
(void **) &element) != SUCCESS)
elog(ERROR, "$_TD['new'] does not contain attribute \"%s\"",
attname);
vals[i] = plphp_zval_get_cstring(element[0], true, true);
}
/* Return to the original context so that the new tuple will survive */
MemoryContextSwitchTo(oldcxt);
/* Build the tuple */
rettuple = BuildTupleFromCStrings(attinmeta, vals);
/* Free the memory used */
MemoryContextDelete(tmpcxt);
return rettuple;
}
/*
* vim:ts=4:sw=4:cino=(0
*/