summaryrefslogtreecommitdiffstats
path: root/contrib/ltree/ltree_io.c
blob: 15115cb29f3c3b5ab5f4f0a0416db66ce5863a49 (plain)
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
/*
 * in/out function for ltree and lquery
 * Teodor Sigaev <teodor@stack.net>
 * contrib/ltree/ltree_io.c
 */
#include "postgres.h"

#include <ctype.h>

#include "crc32.h"
#include "libpq/pqformat.h"
#include "ltree.h"
#include "utils/memutils.h"


typedef struct
{
	const char *start;
	int			len;			/* length in bytes */
	int			flag;
	int			wlen;			/* length in characters */
} nodeitem;

#define LTPRS_WAITNAME	0
#define LTPRS_WAITDELIM 1

static void finish_nodeitem(nodeitem *lptr, const char *ptr,
							bool is_lquery, int pos);


/*
 * expects a null terminated string
 * returns an ltree
 */
static ltree *
parse_ltree(const char *buf)
{
	const char *ptr;
	nodeitem   *list,
			   *lptr;
	int			num = 0,
				totallen = 0;
	int			state = LTPRS_WAITNAME;
	ltree	   *result;
	ltree_level *curlevel;
	int			charlen;
	int			pos = 1;		/* character position for error messages */

#define UNCHAR ereport(ERROR, \
					   errcode(ERRCODE_SYNTAX_ERROR), \
					   errmsg("ltree syntax error at character %d", \
							  pos))

	ptr = buf;
	while (*ptr)
	{
		charlen = pg_mblen(ptr);
		if (t_iseq(ptr, '.'))
			num++;
		ptr += charlen;
	}

	if (num + 1 > LTREE_MAX_LEVELS)
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
				 errmsg("number of ltree labels (%d) exceeds the maximum allowed (%d)",
						num + 1, LTREE_MAX_LEVELS)));
	list = lptr = (nodeitem *) palloc(sizeof(nodeitem) * (num + 1));
	ptr = buf;
	while (*ptr)
	{
		charlen = pg_mblen(ptr);

		switch (state)
		{
			case LTPRS_WAITNAME:
				if (ISALNUM(ptr))
				{
					lptr->start = ptr;
					lptr->wlen = 0;
					state = LTPRS_WAITDELIM;
				}
				else
					UNCHAR;
				break;
			case LTPRS_WAITDELIM:
				if (t_iseq(ptr, '.'))
				{
					finish_nodeitem(lptr, ptr, false, pos);
					totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
					lptr++;
					state = LTPRS_WAITNAME;
				}
				else if (!ISALNUM(ptr))
					UNCHAR;
				break;
			default:
				elog(ERROR, "internal error in ltree parser");
		}

		ptr += charlen;
		lptr->wlen++;
		pos++;
	}

	if (state == LTPRS_WAITDELIM)
	{
		finish_nodeitem(lptr, ptr, false, pos);
		totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
		lptr++;
	}
	else if (!(state == LTPRS_WAITNAME && lptr == list))
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("ltree syntax error"),
				 errdetail("Unexpected end of input.")));

	result = (ltree *) palloc0(LTREE_HDRSIZE + totallen);
	SET_VARSIZE(result, LTREE_HDRSIZE + totallen);
	result->numlevel = lptr - list;
	curlevel = LTREE_FIRST(result);
	lptr = list;
	while (lptr - list < result->numlevel)
	{
		curlevel->len = (uint16) lptr->len;
		memcpy(curlevel->name, lptr->start, lptr->len);
		curlevel = LEVEL_NEXT(curlevel);
		lptr++;
	}

	pfree(list);
	return result;

#undef UNCHAR
}

/*
 * expects an ltree
 * returns a null terminated string
 */
static char *
deparse_ltree(const ltree *in)
{
	char	   *buf,
			   *ptr;
	int			i;
	ltree_level *curlevel;

	ptr = buf = (char *) palloc(VARSIZE(in));
	curlevel = LTREE_FIRST(in);
	for (i = 0; i < in->numlevel; i++)
	{
		if (i != 0)
		{
			*ptr = '.';
			ptr++;
		}
		memcpy(ptr, curlevel->name, curlevel->len);
		ptr += curlevel->len;
		curlevel = LEVEL_NEXT(curlevel);
	}

	*ptr = '\0';
	return buf;
}

/*
 * Basic ltree I/O functions
 */
PG_FUNCTION_INFO_V1(ltree_in);
Datum
ltree_in(PG_FUNCTION_ARGS)
{
	char	   *buf = (char *) PG_GETARG_POINTER(0);

	PG_RETURN_POINTER(parse_ltree(buf));
}

