forked from commandprompt/PL-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plphp.c
1952 lines (1684 loc) · 51.2 KB
/
plphp.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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* plphp.c - PHP as a procedural language for PostgreSQL
*
* This software is copyright (c) Command Prompt Inc.
*
* The author hereby grants permission to use, copy, modify,
* distribute, and license this software and its documentation for any
* purpose, provided that existing copyright notices are retained in
* all copies and that this notice is included verbatim in any
* distributions. No written agreement, license, or royalty fee is
* required for any of the authorized uses. Modifications to this
* software may be copyrighted by their author and need not follow the
* licensing terms described here, provided that the new terms are
* clearly indicated on the first page of each file where they apply.
*
* IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY
* FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
* DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
* NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
* AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
* MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* IDENTIFICATION
* $Id$
*********************************************************************
*/
/* Package configuration generated by autoconf */
#include "config.h"
/* First round of undefs, to eliminate collision between plphp and postgresql
* definitions
*/
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
/* PostgreSQL stuff */
#include "postgres.h"
#include "access/heapam.h"
#include "access/transam.h"
#include "catalog/catversion.h"
#include "catalog/pg_language.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "funcapi.h" /* needed for SRF support */
#include "lib/stringinfo.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
/*
* These are defined again in php.h, so undef them to avoid some
* cpp warnings.
*/
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
/* PHP stuff */
#include "php.h"
#include "php_variables.h"
#include "php_globals.h"
#include "zend_hash.h"
#include "zend_modules.h"
#include "php_ini.h" /* needed for INI_HARDCODED */
#include "php_main.h"
/* Our own stuff */
#include "plphp_io.h"
#include "plphp_spi.h"
/* system stuff */
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#define INI_HARDCODED(name,value) \
zend_alter_ini_entry(name, sizeof(name), value, strlen(value), \
PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
/* Check for PostgreSQL version */
#if (CATALOG_VERSION_NO >= 200709301)
#define PG_VERSION_83_COMPAT
#endif
#if (CATALOG_VERSION_NO >= 200611241)
#define PG_VERSION_82_COMPAT
#endif
/* We only support 8.1 and above */
#if (CATALOG_VERSION_NO >= 200510211)
#define PG_VERSION_81_COMPAT
#else
#error "Unsupported PostgreSQL version"
#endif
#undef DEBUG_PLPHP_MEMORY
#ifdef DEBUG_PLPHP_MEMORY
#define REPORT_PHP_MEMUSAGE(where) \
elog(NOTICE, "PHP mem usage: %s: %u", where, AG(allocated_memory));
#else
#define REPORT_PHP_MEMUSAGE(a)
#endif
/* PostgreSQL starting from v 8.2 requires this define
* for all modules.
*/
#ifdef PG_VERSION_82_COMPAT
PG_MODULE_MAGIC;
#else
/* Supress warnings on 8.1 and below */
#define ReleaseTupleDesc(tupdesc)
#endif
/* PHP 5.2 and earlier do not contain these definitions */
#ifndef Z_SET_ISREF_P
#define Z_SET_ISREF_P(foo) (foo)->is_ref = 1
#define Z_UNSET_ISREF_P(foo) (foo)->is_ref = 0
#endif
/* 8.2 compatibility */
#ifndef TYPTYPE_PSEUDO
#define TYPTYPE_PSEUDO 'p'
#define TYPTYPE_COMPOSITE 'c'
#endif
/* Check the argument type to expect to accept an initial value */
#define IS_ARGMODE_OUT(mode) ((mode) == PROARGMODE_OUT || \
(mode) == PROARGMODE_TABLE)
/*
* Return types. Why on earth is this a bitmask? Beats me.
* We should have separate flags instead.
*/
typedef enum pl_type
{
PL_TUPLE = 1 << 0,
PL_ARRAY = 1 << 1,
PL_PSEUDO = 1 << 2
} pl_type;
/*
* The information we cache about loaded procedures.
*
* "proname" is the name of the function, given by the user.
*
* fn_xmin and fn_cmin are used to know when a function has been redefined and
* needs to be recompiled.
*
* trusted indicates whether the function was created with a trusted handler.
*
* ret_type is a weird bitmask that indicates whether this function returns a
* tuple, an array or a pseudotype. ret_oid is the Oid of the return type.
* retset indicates whether the function was declared to return a set.
*
* arg_argmode indicates whether the argument is IN, OUT or both. It follows
* values in pg_proc.proargmodes.
*
* n_out_args - total number of OUT or INOUT arguments.
* arg_out_tupdesc is a tuple descriptor of the tuple constructed for OUT args.
*
* XXX -- maybe this thing needs to be rethought.
*/
typedef struct plphp_proc_desc
{
char *proname;
TransactionId fn_xmin;
CommandId fn_cmin;
bool trusted;
pl_type ret_type;
Oid ret_oid; /* Oid of returning type */
bool retset;
FmgrInfo result_in_func;
Oid result_typioparam;
int n_out_args;
int n_total_args;
int n_mixed_args;
FmgrInfo arg_out_func[FUNC_MAX_ARGS];
Oid arg_typioparam[FUNC_MAX_ARGS];
char arg_typtype[FUNC_MAX_ARGS];
char arg_argmode[FUNC_MAX_ARGS];
TupleDesc args_out_tupdesc;
} plphp_proc_desc;
/*
* Global data
*/
static bool plphp_first_call = true;
static zval *plphp_proc_array = NULL;
/* for PHP write/flush */
static StringInfo currmsg = NULL;
/*
* for PHP <-> Postgres error message passing
*
* XXX -- it would be much better if we could save errcontext,
* errhint, etc as well.
*/
static char *error_msg = NULL;
/*
* Forward declarations
*/
static void plphp_init_all(void);
void plphp_init(void);
PG_FUNCTION_INFO_V1(plphp_call_handler);
Datum plphp_call_handler(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(plphp_validator);
Datum plphp_validator(PG_FUNCTION_ARGS);
static Datum plphp_trigger_handler(FunctionCallInfo fcinfo,
plphp_proc_desc *desc
TSRMLS_DC);
static Datum plphp_func_handler(FunctionCallInfo fcinfo,
plphp_proc_desc *desc
TSRMLS_DC);
static Datum plphp_srf_handler(FunctionCallInfo fcinfo,
plphp_proc_desc *desc
TSRMLS_DC);
static plphp_proc_desc *plphp_compile_function(Oid fnoid, bool is_trigger TSRMLS_DC);
static zval *plphp_call_php_func(plphp_proc_desc *desc,
FunctionCallInfo fcinfo
TSRMLS_DC);
static zval *plphp_call_php_trig(plphp_proc_desc *desc,
FunctionCallInfo fcinfo, zval *trigdata
TSRMLS_DC);
static void plphp_error_cb(int type, const char *filename, const uint lineno,
const char *fmt, va_list args);
static bool is_valid_php_identifier(char *name);
/*
* FIXME -- this comment is quite misleading actually, which is not surprising
* since it came verbatim from PL/pgSQL. Rewrite memory handling here someday
* and remove it.
*
* This routine is a crock, and so is everyplace that calls it. The problem
* is that the cached form of plphp functions/queries is allocated permanently
* (mostly via malloc()) and never released until backend exit. Subsidiary
* data structures such as fmgr info records therefore must live forever
* as well. A better implementation would store all this stuff in a per-
* function memory context that could be reclaimed at need. In the meantime,
* fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
* it might allocate, and whatever the eventual function might allocate using
* fn_mcxt, will live forever too.
*/
static void
perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
{
fmgr_info_cxt(functionId, finfo, TopMemoryContext);
}
/*
* sapi_plphp_write
* Called when PHP wants to write something to stdout.
*
* We just save the output in a StringInfo until the next Flush call.
*/
static int
sapi_plphp_write(const char *str, uint str_length TSRMLS_DC)
{
if (currmsg == NULL)
currmsg = makeStringInfo();
appendStringInfoString(currmsg, str);
return str_length;
}
/*
* sapi_plphp_flush
* Called when PHP wants to flush stdout.
*
* The stupid PHP implementation calls write and follows with a Flush right
* away -- a good implementation would write several times and flush when the
* message is complete. To make the output look reasonable in Postgres, we
* skip the flushing if the accumulated message does not end in a newline.
*/
static void
sapi_plphp_flush(void *sth)
{
if (currmsg != NULL)
{
Assert(currmsg->data != NULL);
if (currmsg->data[currmsg->len - 1] == '\n')
{
/*
* remove the trailing newline because elog() inserts another
* one
*/
currmsg->data[currmsg->len - 1] = '\0';
}
elog(LOG, "%s", currmsg->data);
pfree(currmsg->data);
pfree(currmsg);
currmsg = NULL;
}
else
elog(LOG, "attempting to flush a NULL message");
}
static int
sapi_plphp_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
{
return 1;
}
static void
php_plphp_log_messages(char *message)
{
elog(LOG, "plphp: %s", message);
}
static sapi_module_struct plphp_sapi_module = {
"plphp", /* name */
"PL/php PostgreSQL Handler",/* pretty name */
NULL, /* startup */
php_module_shutdown_wrapper,/* shutdown */
NULL, /* activate */
NULL, /* deactivate */
sapi_plphp_write, /* unbuffered write */
sapi_plphp_flush, /* flush */
NULL, /* stat */
NULL, /* getenv */
php_error, /* sapi_error(int, const char *, ...) */
NULL, /* header handler */
sapi_plphp_send_headers, /* send headers */
NULL, /* send header */
NULL, /* read POST */
NULL, /* read cookies */
NULL, /* register server variables */
php_plphp_log_messages, /* log message */
NULL, /* Block interrupts */
NULL, /* Unblock interrupts */
STANDARD_SAPI_MODULE_PROPERTIES
};
/*
* plphp_init_all() - Initialize all
*
* XXX This is called each time a function is invoked.
*/
static void
plphp_init_all(void)
{
/* Execute postmaster-startup safe initialization */
if (plphp_first_call)
plphp_init();
/*
* Any other initialization that must be done each time a new
* backend starts -- currently none.
*/
}
/*
* This function must not be static, so that it can be used in
* preload_libraries. If it is, it will be called by postmaster;
* otherwise it will be called by each backend the first time a
* function is called.
*/
void
plphp_init(void)
{
TSRMLS_FETCH();
/* Do initialization only once */
if (!plphp_first_call)
return;
/*
* Need a Pg try/catch block to prevent an initialization-
* failure from bringing the whole server down.
*/
PG_TRY();
{
zend_try
{
/*
* XXX This is a hack -- we are replacing the error callback in an
* invasive manner that should not be expected to work on future PHP
* releases.
*/
zend_error_cb = plphp_error_cb;
/* Omit HTML tags from output */
plphp_sapi_module.phpinfo_as_text = 1;
sapi_startup(&plphp_sapi_module);
if (php_module_startup(&plphp_sapi_module, NULL, 0) == FAILURE)
elog(ERROR, "php_module_startup call failed");
/* php_module_startup changed it, so put it back */
zend_error_cb = plphp_error_cb;
/*
* FIXME -- Figure out what this comment is supposed to mean:
*
* There is no way to see if we must call zend_ini_deactivate()
* since we cannot check if EG(ini_directives) has been initialised
* because the executor's constructor does not initialize it.
* Apart from that there seems no need for zend_ini_deactivate() yet.
* So we error out.
*/
/* Init procedure cache */
MAKE_STD_ZVAL(plphp_proc_array);
array_init(plphp_proc_array);
zend_register_functions(
#if PHP_MAJOR_VERSION == 5
NULL,
#endif
spi_functions, NULL,
MODULE_PERSISTENT TSRMLS_CC);
PG(during_request_startup) = true;
/* Set some defaults */
SG(options) |= SAPI_OPTION_NO_CHDIR;
/* Hard coded defaults which cannot be overwritten in the ini file */
INI_HARDCODED("register_argc_argv", "0");
INI_HARDCODED("html_errors", "0");
INI_HARDCODED("implicit_flush", "1");
INI_HARDCODED("max_execution_time", "0");
INI_HARDCODED("max_input_time", "-1");
/*
* Set memory limit to ridiculously high value. This helps the
* server not to crash, because the PHP allocator has the really
* stupid idea of calling exit() if the limit is exceeded.
*/
{
char limit[15];
snprintf(limit, sizeof(limit), "%d", 1 << 30);
INI_HARDCODED("memory_limit", limit);
}
/* tell the engine we're in non-html mode */
zend_uv.html_errors = false;
/* not initialized but needed for several options */
CG(in_compilation) = false;
EG(uninitialized_zval_ptr) = NULL;
if (php_request_startup(TSRMLS_C) == FAILURE)
{
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
/* Use Postgres log */
elog(ERROR, "php_request_startup call failed");
}
CG(interactive) = false;
PG(during_request_startup) = true;
/* Register the resource for SPI_result */
SPIres_rtype = zend_register_list_destructors_ex(php_SPIresult_destroy,
NULL,
"SPI result",
0);
/* Ok, we're done */
plphp_first_call = false;
}
zend_catch
{
plphp_first_call = true;
if (error_msg)
{
char str[1024];
strncpy(str, error_msg, sizeof(str));
pfree(error_msg);
error_msg = NULL;
elog(ERROR, "fatal error during PL/php initialization: %s",
str);
}
else
elog(ERROR, "fatal error during PL/php initialization");
}
zend_end_try();
}
PG_CATCH();
{
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* plphp_call_handler
*
* The visible function of the PL interpreter. The PostgreSQL function manager
* and trigger manager call this function for execution of php procedures.
*/
Datum
plphp_call_handler(PG_FUNCTION_ARGS)
{
Datum retval;
TSRMLS_FETCH();
/* Initialize interpreter */
plphp_init_all();
PG_TRY();
{
/* Connect to SPI manager */
if (SPI_connect() != SPI_OK_CONNECT)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_FAILURE),
errmsg("could not connect to SPI manager")));
zend_try
{
plphp_proc_desc *desc;
/* Clean up SRF state */
current_fcinfo = NULL;
/* Redirect to the appropiate handler */
if (CALLED_AS_TRIGGER(fcinfo))
{
desc = plphp_compile_function(fcinfo->flinfo->fn_oid, true TSRMLS_CC);
/* Activate PHP safe mode if needed */
PG(safe_mode) = desc->trusted;
retval = plphp_trigger_handler(fcinfo, desc TSRMLS_CC);
}
else
{
desc = plphp_compile_function(fcinfo->flinfo->fn_oid, false TSRMLS_CC);
/* Activate PHP safe mode if needed */
PG(safe_mode) = desc->trusted;
if (desc->retset)
retval = plphp_srf_handler(fcinfo, desc TSRMLS_CC);
else
retval = plphp_func_handler(fcinfo, desc TSRMLS_CC);
}
}
zend_catch
{
REPORT_PHP_MEMUSAGE("reporting error");
if (error_msg)
{
char str[1024];
strncpy(str, error_msg, sizeof(str));
pfree(error_msg);
error_msg = NULL;
elog(ERROR, "%s", str);
}
else
elog(ERROR, "fatal error");
/* not reached, but keep compiler quiet */
return 0;
}
zend_end_try();
}
PG_CATCH();
{
PG_RE_THROW();
}
PG_END_TRY();
return retval;
}
/*
* plphp_validator
*
* Validator function for checking the function's syntax at creation
* time
*/
Datum
plphp_validator(PG_FUNCTION_ARGS)
{
Oid funcoid = PG_GETARG_OID(0);
Form_pg_proc procForm;
HeapTuple procTup;
char tmpname[32];
char funcname[NAMEDATALEN];
char *tmpsrc = NULL,
*prosrc;
Datum prosrcdatum;
TSRMLS_FETCH();
/* Initialize interpreter */
plphp_init_all();
PG_TRY();
{
bool isnull;
/* Grab the pg_proc tuple */
procTup = SearchSysCache(PROCOID,
ObjectIdGetDatum(funcoid),
0, 0, 0);
if (!HeapTupleIsValid(procTup))
elog(ERROR, "cache lookup failed for function %u", funcoid);
procForm = (Form_pg_proc) GETSTRUCT(procTup);
/* Get the function source code */
prosrcdatum = SysCacheGetAttr(PROCOID,
procTup,
Anum_pg_proc_prosrc,
&isnull);
if (isnull)
elog(ERROR, "cache lookup yielded NULL prosrc");
prosrc = DatumGetCString(DirectFunctionCall1(textout,
prosrcdatum));
/* Get the function name, for the error message */
StrNCpy(funcname, NameStr(procForm->proname), NAMEDATALEN);
/* Let go of the pg_proc tuple */
ReleaseSysCache(procTup);
/* Create a PHP function creation statement */
snprintf(tmpname, sizeof(tmpname), "plphp_temp_%u", funcoid);
tmpsrc = (char *) palloc(strlen(prosrc) +
strlen(tmpname) +
strlen("function ($args, $argc){ } "));
sprintf(tmpsrc, "function %s($args, $argc){%s}",
tmpname, prosrc);
pfree(prosrc);
zend_try
{
/*
* Delete the function from the PHP function table, just in case it
* already existed. This is quite unlikely, but still.
*/
zend_hash_del(CG(function_table), tmpname, strlen(tmpname) + 1);
/*
* Let the user see the fireworks. If the function doesn't validate,
* the ERROR will be raised and the function will not be created.
*/
if (zend_eval_string(tmpsrc, NULL,
"plphp function temp source" TSRMLS_CC) == FAILURE)
elog(ERROR, "function \"%s\" does not validate", funcname);
pfree(tmpsrc);
tmpsrc = NULL;
/* Delete the newly-created function from the PHP function table. */
zend_hash_del(CG(function_table), tmpname, strlen(tmpname) + 1);
}
zend_catch
{
if (tmpsrc != NULL)
pfree(tmpsrc);
if (error_msg)
{
char str[1024];
StrNCpy(str, error_msg, sizeof(str));
pfree(error_msg);
error_msg = NULL;
elog(ERROR, "function \"%s\" does not validate: %s", funcname, str);
}
else
elog(ERROR, "fatal error");
/* not reached, but keep compiler quiet */
return 0;
}
zend_end_try();
/* The result of a validator is ignored */
PG_RETURN_VOID();
}
PG_CATCH();
{
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* plphp_get_function_tupdesc
*
* Returns a TupleDesc of the function's return type.
*/
static TupleDesc
plphp_get_function_tupdesc(Oid result_type, Node *rsinfo)
{
if (result_type == RECORDOID)
{
ReturnSetInfo *rs = (ReturnSetInfo *) rsinfo;
/* We must get the information from call context */
if (!rsinfo || !IsA(rsinfo, ReturnSetInfo) || rs->expectedDesc == NULL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
return rs->expectedDesc;
}
else
/* ordinary composite type */
return lookup_rowtype_tupdesc(result_type, -1);
}
/*
* Build the $_TD array for the trigger function.
*/
static zval *
plphp_trig_build_args(FunctionCallInfo fcinfo)
{
TriggerData *tdata;
TupleDesc tupdesc;
zval *retval;
int i;
MAKE_STD_ZVAL(retval);
array_init(retval);
tdata = (TriggerData *) fcinfo->context;
tupdesc = tdata->tg_relation->rd_att;
/* The basic variables */
add_assoc_string(retval, "name", tdata->tg_trigger->tgname, 1);
add_assoc_long(retval, "relid", tdata->tg_relation->rd_id);
add_assoc_string(retval, "relname", SPI_getrelname(tdata->tg_relation), 1);
add_assoc_string(retval, "schemaname", SPI_getnspname(tdata->tg_relation), 1);
/* EVENT */
if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
add_assoc_string(retval, "event", "INSERT", 1);
else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
add_assoc_string(retval, "event", "DELETE", 1);
else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
add_assoc_string(retval, "event", "UPDATE", 1);
else
elog(ERROR, "unknown firing event for trigger function");
/* NEW and OLD as appropiate */
if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
{
if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
{
zval *hashref;
hashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);
add_assoc_zval(retval, "new", hashref);
}
else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
{
zval *hashref;
hashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);
add_assoc_zval(retval, "old", hashref);
}
else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
{
zval *hashref;
hashref = plphp_build_tuple_argument(tdata->tg_newtuple, tupdesc);
add_assoc_zval(retval, "new", hashref);
hashref = plphp_build_tuple_argument(tdata->tg_trigtuple, tupdesc);
add_assoc_zval(retval, "old", hashref);
}
else
elog(ERROR, "unknown firing event for trigger function");
}
/* ARGC and ARGS */
add_assoc_long(retval, "argc", tdata->tg_trigger->tgnargs);
if (tdata->tg_trigger->tgnargs > 0)
{
zval *hashref;
MAKE_STD_ZVAL(hashref);
array_init(hashref);
for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
add_index_string(hashref, i, tdata->tg_trigger->tgargs[i], 1);
zend_hash_update(retval->value.ht, "args", strlen("args") + 1,
(void *) &hashref, sizeof(zval *), NULL);
}
/* WHEN */
if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
add_assoc_string(retval, "when", "BEFORE", 1);
else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
add_assoc_string(retval, "when", "AFTER", 1);
else
elog(ERROR, "unknown firing time for trigger function");
/* LEVEL */
if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
add_assoc_string(retval, "level", "ROW", 1);
else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
add_assoc_string(retval, "level", "STATEMENT", 1);
else
elog(ERROR, "unknown firing level for trigger function");
return retval;
}
/*
* plphp_trigger_handler
* Handler for trigger function calls
*/
static Datum
plphp_trigger_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)
{
Datum retval = 0;
char *srv;
zval *phpret,
*zTrigData;
TriggerData *trigdata;
REPORT_PHP_MEMUSAGE("going to build the trigger arg");
zTrigData = plphp_trig_build_args(fcinfo);
REPORT_PHP_MEMUSAGE("going to call the trigger function");
phpret = plphp_call_php_trig(desc, fcinfo, zTrigData TSRMLS_CC);
if (!phpret)
elog(ERROR, "error during execution of function %s", desc->proname);
REPORT_PHP_MEMUSAGE("trigger called, going to build the return value");
/*
* Disconnect from SPI manager and then create the return values datum (if
* the input function does a palloc for it this must not be allocated in
* the SPI memory context because SPI_finish would free it).
*/
if (SPI_finish() != SPI_OK_FINISH)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
errmsg("could not disconnect from SPI manager")));
trigdata = (TriggerData *) fcinfo->context;
if (zTrigData->type != IS_ARRAY)
elog(ERROR, "$_TD is not an array");
/*
* In a BEFORE trigger, compute the return value. In an AFTER trigger
* it'll be ignored, so don't bother.
*/
if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
{
switch (phpret->type)
{
case IS_STRING:
srv = phpret->value.str.val;
if (strcasecmp(srv, "SKIP") == 0)
{
/* do nothing */
break;
}
else if (strcasecmp(srv, "MODIFY") == 0)
{
if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||
TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
retval = PointerGetDatum(plphp_modify_tuple(zTrigData,
trigdata));
else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("on delete trigger can not modify the the return tuple")));
else
elog(ERROR, "unknown event in trigger function");
}
else
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("expected trigger function to return NULL, 'SKIP' or 'MODIFY'")));
break;
case IS_NULL:
if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||
TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
retval = (Datum) trigdata->tg_trigtuple;
else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
retval = (Datum) trigdata->tg_newtuple;
break;
default:
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("expected trigger function to return NULL, 'SKIP' or 'MODIFY'")));
break;
}
}
REPORT_PHP_MEMUSAGE("freeing some variables");
zval_dtor(zTrigData);
zval_dtor(phpret);
FREE_ZVAL(phpret);
FREE_ZVAL(zTrigData);
REPORT_PHP_MEMUSAGE("trigger call done");
return retval;
}
/*
* plphp_func_handler
* Handler for regular function calls
*/
static Datum
plphp_func_handler(FunctionCallInfo fcinfo, plphp_proc_desc *desc TSRMLS_DC)
{
zval *phpret = NULL;
Datum retval;
char *retvalbuffer = NULL;
/* SRFs are handled separately */
Assert(!desc->retset);
/* Call the PHP function. */
phpret = plphp_call_php_func(desc, fcinfo TSRMLS_CC);
if (!phpret)
elog(ERROR, "error during execution of function %s", desc->proname);
REPORT_PHP_MEMUSAGE("function invoked");
/* Basic datatype checks */
if ((desc->ret_type & PL_ARRAY) && phpret->type != IS_ARRAY)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("function declared to return array must return an array")));
if ((desc->ret_type & PL_TUPLE) && phpret->type != IS_ARRAY)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("function declared to return tuple must return an array")));
/*
* Disconnect from SPI manager and then create the return values datum (if
* the input function does a palloc for it this must not be allocated in
* the SPI memory context because SPI_finish would free it).
*/
if (SPI_finish() != SPI_OK_FINISH)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
errmsg("could not disconnect from SPI manager")));
retval = (Datum) 0;
if (desc->ret_type & PL_PSEUDO)
{
HeapTuple retTypeTup;