Debian Codegraph @

contrib/jsonb_plpython/jsonb_plpython.c

raw
1 #include "postgres.h"
2
3 #include "miscadmin.h"
4 #include "plpy_elog.h"
5 #include "plpy_typeio.h"
6 #include "plpy_util.h"
7 #include "utils/fmgrprotos.h"
8 #include "utils/jsonb.h"
9 #include "utils/numeric.h"
10
11 PG_MODULE_MAGIC_EXT(
12 .name = "jsonb_plpython",
13 .version = PG_VERSION
14 );
15
16 /* for PLyObject_AsString in plpy_typeio.c */
17 typedef char *(*PLyObject_AsString_t) (PyObject *plrv);
18 static PLyObject_AsString_t PLyObject_AsString_p;
19
20 typedef void (*PLy_elog_impl_t) (int elevel, const char *fmt,...);
21 static PLy_elog_impl_t PLy_elog_impl_p;
22
23 /*
24 * decimal_constructor is a function from python library and used
25 * for transforming strings into python decimal type
26 */
27 static PyObject *decimal_constructor;
28
29 static PyObject *PLyObject_FromJsonbContainer(JsonbContainer *jsonb);
30 static JsonbValue *PLyObject_ToJsonbValue(PyObject *obj,
31 JsonbParseState **jsonb_state, bool is_elem);
32
33 typedef PyObject *(*PLyUnicode_FromStringAndSize_t)
34 (const char *s, Py_ssize_t size);
35 static PLyUnicode_FromStringAndSize_t PLyUnicode_FromStringAndSize_p;
36
37 /*
38 * Module initialize function: fetch function pointers for cross-module calls.
39 */
40 void
41 _PG_init(void)
42 {
43 /* Asserts verify that typedefs above match original declarations */
44 AssertVariableIsOfType(&PLyObject_AsString, PLyObject_AsString_t);
45 PLyObject_AsString_p = (PLyObject_AsString_t)
46 load_external_function("$libdir/" PLPYTHON_LIBNAME, "PLyObject_AsString",
47 true, NULL);
48 AssertVariableIsOfType(&PLyUnicode_FromStringAndSize, PLyUnicode_FromStringAndSize_t);
49 PLyUnicode_FromStringAndSize_p = (PLyUnicode_FromStringAndSize_t)
50 load_external_function("$libdir/" PLPYTHON_LIBNAME, "PLyUnicode_FromStringAndSize",
51 true, NULL);
52 AssertVariableIsOfType(&PLy_elog_impl, PLy_elog_impl_t);
53 PLy_elog_impl_p = (PLy_elog_impl_t)
54 load_external_function("$libdir/" PLPYTHON_LIBNAME, "PLy_elog_impl",
55 true, NULL);
56 }
57
58 /* These defines must be after the _PG_init */
59 #define PLyObject_AsString (PLyObject_AsString_p)
60 #define PLyUnicode_FromStringAndSize (PLyUnicode_FromStringAndSize_p)
61 #undef PLy_elog
62 #define PLy_elog (PLy_elog_impl_p)
63
64 /*
65 * PLyUnicode_FromJsonbValue
66 *
67 * Transform string JsonbValue to Python string.
68 */
69 static PyObject *
70 PLyUnicode_FromJsonbValue(JsonbValue *jbv)
71 {
72 Assert(jbv->type == jbvString);
73
74 return PLyUnicode_FromStringAndSize(jbv->val.string.val, jbv->val.string.len);
75 }
76
77 /*
78 * PLyUnicode_ToJsonbValue
79 *
80 * Transform Python string to JsonbValue.
81 */
82 static void
83 PLyUnicode_ToJsonbValue(PyObject *obj, JsonbValue *jbvElem)
84 {
85 jbvElem->type = jbvString;
86 jbvElem->val.string.val = PLyObject_AsString(obj);
87 jbvElem->val.string.len = strlen(jbvElem->val.string.val);
88 }
89
90 /*
91 * PLyObject_FromJsonbValue
92 *
93 * Transform JsonbValue to PyObject.
94 */
95 static PyObject *
96 PLyObject_FromJsonbValue(JsonbValue *jsonbValue)
97 {
98 switch (jsonbValue->type)
99 {
100 case jbvNull:
101 Py_RETURN_NONE;
102
103 case jbvBinary:
104 return PLyObject_FromJsonbContainer(jsonbValue->val.binary.data);
105
106 case jbvNumeric:
107 {
108 Datum num;
109 char *str;
110
111 num = NumericGetDatum(jsonbValue->val.numeric);
112 str = DatumGetCString(DirectFunctionCall1(numeric_out, num));
113
114 return PyObject_CallFunction(decimal_constructor, "s", str);
115 }
116
117 case jbvString:
118 return PLyUnicode_FromJsonbValue(jsonbValue);
119
120 case jbvBool:
121 if (jsonbValue->val.boolean)
122 Py_RETURN_TRUE;
123 else
124 Py_RETURN_FALSE;
125
126 default:
127 elog(ERROR, "unexpected jsonb value type: %d", jsonbValue->type);
128 return NULL;
129 }
130 }
131
132 /*
133 * PLyObject_FromJsonbContainer
134 *
135 * Transform JsonbContainer to PyObject.
136 */
137 static PyObject *
138 PLyObject_FromJsonbContainer(JsonbContainer *jsonb)
139 {
140 JsonbIteratorToken r;
141 JsonbValue v;
142 JsonbIterator *it;
143 PyObject *result;
144
145 /* this can recurse via PLyObject_FromJsonbValue() */
146 check_stack_depth();
147
148 it = JsonbIteratorInit(jsonb);
149 r = JsonbIteratorNext(&it, &v, true);
150
151 switch (r)
152 {
153 case WJB_BEGIN_ARRAY:
154 if (v.val.array.rawScalar)
155 {
156 JsonbValue tmp;
157
158 if ((r = JsonbIteratorNext(&it, &v, true)) != WJB_ELEM ||
159 (r = JsonbIteratorNext(&it, &tmp, true)) != WJB_END_ARRAY ||
160 (r = JsonbIteratorNext(&it, &tmp, true)) != WJB_DONE)
161 elog(ERROR, "unexpected jsonb token: %d", r);
162
163 result = PLyObject_FromJsonbValue(&v);
164 }
165 else
166 {
167 PyObject *volatile elem = NULL;
168
169 result = PyList_New(0);
170 if (!result)
171 return NULL;
172
173 PG_TRY();
174 {
175 while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE)
176 {
177 if (r != WJB_ELEM)
178 continue;
179
180 elem = PLyObject_FromJsonbValue(&v);
181
182 PyList_Append(result, elem);
183 Py_XDECREF(elem);
184 elem = NULL;
185 }
186 }
187 PG_CATCH();
188 {
189 Py_XDECREF(elem);
190 Py_XDECREF(result);
191 PG_RE_THROW();
192 }
193 PG_END_TRY();
194 }
195 break;
196
197 case WJB_BEGIN_OBJECT:
198 {
199 PyObject *volatile result_v = PyDict_New();
200 PyObject *volatile key = NULL;
201 PyObject *volatile val = NULL;
202
203 if (!result_v)
204 return NULL;
205
206 PG_TRY();
207 {
208 while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE)
209 {
210 if (r != WJB_KEY)
211 continue;
212
213 key = PLyUnicode_FromJsonbValue(&v);
214 if (!key)
215 {
216 Py_XDECREF(result_v);
217 result_v = NULL;
218 break;
219 }
220
221 if ((r = JsonbIteratorNext(&it, &v, true)) != WJB_VALUE)
222 elog(ERROR, "unexpected jsonb token: %d", r);
223
224 val = PLyObject_FromJsonbValue(&v);
225 if (!val)
226 {
227 Py_XDECREF(key);
228 key = NULL;
229 Py_XDECREF(result_v);
230 result_v = NULL;
231 break;
232 }
233
234 PyDict_SetItem(result_v, key, val);
235
236 Py_XDECREF(key);
237 key = NULL;
238 Py_XDECREF(val);
239 val = NULL;
240 }
241 }
242 PG_CATCH();
243 {
244 Py_XDECREF(result_v);
245 Py_XDECREF(key);
246 Py_XDECREF(val);
247 PG_RE_THROW();
248 }
249 PG_END_TRY();
250
251 result = result_v;
252 }
253 break;
254
255 default:
256 elog(ERROR, "unexpected jsonb token: %d", r);
257 return NULL;
258 }
259
260 return result;
261 }
262
263 /*
264 * PLyMapping_ToJsonbValue
265 *
266 * Transform Python dict to JsonbValue.
267 */
268 static JsonbValue *
269 PLyMapping_ToJsonbValue(PyObject *obj, JsonbParseState **jsonb_state)
270 {
271 Py_ssize_t pcount;
272 PyObject *volatile items;
273 JsonbValue *volatile out;
274
275 pcount = PyMapping_Size(obj);
276 if (pcount < 0)
277 PLy_elog(ERROR, "could not get size of Python mapping");
278
279 items = PyMapping_Items(obj);
280 if (items == NULL)
281 PLy_elog(ERROR, "could not get items from Python mapping");
282
283 PG_TRY();
284 {
285 Py_ssize_t i;
286
287 pushJsonbValue(jsonb_state, WJB_BEGIN_OBJECT, NULL);
288
289 for (i = 0; i < pcount; i++)
290 {
291 JsonbValue jbvKey;
292 PyObject *item = PyList_GetItem(items, i);
293 PyObject *key;
294 PyObject *value;
295
296 /* The mapping's items() must yield key/value pairs */
297 if (item == NULL || !PyTuple_Check(item) || PyTuple_Size(item) < 2)
298 PLy_elog(ERROR, "items() of a Python mapping must return key/value pairs");
299
300 key = PyTuple_GetItem(item, 0);
301 value = PyTuple_GetItem(item, 1);
302
303 /* Python dictionary can have None as key */
304 if (key == Py_None)
305 {
306 jbvKey.type = jbvString;
307 jbvKey.val.string.len = 0;
308 jbvKey.val.string.val = "";
309 }
310 else
311 {
312 /* All others types of keys we serialize to string */
313 PLyUnicode_ToJsonbValue(key, &jbvKey);
314 }
315
316 (void) pushJsonbValue(jsonb_state, WJB_KEY, &jbvKey);
317 (void) PLyObject_ToJsonbValue(value, jsonb_state, false);
318 }
319
320 out = pushJsonbValue(jsonb_state, WJB_END_OBJECT, NULL);
321 }
322 PG_FINALLY();
323 {
324 Py_DECREF(items);
325 }
326 PG_END_TRY();
327
328 return out;
329 }
330
331 /*
332 * PLySequence_ToJsonbValue
333 *
334 * Transform python list to JsonbValue. Expects transformed PyObject and
335 * a state required for jsonb construction.
336 */
337 static JsonbValue *
338 PLySequence_ToJsonbValue(PyObject *obj, JsonbParseState **jsonb_state)
339 {
340 Py_ssize_t i;
341 Py_ssize_t pcount;
342 PyObject *volatile value = NULL;
343
344 pcount = PySequence_Size(obj);
345
346 pushJsonbValue(jsonb_state, WJB_BEGIN_ARRAY, NULL);
347
348 PG_TRY();
349 {
350 for (i = 0; i < pcount; i++)
351 {
352 value = PySequence_GetItem(obj, i);
353
354 /* PySequence_GetItem() can return NULL, with an exception set */
355 if (value == NULL)
356 PLy_elog(ERROR, "could not get element %d from sequence", (int) i);
357
358 (void) PLyObject_ToJsonbValue(value, jsonb_state, true);
359 Py_XDECREF(value);
360 value = NULL;
361 }
362 }
363 PG_CATCH();
364 {
365 Py_XDECREF(value);
366 PG_RE_THROW();
367 }
368 PG_END_TRY();
369
370 return pushJsonbValue(jsonb_state, WJB_END_ARRAY, NULL);
371 }
372
373 /*
374 * PLyNumber_ToJsonbValue(PyObject *obj)
375 *
376 * Transform python number to JsonbValue.
377 */
378 static JsonbValue *
379 PLyNumber_ToJsonbValue(PyObject *obj, JsonbValue *jbvNum)
380 {
381 Numeric num;
382 char *str = PLyObject_AsString(obj);
383
384 PG_TRY();
385 {
386 Datum numd;
387
388 numd = DirectFunctionCall3(numeric_in,
389 CStringGetDatum(str),
390 ObjectIdGetDatum(InvalidOid),
391 Int32GetDatum(-1));
392 num = DatumGetNumeric(numd);
393 }
394 PG_CATCH();
395 {
396 ereport(ERROR,
397 (errcode(ERRCODE_DATATYPE_MISMATCH),
398 errmsg("could not convert value \"%s\" to jsonb", str)));
399 }
400 PG_END_TRY();
401
402 pfree(str);
403
404 /*
405 * jsonb doesn't allow NaN or infinity (per JSON specification), so we
406 * have to reject those here explicitly.
407 */
408 if (numeric_is_nan(num))
409 ereport(ERROR,
410 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
411 errmsg("cannot convert NaN to jsonb")));
412 if (numeric_is_inf(num))
413 ereport(ERROR,
414 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
415 errmsg("cannot convert infinity to jsonb")));
416
417 jbvNum->type = jbvNumeric;
418 jbvNum->val.numeric = num;
419
420 return jbvNum;
421 }
422
423 /*
424 * PLyObject_ToJsonbValue(PyObject *obj)
425 *
426 * Transform python object to JsonbValue.
427 */
428 static JsonbValue *
429 PLyObject_ToJsonbValue(PyObject *obj, JsonbParseState **jsonb_state, bool is_elem)
430 {
431 JsonbValue *out;
432
433 /* this can recurse via PLyMapping_ToJsonbValue() */
434 check_stack_depth();
435
436 if (!PyUnicode_Check(obj))
437 {
438 if (PySequence_Check(obj))
439 return PLySequence_ToJsonbValue(obj, jsonb_state);
440 else if (PyMapping_Check(obj))
441 return PLyMapping_ToJsonbValue(obj, jsonb_state);
442 }
443
444 out = palloc(sizeof(JsonbValue));
445
446 if (obj == Py_None)
447 out->type = jbvNull;
448 else if (PyUnicode_Check(obj))
449 PLyUnicode_ToJsonbValue(obj, out);
450
451 /*
452 * PyNumber_Check() returns true for booleans, so boolean check should
453 * come first.
454 */
455 else if (PyBool_Check(obj))
456 {
457 out->type = jbvBool;
458 out->val.boolean = (obj == Py_True);
459 }
460 else if (PyNumber_Check(obj))
461 out = PLyNumber_ToJsonbValue(obj, out);
462 else
463 ereport(ERROR,
464 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
465 errmsg("Python type \"%s\" cannot be transformed to jsonb",
466 PLyObject_AsString((PyObject *) obj->ob_type))));
467
468 /* Push result into 'jsonb_state' unless it is raw scalar value. */
469 return (*jsonb_state ?
470 pushJsonbValue(jsonb_state, is_elem ? WJB_ELEM : WJB_VALUE, out) :
471 out);
472 }
473
474 /*
475 * plpython_to_jsonb
476 *
477 * Transform python object to Jsonb datum
478 */
479 PG_FUNCTION_INFO_V1(plpython_to_jsonb);
480 Datum
481 plpython_to_jsonb(PG_FUNCTION_ARGS)
482 {
483 PyObject *obj;
484 JsonbValue *out;
485 JsonbParseState *jsonb_state = NULL;
486
487 obj = (PyObject *) PG_GETARG_POINTER(0);
488 out = PLyObject_ToJsonbValue(obj, &jsonb_state, true);
489 PG_RETURN_POINTER(JsonbValueToJsonb(out));
490 }
491
492 /*
493 * jsonb_to_plpython
494 *
495 * Transform Jsonb datum to PyObject and return it as internal.
496 */
497 PG_FUNCTION_INFO_V1(jsonb_to_plpython);
498 Datum
499 jsonb_to_plpython(PG_FUNCTION_ARGS)
500 {
501 PyObject *result;
502 Jsonb *in = PG_GETARG_JSONB_P(0);
503
504 /*
505 * Initialize pointer to Decimal constructor. First we try "cdecimal", C
506 * version of decimal library. In case of failure we use slower "decimal"
507 * module.
508 */
509 if (!decimal_constructor)
510 {
511 PyObject *decimal_module = PyImport_ImportModule("cdecimal");
512
513 if (!decimal_module)
514 {
515 PyErr_Clear();
516 decimal_module = PyImport_ImportModule("decimal");
517 }
518 Assert(decimal_module);
519 decimal_constructor = PyObject_GetAttrString(decimal_module, "Decimal");
520 }
521
522 result = PLyObject_FromJsonbContainer(&in->root);
523 if (!result)
524 PLy_elog(ERROR, "transformation from jsonb to Python failed");
525
526 return PointerGetDatum(result);
527 }