PG_FUNCTION_INFO_V1(ltree_out);
Datum
ltree_out(PG_FUNCTION_ARGS)
{
	ltree	   *in = PG_GETARG_LTREE_P(0);

	PG_RETURN_POINTER(deparse_ltree(in));
}

/*
 * ltree type send function
 *
 * The type is sent as text in binary mode, so this is almost the same
 * as the output function, but it's prefixed with a version number so we
 * can change the binary format sent in future if necessary. For now,
 * only version 1 is supported.
 */
PG_FUNCTION_INFO_V1(ltree_send);
Datum
ltree_send(PG_FUNCTION_ARGS)
{
	ltree	   *in = PG_GETARG_LTREE_P(0);
	StringInfoData buf;
	int			version = 1;
	char	   *res = deparse_ltree(in);

	pq_begintypsend(&buf);
	pq_sendint8(&buf, version);
	pq_sendtext(&buf, res, strlen(res));
	pfree(res);

	PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

/*
 * ltree type recv function
 *
 * The type is sent as text in binary mode, so this is almost the same
 * as the input function, but it's prefixed with a version number so we
 * can change the binary format sent in future if necessary. For now,
 * only version 1 is supported.
 */
PG_FUNCTION_INFO_V1(ltree_recv);
Datum
ltree_recv(PG_FUNCTION_ARGS)
{
	StringInfo	buf = (StringInfo) PG_GETARG_POINTER(0);
	int			version = pq_getmsgint(buf, 1);
	char	   *str;
	int			nbytes;
	ltree	   *res;

	if (version != 1)
		elog(ERROR, "unsupported ltree version number %d", version);

	str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
	res = parse_ltree(str);
	pfree(str);

	PG_RETURN_POINTER(res);
}


#define LQPRS_WAITLEVEL 0
#define LQPRS_WAITDELIM 1
#define LQPRS_WAITOPEN	2
#define LQPRS_WAITFNUM	3
#define LQPRS_WAITSNUM	4
#define LQPRS_WAITND	5
#define LQPRS_WAITCLOSE 6
#define LQPRS_WAITEND	7
#define LQPRS_WAITVAR	8


#define GETVAR(x) ( *((nodeitem**)LQL_FIRST(x)) )
#define ITEMSIZE	MAXALIGN(LQL_HDRSIZE+sizeof(nodeitem*))
#define NEXTLEV(x) ( (lquery_level*)( ((char*)(x)) + ITEMSIZE) )

/*
 * expects a null terminated string
 * returns an lquery
 */
static lquery *
parse_lquery(const char *buf)
{
	const char *ptr;
	int			num = 0,
				totallen = 0,
				numOR = 0;
	int			state = LQPRS_WAITLEVEL;
	lquery	   *result;
	nodeitem   *lptr = NULL;
	lquery_level *cur,
			   *curqlevel,
			   *tmpql;
	lquery_variant *lrptr = NULL;
	bool		hasnot = false;
	bool		wasbad = false;
	int			charlen;
	int			pos = 1;		/* character position for error messages */

#define UNCHAR ereport(ERROR, \
					   errcode(ERRCODE_SYNTAX_ERROR), \
					   errmsg("lquery syntax error at character %d", \
							  pos))

	ptr = buf;
	while (*ptr)
	{
		charlen = pg_mblen(ptr);

		if (t_iseq(ptr, '.'))
			num++;
		else if (t_iseq(ptr, '|'))
			numOR++;

		ptr += charlen;
	}

	num++;
	if (num > LQUERY_MAX_LEVELS)
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
				 errmsg("number of lquery items (%d) exceeds the maximum allowed (%d)",
						num, LQUERY_MAX_LEVELS)));
	curqlevel = tmpql = (lquery_level *) palloc0(ITEMSIZE * num);
	ptr = buf;
	while (*ptr)
	{
		charlen = pg_mblen(ptr);

		switch (state)
		{
			case LQPRS_WAITLEVEL:
				if (ISALNUM(ptr))
				{
					GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1));
					lptr->start = ptr;
					state = LQPRS_WAITDELIM;
					curqlevel->numvar = 1;
				}
				else if (t_iseq(ptr, '!'))
				{
					GETVAR(curqlevel) = lptr = (nodeitem *) palloc0(sizeof(nodeitem) * (numOR + 1));
					lptr->start = ptr + 1;
					lptr->wlen = -1;	/* compensate for counting ! below */
					state = LQPRS_WAITDELIM;
					curqlevel->numvar = 1;
					curqlevel->flag |= LQL_NOT;
					hasnot = true;
				}
				else if (t_iseq(ptr, '*'))
					state = LQPRS_WAITOPEN;
				else
					UNCHAR;
				break;
			case LQPRS_WAITVAR:
				if (ISALNUM(ptr))
				{
					lptr++;
					lptr->start = ptr;
					state = LQPRS_WAITDELIM;
					curqlevel->numvar++;
				}
				else
					UNCHAR;
				break;
			case LQPRS_WAITDELIM:
				if (t_iseq(ptr, '@'))
				{
					lptr->flag |= LVAR_INCASE;
					curqlevel->flag |= LVAR_INCASE;
				}
				else if (t_iseq(ptr, '*'))
				{
					lptr->flag |= LVAR_ANYEND;
					curqlevel->flag |= LVAR_ANYEND;
				}
				else if (t_iseq(ptr, '%'))
				{
					lptr->flag |= LVAR_SUBLEXEME;
					curqlevel->flag |= LVAR_SUBLEXEME;
				}
				else if (t_iseq(ptr, '|'))
				{
					finish_nodeitem(lptr, ptr, true, pos);
					state = LQPRS_WAITVAR;
				}
				else if (t_iseq(ptr, '{'))
				{
					finish_nodeitem(lptr, ptr, true, pos);
					curqlevel->flag |= LQL_COUNT;
					state = LQPRS_WAITFNUM;
				}
				else if (t_iseq(ptr, '.'))
				{
					finish_nodeitem(lptr, ptr, true, pos);
					state = LQPRS_WAITLEVEL;
					curqlevel = NEXTLEV(curqlevel);
				}
				else if (ISALNUM(ptr))
				{
					/* disallow more chars after a flag */
					if (lptr->flag)
						UNCHAR;
				}
				else
					UNCHAR;
				break;
			case LQPRS_WAITOPEN:
				if (t_iseq(ptr, '{'))
					state = LQPRS_WAITFNUM;
				else if (t_iseq(ptr, '.'))
				{
					/* We only get here for '*', so these are correct defaults */
					curqlevel->low = 0;
					curqlevel->high = LTREE_MAX_LEVELS;
					curqlevel = NEXTLEV(curqlevel);
					state = LQPRS_WAITLEVEL;
				}
				else
					UNCHAR;
				break;
			case LQPRS_WAITFNUM:
				if (t_iseq(ptr, ','))
					state = LQPRS_WAITSNUM;
				else if (t_isdigit(ptr))
				{
					int			low = atoi(ptr);

					if (low < 0 || low > LTREE_MAX_LEVELS)
						ereport(ERROR,
								(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
								 errmsg("lquery syntax error"),
								 errdetail("Low limit (%d) exceeds the maximum allowed (%d), at character %d.",
										   low, LTREE_MAX_LEVELS, pos)));

					curqlevel->low = (uint16) low;
					state = LQPRS_WAITND;
				}
				else
					UNCHAR;
				break;
			case LQPRS_WAITSNUM:
				if (t_isdigit(ptr))
				{
					int			high = atoi(ptr);

					if (high < 0 || high > LTREE_MAX_LEVELS)
						ereport(ERROR,
								(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
								 errmsg("lquery syntax error"),
								 errdetail("High limit (%d) exceeds the maximum allowed (%d), at character %d.",
										   high, LTREE_MAX_LEVELS, pos)));
					else if (curqlevel->low > high)
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
								 errmsg("lquery syntax error"),
								 errdetail("Low limit (%d) is greater than high limit (%d), at character %d.",
										   curqlevel->low, high, pos)));

					curqlevel->high = (uint16) high;
					state = LQPRS_WAITCLOSE;
				}
				else if (t_iseq(ptr, '}'))
				{
					curqlevel->high = LTREE_MAX_LEVELS;
					state = LQPRS_WAITEND;
				}
				else
					UNCHAR;
				break;
			case LQPRS_WAITCLOSE:
				if (t_iseq(ptr, '}'))
					state = LQPRS_WAITEND;
				else if (!t_isdigit(ptr))
					UNCHAR;
				break;
			case LQPRS_WAITND:
				if (t_iseq(ptr, '}'))
				{
					curqlevel->high = curqlevel->low;
					state = LQPRS_WAITEND;
				}
				else if (t_iseq(ptr, ','))
					state = LQPRS_WAITSNUM;
				else if (!t_isdigit(ptr))
					UNCHAR;
				break;
			case LQPRS_WAITEND:
				if (t_iseq(ptr, '.'))
				{
					state = LQPRS_WAITLEVEL;
					curqlevel = NEXTLEV(curqlevel);
				}
				else
					UNCHAR;
				break;
			default:
				elog(ERROR, "internal error in lquery parser");
		}

		ptr += charlen;
		if (state == LQPRS_WAITDELIM)
			lptr->wlen++;
		pos++;
	}

	if (state == LQPRS_WAITDELIM)
		finish_nodeitem(lptr, ptr, true, pos);
	else if (state == LQPRS_WAITOPEN)
		curqlevel->high = LTREE_MAX_LEVELS;
	else if (state != LQPRS_WAITEND)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("lquery syntax error"),
				 errdetail("Unexpected end of input.")));

	curqlevel = tmpql;
	totallen = LQUERY_HDRSIZE;
	while ((char *) curqlevel - (char *) tmpql < num * ITEMSIZE)
	{
		totallen += LQL_HDRSIZE;
		if (curqlevel->numvar)
		{
			lptr = GETVAR(curqlevel);
			while (lptr - GETVAR(curqlevel) < curqlevel->numvar)
			{
				totallen += MAXALIGN(LVAR_HDRSIZE + lptr->len);
				lptr++;
			}
		}
		curqlevel = NEXTLEV(curqlevel);
	}

	result = (lquery *) palloc0(totallen);
	SET_VARSIZE(result, totallen);
	result->numlevel = num;
	result->firstgood = 0;
	result->flag = 0;
	if (hasnot)
		result->flag |= LQUERY_HASNOT;
	cur = LQUERY_FIRST(result);
	curqlevel = tmpql;
	while ((char *) curqlevel - (char *) tmpql < num * ITEMSIZE)
	{
		memcpy(cur, curqlevel, LQL_HDRSIZE);
		cur->totallen = LQL_HDRSIZE;
		if (curqlevel->numvar)
		{
			lrptr = LQL_FIRST(cur);
			lptr = GETVAR(curqlevel);
			while (lptr - GETVAR(curqlevel) < curqlevel->numvar)
			{
				cur->totallen += MAXALIGN(LVAR_HDRSIZE + lptr->len);
				lrptr->len = lptr->len;
				lrptr->flag = lptr->flag;
				lrptr->val = ltree_crc32_sz(lptr->start, lptr->len);
				memcpy(lrptr->name, lptr->start, lptr->len);
				lptr++;
				lrptr = LVAR_NEXT(lrptr);
			}
			pfree(GETVAR(curqlevel));
			if (cur->numvar > 1 || cur->flag != 0)
			{
				/* Not a simple match */
				wasbad = true;
			}
			else if (wasbad == false)
			{
				/* count leading simple matches */
				(result->firstgood)++;
			}
		}
		else
		{
			/* '*', so this isn't a simple match */
			wasbad = true;
		}
		curqlevel = NEXTLEV(curqlevel);
		cur = LQL_NEXT(cur);
	}

	pfree(tmpql);
	return result;

