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