Debian Codegraph @

contrib/ltree/ltxtquery_io.c

raw
1 /*
2 * txtquery io
3 * Teodor Sigaev <[email protected]>
4 * contrib/ltree/ltxtquery_io.c
5 */
6 #include "postgres.h"
7
8 #include <ctype.h>
9
10 #include "crc32.h"
11 #include "libpq/pqformat.h"
12 #include "ltree.h"
13 #include "miscadmin.h"
14 #include "nodes/miscnodes.h"
15 #include "varatt.h"
16
17
18 /* parser's states */
19 #define WAITOPERAND 1
20 #define INOPERAND 2
21 #define WAITOPERATOR 3
22
23 /*
24 * node of query tree, also used
25 * for storing polish notation in parser
26 */
27 typedef struct NODE
28 {
29 int32 type;
30 int32 val;
31 int16 distance;
32 int16 length;
33 uint16 flag;
34 struct NODE *next;
35 } NODE;
36
37 typedef struct
38 {
39 char *buf;
40 int32 state;
41 int32 count;
42 struct Node *escontext;
43 /* reverse polish notation in list (for temporary usage) */
44 NODE *str;
45 /* number in str */
46 int32 num;
47
48 /* user-friendly operand */
49 int32 lenop;
50 int32 sumlen;
51 char *op;
52 char *curop;
53 } QPRS_STATE;
54
55 /*
56 * get token from query string
57 *
58 * caller needs to check if a soft-error was set if the result is ERR.
59 */
60 static int32
61 gettoken_query(QPRS_STATE *state, int32 *val, int32 *lenval, char **strval, uint16 *flag)
62 {
63 int charlen;
64
65 for (;;)
66 {
67 charlen = pg_mblen_cstr(state->buf);
68
69 switch (state->state)
70 {
71 case WAITOPERAND:
72 if (t_iseq(state->buf, '!'))
73 {
74 (state->buf)++;
75 *val = (int32) '!';
76 return OPR;
77 }
78 else if (t_iseq(state->buf, '('))
79 {
80 state->count++;
81 (state->buf)++;
82 return OPEN;
83 }
84 else if (ISLABEL(state->buf))
85 {
86 state->state = INOPERAND;
87 *strval = state->buf;
88 *lenval = charlen;
89 *flag = 0;
90 }
91 else if (!isspace((unsigned char) *state->buf))
92 ereturn(state->escontext, ERR,
93 (errcode(ERRCODE_SYNTAX_ERROR),
94 errmsg("operand syntax error")));
95 break;
96 case INOPERAND:
97 if (ISLABEL(state->buf))
98 {
99 if (*flag)
100 ereturn(state->escontext, ERR,
101 (errcode(ERRCODE_SYNTAX_ERROR),
102 errmsg("modifiers syntax error")));
103 *lenval += charlen;
104 }
105 else if (t_iseq(state->buf, '%'))
106 *flag |= LVAR_SUBLEXEME;
107 else if (t_iseq(state->buf, '@'))
108 *flag |= LVAR_INCASE;
109 else if (t_iseq(state->buf, '*'))
110 *flag |= LVAR_ANYEND;
111 else
112 {
113 state->state = WAITOPERATOR;
114 return VAL;
115 }
116 break;
117 case WAITOPERATOR:
118 if (t_iseq(state->buf, '&') || t_iseq(state->buf, '|'))
119 {
120 state->state = WAITOPERAND;
121 *val = (int32) *(state->buf);
122 (state->buf)++;
123 return OPR;
124 }
125 else if (t_iseq(state->buf, ')'))
126 {
127 (state->buf)++;
128 state->count--;
129 return (state->count < 0) ? ERR : CLOSE;
130 }
131 else if (*(state->buf) == '\0')
132 {
133 return (state->count) ? ERR : END;
134 }
135 else if (!t_iseq(state->buf, ' '))
136 {
137 return ERR;
138 }
139 break;
140 default:
141 return ERR;
142 break;
143 }
144
145 state->buf += charlen;
146 }
147
148 /* should not get here */
149 }
150
151 /*
152 * push new one in polish notation reverse view
153 */
154 static bool
155 pushquery(QPRS_STATE *state, int32 type, int32 val, int32 distance, int32 lenval, uint16 flag)
156 {
157 NODE *tmp = (NODE *) palloc(sizeof(NODE));
158
159 tmp->type = type;
160 tmp->val = val;
161 tmp->flag = flag;
162 if (distance > 0xffff)
163 ereturn(state->escontext, false,
164 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
165 errmsg("value is too big")));
166 if (lenval > 0xff)
167 ereturn(state->escontext, false,
168 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
169 errmsg("operand is too long")));
170 tmp->distance = distance;
171 tmp->length = lenval;
172 tmp->next = state->str;
173 state->str = tmp;
174 state->num++;
175 return true;
176 }
177
178 /*
179 * This function is used for query text parsing
180 */
181 static bool
182 pushval_asis(QPRS_STATE *state, int type, char *strval, int lenval, uint16 flag)
183 {
184 if (lenval > 0xffff)
185 ereturn(state->escontext, false,
186 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
187 errmsg("word is too long")));
188
189 if (!pushquery(state, type, ltree_crc32_sz(strval, lenval),
190 state->curop - state->op, lenval, flag))
191 return false;
192
193 while (state->curop - state->op + lenval + 1 >= state->lenop)
194 {
195 int32 tmp = state->curop - state->op;
196
197 state->lenop *= 2;
198 state->op = (char *) repalloc(state->op, state->lenop);
199 state->curop = state->op + tmp;
200 }
201 memcpy(state->curop, strval, lenval);
202 state->curop += lenval;
203 *(state->curop) = '\0';
204 state->curop++;
205 state->sumlen += lenval + 1;
206 return true;
207 }
208
209 #define STACKDEPTH 32
210 /*
211 * make polish notation of query
212 */
213 static int32
214 makepol(QPRS_STATE *state)
215 {
216 int32 val = 0,
217 type;
218 int32 lenval = 0;
219 char *strval = NULL;
220 int32 stack[STACKDEPTH];
221 int32 lenstack = 0;
222 uint16 flag = 0;
223
224 /* since this function recurses, it could be driven to stack overflow */
225 check_stack_depth();
226
227 while ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END)
228 {
229 switch (type)
230 {
231 case VAL:
232 if (!pushval_asis(state, VAL, strval, lenval, flag))
233 return ERR;
234 while (lenstack && (stack[lenstack - 1] == (int32) '&' ||
235 stack[lenstack - 1] == (int32) '!'))
236 {
237 lenstack--;
238 if (!pushquery(state, OPR, stack[lenstack], 0, 0, 0))
239 return ERR;
240 }
241 break;
242 case OPR:
243 if (lenstack && val == (int32) '|')
244 {
245 if (!pushquery(state, OPR, val, 0, 0, 0))
246 return ERR;
247 }
248 else
249 {
250 if (lenstack == STACKDEPTH)
251 /* internal error */
252 elog(ERROR, "stack too short");
253 stack[lenstack] = val;
254 lenstack++;
255 }
256 break;
257 case OPEN:
258 if (makepol(state) == ERR)
259 return ERR;
260 while (lenstack && (stack[lenstack - 1] == (int32) '&' ||
261 stack[lenstack - 1] == (int32) '!'))
262 {
263 lenstack--;
264 if (!pushquery(state, OPR, stack[lenstack], 0, 0, 0))
265 return ERR;
266 }
267 break;
268 case CLOSE:
269 while (lenstack)
270 {
271 lenstack--;
272 if (!pushquery(state, OPR, stack[lenstack], 0, 0, 0))
273 return ERR;
274 };
275 return END;
276 break;
277 case ERR:
278 if (SOFT_ERROR_OCCURRED(state->escontext))
279 return ERR;
280 /* fall through */
281 default:
282 ereturn(state->escontext, ERR,
283 (errcode(ERRCODE_SYNTAX_ERROR),
284 errmsg("syntax error")));
285
286 }
287 }
288 while (lenstack)
289 {
290 lenstack--;
291 if (!pushquery(state, OPR, stack[lenstack], 0, 0, 0))
292 return ERR;
293 };
294 return END;
295 }
296
297 /*
298 * Recursively fill the "left" fields of an ITEM array that represents
299 * a valid postfix tree.
300 *
301 * state: only needed for error reporting
302 * ptr: starting element of array
303 * pos: in/out argument, the array index this call is responsible to fill
304 *
305 * At exit, *pos has been incremented to point after the sub-tree whose
306 * top is the entry-time value of *pos.
307 *
308 * Returns true if okay, false if error (the only possible error is
309 * overflow of a "left" field).
310 */
311 static bool
312 findoprnd(QPRS_STATE *state, ITEM *ptr, int32 *pos)
313 {
314 int32 mypos;
315
316 /* since this function recurses, it could be driven to stack overflow. */
317 check_stack_depth();
318
319 /* get the position this call is supposed to update */
320 mypos = *pos;
321
322 /* in all cases, we should increment *pos to advance over this item */
323 (*pos)++;
324
325 if (ptr[mypos].type == VAL || ptr[mypos].type == VALTRUE)
326 {
327 /* base case: a VAL has no operand, so just set its left to zero */
328 ptr[mypos].left = 0;
329 }
330 else if (ptr[mypos].val == (int32) '!')
331 {
332 /* unary operator, likewise easy: operand is just after it */
333 ptr[mypos].left = 1;
334 /* recurse to scan operand */
335 if (!findoprnd(state, ptr, pos))
336 return false;
337 }
338 else
339 {
340 /* binary operator */
341 int32 delta;
342
343 /* recurse to scan right operand */
344 if (!findoprnd(state, ptr, pos))
345 return false;
346 /* we must fill left with offset to left operand's top */
347 /* delta can't overflow, see LTXTQUERY_TOO_BIG ... */
348 delta = *pos - mypos;
349 /* ... but it might be too large to fit in the 16-bit left field */
350 Assert(delta > 0);
351 if (unlikely(delta > PG_INT16_MAX))
352 ereturn(state->escontext, false,
353 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
354 errmsg("ltxtquery is too large")));
355 ptr[mypos].left = (int16) delta;
356 /* recurse to scan left operand */
357 if (!findoprnd(state, ptr, pos))
358 return false;
359 }
360
361 return true;
362 }
363
364
365 /*
366 * input
367 */
368 static ltxtquery *
369 queryin(char *buf, struct Node *escontext)
370 {
371 QPRS_STATE state;
372 int32 i;
373 ltxtquery *query;
374 int32 commonlen;
375 ITEM *ptr;
376 NODE *tmp;
377 int32 pos = 0;
378
379 #ifdef BS_DEBUG
380 char pbuf[16384],
381 *cur;
382 #endif
383
384 /* init state */
385 state.buf = buf;
386 state.state = WAITOPERAND;
387 state.count = 0;
388 state.num = 0;
389 state.str = NULL;
390 state.escontext = escontext;
391
392 /* init list of operand */
393 state.sumlen = 0;
394 state.lenop = 64;
395 state.curop = state.op = (char *) palloc(state.lenop);
396 *(state.curop) = '\0';
397
398 /* parse query & make polish notation (postfix, but in reverse order) */
399 if (makepol(&state) == ERR)
400 return NULL;
401 if (!state.num)
402 ereturn(escontext, NULL,
403 (errcode(ERRCODE_SYNTAX_ERROR),
404 errmsg("syntax error"),
405 errdetail("Empty query.")));
406
407 if (LTXTQUERY_TOO_BIG(state.num, state.sumlen))
408 ereturn(escontext, NULL,
409 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
410 errmsg("ltxtquery is too large")));
411 commonlen = COMPUTESIZE(state.num, state.sumlen);
412
413 query = (ltxtquery *) palloc0(commonlen);
414 SET_VARSIZE(query, commonlen);
415 query->size = state.num;
416 ptr = GETQUERY(query);
417
418 /* set item in polish notation */
419 for (i = 0; i < state.num; i++)
420 {
421 ptr[i].type = state.str->type;
422 ptr[i].val = state.str->val;
423 ptr[i].distance = state.str->distance;
424 ptr[i].length = state.str->length;
425 ptr[i].flag = state.str->flag;
426 tmp = state.str->next;
427 pfree(state.str);
428 state.str = tmp;
429 }
430
431 /* set user-friendly operand view */
432 memcpy(GETOPERAND(query), state.op, state.sumlen);
433 pfree(state.op);
434
435 /* set left operand's position for every operator */
436 pos = 0;
437 if (!findoprnd(&state, ptr, &pos))
438 return NULL;
439 /* if successful, findoprnd should have scanned the whole array */
440 Assert(pos == state.num);
441
442 return query;
443 }
444
445 /*
446 * in without morphology
447 */
448 PG_FUNCTION_INFO_V1(ltxtq_in);
449 Datum
450 ltxtq_in(PG_FUNCTION_ARGS)
451 {
452 ltxtquery *res;
453
454 if ((res = queryin(PG_GETARG_POINTER(0), fcinfo->context)) == NULL)
455 PG_RETURN_NULL();
456 PG_RETURN_POINTER(res);
457 }
458
459 /*
460 * ltxtquery type recv function
461 *
462 * The type is sent as text in binary mode, so this is almost the same
463 * as the input function, but it's prefixed with a version number so we
464 * can change the binary format sent in future if necessary. For now,
465 * only version 1 is supported.
466 */
467 PG_FUNCTION_INFO_V1(ltxtq_recv);
468 Datum
469 ltxtq_recv(PG_FUNCTION_ARGS)
470 {
471 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
472 int version = pq_getmsgint(buf, 1);
473 char *str;
474 int nbytes;
475 ltxtquery *res;
476
477 if (version != 1)
478 elog(ERROR, "unsupported ltxtquery version number %d", version);
479
480 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
481 res = queryin(str, NULL);
482 pfree(str);
483
484 PG_RETURN_POINTER(res);
485 }
486
487 /*
488 * out function
489 */
490 typedef struct
491 {
492 ITEM *curpol;
493 char *buf;
494 char *cur;
495 char *op;
496 int32 buflen;
497 } INFIX;
498
499 #define RESIZEBUF(inf,addsize) \
500 while( ( (inf)->cur - (inf)->buf ) + (addsize) + 1 >= (inf)->buflen ) \
501 { \
502 int32 len = (inf)->cur - (inf)->buf; \
503 (inf)->buflen *= 2; \
504 (inf)->buf = (char*) repalloc( (void*)(inf)->buf, (inf)->buflen ); \
505 (inf)->cur = (inf)->buf + len; \
506 }
507
508 /*
509 * recursive walk on tree and print it in
510 * infix (human-readable) view
511 */
512 static void
513 infix(INFIX *in, bool first)
514 {
515 /* since this function recurses, it could be driven to stack overflow. */
516 check_stack_depth();
517
518 if (in->curpol->type == VAL)
519 {
520 char *op = in->op + in->curpol->distance;
521
522 RESIZEBUF(in, in->curpol->length * 2 + 5);
523 while (*op)
524 {
525 *(in->cur) = *op;
526 op++;
527 in->cur++;
528 }
529 if (in->curpol->flag & LVAR_SUBLEXEME)
530 {
531 *(in->cur) = '%';
532 in->cur++;
533 }
534 if (in->curpol->flag & LVAR_INCASE)
535 {
536 *(in->cur) = '@';
537 in->cur++;
538 }
539 if (in->curpol->flag & LVAR_ANYEND)
540 {
541 *(in->cur) = '*';
542 in->cur++;
543 }
544 *(in->cur) = '\0';
545 in->curpol++;
546 }
547 else if (in->curpol->val == (int32) '!')
548 {
549 bool isopr = false;
550
551 RESIZEBUF(in, 1);
552 *(in->cur) = '!';
553 in->cur++;
554 *(in->cur) = '\0';
555 in->curpol++;
556 if (in->curpol->type == OPR)
557 {
558 isopr = true;
559 RESIZEBUF(in, 2);
560 sprintf(in->cur, "( ");
561 in->cur = strchr(in->cur, '\0');
562 }
563 infix(in, isopr);
564 if (isopr)
565 {
566 RESIZEBUF(in, 2);
567 sprintf(in->cur, " )");
568 in->cur = strchr(in->cur, '\0');
569 }
570 }
571 else
572 {
573 int32 op = in->curpol->val;
574 INFIX nrm;
575
576 in->curpol++;
577 if (op == (int32) '|' && !first)
578 {
579 RESIZEBUF(in, 2);
580 sprintf(in->cur, "( ");
581 in->cur = strchr(in->cur, '\0');
582 }
583
584 nrm.curpol = in->curpol;
585 nrm.op = in->op;
586 nrm.buflen = 16;
587 nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
588
589 /* get right operand */
590 infix(&nrm, false);
591
592 /* get & print left operand */
593 in->curpol = nrm.curpol;
594 infix(in, false);
595
596 /* print operator & right operand */
597 RESIZEBUF(in, 3 + (nrm.cur - nrm.buf));
598 sprintf(in->cur, " %c %s", op, nrm.buf);
599 in->cur = strchr(in->cur, '\0');
600 pfree(nrm.buf);
601
602 if (op == (int32) '|' && !first)
603 {
604 RESIZEBUF(in, 2);
605 sprintf(in->cur, " )");
606 in->cur = strchr(in->cur, '\0');
607 }
608 }
609 }
610
611 PG_FUNCTION_INFO_V1(ltxtq_out);
612 Datum
613 ltxtq_out(PG_FUNCTION_ARGS)
614 {
615 ltxtquery *query = PG_GETARG_LTXTQUERY_P(0);
616 INFIX nrm;
617
618 if (query->size == 0)
619 ereport(ERROR,
620 (errcode(ERRCODE_SYNTAX_ERROR),
621 errmsg("syntax error"),
622 errdetail("Empty query.")));
623
624 nrm.curpol = GETQUERY(query);
625 nrm.buflen = 32;
626 nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
627 *(nrm.cur) = '\0';
628 nrm.op = GETOPERAND(query);
629 infix(&nrm, true);
630
631 PG_RETURN_POINTER(nrm.buf);
632 }
633
634 /*
635 * ltxtquery type send function
636 *
637 * The type is sent as text in binary mode, so this is almost the same
638 * as the output function, but it's prefixed with a version number so we
639 * can change the binary format sent in future if necessary. For now,
640 * only version 1 is supported.
641 */
642 PG_FUNCTION_INFO_V1(ltxtq_send);
643 Datum
644 ltxtq_send(PG_FUNCTION_ARGS)
645 {
646 ltxtquery *query = PG_GETARG_LTXTQUERY_P(0);
647 StringInfoData buf;
648 int version = 1;
649 INFIX nrm;
650
651 if (query->size == 0)
652 ereport(ERROR,
653 (errcode(ERRCODE_SYNTAX_ERROR),
654 errmsg("syntax error"),
655 errdetail("Empty query.")));
656
657 nrm.curpol = GETQUERY(query);
658 nrm.buflen = 32;
659 nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
660 *(nrm.cur) = '\0';
661 nrm.op = GETOPERAND(query);
662 infix(&nrm, true);
663
664 pq_begintypsend(&buf);
665 pq_sendint8(&buf, version);
666 pq_sendtext(&buf, nrm.buf, strlen(nrm.buf));
667 pfree(nrm.buf);
668
669 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
670 }