#undef UNCHAR
}

/*
 * Close out parsing an ltree or lquery nodeitem:
 * compute the correct length, and complain if it's not OK
 */
static void
finish_nodeitem(nodeitem *lptr, const char *ptr, bool is_lquery, int pos)
{
	if (is_lquery)
	{
		/*
		 * Back up over any flag characters, and discount them from length and
		 * position.
		 */
		while (ptr > lptr->start && strchr("@*%", ptr[-1]) != NULL)
		{
			ptr--;
			lptr->wlen--;
			pos--;
		}
	}

	/* Now compute the byte length, which we weren't tracking before. */
	lptr->len = ptr - lptr->start;

	/* Complain if it's empty or too long */
	if (lptr->len == 0)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 is_lquery ?
				 errmsg("lquery syntax error at character %d", pos) :
				 errmsg("ltree syntax error at character %d", pos),
				 errdetail("Empty labels are not allowed.")));
	if (lptr->wlen > LTREE_LABEL_MAX_CHARS)
		ereport(ERROR,
				(errcode(ERRCODE_NAME_TOO_LONG),
				 errmsg("label string is too long"),
				 errdetail("Label length is %d, must be at most %d, at character %d.",
						   lptr->wlen, LTREE_LABEL_MAX_CHARS, pos)));
}

