Merge branch 'v1.1.x'
[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 int php_pq_compare_index(const void *lptr, const void *rptr)
107 {
108 zend_ulong l = ((const Bucket *) lptr)->h;
109 zend_ulong r = ((const Bucket *) rptr)->h;
110
111 if (l < r) {
112 return -1;
113 }
114 if (l > r) {
115 return 1;
116 }
117 return 0;
118 }
119
120 void php_pq_hash_ptr_dtor(zval *p)
121 {
122 efree(Z_PTR_P(p));
123 }
124
125 zend_class_entry *php_pqdt_class_entry;
126
127 ZEND_BEGIN_ARG_INFO_EX(ai_pqdt_to_string, 0, 0, 0)
128 ZEND_END_ARG_INFO();
129 static PHP_METHOD(pqdt, __toString)
130 {
131 zval rv, tmp;
132
133 ZVAL_NULL(&rv);
134 zend_call_method_with_1_params(getThis(), php_pqdt_class_entry, NULL, "format", &rv,
135 zend_read_property(php_pqdt_class_entry, getThis(), ZEND_STRL("format"), 0, &tmp));
136 RETVAL_ZVAL(&rv, 1, 1);
137 }
138
139 ZEND_BEGIN_ARG_INFO_EX(ai_pqdt_create_from_format, 0, 0, 2)
140 ZEND_ARG_INFO(0, format)
141 ZEND_ARG_INFO(0, datetime)
142 ZEND_ARG_INFO(0, timezone)
143 ZEND_END_ARG_INFO();
144 static PHP_METHOD(pqdt, createFromFormat)
145 {
146 zend_error_handling zeh;
147 char *fmt_str, *dt_str;
148 size_t fmt_len, dt_len;
149 zval *ztz = NULL;
150 ZEND_RESULT_CODE rv;
151
152 zend_replace_error_handling(EH_THROW, exce(EX_INVALID_ARGUMENT), &zeh);
153 rv = zend_parse_parameters(ZEND_NUM_ARGS(), "ss|O", &fmt_str, &fmt_len, &dt_str, &dt_len, &ztz, php_date_get_timezone_ce());
154 zend_restore_error_handling(&zeh);
155
156 if (SUCCESS == rv) {
157 php_pqdt_from_string(return_value, fmt_str, dt_str, dt_len, "Y-m-d H:i:s.uO", ztz);
158 }
159 }
160
161 static zend_function_entry php_pqdt_methods[] = {
162 PHP_ME(pqdt, createFromFormat, ai_pqdt_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
163 PHP_ME(pqdt, __toString, ai_pqdt_to_string, ZEND_ACC_PUBLIC)
164 PHP_MALIAS(pqdt, jsonSerialize, __toString, ai_pqdt_to_string, ZEND_ACC_PUBLIC)
165 {0}
166 };
167
168 zval *php_pqdt_from_string(zval *zv, char *input_fmt, char *dt_str, size_t dt_len, char *output_fmt, zval *ztimezone)
169 {
170 php_date_obj *dobj;
171
172 php_date_instantiate(php_pqdt_class_entry, zv);
173 dobj = php_date_obj_from_obj(Z_OBJ_P(zv));
174 if (!php_date_initialize(dobj, dt_str, dt_len, input_fmt, ztimezone, 1)) {
175 zval_dtor(zv);
176 ZVAL_NULL(zv);
177 } else if (output_fmt) {
178 zend_update_property_string(php_pqdt_class_entry, zv, ZEND_STRL("format"), output_fmt);
179 }
180
181 return zv;
182 }
183
184 zend_string *php_pqdt_to_string(zval *zdt, const char *format)
185 {
186 zval rv;
187
188 ZVAL_NULL(&rv);
189
190 if (Z_OBJ_HT_P(zdt)->cast_object
191 && SUCCESS == Z_OBJ_HT_P(zdt)->cast_object(zdt, &rv, IS_STRING)
192 ) {
193 return Z_STR(rv);
194 } else if (instanceof_function(Z_OBJCE_P(zdt), php_date_get_date_ce())) {
195 zval rv, zfmt;
196
197 ZVAL_NULL(&rv);
198 ZVAL_STRING(&zfmt, format);
199 zend_call_method_with_1_params(zdt, Z_OBJCE_P(zdt), NULL, "format", &rv, &zfmt);
200 zval_ptr_dtor(&zfmt);
201
202 if (Z_TYPE(rv) == IS_STRING) {
203 return Z_STR(rv);
204 }
205 zval_ptr_dtor(&rv);
206 }
207
208 return NULL;
209 }
210
211 zend_class_entry *php_pqconv_class_entry;
212
213 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_types, 0, 0, 0)
214 ZEND_END_ARG_INFO();
215
216 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_from_string, 0, 0, 2)
217 ZEND_ARG_INFO(0, data)
218 ZEND_ARG_INFO(0, type)
219 ZEND_END_ARG_INFO();
220
221 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_to_string, 0, 0, 2)
222 ZEND_ARG_INFO(0, data)
223 ZEND_ARG_INFO(0, type)
224 ZEND_END_ARG_INFO();
225
226 zend_function_entry php_pqconv_methods[] = {
227 PHP_ABSTRACT_ME(pqconv, convertTypes, ai_pqconv_convert_types)
228 PHP_ABSTRACT_ME(pqconv, convertFromString, ai_pqconv_convert_from_string)
229 PHP_ABSTRACT_ME(pqconv, convertToString, ai_pqconv_convert_to_string)
230 {0}
231 };
232
233
234 PHP_MINIT_FUNCTION(pq_misc)
235 {
236 zend_class_entry *json, ce = {0};
237
238 INIT_NS_CLASS_ENTRY(ce, "pq", "Converter", php_pqconv_methods);
239 php_pqconv_class_entry = zend_register_internal_interface(&ce);
240
241 memset(&ce, 0, sizeof(ce));
242 INIT_NS_CLASS_ENTRY(ce ,"pq", "DateTime", php_pqdt_methods);
243 php_pqdt_class_entry = zend_register_internal_class_ex(&ce, php_date_get_date_ce());
244
245 zend_declare_property_stringl(php_pqdt_class_entry, ZEND_STRL("format"), ZEND_STRL("Y-m-d H:i:s.uO"), ZEND_ACC_PUBLIC);
246
247 /* stop reading this file right here! */
248 if ((json = zend_hash_str_find_ptr(CG(class_table), ZEND_STRL("jsonserializable")))) {
249 zend_class_implements(php_pqdt_class_entry, 1, json);
250 }
251
252 return SUCCESS;
253 }
254
255 typedef struct _HashTableList {
256 zval arr;
257 struct _HashTableList *parent;
258 } HashTableList;
259
260 typedef struct _ArrayParserState {
261 const char *ptr, *end;
262 HashTableList *list;
263 php_pqres_t *res;
264 Oid typ;
265 unsigned quotes:1;
266 unsigned escaped:1;
267 } ArrayParserState;
268
269 static char caa(ArrayParserState *a, const char *any, unsigned advance)
270 {
271 const char *p = any;
272
273 do {
274 if (*p == *a->ptr) {
275 a->ptr += advance;
276 return *p;
277 }
278 } while (*++p);
279
280 php_error_docref(NULL, E_WARNING, "Failed to parse array: expected one of '%s', got '%c'", any, *a->ptr); \
281 return 0;
282 }
283
284 static ZEND_RESULT_CODE add_element(ArrayParserState *a, const char *start)
285 {
286 zval zelem;
287 zend_string *zstr = zend_string_init(start, a->ptr - start, 0);
288
289 if (a->quotes) {
290 php_stripslashes(zstr);
291 ZVAL_STR(&zelem, zstr);
292 } else if (!zend_string_equals_literal(zstr, "NULL")) {
293 ZVAL_STR(&zelem, zstr);
294 } else {
295 zend_string_release(zstr);
296 ZVAL_NULL(&zelem);
297 }
298
299 if (!ZVAL_IS_NULL(&zelem)) {
300 php_pqres_typed_zval(a->res, a->typ, &zelem);
301 }
302
303 add_next_index_zval(&a->list->arr, &zelem);
304 return SUCCESS;
305 }
306
307 static ZEND_RESULT_CODE parse_array(ArrayParserState *a);
308
309 static ZEND_RESULT_CODE parse_element(ArrayParserState *a, char delim)
310 {
311 const char *el;
312
313 switch (*a->ptr) {
314 case '{':
315 return parse_array(a);
316
317 case '"':
318 a->quotes = 1;
319 ++a->ptr;
320 break;
321 }
322
323 for (el = a->ptr; a->ptr < a->end; ++a->ptr) {
324 switch (*a->ptr) {
325 case '\\':
326 a->escaped = !a->escaped;
327 break;
328
329 case '"':
330 if (a->escaped) {
331 a->escaped = 0;
332 } else if (a->quotes) {
333 if (SUCCESS != add_element(a, el)) {
334 return FAILURE;
335 }
336 a->quotes = 0;
337 ++a->ptr;
338 return SUCCESS;
339 } else {
340 php_error_docref(NULL, E_WARNING, "Failed to parse element, unexpected quote: '%.*s'", (int) (a->ptr - el), el);
341 return FAILURE;
342 }
343 break;
344
345 default:
346 if (delim != *a->ptr) {
347 a->escaped = 0;
348 break;
349 }
350 /* no break */
351 case '}':
352 if (!a->quotes) {
353 return add_element(a, el);
354 }
355 break;
356
357 }
358 }
359
360 php_error_docref(NULL, E_WARNING, "Failed to parse element, reached end of input");
361 return FAILURE;
362 }
363
364 static ZEND_RESULT_CODE parse_elements(ArrayParserState *a)
365 {
366 char delims[] = {'}', PHP_PQ_DELIM_OF_ARRAY(a->typ), 0};
367
368 while (SUCCESS == parse_element(a, delims[1])) {
369 switch (caa(a, delims, 0)) {
370 case 0:
371 return FAILURE;
372
373 case '}':
374 return SUCCESS;
375
376 default:
377 if (!*++a->ptr) {
378 php_error_docref(NULL, E_WARNING, "Failed to parse elements, reached end of input");
379 return FAILURE;
380 }
381 break;
382 }
383 }
384
385 return FAILURE;
386 }
387
388 static ZEND_RESULT_CODE parse_array(ArrayParserState *a)
389 {
390 HashTableList *list;
391
392 if (!caa(a, "{", 1)) {
393 return FAILURE;
394 }
395
396 list = ecalloc(1, sizeof(*list));
397 array_init(&list->arr);
398
399 if (a->list) {
400 add_next_index_zval(&a->list->arr, &list->arr);
401 list->parent = a->list;
402 }
403 a->list = list;
404
405 if (SUCCESS != parse_elements(a)) {
406 return FAILURE;
407 }
408
409 if (!caa(a, "}", 1)) {
410 return FAILURE;
411 }
412
413 /* step one level back up */
414 if (a->list->parent) {
415 HashTableList *l = a->list->parent;
416
417 efree(a->list);
418 a->list = l;
419 }
420
421 return SUCCESS;
422 }
423
424 HashTable *php_pq_parse_array(php_pqres_t *res, const char *val_str, size_t val_len, Oid typ)
425 {
426 HashTable *ht = NULL;
427 ArrayParserState a = {0};
428
429 a.typ = typ;
430 a.ptr = val_str;
431 a.end = val_str + val_len;
432 a.res = res;
433
434 if (SUCCESS != parse_array(&a)) {
435 while (a.list) {
436 HashTableList *l = a.list->parent;
437
438 zval_dtor(&a.list->arr);
439 efree(a.list);
440 a.list = l;
441 }
442 return ht;
443 }
444
445 if (*a.ptr) {
446 php_error_docref(NULL, E_NOTICE, "Trailing input: '%s'", a.ptr);
447 }
448
449 while (a.list) {
450 HashTableList *l = a.list->parent;
451
452 ht = Z_ARRVAL(a.list->arr);
453 efree(a.list);
454 a.list = l;
455 }
456
457 return ht;
458 }
459
460
461 /*
462 * Local variables:
463 * tab-width: 4
464 * c-basic-offset: 4
465 * End:
466 * vim600: noet sw=4 ts=4 fdm=marker
467 * vim<600: noet sw=4 ts=4
468 */