-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_yottadb.c
2485 lines (2238 loc) · 89.7 KB
/
_yottadb.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
/****************************************************************
* *
* Copyright (c) 2019-2021 Peter Goss All rights reserved. *
* *
* Copyright (c) 2019-2025 YottaDB LLC and/or its subsidiaries. *
* All rights reserved. *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
#define _POSIX_C_SOURCE 200809L // Provide access to strnlen, per https://man7.org/linux/man-pages/man7/feature_test_macros.7.html
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <stdarg.h>
#include <pthread.h>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "_yottadb.h"
#include "_yottadbconstants.h"
#define DECREF_AND_RETURN(PY_OBJECT, RET) \
{ \
if (NULL != PY_OBJECT) { \
Py_DECREF(PY_OBJECT); \
} \
return RET; \
}
/* Utility structure for maintaining call-in information
* used in ydb_cip calls.
*
* This struct serves as an anchor point for the C call-in routine descriptor
* used by cip() that provides for less call-in overhead than ci() as the descriptor
* contains fastpath information filled in by YottaDB after the first call. This allows
* subsequent calls to have minimal overhead. Because this structure's contents contain
* pointers to C allocated storage, it is not exposed to Python-level users.
*/
typedef struct {
char * routine_name;
bool has_parm_types;
ci_name_descriptor ci_info;
ci_parm_type parm_types;
} py_ci_name_descriptor;
// Initialize a global struct to store call-in information
py_ci_name_descriptor ci_info = {.routine_name = NULL, .has_parm_types = FALSE, .ci_info = {.handle = NULL}};
/* Counts the total number of arguments between two integer bitmaps,
* one representing input arguments and another representing output
* arguments by bitwise ORing the two integers together and ANDing
* on each bit in this combined bitmap.
*/
static unsigned int count_args(unsigned int in, unsigned int out) {
unsigned int count, total;
total = in | out;
count = 0;
while (total) {
count += (total & 1);
total >>= 1;
}
return count;
}
/* Routine that raises the appropriate Python Error during validation of Python input
* parameters. The 2 types of errors that will be raised are:
* 1) TypeError in the case that the parameter is of the wrong type
* 2) ValueError if the parameter is of the right type but is invalid in some other way (e.g. too long)
*
* Parameters:
* status - the error message status number (specific values defined in _yottdb.h)
* message - the message to be set in the Python exception.
*/
static void raise_ValidationError(YDBPythonErrorType err_type, char *format_prefix, char *err_format, ...) {
va_list args;
char err_message[YDBPY_MAX_ERRORMSG];
char prefixed_err_message[YDBPY_MAX_ERRORMSG];
int copied;
va_start(args, err_format);
copied = vsnprintf(err_message, YDBPY_MAX_ERRORMSG, err_format, args);
assert(YDBPY_MAX_ERRORMSG > copied);
UNUSED(copied);
va_end(args);
if (NULL != format_prefix) {
copied = snprintf(prefixed_err_message, YDBPY_MAX_ERRORMSG, format_prefix, err_message);
} else {
copied = snprintf(prefixed_err_message, YDBPY_MAX_ERRORMSG, "%s", err_message);
}
assert(0 <= copied);
if (YDBPY_MAX_ERRORMSG <= copied) {
char * ellipsis = "...";
size_t ellipsis_len;
ellipsis_len = strlen(ellipsis);
memcpy(&prefixed_err_message[YDBPY_MAX_ERRORMSG - (ellipsis_len + 1)], ellipsis, ellipsis_len);
assert('\0' == prefixed_err_message[YDBPY_MAX_ERRORMSG - 1]);
}
switch (err_type) {
case YDBPython_TypeError:
PyErr_SetString(PyExc_TypeError, prefixed_err_message);
break;
case YDBPython_ValueError:
PyErr_SetString(PyExc_ValueError, prefixed_err_message);
break;
case YDBPython_OSError:
PyErr_SetString(PyExc_OSError, err_message);
break;
default:
// Only TypeError and ValueError are possible, so we should never get here.
assert(FALSE);
break;
}
}
/* Convert a PyObject referencing a Python `bytes` or `str` object to a ydb_buffer_t struct
* and validate the size of resulting buffer to enforce YottaDB variable name and value limits.
* If set, the `is_varname` flag signals that the object should be validated as a variable,
* otherwise the object will be validated as a value.
*/
static int anystr_to_buffer(PyObject *object, ydb_buffer_t *buffer, bool is_varname) {
char * bytes;
bool decref_object;
Py_ssize_t bytes_ssize;
unsigned int bytes_len;
int done;
if (PyUnicode_Check(object)) {
// Convert Unicode object into Python bytes object
object = PyUnicode_AsEncodedString(object, "utf-8", "strict"); // New reference
if (NULL == object) {
PyErr_SetString(YDBPythonError, "failed to encode Unicode string to bytes object");
return !YDB_OK;
}
decref_object = TRUE;
} else if (PyBytes_Check(object)) {
// Object is a bytes object, no Unicode encoding needed
decref_object = FALSE;
} else {
/* Object is not bytes or str (Unicode), but one of these types was expected.
* So, raise an exception.
*/
raise_ValidationError(YDBPython_TypeError, NULL, YDBPY_ERR_ARG_NOT_BYTES_LIKE);
return !YDB_OK;
}
// Convert Python bytes object to C character string (char *)
bytes_ssize = PyBytes_Size(object);
if (INT32_MAX < bytes_ssize) {
/* Python bytes objects may have more bytes than can be represented by a 32-bit unsigned integer.
* If `object` is 1 more than INT32_MAX, `bytes_len` below would be set to 0, falsely indicating a
* 0-byte long bytes object. So, we need to detect this integer overflow before calling Py_SAFE_DOWNCAST,
* in which case we raise an exception, cleanup, and return the failure to the caller.
*/
if (is_varname) {
raise_ValidationError(YDBPython_ValueError, NULL, YDBPY_ERR_VARNAME_TOO_LONG, bytes_ssize, YDB_MAX_IDENT);
} else {
raise_ValidationError(YDBPython_ValueError, NULL, YDBPY_ERR_BYTES_TOO_LONG, bytes_ssize, YDB_MAX_STR);
}
if (decref_object) {
// Optionally cleanup new reference
Py_DECREF(object);
}
return !YDB_OK;
}
bytes_len = Py_SAFE_DOWNCAST(bytes_ssize, Py_ssize_t, unsigned int);
bytes = PyBytes_AsString(object);
// Allocate and populate YDB buffer
YDB_MALLOC_BUFFER(buffer, bytes_len + 1); // Null terminator used in some scenarios
YDB_COPY_BYTES_TO_BUFFER(bytes, bytes_len, buffer, done);
buffer->buf_addr[buffer->len_used] = '\0';
// Optionally cleanup new reference
if (decref_object) {
Py_DECREF(object);
}
// Defer error emission until after optional cleanup to reduce duplication
if (!done) {
PyErr_SetString(YDBPythonError, "failed to copy bytes object to buffer array");
YDB_FREE_BUFFER(buffer);
return !YDB_OK;
}
/* Enforce variable name length limit, i.e. YDB_MAX_IDENT for locals and YDB_MAX_IDENT + 1 for globals.
* YDB_MAX_IDENT + 1 is acceptable for global variable names, since '^' does not count toward variable
* name length. If the variable name is too long, raise an exception.
*/
if (is_varname) {
if ((('^' == buffer->buf_addr[0]) && ((YDB_MAX_IDENT + 1) < buffer->len_used))
|| (('^' != buffer->buf_addr[0]) && ((YDB_MAX_IDENT) < buffer->len_used))) {
raise_ValidationError(YDBPython_ValueError, NULL, YDBPY_ERR_VARNAME_TOO_LONG, buffer->len_used,
YDB_MAX_IDENT);
YDB_FREE_BUFFER(buffer);
return !YDB_OK;
}
} else if ((YDB_MAX_STR) < buffer->len_used) {
// This is a value and not a variable, so accept up to YDB_MAX_STR length
raise_ValidationError(YDBPython_ValueError, NULL, YDBPY_ERR_VARNAME_TOO_LONG, buffer->len_used, YDB_MAX_IDENT);
YDB_FREE_BUFFER(buffer);
return !YDB_OK;
}
return YDB_OK;
}
static int anystr_to_ydb_string_t(PyObject *object, ydb_string_t *buffer) {
char * bytes;
bool decref_object;
Py_ssize_t bytes_ssize;
unsigned int bytes_len;
if (PyUnicode_Check(object)) {
// Convert Unicode object into Python bytes object
object = PyUnicode_AsEncodedString(object, "utf-8", "strict"); // New reference
if (NULL == object) {
PyErr_SetString(YDBPythonError, "failed to encode Unicode string to bytes object");
return !YDB_OK;
}
decref_object = TRUE;
} else if (PyBytes_Check(object)) {
// Object is a bytes object, no Unicode encoding needed
decref_object = FALSE;
} else {
/* Object is not bytes or str (Unicode). Signal this to
* the caller and let it decide whether to issue an error
* or check for additional Python types.
*/
return YDBPY_CHECK_TYPE;
}
// Convert Python bytes object to C character string (char *)
bytes_ssize = PyBytes_Size(object);
bytes_len = Py_SAFE_DOWNCAST(bytes_ssize, Py_ssize_t, unsigned int);
bytes = PyBytes_AsString(object);
// Allocate and populate YDB buffer
buffer->address = malloc((bytes_len + 1) * sizeof(char)); // Null terminator used in some scenarios
memcpy(buffer->address, bytes, bytes_len);
buffer->address[bytes_len] = '\0';
buffer->length = bytes_len;
// Optionally cleanup new reference
if (decref_object) {
Py_DECREF(object);
}
return YDB_OK;
}
/* Check if a numeric conversion error occurred in Python API code.
* If so, raise an exception and return TRUE, otherwise just return FALSE.
*/
static int is_conversion_error() {
PyObject *err_type;
err_type = PyErr_Occurred();
if (NULL != err_type) {
// A non-overflow Python error occurred, so raise a matching exception manually
PyErr_SetString(err_type, YDBPY_ERR_FAILED_NUMERIC_CONVERSION);
return TRUE;
} else {
return FALSE;
}
}
static int object_to_ydb_string_t(PyObject *object, ydb_string_t *buffer) {
int status;
status = anystr_to_ydb_string_t(object, buffer);
if (YDBPY_CHECK_TYPE == status) {
status = YDB_OK;
buffer->address = calloc(CANONICAL_NUMBER_TO_STRING_MAX, sizeof(char));
if (PyLong_Check(object)) {
long num;
num = PyLong_AsLong(object); // Raises exception if Python int doesn't fit in C long
if ((-1 == num) && is_conversion_error()) {
free(buffer->address);
status = !YDB_OK;
} else {
buffer->length = snprintf(buffer->address, CANONICAL_NUMBER_TO_STRING_MAX, "%ld", num);
assert(buffer->length < CANONICAL_NUMBER_TO_STRING_MAX);
}
} else if (PyFloat_Check(object)) {
double num;
num = PyFloat_AsDouble(object);
if ((-1 == num) && is_conversion_error()) {
free(buffer->address);
status = !YDB_OK;
} else {
buffer->length = snprintf(buffer->address, CANONICAL_NUMBER_TO_STRING_MAX, "%lf", num);
assert(buffer->length < CANONICAL_NUMBER_TO_STRING_MAX);
}
} else {
/* Object is not str, bytes, int, or float, and so cannot be converted to
* a C type accepted by ydb_ci. Cleanup and signal error to caller, who will
* raise an exception based on context.
*/
free(buffer->address);
status = !YDB_OK;
}
}
return status;
}
/* Local Utility Functions */
/* Routine to create an array of empty ydb_buffer_ts with num elements each with
* an allocated length of len
*
* Parameters:
* num - the number of buffers to allocate in the array
* len - the length of the string to allocate for each of the the ydb_buffer_ts
*
* free with FREE_BUFFER_ARRAY macro
*/
static ydb_buffer_t *create_empty_buffer_array(int num, int len) {
int i;
ydb_buffer_t *return_buffer_array;
return_buffer_array = malloc(num * sizeof(ydb_buffer_t));
for (i = 0; i < num; i++)
YDB_MALLOC_BUFFER(&return_buffer_array[i], len);
return return_buffer_array;
}
/* Conversion Utilities */
/* Returns a new PyObject set to the value contained in a YDB buffer.
*
* This is accomplished by determining the type of an existing Python object
* and generating a new PyObject from the value of the YDB buffer via
* an appropriate intermediate C type.
*
* Python types supported are: int, float, bytes, and str.
*
* On success, this function creates a new PyObject reference.
* On error, no references will be created and the error will be signalled
* by a NULL return value. Note that this function will only raise its own
* exceptions for failed system calls, while any other exceptions will have
* occurred within Python library calls and will be raised there. In either
* case, the caller need not raise any exceptions.
*
* Parameters:
* object - the Python object to be type checked
* value - the YDB string containing the value to which the object is to be set
*
* Returns:
* ret - a new PyObject, or NULL in case of error
*/
static PyObject *new_object_from_object_and_string(PyObject *object, ydb_string_t *value) {
PyObject *ret;
/* Add null terminator at new length, as it may have been
* shortened during an M call-in.
*/
value->address[value->length] = '\0';
if (PyLong_Check(object)) {
long val;
val = strtol(value->address, NULL, 10);
if ((ERANGE != errno) && (0 <= val) && (LONG_MAX >= val)) {
ret = PyLong_FromLong(val);
} else {
raise_ValidationError(YDBPython_OSError, NULL, YDBPY_ERR_SYSCALL, "strtol", errno, strerror(errno));
ret = NULL;
}
} else if (PyFloat_Check(object)) {
double val;
val = strtod(value->address, NULL);
if ((ERANGE != errno) && (HUGE_VAL != val) && (-HUGE_VAL != val)) {
ret = PyFloat_FromDouble(val);
} else {
raise_ValidationError(YDBPython_OSError, NULL, YDBPY_ERR_SYSCALL, "strtod", errno, strerror(errno));
ret = NULL;
}
} else if (PyUnicode_Check(object)) {
ret = PyUnicode_FromStringAndSize(value->address, value->length);
} else if (PyBytes_Check(object)) {
ret = PyBytes_FromStringAndSize(value->address, value->length);
} else {
/* Any unacceptable type should have been detected during initial
* validation of any PyObjects passed from Python to the C API,
* so we should never get here. So, assert this.
*/
assert(FALSE);
ret = NULL;
}
/* Conversion was successful and a new object was created,
* so cleanup the previous object before returning.
*/
if (NULL != ret) {
Py_DECREF(object);
}
return ret;
}
/* Confirm that the passed PyObject is a valid Python Sequence,
* i.e. a Sequence of Python `str` (i.e. Unicode) objects.
*
* Validation and error reporting will vary depending on the type of Sequence
* to be validated.
*
* Note: If YDBPython API calls are to accept Python `bytes` objects in
* addition to `str` objects, this function will need to be updated.
*
* Parameters:
* object - the Python object to check
* sequence_type - the type of Sequence to check for
*/
static bool is_valid_sequence(PyObject *object, YDBPythonSequenceType sequence_type, char *extra_prefix) {
int max_sequence_len, max_item_len;
Py_ssize_t i, sequence_len, item_len;
PyObject * item, *sequence;
char * err_prefix;
if (Py_None == object) {
// Allow Python None type
return TRUE;
}
/* Different checks will need to be performed and error messages issued
* depending on the type of Sequence we are validating. So, check that
* here and initialize relevant variables accordingly.
*/
switch (sequence_type) {
case YDBPython_VarnameSequence:
max_sequence_len = YDB_MAX_NAMES;
max_item_len = YDB_MAX_IDENT;
err_prefix = YDBPY_ERR_VARNAME_INVALID;
break;
case YDBPython_SubsarraySequence:
max_sequence_len = YDB_MAX_SUBS;
max_item_len = YDB_MAX_STR;
err_prefix = YDBPY_ERR_SUBSARRAY_INVALID;
break;
case YDBPython_KeySequence:
max_sequence_len = YDB_MAX_SUBS;
max_item_len = YDB_MAX_STR;
/* Aggregate multiple levels of error message nesting into single prefix.
* This allows for failures in Sequences of Keys to be tracked through the
* multiple levels of indirection implicated in that case. Specifically, this
* allows error messages to report which item in the Key Sequence is faulty, as
* well as which item within the Key itself is faulty.
*/
err_prefix = extra_prefix;
break;
default:
assert(FALSE);
/* NULL/0 initialize otherwise unused variables, in case of release builds,
* where this assert will not be triggered.
*/
err_prefix = NULL;
max_item_len = 0;
max_sequence_len = 0;
break;
}
/* Confirm object is a Sequence */
sequence = PySequence_Fast(object, "argument must be iterable"); // New Reference
if (!sequence || !(PyTuple_Check(object) || PyList_Check(object))) {
raise_ValidationError(YDBPython_TypeError, err_prefix, YDBPY_ERR_NOT_LIST_OR_TUPLE);
if (sequence) {
DECREF_AND_RETURN(sequence, FALSE);
} else {
return FALSE;
}
}
/* Validate Sequence length */
sequence_len = PySequence_Fast_GET_SIZE(sequence);
if (max_sequence_len < sequence_len) {
raise_ValidationError(YDBPython_ValueError, err_prefix, YDBPY_ERR_SEQUENCE_TOO_LONG, sequence_len,
max_sequence_len);
DECREF_AND_RETURN(sequence, FALSE);
}
/* Validate Sequence contents */
for (i = 0; i < sequence_len; i++) {
item = PySequence_Fast_GET_ITEM(sequence, i); // Borrowed Reference
/* Validate item type (str or bytes) */
if (PyUnicode_Check(item)) {
// Get length of Unicode object by multiplying code points by code point size
item_len = PyUnicode_GET_LENGTH(item) * PyUnicode_KIND(item);
} else if (PyBytes_Check(item)) {
item_len = PyBytes_Size(item);
} else {
raise_ValidationError(YDBPython_TypeError, err_prefix, YDBPY_ERR_ITEM_NOT_BYTES_LIKE, i);
DECREF_AND_RETURN(sequence, FALSE);
}
/* Validate item length */
if ((0 == max_item_len) || (max_item_len < item_len)) {
raise_ValidationError(YDBPython_ValueError, err_prefix, YDBPY_ERR_BYTES_TOO_LONG, item_len, max_item_len);
DECREF_AND_RETURN(sequence, FALSE);
}
}
Py_DECREF(sequence);
return TRUE;
}
/* Routine to convert a sequence of Python bytes objects into a C array of
* ydb_buffer_ts. Routine assumes sequence was already validated with
* 'is_valid_sequence' function or the special case macro
* RETURN_IF_INVALID_SEQUENCE. The function creates a
* copy of each Python bytes' data so the resulting array should be
* freed by using the 'FREE_BUFFER_ARRAY' macro.
*
* Parameters:
* sequence - a Python Object that is expected to be a Python Sequence containing Strings.
*/
int convert_py_sequence_to_ydb_buffer_array(PyObject *sequence, int sequence_len, ydb_buffer_t *buffer_array) {
PyObject *bytes, *seq;
int status;
seq = PySequence_Fast(sequence, "argument must be iterable"); // New Reference
if (!seq) {
PyErr_SetString(YDBPythonError, "Can't convert none sequence to buffer array.");
FREE_BUFFER_ARRAY(buffer_array, 0);
return !YDB_OK;
}
for (int i = 0; i < sequence_len; i++) {
bytes = PySequence_GetItem(seq, i); // New reference
status = anystr_to_buffer(bytes, &buffer_array[i], FALSE); // Allocates buffer
Py_DECREF(bytes);
if (YDB_OK != status) {
FREE_BUFFER_ARRAY(buffer_array, i);
Py_DECREF(seq);
return !YDB_OK;
}
}
Py_DECREF(seq);
return YDB_OK;
}
int populate_subs_used_and_subsarray(PyObject *pysubs, int *ret_subs_used, ydb_buffer_t **subsarray) {
int status = YDB_OK;
int subs_used;
subs_used = 0;
(*subsarray) = NULL;
if (Py_None != pysubs) {
subs_used = PySequence_Length(pysubs);
(*subsarray) = malloc(subs_used * sizeof(ydb_buffer_t));
status = convert_py_sequence_to_ydb_buffer_array(pysubs, subs_used, (*subsarray));
if (YDB_OK != status) {
FREE_BUFFER_ARRAY((*subsarray), subs_used);
}
}
(*ret_subs_used) = subs_used;
return status;
}
/* converts an array of ydb_buffer_ts into a sequence (Tuple) of Python strings.
*
* Parameters:
* buffer_array - a C array of ydb_buffer_ts
* len - the length of the above array
*/
PyObject *convert_ydb_buffer_array_to_py_tuple(ydb_buffer_t *buffer_array, int len) {
int i;
PyObject *return_tuple;
return_tuple = PyTuple_New(len); // New Reference
for (i = 0; i < len; i++)
PyTuple_SetItem(return_tuple, i, Py_BuildValue("y#", buffer_array[i].buf_addr, buffer_array[i].len_used));
return return_tuple;
}
/* This function will take an already allocated array of YDBKey structures and load it with the
* data contained in the PyObject arguments.
*
* Parameters:
* dest - pointer to the YDBKey to fill.
* varname - Python bytes object representing the varname
* subsarray - array of Python bytes objects representing the array of subscripts
* Note: Because this function calls `convert_py_sequence_to_ydb_buffer_array`
* subsarray should be validated with the
* RETURN_IF_INVALID_SEQUENCE macro.
*/
static bool load_YDBKey(YDBKey *dest, PyObject *varname, PyObject *subsarray) {
bool done;
Py_ssize_t len_ssize, sequence_len_ssize;
unsigned int len;
int status;
char * bytes_c;
ydb_buffer_t *varname_y, *subsarray_y;
if (!PyBytes_Check(varname)) {
// Convert Unicode object to bytes object
varname = PyUnicode_AsEncodedString(varname, "utf-8", "strict"); // New reference
assert(PyBytes_Check(varname));
}
len_ssize = PyBytes_Size(varname);
len = Py_SAFE_DOWNCAST(len_ssize, Py_ssize_t, unsigned int);
bytes_c = PyBytes_AsString(varname);
varname_y = malloc(1 * sizeof(ydb_buffer_t));
YDB_MALLOC_BUFFER(varname_y, len);
YDB_COPY_BYTES_TO_BUFFER(bytes_c, len, varname_y, done);
if (!done) {
YDB_FREE_BUFFER(varname_y);
free(varname_y);
PyErr_SetString(YDBPythonError, "failed to copy bytes object to buffer");
return false;
}
dest->varname = varname_y;
if (Py_None != subsarray) {
sequence_len_ssize = PySequence_Length(subsarray);
dest->subs_used = Py_SAFE_DOWNCAST(sequence_len_ssize, Py_ssize_t, unsigned int);
subsarray_y = malloc(dest->subs_used * sizeof(ydb_buffer_t));
status = convert_py_sequence_to_ydb_buffer_array(subsarray, dest->subs_used, subsarray_y);
if (YDB_OK == status) {
dest->subsarray = subsarray_y;
} else {
YDB_FREE_BUFFER(varname_y);
free(varname_y);
FREE_BUFFER_ARRAY(subsarray_y, dest->subs_used);
PyErr_SetString(YDBPythonError, "failed to covert sequence to buffer array");
return false;
}
} else {
dest->subs_used = 0;
dest->subsarray = NULL;
}
return true;
}
/* Routine to free a YDBKey structure.
*
* Parameters:
* key - pointer to the YDBKey to free.
*/
static void free_YDBKey(YDBKey *key) {
if (NULL != key) {
YDB_FREE_BUFFER((key->varname));
FREE_BUFFER_ARRAY(key->subsarray, key->subs_used);
}
}
/* Routine to validate a sequence of Python sequences representing keys. (Used
* only by lock().)
* Validation rule:
* 1) key_sequence must be a sequence
* 2) each item in key_sequence must be a sequence
* 3) each item must be a sequence of 1 or 2 sub-items.
* 4) item[0] must be a bytes object.
* 5) item[1] either does not exist, is None or a sequence
* 6) if item[1] is a sequence then it must contain only bytes objects.
*
* Parameters:
* keys_sequence - a Python object that is to be validated.
* max_len - the number of keys that are allowed in the keys_sequence
* error_message - a preallocated string for storing the reason for validation failure.
*/
static int is_valid_key_sequence(PyObject *keys_sequence, int max_len) {
Py_ssize_t i, len_keys, len_key_seq;
PyObject * key, *varname, *subsarray, *seq, *key_seq;
bool error_encountered;
/* validate key sequence type */
seq = PySequence_Fast(keys_sequence, "'keys' argument must be a Sequence"); // New Reference
if (!(PyTuple_Check(keys_sequence) || PyList_Check(keys_sequence))) {
raise_ValidationError(YDBPython_TypeError, YDBPY_ERR_KEYS_INVALID, YDBPY_ERR_NOT_LIST_OR_TUPLE);
DECREF_AND_RETURN(seq, FALSE);
}
/* validate key sequence length */
len_keys = PySequence_Fast_GET_SIZE(seq);
if (max_len < len_keys) {
raise_ValidationError(YDBPython_ValueError, YDBPY_ERR_KEYS_INVALID, YDBPY_ERR_SEQUENCE_TOO_LONG, len_keys, max_len);
DECREF_AND_RETURN(seq, FALSE);
}
/* validate each item/key in key sequence */
error_encountered = FALSE;
for (i = 0; i < len_keys; i++) {
key = PySequence_Fast_GET_ITEM(seq, i); // Borrowed Reference
if (!(PyTuple_Check(key) || PyList_Check(key))) {
raise_ValidationError(YDBPython_TypeError, YDBPY_ERR_KEYS_INVALID, YDBPY_ERR_NOT_LIST_OR_TUPLE);
DECREF_AND_RETURN(seq, FALSE);
}
key_seq = PySequence_Fast(key, ""); // New Reference
len_key_seq = PySequence_Fast_GET_SIZE(key_seq);
if (1 <= len_key_seq) {
varname = PySequence_Fast_GET_ITEM(key_seq, 0); // Borrowed Reference
if ((!PyUnicode_Check(varname)) && (!PyBytes_Check(varname))) {
raise_ValidationError(YDBPython_TypeError, YDBPY_ERR_KEYS_INVALID,
YDBPY_ERR_VARNAME_NOT_BYTES_LIKE);
Py_DECREF(key_seq);
DECREF_AND_RETURN(seq, FALSE);
}
} else {
varname = Py_None;
}
if (2 <= len_key_seq) {
subsarray = PySequence_GetItem(key, 1); // Borrowed Reference
} else {
subsarray = Py_None;
}
if (!key_seq || ((2 == i) && !(PyTuple_Check(key) || PyList_Check(key)))) {
/* Validate item/key type [list or tuple]. Only relevant for second
* item, i.e. subsarray, not varname
*/
raise_ValidationError(YDBPython_TypeError, YDBPY_ERR_KEYS_INVALID,
YDBPY_ERR_KEY_IN_SEQUENCE_NOT_LIST_OR_TUPLE, i);
error_encountered = TRUE;
} else if ((1 != len_key_seq) && (2 != len_key_seq)) {
/* validate item/key length [1 or 2] */
raise_ValidationError(YDBPython_ValueError, YDBPY_ERR_KEYS_INVALID,
YDBPY_ERR_KEY_IN_SEQUENCE_INCORRECT_LENGTH, i);
error_encountered = TRUE;
} else if ((!PyUnicode_Check(varname)) && (!PyBytes_Check(varname))) {
/* validate item/key first element (varname) type */
raise_ValidationError(YDBPython_TypeError, YDBPY_ERR_KEYS_INVALID, YDBPY_ERR_ITEM_NOT_BYTES_LIKE, i);
error_encountered = TRUE;
} else if (2 == len_key_seq) {
/* validate item/key second element (subsarray) if it exists */
if (Py_None != subsarray) {
int copied;
char tmp_prefix[YDBPY_MAX_ERRORMSG];
char err_prefix[YDBPY_MAX_ERRORMSG];
/* Incrementally build up error prefix format string to create
* a nested error message that contains full error information
* for the validation failure in the given sequence. This is
* needed to account for the fact that lock() accepts Sequences
* within Sequences. Specifically, it accepts a Sequence of
* YDBKeys, which are themselves Sequences. Accordingly, a full
* error message notes which YDBKey is invalid as well as which
* element of the YDBKey subsarray Sequence is invalid.
*/
copied = snprintf(tmp_prefix, YDBPY_MAX_ERRORMSG, YDBPY_ERR_KEYS_INVALID,
YDBPY_ERR_KEY_IN_SEQUENCE_SUBSARRAY_INVALID);
assert(copied < YDBPY_MAX_ERRORMSG);
UNUSED(copied);
copied = snprintf(err_prefix, YDBPY_MAX_ERRORMSG, tmp_prefix, i, "%s");
assert(copied < YDBPY_MAX_ERRORMSG);
UNUSED(copied);
if (!is_valid_sequence(subsarray, YDBPython_KeySequence, err_prefix)) {
error_encountered = TRUE;
}
}
}
Py_DECREF(key_seq);
if (error_encountered) {
DECREF_AND_RETURN(seq, FALSE);
}
}
Py_DECREF(seq);
return TRUE;
}
/* Takes an already validated (by 'validate_py_keys_sequence' above) PyObject sequence
* that represents a series of keys loads that data into an already allocated array
* of YDBKeys. (note: 'ret_keys' should later be freed by 'free_YDBKey_array' below)
*
* Parameters:
* sequence - a Python object that has already been validated with 'validate_py_keys_sequence' or equivalent.
*/
static bool load_YDBKeys_from_key_sequence(PyObject *sequence, Py_ssize_t len_keys, YDBKey *ret_keys) {
bool success = true;
Py_ssize_t i;
PyObject * key, *varname, *subsarray, *seq, *key_seq;
seq = PySequence_Fast(sequence, "argument must be iterable"); // New Reference
if ((NULL == seq) || (0 == len_keys)) {
return false;
}
for (i = 0; i < len_keys; i++) {
key = PySequence_Fast_GET_ITEM(seq, i); // Borrowed Reference
key_seq = PySequence_Fast(key, "argument must be iterable"); // New Reference
if (NULL == key_seq) {
Py_DECREF(seq);
return false;
}
varname = PySequence_Fast_GET_ITEM(key_seq, 0); // Borrowed Reference
if (2 == PySequence_Fast_GET_SIZE(key_seq)) {
subsarray = PySequence_Fast_GET_ITEM(key_seq, 1); // Borrowed Reference
} else {
subsarray = Py_None;
}
success = load_YDBKey(&ret_keys[i], varname, subsarray);
Py_DECREF(key_seq);
if (!success)
break;
}
Py_DECREF(seq);
return success;
}
/* Routine to free an array of YDBKeys as returned by above
* 'load_YDBKeys_from_key_sequence'.
*
* Parameters:
* keysarray - the array that is to be freed.
* len - the number of elements in keysarray.
*/
static void free_YDBKey_array(YDBKey *keysarray, int len) {
int i;
if (NULL != keysarray) {
for (i = 0; i < len; i++)
free_YDBKey(&keysarray[i]);
free(keysarray);
}
}
/* Routine to help raise a YDBError. The caller still needs to return NULL for
* the Exception to be raised.
*
* Parameters:
* status - the error code that is returned by the wrapped ydb_ function.
*/
static void raise_YDBError(int status) {
ydb_char_t error_string[YDBPY_MAX_ERRORMSG];
ydb_buffer_t error_buffer;
PyObject * error_type;
PyObject * message;
int copied = 0, zstatus;
char full_error_message[YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX];
/* YDB_ERR_NODEEND and errors in the YDB_DEFER_HANDLER to YDB_INT_MAX
* range will not have a value stored in $ZSTATUS, so look up the
* error message manually. In the cases of YDB_NOTOK and YDB_DEFER_HANDLER,
* which have no valid error message and are not possible in YDBPython,
* just use the error code number with no text description.
*/
if ((YDB_ERR_TPTIMEOUT == status) || (YDB_ERR_NODEEND == status)
|| ((YDB_INT_MAX > status) && (YDB_DEFER_HANDLER <= status))) {
if ((YDB_ERR_TPTIMEOUT == status) || (YDB_ERR_NODEEND == status) || (YDB_LOCK_TIMEOUT == status)) {
error_buffer.buf_addr = error_string;
error_buffer.len_alloc = YDBPY_MAX_ERRORMSG;
error_buffer.len_used = 0;
zstatus = ydb_message(status, &error_buffer);
assert(YDB_OK == zstatus);
error_buffer.buf_addr[error_buffer.len_used] = '\0';
}
if (YDB_TP_ROLLBACK == status) {
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX,
"%d, %%YDB-TP-ROLLBACK: Transaction not committed.", status);
error_type = YDBTPRollback;
} else if (YDB_TP_RESTART == status) {
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX,
"%d, %%YDB-TP-RESTART: Restarting transaction.", status);
error_type = YDBTPRestart;
} else if (YDB_ERR_TPTIMEOUT == status) {
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX, "%d, %s", status,
error_string);
error_type = YDBTPTimeoutError;
} else if (YDB_NOTOK == status) {
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX, "%d", status);
error_type = YDBNotOk;
} else if (YDB_LOCK_TIMEOUT == status) {
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX, "%d, %s", status,
error_string);
error_type = YDBLockTimeoutError;
} else if (YDB_DEFER_HANDLER == status) {
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX, "%d", status);
error_type = YDBDeferHandler;
} else if (YDB_ERR_NODEEND == status) {
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG + CANONICAL_NUMBER_TO_STRING_MAX, "%d, %s", status,
error_string);
error_type = YDBNodeEnd;
} else {
assert(FALSE);
}
} else {
zstatus = ydb_zstatus(error_string, YDB_MAX_ERRORMSG);
if ((YDB_OK == zstatus) || (YDB_ERR_INVSTRLEN == zstatus)) {
assert(NULL != error_string);
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG, "%s", error_string);
error_type = YDBError;
} else {
assert(FALSE);
copied = snprintf(full_error_message, YDBPY_MAX_ERRORMSG, "%d, UNKNOWN error", status);
error_type = YDBError;
}
}
assert((0 <= copied) && (YDBPY_MAX_ERRORMSG > copied));
UNUSED(copied);
message = Py_BuildValue("s", full_error_message); // New Reference
// Note that the below call to Py_BuildValue with a first argument of "y" is done in addition
// to the call above with "s" due to the reasoning at:
// https://gitlab.com/YottaDB/Lang/YDBPython/-/merge_requests/61#note_2283744959
if (NULL == message) {
message = Py_BuildValue("y", full_error_message); // New Reference
}
RAISE_SPECIFIC_ERROR(error_type, message);
Py_DECREF(message);
}
/* API Wrappers */
/* FOR ALL BELOW WRAPPERS:
* Each function converts Python types to the appropriate C types and passes them to the matching
* YottaDB Simple API function then convert the return types and errors into appropriate Python types
* and return those values
*
* Parameters:
* self - the object that this method belongs to (in this case it's the _yottadb module.)
* args - a Python tuple of the positional arguments passed to the function.
* kwds - a Python dictionary of the keyword arguments passed to the function.
*/
/* Initialize a py_ci_name_descriptor struct with the name of a call-in routine.
* Used by cip() to prepare for a YottaDB call-in.
*/
static int set_routine_name(char *routine_name) {
assert(NULL != routine_name);
ci_info.ci_info.rtn_name.length = strnlen(routine_name, YDB_MAX_IDENT);
if (0 >= ci_info.ci_info.rtn_name.length) {
PyErr_Format(YDBPythonError, "Failed to initialize call-in information for routine: %s", routine_name);
return !YDB_OK;
}
ci_info.ci_info.rtn_name.length++; // Null terminator
if (NULL != ci_info.ci_info.rtn_name.address) {
free(ci_info.ci_info.rtn_name.address);
}
ci_info.ci_info.rtn_name.address = malloc((ci_info.ci_info.rtn_name.length) * sizeof(char));
memcpy(ci_info.ci_info.rtn_name.address, routine_name, ci_info.ci_info.rtn_name.length);
ci_info.ci_info.handle = NULL;
ci_info.has_parm_types = FALSE;
return YDB_OK;
}
/* Cleans up a ci_name_descriptor struct by freeing memory and resetting
* member values of the global ci_info struct.
*/
static void free_ci_name_descriptor() {
if (NULL != ci_info.ci_info.rtn_name.address) {
free(ci_info.ci_info.rtn_name.address);
ci_info.ci_info.rtn_name.address = NULL;
}
ci_info.ci_info.rtn_name.length = 0;
ci_info.ci_info.handle = NULL;
ci_info.has_parm_types = FALSE;
}
static PyObject *ci_wrapper(PyObject *args, PyObject *kwds, bool is_cip) {
bool return_null = false;
int status, has_retval;
PyObject * routine, *routine_args, *seq, *py_arg, *ret;
unsigned int inmask, outmask, io_args, num_args, cur_index, cur_arg;
ydb_buffer_t routine_name;
ydb_string_t *args_ydb;
ydb_string_t ret_val;
gparam_list arg_values;
ci_parm_type parm_types;
seq = routine_args = NULL;
has_retval = FALSE;
ret = NULL; // Initialize to prevent "maybe-uninitialized" compiler warning on old versions of GCC
// Parse and validate
static char *kwlist[] = {"routine", "args", "has_retval", NULL};
// Parsed values are borrowed references, do not Py_DECREF them.
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Op", kwlist, &routine, &routine_args, &has_retval)) {
return NULL;
}
if (Py_None == routine) {
raise_ValidationError(YDBPython_ValueError, NULL, YDBPY_ERR_ROUTINE_UNSPECIFIED);
return NULL;
}
// Lookup routine parameter information for construction of argument array
if (is_cip) {
return_null = anystr_to_buffer(routine, &routine_name, FALSE);
} else {
return_null = anystr_to_buffer(routine, &routine_name, FALSE);
}
if (return_null) {
return NULL;
}
assert(routine_name.len_used < routine_name.len_alloc);
routine_name.buf_addr[routine_name.len_used] = '\0';
/* Update routine information on initial call to cip() or when