/*
 * expects an lquery
 * returns a null terminated string
 */
static char *
deparse_lquery(const lquery *in)
{
	char	   *buf,
			   *ptr;
	int			i,
				j,
				totallen = 1;
	lquery_level *curqlevel;
	lquery_variant *curtlevel;

	curqlevel = LQUERY_FIRST(in);
	for (i = 0; i < in->numlevel; i++)
	{
		totallen++;
		if (curqlevel->numvar)
		{
			totallen += 1 + (curqlevel->numvar * 4) + curqlevel->totallen;
			if (curqlevel->flag & LQL_COUNT)
				totallen += 2 * 11 + 3;
		}
		else
			totallen += 2 * 11 + 4;
		curqlevel = LQL_NEXT(curqlevel);
	}

	ptr = buf = (char *) palloc(totallen);
	curqlevel = LQUERY_FIRST(in);
	for (i = 0; i < in->numlevel; i++)
	{
		if (i != 0)
		{
			*ptr = '.';
			ptr++;
		}
		if (curqlevel->numvar)
		{
			if (curqlevel->flag & LQL_NOT)
			{
				*ptr = '!';
				ptr++;
			}
			curtlevel = LQL_FIRST(curqlevel);
			for (j = 0; j < curqlevel->numvar; j++)
			{
				if (j != 0)
				{
					*ptr = '|';
					ptr++;
				}
				memcpy(ptr, curtlevel->name, curtlevel->len);
				ptr += curtlevel->len;
				if ((curtlevel->flag & LVAR_SUBLEXEME))
				{
					*ptr = '%';
					ptr++;
				}
				if ((curtlevel->flag & LVAR_INCASE))
				{
					*ptr = '@';
					ptr++;
				}
				if ((curtlevel->flag & LVAR_ANYEND))
				{
					*ptr = '*';
					ptr++;
				}
				curtlevel = LVAR_NEXT(curtlevel);
			}
		}
		else
		{
			*ptr = '*';
			ptr++;
		}

		if ((curqlevel->flag & LQL_COUNT) || curqlevel->numvar == 0)
		{
			if (curqlevel->low == curqlevel->high)
			{
				sprintf(ptr, "{%d}", curqlevel->low);
			}
			else if (curqlevel->low == 0)
			{
				if (curqlevel->high == LTREE_MAX_LEVELS)
				{
					if (curqlevel->numvar == 0)
					{
						/* This is default for '*', so print nothing */
						*ptr = '\0';
					}
					else
						sprintf(ptr, "{,}");
				}
				else
					sprintf(ptr, "{,%d}", curqlevel->high);
			}
			else if (curqlevel->high == LTREE_MAX_LEVELS)
			{
				sprintf(ptr, "{%d,}", curqlevel->low);
			}
			else
				sprintf(ptr, "{%d,%d}", curqlevel->low, curqlevel->high);
			ptr = strchr(ptr, '\0');
		}

		curqlevel = LQL_NEXT(curqlevel);
	}

	*ptr = '\0';
	return buf;
}

