70f32da7bcbfac48dd70612c97e74a86ecf9b29b
[m6w6/ext-pq] / src / php_pq_misc.c
1 /*
2 +--------------------------------------------------------------------+
3 | PECL :: pq |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted provided that the conditions mentioned |
7 | in the accompanying LICENSE file are met. |
8 +--------------------------------------------------------------------+
9 | Copyright (c) 2013, Michael Wallner <mike@php.net> |
10 +--------------------------------------------------------------------+
11 */
12
13 #ifdef HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include <php.h>
18 #include <ext/date/php_date.h>
19 #include <ext/standard/php_string.h>
20
21 #include <Zend/zend_interfaces.h>
22
23 #include <libpq/libpq-fs.h>
24
25 #include "php_pq.h"
26 #include "php_pqexc.h"
27 #include "php_pq_misc.h"
28 #include "php_pqconn_event.h"
29 #undef PHP_PQ_TYPE
30 #include "php_pq_type.h"
31
32
33 /* clear result object associated with a result handle */
34 void php_pqres_clear(PGresult *r) {
35 php_pq_object_t *o = PQresultInstanceData(r, php_pqconn_event);
36
37 if (o) {
38 php_pq_object_delref(o);
39 } else {
40 PQclear(r);
41 }
42 }
43
44 /* clear any asynchronous results */
45 void php_pqconn_clear(PGconn *conn) {
46 PGresult *r;
47 php_pqconn_event_data_t *evdata = PQinstanceData(conn, php_pqconn_event);
48
49 while ((r = PQgetResult(conn))) {
50 php_pqres_clear(r);
51 }
52
53 if (evdata && evdata->obj) {
54 if (php_pq_callback_is_enabled(&evdata->obj->intern->onevent)) {
55 if (php_pq_callback_is_locked(&evdata->obj->intern->onevent)) {
56 php_pq_callback_disable(&evdata->obj->intern->onevent);
57 } else {
58 php_pq_callback_dtor(&evdata->obj->intern->onevent);
59 }
60 }
61 }
62 }
63
64 /* safe wrappers to clear any asynchronous wrappers before querying synchronously */
65 PGresult *php_pq_exec(PGconn *conn, const char *query) {
66 php_pqconn_clear(conn);
67 return PQexec(conn, query);
68 }
69 PGresult *php_pq_exec_params(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const * paramValues, const int *paramLengths, const int *paramFormats, int resultFormat) {
70 php_pqconn_clear(conn);
71 return PQexecParams(conn, command, nParams, paramTypes, paramValues, paramLengths, paramFormats, resultFormat);
72 }
73 PGresult *php_pq_prepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes) {
74 php_pqconn_clear(conn);
75 return PQprepare(conn, stmtName, query, nParams, paramTypes);
76 }
77 PGresult *php_pq_exec_prepared(PGconn *conn, const char *stmtName, int nParams, const char *const * paramValues, const int *paramLengths, const int *paramFormats, int resultFormat) {
78 php_pqconn_clear(conn);
79 return PQexecPrepared(conn, stmtName, nParams, paramValues, paramLengths, paramFormats, resultFormat);
80 }
81
82 char *php_pq_rtrim(char *e)
83 {
84 size_t l = strlen(e);
85
86 while (l-- > 0 && e[l] == '\n') {
87 e[l] = '\0';
88 }
89 return e;
90 }
91
92 const char *php_pq_strmode(long mode)
93 {
94 switch (mode & (INV_READ|INV_WRITE)) {
95 case INV_READ|INV_WRITE:
96 return "rw";
97 case INV_READ:
98 return "r";
99 case INV_WRITE:
100 return "w";
101 default:
102 return "-";
103 }
104 }
105
106 static inline int compare_index(zend_ulong l, zend_ulong r)
107 {
108 if (l < r) {
109 return -1;
110 }
111 if (l > r) {
112 return 1;
113 }
114 return 0;
115 }
116 #if PHP_VERSION_ID >= 80000
117 int php_pq_compare_index(Bucket *lptr, Bucket *rptr)
118 {
119 return compare_index(lptr->h, rptr->h);
120 }
121 #else
122 int php_pq_compare_index(const void *lptr, const void *rptr) {
123 return compare_index(((const Bucket *) lptr)->h, ((const Bucket *) rptr)->h);
124 }
125 #endif
126
127 void php_pq_hash_ptr_dtor(zval *p)
128 {
129 efree(Z_PTR_P(p));
130 }
131
132 zend_class_entry *php_pqdt_class_entry;
133
134 #if PHP_VERSION_ID >= 80100
135 ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_TYPE_INFO_EX(ai_pqdt_jsonserialize, 0, 0, IS_MIXED, 0)
136 ZEND_END_ARG_INFO()
137 #else
138 #define ai_pqdt_jsonserialize ai_pqdt_to_string
139 #endif
140
141 ZEND_BEGIN_ARG_INFO_EX(ai_pqdt_to_string, 0, 0, 0)
142 ZEND_END_ARG_INFO();
143 static PHP_METHOD(pqdt, __toString)
144 {
145 zval rv, tmp;
146
147 ZVAL_NULL(&rv);
148 php_pq_call_method(getThis(), "format", 1, &rv, php_pq_read_property(getThis(), "format", &tmp));
149 RETVAL_ZVAL(&rv, 1, 1);
150 }
151
152 #if PHP_VERSION_ID >= 80100
153 ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_OBJ_TYPE_MASK_EX(ai_pqdt_create_from_format, 0, 2, DateTime, MAY_BE_FALSE)
154 #else
155 ZEND_BEGIN_ARG_INFO_EX(ai_pqdt_create_from_format, 0, 0, 2)
156 #endif
157 ZEND_ARG_INFO(0, format)
158 ZEND_ARG_INFO(0, datetime)
159 #if PHP_VERSION_ID >= 70200
160 ZEND_ARG_OBJ_INFO(0, object, DateTimeZone, 1)
161 #else
162 ZEND_ARG_INFO(0, timezone)
163 #endif
164 ZEND_END_ARG_INFO();
165 static PHP_METHOD(pqdt, createFromFormat)
166 {
167 zend_error_handling zeh;
168 char *fmt_str, *dt_str;
169 size_t fmt_len, dt_len;
170 zval *ztz = NULL;
171 ZEND_RESULT_CODE rv;
172
173 zend_replace_error_handling(EH_THROW, exce(EX_INVALID_ARGUMENT), &zeh);
174 rv = zend_parse_parameters(ZEND_NUM_ARGS(), "ss|O", &fmt_str, &fmt_len, &dt_str, &dt_len, &ztz, php_date_get_timezone_ce());
175 zend_restore_error_handling(&zeh);
176
177 if (SUCCESS == rv) {
178 php_pqdt_from_string(return_value, fmt_str, dt_str, dt_len, "Y-m-d H:i:s.uO", ztz);
179 }
180 }
181
182 static zend_function_entry php_pqdt_methods[] = {
183 PHP_ME(pqdt, createFromFormat, ai_pqdt_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
184 PHP_ME(pqdt, __toString, ai_pqdt_to_string, ZEND_ACC_PUBLIC)
185 PHP_MALIAS(pqdt, jsonSerialize, __toString, ai_pqdt_jsonserialize, ZEND_ACC_PUBLIC)
186 {0}
187 };
188
189 zval *php_pqdt_from_string(zval *zv, char *input_fmt, char *dt_str, size_t dt_len, const char *output_fmt, zval *ztimezone)
190 {
191 php_date_obj *dobj;
192
193 php_date_instantiate(php_pqdt_class_entry, zv);
194 dobj = php_date_obj_from_obj(Z_OBJ_P(zv));
195 if (!php_date_initialize(dobj, dt_str, dt_len, input_fmt, ztimezone, 1)) {
196 zval_dtor(zv);
197 ZVAL_NULL(zv);
198 } else if (output_fmt) {
199 zval fmt;
200 ZVAL_STRING(&fmt, output_fmt);
201 php_pq_update_property(zv, "format", &fmt);
202 zval_ptr_dtor(&fmt);
203 }
204
205 return zv;
206 }
207
208 zend_string *php_pqdt_to_string(zval *zdt, const char *format)
209 {
210 zval rv;
211
212 ZVAL_NULL(&rv);
213
214 if (php_pq_cast_object(zdt, IS_STRING, &rv)) {
215 return Z_STR(rv);
216 } else if (instanceof_function(Z_OBJCE_P(zdt), php_date_get_date_ce())) {
217 zval rv, zfmt;
218
219 ZVAL_NULL(&rv);
220 ZVAL_STRING(&zfmt, format);
221 php_pq_call_method(zdt, "format", 1, &rv, &zfmt);
222 zval_ptr_dtor(&zfmt);
223
224 if (Z_TYPE(rv) == IS_STRING) {
225 return Z_STR(rv);
226 }
227 zval_ptr_dtor(&rv);
228 }
229
230 return NULL;
231 }
232
233 zend_class_entry *php_pqconv_class_entry;
234
235 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_types, 0, 0, 0)
236 ZEND_END_ARG_INFO();
237
238 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_from_string, 0, 0, 2)
239 ZEND_ARG_INFO(0, data)
240 ZEND_ARG_INFO(0, type)
241 ZEND_END_ARG_INFO();
242
243 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_to_string, 0, 0, 2)
244 ZEND_ARG_INFO(0, data)
245 ZEND_ARG_INFO(0, type)
246 ZEND_END_ARG_INFO();
247
248 zend_function_entry php_pqconv_methods[] = {
249 PHP_ABSTRACT_ME(pqconv, convertTypes, ai_pqconv_convert_types)
250 PHP_ABSTRACT_ME(pqconv, convertFromString, ai_pqconv_convert_from_string)
251 PHP_ABSTRACT_ME(pqconv, convertToString, ai_pqconv_convert_to_string)
252 {0}
253 };
254
255
256 PHP_MINIT_FUNCTION(pq_misc)
257 {
258 zend_class_entry *json, ce = {0};
259
260 INIT_NS_CLASS_ENTRY(ce, "pq", "Converter", php_pqconv_methods);
261 php_pqconv_class_entry = zend_register_internal_interface(&ce);
262
263 memset(&ce, 0, sizeof(ce));
264 INIT_NS_CLASS_ENTRY(ce ,"pq", "DateTime", php_pqdt_methods);
265 php_pqdt_class_entry = zend_register_internal_class_ex(&ce, php_date_get_date_ce());
266
267 zend_declare_property_stringl(php_pqdt_class_entry, ZEND_STRL("format"), ZEND_STRL("Y-m-d H:i:s.uO"), ZEND_ACC_PUBLIC);
268
269 /* stop reading this file right here! */
270 if ((json = zend_hash_str_find_ptr(CG(class_table), ZEND_STRL("jsonserializable")))) {
271 zend_class_implements(php_pqdt_class_entry, 1, json);
272 }
273
274 return SUCCESS;
275 }
276
277 typedef struct _HashTableList {
278 zval arr;
279 struct _HashTableList *parent;
280 } HashTableList;
281
282 typedef struct _ArrayParserState {
283 const char *ptr, *end;
284 HashTableList *list;
285 php_pqres_t *res;
286 Oid typ;
287 unsigned quotes:1;
288 unsigned escaped:1;
289 } ArrayParserState;
290
291 static char caa(ArrayParserState *a, const char *any, unsigned advance)
292 {
293 const char *p = any;
294
295 do {
296 if (*p == *a->ptr) {
297 a->ptr += advance;
298 return *p;
299 }
300 } while (*++p);
301
302 php_error_docref(NULL, E_WARNING, "Failed to parse array: expected one of '%s', got '%c'", any, *a->ptr); \
303 return 0;
304 }
305
306 static ZEND_RESULT_CODE add_element(ArrayParserState *a, const char *start)
307 {
308 zval zelem;
309 zend_string *zstr = zend_string_init(start, a->ptr - start, 0);
310
311 if (a->quotes) {
312 php_stripslashes(zstr);
313 ZVAL_STR(&zelem, zstr);
314 } else if (!zend_string_equals_literal(zstr, "NULL")) {
315 ZVAL_STR(&zelem, zstr);
316 } else {
317 zend_string_release(zstr);
318 ZVAL_NULL(&zelem);
319 }
320
321 if (!ZVAL_IS_NULL(&zelem)) {
322 php_pqres_typed_zval(a->res, a->typ, &zelem);
323 }
324
325 add_next_index_zval(&a->list->arr, &zelem);
326 return SUCCESS;
327 }
328
329 static ZEND_RESULT_CODE parse_array(ArrayParserState *a);
330
331 static ZEND_RESULT_CODE parse_element(ArrayParserState *a, char delim)
332 {
333 const char *el;
334
335 switch (*a->ptr) {
336 case '{':
337 return parse_array(a);
338
339 case '}':
340 return SUCCESS;
341
342 case '"':
343 a->quotes = 1;
344 ++a->ptr;
345 break;
346 }
347
348 for (el = a->ptr; a->ptr < a->end; ++a->ptr) {
349 switch (*a->ptr) {
350 case '\\':
351 a->escaped = !a->escaped;
352 break;
353
354 case '"':
355 if (a->escaped) {
356 a->escaped = 0;
357 } else if (a->quotes) {
358 if (SUCCESS != add_element(a, el)) {
359 return FAILURE;
360 }
361 a->quotes = 0;
362 ++a->ptr;
363 return SUCCESS;
364 } else {
365 php_error_docref(NULL, E_WARNING, "Failed to parse element, unexpected quote: '%.*s'", (int) (a->ptr - el), el);
366 return FAILURE;
367 }
368 break;
369
370 default:
371 if (delim != *a->ptr) {
372 a->escaped = 0;
373 break;
374 }
375 /* no break */
376 case '}':
377 if (!a->quotes) {
378 return add_element(a, el);
379 }
380 break;
381
382 }
383 }
384
385 php_error_docref(NULL, E_WARNING, "Failed to parse element, reached end of input");
386 return FAILURE;
387 }
388
389 static ZEND_RESULT_CODE parse_elements(ArrayParserState *a)
390 {
391 char delims[] = {'}', (char) PHP_PQ_DELIM_OF_ARRAY(a->typ), 0};
392
393 while (SUCCESS == parse_element(a, delims[1])) {
394 switch (caa(a, delims, 0)) {
395 case 0:
396 return FAILURE;
397
398 case '}':
399 return SUCCESS;
400
401 default:
402 if (!*++a->ptr) {
403 php_error_docref(NULL, E_WARNING, "Failed to parse elements, reached end of input");
404 return FAILURE;
405 }
406 break;
407 }
408 }
409
410 return FAILURE;
411 }
412
413 static ZEND_RESULT_CODE parse_array(ArrayParserState *a)
414 {
415 HashTableList *list;
416
417 if (!caa(a, "{", 1)) {
418 return FAILURE;
419 }
420
421 list = ecalloc(1, sizeof(*list));
422 array_init(&list->arr);
423
424 if (a->list) {
425 add_next_index_zval(&a->list->arr, &list->arr);
426 list->parent = a->list;
427 }
428 a->list = list;
429
430 if (SUCCESS != parse_elements(a)) {
431 return FAILURE;
432 }
433
434 if (!caa(a, "}", 1)) {
435 return FAILURE;
436 }
437
438 /* step one level back up */
439 if (a->list->parent) {
440 HashTableList *l = a->list->parent;
441
442 efree(a->list);
443 a->list = l;
444 }
445
446 return SUCCESS;
447 }
448
449 HashTable *php_pq_parse_array(php_pqres_t *res, const char *val_str, size_t val_len, Oid typ)
450 {
451 HashTable *ht = NULL;
452 ArrayParserState a = {0};
453
454 a.typ = typ;
455 a.ptr = val_str;
456 a.end = val_str + val_len;
457 a.res = res;
458
459 if (SUCCESS != parse_array(&a)) {
460 while (a.list) {
461 HashTableList *l = a.list->parent;
462
463 zval_dtor(&a.list->arr);
464 efree(a.list);
465 a.list = l;
466 }
467 return ht;
468 }
469
470 if (*a.ptr) {
471 php_error_docref(NULL, E_NOTICE, "Trailing input: '%s'", a.ptr);
472 }
473
474 while (a.list) {
475 HashTableList *l = a.list->parent;
476
477 ht = Z_ARRVAL(a.list->arr);
478 efree(a.list);
479 a.list = l;
480 }
481
482 return ht;
483 }
484
485
486 /*
487 * Local variables:
488 * tab-width: 4
489 * c-basic-offset: 4
490 * End:
491 * vim600: noet sw=4 ts=4 fdm=marker
492 * vim<600: noet sw=4 ts=4
493 */