/*
 * Basic lquery I/O functions
 */
PG_FUNCTION_INFO_V1(lquery_in);
Datum
lquery_in(PG_FUNCTION_ARGS)
{
	char	   *buf = (char *) PG_GETARG_POINTER(0);

	PG_RETURN_POINTER(parse_lquery(buf));
}

PG_FUNCTION_INFO_V1(lquery_out);
Datum
lquery_out(PG_FUNCTION_ARGS)
{
	lquery	   *in = PG_GETARG_LQUERY_P(0);

	PG_RETURN_POINTER(deparse_lquery(in));
}

/*
 * lquery type send function
 *
 * The type is sent as text in binary mode, so this is almost the same
 * as the output function, but it's prefixed with a version number so we
 * can change the binary format sent in future if necessary. For now,
 * only version 1 is supported.
 */
PG_FUNCTION_INFO_V1(lquery_send);
Datum
lquery_send(PG_FUNCTION_ARGS)
{
	lquery	   *in = PG_GETARG_LQUERY_P(0);
	StringInfoData buf;
	int			version = 1;
	char	   *res = deparse_lquery(in);

	pq_begintypsend(&buf);
	pq_sendint8(&buf, version);
	pq_sendtext(&buf, res, strlen(res));
	pfree(res);

	PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

/*
 * lquery type recv function
 *
 * The type is sent as text in binary mode, so this is almost the same
 * as the input function, but it's prefixed with a version number so we
 * can change the binary format sent in future if necessary. For now,
 * only version 1 is supported.
 */
PG_FUNCTION_INFO_V1(lquery_recv);
Datum
lquery_recv(PG_FUNCTION_ARGS)
{
	StringInfo	buf = (StringInfo) PG_GETARG_POINTER(0);
	int			version = pq_getmsgint(buf, 1);
	char	   *str;
	int			nbytes;
	lquery	   *res;

	if (version != 1)
		elog(ERROR, "unsupported lquery version number %d", version);

	str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
	res = parse_lquery(str);
	pfree(str);

	PG_RETURN_POINTER(res);
}