_int.c 47.2 KB
Newer Older
1 2 3 4 5 6
/******************************************************************************
  This file contains routines that can be bound to a Postgres backend and
  called by the backend in the process of processing queries.  The calling
  format for these routines is dictated by Postgres architecture.
******************************************************************************/

7
/*
8
#define BS_DEBUG
9
#define GIST_DEBUG
10
#define GIST_QUERY_DEBUG
11 12
*/

13 14
#include "postgres.h"

15 16 17 18 19 20 21 22 23 24 25
#include <float.h>

#include "access/gist.h"
#include "access/itup.h"
#include "access/rtree.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "storage/bufpage.h"

26
/* number ranges for compression */
27
#define MAXNUMRANGE 100
28

29 30 31
#define max(a,b)		((a) >	(b) ? (a) : (b))
#define min(a,b)		((a) <= (b) ? (a) : (b))
#define abs(a)			((a) <	(0) ? -(a) : (a))
32

33 34 35
/* dimension of array */
#define NDIM 1

Tom Lane's avatar
Tom Lane committed
36 37 38 39 40 41 42
/* 
 * flags for gist__int_ops, use ArrayType->flags 
 * which is unused (see array.h)
 */
#define LEAFKEY		(1<<31)
#define ISLEAFKEY(x)	( ((ArrayType*)(x))->flags & LEAFKEY )

43
/* useful macros for accessing int4 arrays */
44
#define ARRPTR(x)  ( (int4 *) ARR_DATA_PTR(x) )
45
#define ARRNELEMS(x)  ArrayGetNItems( ARR_NDIM(x), ARR_DIMS(x))
46

Tom Lane's avatar
Tom Lane committed
47
#define ARRISVOID(x) ( (x) ? ( ( ARR_NDIM(x) == NDIM ) ? ( ( ARRNELEMS( x ) ) ? 0 : 1 ) : ( ( ARR_NDIM(x) ) ? (elog(ERROR,"Array is not one-dimensional: %d dimensions",ARRNELEMS( x )),1) : 0 )  ) : 0 )
48 49 50 51

#define SORT(x) \
	do { \
		 if ( ARRNELEMS( x ) > 1 ) \
52
			isort( ARRPTR( x ), ARRNELEMS( x ) ); \
53
	} while(0)
54

55
#define PREPAREARR(x) \
56 57
	do { \
		 if ( ARRNELEMS( x ) > 1 ) \
58
			if ( isort( ARRPTR( x ), ARRNELEMS( x ) ) ) \
59 60 61 62 63 64
				x = _int_unique( x ); \
	} while(0)

/* "wish" function */
#define WISH_F(a,b,c) (double)( -(double)(((a)-(b))*((a)-(b))*((a)-(b)))*(c) )

65 66 67

/* bigint defines */
#define BITBYTE 8
68 69
#define SIGLENINT  64			/* >122 => key will toast, so very slow!!! */
#define SIGLEN	( sizeof(int)*SIGLENINT )
70 71 72
#define SIGLENBIT (SIGLEN*BITBYTE)

typedef char BITVEC[SIGLEN];
73 74
typedef char *BITVECP;

75 76 77 78
#define SIGPTR(x)  ( (BITVECP) ARR_DATA_PTR(x) )


#define LOOPBYTE(a) \
79 80 81
		for(i=0;i<SIGLEN;i++) {\
				a;\
		}
82 83

#define LOOPBIT(a) \
84 85 86
		for(i=0;i<SIGLENBIT;i++) {\
				a;\
		}
87

88
/* beware of multiple evaluation of arguments to these macros! */
89
#define GETBYTE(x,i) ( *( (BITVECP)(x) + (int)( (i) / BITBYTE ) ) )
Tom Lane's avatar
Tom Lane committed
90
#define GETBITBYTE(x,i) ( (*((char*)(x)) >> (i)) & 0x01 )
91 92 93
#define CLRBIT(x,i)   GETBYTE(x,i) &= ~( 0x01 << ( (i) % BITBYTE ) )
#define SETBIT(x,i)   GETBYTE(x,i) |=  ( 0x01 << ( (i) % BITBYTE ) )
#define GETBIT(x,i) ( (GETBYTE(x,i) >> ( (i) % BITBYTE )) & 0x01 )
Tom Lane's avatar
Tom Lane committed
94
#define HASHVAL(val) (((unsigned int)(val)) % SIGLENBIT)
95
#define HASH(sign, val) SETBIT((sign), HASHVAL(val))
96 97


98
#ifdef GIST_DEBUG
99 100 101 102 103 104 105 106 107
static void
printarr(ArrayType *a, int num)
{
	char		bbb[16384];
	char	   *cur;
	int			l;
	int		   *d;

	d = ARRPTR(a);
108 109
	*bbb = '\0';
	cur = bbb;
110 111 112 113
	for (l = 0; l < min(num, ARRNELEMS(a)); l++)
	{
		sprintf(cur, "%d ", d[l]);
		cur = strchr(cur, '\0');
114 115 116
	}
	elog(NOTICE, "\t\t%s", bbb);
}
117 118 119 120 121 122 123 124 125 126
static void
printbitvec(BITVEC bv)
{
	int			i;
	char		str[SIGLENBIT + 1];

	str[SIGLENBIT] = '\0';
	LOOPBIT(str[i] = (GETBIT(bv, i)) ? '1' : '0');

	elog(NOTICE, "BV: %s", str);
127
}
128

129 130
#endif

131 132 133
/*
** types for functions
*/
134 135
typedef ArrayType *(*formarray) (ArrayType *, ArrayType *);
typedef void (*formfloat) (ArrayType *, float *);
136

137 138 139
/*
** usefull function
*/
140
static bool isort(int4 *a, const int len);
141 142 143 144 145
static ArrayType *new_intArrayType(int num);
static ArrayType *copy_intArrayType(ArrayType *a);
static ArrayType *resize_intArrayType(ArrayType *a, int num);
static int	internal_size(int *a, int len);
static ArrayType *_int_unique(ArrayType *a);
146

147
/* common GiST function*/
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
static GIST_SPLITVEC *_int_common_picksplit(bytea *entryvec,
					  GIST_SPLITVEC *v,
					  formarray unionf,
					  formarray interf,
					  formfloat sizef,
					  float coef);
static float *_int_common_penalty(GISTENTRY *origentry,
					GISTENTRY *newentry,
					float *result,
					formarray unionf,
					formfloat sizef);
static ArrayType *_int_common_union(bytea *entryvec,
				  int *sizep,
				  formarray unionf);

/*
164 165
** GiST support methods
*/
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
PG_FUNCTION_INFO_V1( g_int_consistent );
PG_FUNCTION_INFO_V1( g_int_compress );
PG_FUNCTION_INFO_V1( g_int_decompress );
PG_FUNCTION_INFO_V1( g_int_penalty );
PG_FUNCTION_INFO_V1( g_int_picksplit );
PG_FUNCTION_INFO_V1( g_int_union );
PG_FUNCTION_INFO_V1( g_int_same );

Datum	g_int_consistent(PG_FUNCTION_ARGS);
Datum	g_int_compress(PG_FUNCTION_ARGS);
Datum	g_int_decompress(PG_FUNCTION_ARGS);
Datum	g_int_penalty(PG_FUNCTION_ARGS);
Datum	g_int_picksplit(PG_FUNCTION_ARGS);
Datum	g_int_union(PG_FUNCTION_ARGS);
Datum	g_int_same(PG_FUNCTION_ARGS);
181 182 183


/*
184
** R-tree support functions
185
*/
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
static bool		inner_int_contains(ArrayType *a, ArrayType *b);
static bool		inner_int_overlap(ArrayType *a, ArrayType *b);
static ArrayType  *inner_int_union(ArrayType *a, ArrayType *b);
static ArrayType  *inner_int_inter(ArrayType *a, ArrayType *b);
static void		rt__int_size(ArrayType *a, float *sz);

PG_FUNCTION_INFO_V1( _int_different );
PG_FUNCTION_INFO_V1( _int_same );
PG_FUNCTION_INFO_V1( _int_contains );
PG_FUNCTION_INFO_V1( _int_contained );
PG_FUNCTION_INFO_V1( _int_overlap );
PG_FUNCTION_INFO_V1( _int_union );
PG_FUNCTION_INFO_V1( _int_inter );

Datum	_int_different(PG_FUNCTION_ARGS);
Datum	_int_same(PG_FUNCTION_ARGS);
Datum	_int_contains(PG_FUNCTION_ARGS);
Datum	_int_contained(PG_FUNCTION_ARGS);
Datum	_int_overlap(PG_FUNCTION_ARGS);
Datum	_int_union(PG_FUNCTION_ARGS);
Datum	_int_inter(PG_FUNCTION_ARGS);
207

208 209 210
/*
** _intbig methods
*/
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
PG_FUNCTION_INFO_V1( g_intbig_consistent );
PG_FUNCTION_INFO_V1( g_intbig_compress );
PG_FUNCTION_INFO_V1( g_intbig_decompress );
PG_FUNCTION_INFO_V1( g_intbig_penalty );
PG_FUNCTION_INFO_V1( g_intbig_picksplit );
PG_FUNCTION_INFO_V1( g_intbig_union );
PG_FUNCTION_INFO_V1( g_intbig_same );

Datum	g_intbig_consistent(PG_FUNCTION_ARGS);
Datum	g_intbig_compress(PG_FUNCTION_ARGS);
Datum	g_intbig_decompress(PG_FUNCTION_ARGS);
Datum	g_intbig_penalty(PG_FUNCTION_ARGS);
Datum	g_intbig_picksplit(PG_FUNCTION_ARGS);
Datum	g_intbig_union(PG_FUNCTION_ARGS);
Datum	g_intbig_same(PG_FUNCTION_ARGS);
226 227 228 229 230

static bool _intbig_contains(ArrayType *a, ArrayType *b);
static bool _intbig_overlap(ArrayType *a, ArrayType *b);
static ArrayType *_intbig_union(ArrayType *a, ArrayType *b);

231
static ArrayType *	_intbig_inter(ArrayType *a, ArrayType *b);
232
static void rt__intbig_size(ArrayType *a, float *sz);
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



/*****************************************************************************
 *		 	Boolean Search	
 *****************************************************************************/

#define BooleanSearchStrategy	20

/*
 * item in polish notation with back link
 * to left operand
 */
typedef struct ITEM {
	int2    type;
	int2	left;
	int4    val;
} ITEM;

typedef struct {
	int4	len;
	int4	size;
	char	data[1];
} QUERYTYPE;

#define HDRSIZEQT	( 2*sizeof(int4) )
#define COMPUTESIZE(size)	( HDRSIZEQT + size * sizeof(ITEM) )
#define GETQUERY(x)  (ITEM*)( (char*)(x)+HDRSIZEQT )

PG_FUNCTION_INFO_V1(bqarr_in);
PG_FUNCTION_INFO_V1(bqarr_out);
Datum   bqarr_in(PG_FUNCTION_ARGS);  
Datum   bqarr_out(PG_FUNCTION_ARGS);
 
PG_FUNCTION_INFO_V1(boolop);
Datum   boolop(PG_FUNCTION_ARGS);  

PG_FUNCTION_INFO_V1(rboolop);
Datum   rboolop(PG_FUNCTION_ARGS);  

PG_FUNCTION_INFO_V1(querytree);
Datum   querytree(PG_FUNCTION_ARGS);  

static bool signconsistent( QUERYTYPE *query, BITVEC sign, bool leaf );
static bool execconsistent( QUERYTYPE *query, ArrayType *array, bool leaf );
278 279

/*****************************************************************************
280
 *						   GiST functions
281 282 283 284 285 286 287 288
 *****************************************************************************/

/*
** The GiST Consistent method for _intments
** Should return false if for all data items x below entry,
** the predicate x op query == FALSE, where op is the oper
** corresponding to strategy in the pg_amop table.
*/
289 290 291 292 293
Datum
g_int_consistent(PG_FUNCTION_ARGS) {
	GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
	ArrayType *query = ( ArrayType * )PG_GETARG_POINTER(1);
	StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
294 295
	bool		retval;

296 297 298
	if ( strategy == BooleanSearchStrategy )
		PG_RETURN_BOOL(execconsistent( (QUERYTYPE*)query, 
						(ArrayType *) DatumGetPointer(entry->key),
Tom Lane's avatar
Tom Lane committed
299
						ISLEAFKEY( (ArrayType *) DatumGetPointer(entry->key) ) ) );
300
	
301 302
	/* XXX are we sure it's safe to scribble on the query object here? */
	/* XXX what about toasted input? */
Tom Lane's avatar
Tom Lane committed
303
	/* sort query for fast search, key is already sorted */
304
	if ( ARRISVOID( query ) )
Tom Lane's avatar
Tom Lane committed
305
		PG_RETURN_BOOL(false);
306 307 308 309 310
	PREPAREARR(query);

	switch (strategy)
	{
		case RTOverlapStrategyNumber:
311 312
			retval = inner_int_overlap((ArrayType *) DatumGetPointer(entry->key),
									   query);
313 314 315
			break;
		case RTSameStrategyNumber:
		case RTContainsStrategyNumber:
316 317
			retval = inner_int_contains((ArrayType *) DatumGetPointer(entry->key),
										query);
318 319
			break;
		case RTContainedByStrategyNumber:
Tom Lane's avatar
Tom Lane committed
320 321 322 323 324
			if ( GIST_LEAF(entry) ) 
				retval = inner_int_contains(query,
					(ArrayType *) DatumGetPointer(entry->key) );
			else 
				retval = inner_int_overlap((ArrayType *) DatumGetPointer(entry->key),
325
									   query);
326 327 328 329
			break;
		default:
			retval = FALSE;
	}
330
	PG_RETURN_BOOL(retval);
331 332
}

333 334
Datum
g_int_union(PG_FUNCTION_ARGS)
335
{
336 337 338 339 340
	PG_RETURN_POINTER( _int_common_union(
		(bytea *) PG_GETARG_POINTER(0), 
		(int *) PG_GETARG_POINTER(1), 
		inner_int_union 
	) );
341 342 343 344 345
}

/*
** GiST Compress and Decompress methods
*/
346 347
Datum
g_int_compress(PG_FUNCTION_ARGS)
348
{
349
	GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
350 351 352 353 354 355 356
	GISTENTRY  *retval;
	ArrayType  *r;
	int			len;
	int		   *dr;
	int			i,
				min,
				cand;
357

Tom Lane's avatar
Tom Lane committed
358
	if (entry->leafkey) {
359
		r = (ArrayType *) PG_DETOAST_DATUM_COPY(entry->key);
Tom Lane's avatar
Tom Lane committed
360 361 362 363 364
		PREPAREARR(r);
		r->flags |= LEAFKEY;
		retval = palloc(sizeof(GISTENTRY));
		gistentryinit(*retval, PointerGetDatum(r),
				  entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
365

366
		PG_RETURN_POINTER(retval);
367
	}
368

Tom Lane's avatar
Tom Lane committed
369 370 371 372 373 374
	r = (ArrayType *) PG_DETOAST_DATUM(entry->key);
	if ( ISLEAFKEY( r ) || ARRISVOID(r) ) {
		if ( r != (ArrayType*)DatumGetPointer(entry->key) )
			pfree(r);
		PG_RETURN_POINTER(entry);
	} 
375

Tom Lane's avatar
Tom Lane committed
376 377 378
	if ( (len=ARRNELEMS(r)) >= 2 * MAXNUMRANGE) {	/* compress */
		if ( r == (ArrayType*)DatumGetPointer( entry->key) ) 
			r = (ArrayType *) PG_DETOAST_DATUM_COPY(entry->key);
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
		r = resize_intArrayType(r, 2 * (len));

		dr = ARRPTR(r);

		for (i = len - 1; i >= 0; i--)
			dr[2 * i] = dr[2 * i + 1] = dr[i];

		len *= 2;
		cand = 1;
		while (len > MAXNUMRANGE * 2)
		{
			min = 0x7fffffff;
			for (i = 2; i < len; i += 2)
				if (min > (dr[i] - dr[i - 1]))
				{
					min = (dr[i] - dr[i - 1]);
					cand = i;
				}
			memmove((void *) &dr[cand - 1], (void *) &dr[cand + 1], (len - cand - 1) * sizeof(int));
			len -= 2;
		}
		r = resize_intArrayType(r, len);
Tom Lane's avatar
Tom Lane committed
401 402
		retval = palloc(sizeof(GISTENTRY));
		gistentryinit(*retval, PointerGetDatum(r),
403
				  entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
Tom Lane's avatar
Tom Lane committed
404 405 406 407
		PG_RETURN_POINTER(retval);
	} else {
		PG_RETURN_POINTER(entry);
	}
408

Tom Lane's avatar
Tom Lane committed
409
	PG_RETURN_POINTER(entry);
410 411
}

412 413
Datum
g_int_decompress(PG_FUNCTION_ARGS)
414
{
415
	GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
416 417 418 419 420 421 422 423 424
	GISTENTRY  *retval;
	ArrayType  *r;
	int		   *dr,
				lenr;
	ArrayType  *in;
	int			lenin;
	int		   *din;
	int			i,
				j;
425

Tom Lane's avatar
Tom Lane committed
426
	in = (ArrayType *) PG_DETOAST_DATUM(entry->key);
427

Tom Lane's avatar
Tom Lane committed
428 429
	if ( ARRISVOID(in) ) {
		PG_RETURN_POINTER(entry);
430
	}
431

432 433
	lenin = ARRNELEMS(in);

Tom Lane's avatar
Tom Lane committed
434 435 436 437 438 439 440 441
	if (lenin < 2 * MAXNUMRANGE || ISLEAFKEY( in ) ) { /* not comressed value */
		if ( in != (ArrayType *) DatumGetPointer(entry->key)) {
			retval = palloc(sizeof(GISTENTRY));
			gistentryinit(*retval, PointerGetDatum(in), 
				entry->rel, entry->page, entry->offset, VARSIZE(in), FALSE);

			PG_RETURN_POINTER(retval);
		} 
442
		PG_RETURN_POINTER(entry);
443
	}
444

Tom Lane's avatar
Tom Lane committed
445
	din = ARRPTR(in);
446
	lenr = internal_size(din, lenin);
447

448 449
	r = new_intArrayType(lenr);
	dr = ARRPTR(r);
450

451 452 453 454
	for (i = 0; i < lenin; i += 2)
		for (j = din[i]; j <= din[i + 1]; j++)
			if ((!i) || *(dr - 1) != j)
				*dr++ = j;
455

456
	if (in != (ArrayType *) DatumGetPointer(entry->key))
457 458
		pfree(in);
	retval = palloc(sizeof(GISTENTRY));
Tom Lane's avatar
Tom Lane committed
459 460
	gistentryinit(*retval, PointerGetDatum(r), 
		entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
461

462
	PG_RETURN_POINTER(retval);
463 464 465 466 467
}

/*
** The GiST Penalty method for _intments
*/
468 469
Datum
g_int_penalty(PG_FUNCTION_ARGS)
470
{
471 472 473 474 475 476
	PG_RETURN_POINTER( _int_common_penalty( 
		(GISTENTRY *)PG_GETARG_POINTER(0), 
		(GISTENTRY *)PG_GETARG_POINTER(1), 
		(float *)    PG_GETARG_POINTER(2), 
		inner_int_union, rt__int_size
	) );
477 478 479
}


480 481
Datum
g_int_picksplit(PG_FUNCTION_ARGS)
482
{
483 484 485 486 487 488
	PG_RETURN_POINTER( _int_common_picksplit(
		(bytea *)PG_GETARG_POINTER(0), 
		(GIST_SPLITVEC *)PG_GETARG_POINTER(1),
		inner_int_union,
		inner_int_inter,
		rt__int_size,
Tom Lane's avatar
Tom Lane committed
489
		0.01	
490
	) );
491 492 493 494 495 496 497
}

/*
** Equality methods
*/


498 499
Datum
g_int_same(PG_FUNCTION_ARGS)
500
{
501 502
	ArrayType	*a = (ArrayType*)PointerGetDatum(PG_GETARG_POINTER(0));
	ArrayType	*b = (ArrayType*)PointerGetDatum(PG_GETARG_POINTER(1));
503
	bool *result = (bool *)PG_GETARG_POINTER(2);
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
	int4 n = ARRNELEMS(a);
	int4 *da, *db;

	if ( n != ARRNELEMS(b) ) {
		*result = false;
		PG_RETURN_POINTER(result);
	}
	*result = TRUE;
	da = ARRPTR(a);
	db = ARRPTR(b);
	while(n--)
		if (*da++ != *db++) {
			*result = FALSE;
			break;
		}
519

520
	PG_RETURN_POINTER(result);
521 522
}

523 524
Datum 
_int_contained(PG_FUNCTION_ARGS)
525
{
526 527 528 529 530 531 532
	PG_RETURN_BOOL( DatumGetBool( 
		DirectFunctionCall2( 
			_int_contains, 
			PointerGetDatum(PG_GETARG_POINTER(1)), 
			PointerGetDatum(PG_GETARG_POINTER(0)) 
		)
	));
533 534
}

535 536
Datum
_int_contains(PG_FUNCTION_ARGS)
537
{
538 539
	ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
	ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
540
	bool		res;
541

Tom Lane's avatar
Tom Lane committed
542
	if (ARRISVOID(a) || ARRISVOID(b))
543
		return FALSE;
544

545 546 547 548 549
	PREPAREARR(a);
	PREPAREARR(b);
	res = inner_int_contains(a, b);
	pfree(a);
	pfree(b);
550
	PG_RETURN_BOOL( res );
551 552
}

553
static bool
554 555 556 557 558 559 560 561 562 563
inner_int_contains(ArrayType *a, ArrayType *b)
{
	int			na,
				nb;
	int			i,
				j,
				n;
	int		   *da,
			   *db;

Tom Lane's avatar
Tom Lane committed
564
	if (ARRISVOID(a) || ARRISVOID(b))
565 566 567 568 569 570
		return FALSE;

	na = ARRNELEMS(a);
	nb = ARRNELEMS(b);
	da = ARRPTR(a);
	db = ARRPTR(b);
571 572

#ifdef GIST_DEBUG
573
	elog(NOTICE, "contains %d %d", na, nb);
574 575 576
#endif

	i = j = n = 0;
577 578
	while (i < na && j < nb)
		if (da[i] < db[j])
579
			i++;
580 581 582 583 584 585 586
		else if (da[i] == db[j])
		{
			n++;
			i++;
			j++;
		}
		else
587
			j++;
588 589

	return (n == nb) ? TRUE : FALSE;
590 591 592 593 594 595
}

/*****************************************************************************
 * Operator class for R-tree indexing
 *****************************************************************************/

596 597
Datum 
_int_different(PG_FUNCTION_ARGS)
598
{
599 600 601 602 603 604 605
	PG_RETURN_BOOL( ! DatumGetBool( 
		DirectFunctionCall2( 
			_int_same, 
			PointerGetDatum(PG_GETARG_POINTER(0)), 
			PointerGetDatum(PG_GETARG_POINTER(1)) 
		)
	));
606 607
}

608 609
Datum
_int_same(PG_FUNCTION_ARGS)
610
{
611 612
	ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
	ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
613 614 615 616 617 618
	int			na,
				nb;
	int			n;
	int		   *da,
			   *db;
	bool		result;
Tom Lane's avatar
Tom Lane committed
619 620
	bool		avoid = ARRISVOID(a);
	bool		bvoid = ARRISVOID(b);
621

Tom Lane's avatar
Tom Lane committed
622 623
	if (avoid || bvoid)
		return (avoid && bvoid) ? TRUE : FALSE;
624

625 626 627 628 629 630
	SORT(a);
	SORT(b);
	na = ARRNELEMS(a);
	nb = ARRNELEMS(b);
	da = ARRPTR(a);
	db = ARRPTR(b);
631 632 633

	result = FALSE;

634
	if (na == nb)
635 636
	{
		result = TRUE;
637 638 639 640 641 642
		for (n = 0; n < na; n++)
			if (da[n] != db[n])
			{
				result = FALSE;
				break;
			}
643 644
	}

645 646
	pfree(a);
	pfree(b);
647

648
	PG_RETURN_BOOL(result);
649 650
}

651
/*	_int_overlap -- does a overlap b?
652
 */
653 654
Datum
_int_overlap(PG_FUNCTION_ARGS)
655
{
656 657
	ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
	ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
658
	bool		result;
659

Tom Lane's avatar
Tom Lane committed
660
	if (ARRISVOID(a) || ARRISVOID(b))
661 662
		return FALSE;

663 664
	SORT(a);
	SORT(b);
665

666
	result = inner_int_overlap(a, b);
667

668 669
	pfree(a);
	pfree(b);
670

671
	PG_RETURN_BOOL( result );
672 673
}

674
static bool
675 676 677 678 679 680 681 682
inner_int_overlap(ArrayType *a, ArrayType *b)
{
	int			na,
				nb;
	int			i,
				j;
	int		   *da,
			   *db;
683

Tom Lane's avatar
Tom Lane committed
684
	if (ARRISVOID(a) || ARRISVOID(b))
685 686 687 688 689 690
		return FALSE;

	na = ARRNELEMS(a);
	nb = ARRNELEMS(b);
	da = ARRPTR(a);
	db = ARRPTR(b);
691 692

#ifdef GIST_DEBUG
693
	elog(NOTICE, "g_int_overlap");
694 695 696
#endif

	i = j = 0;
697 698
	while (i < na && j < nb)
		if (da[i] < db[j])
699
			i++;
700 701 702
		else if (da[i] == db[j])
			return TRUE;
		else
703
			j++;
704

705 706 707
	return FALSE;
}

708 709
Datum
_int_union(PG_FUNCTION_ARGS)
710
{
711 712
	ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
	ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
713 714
	ArrayType  *result;

Tom Lane's avatar
Tom Lane committed
715
	if (!ARRISVOID(a))
716
		SORT(a);
Tom Lane's avatar
Tom Lane committed
717
	if (!ARRISVOID(b))
718
		SORT(b);
719

720
	result = inner_int_union(a, b);
721

722 723 724 725
	if (a)
		pfree(a);
	if (b)
		pfree(b);
726

727
	PG_RETURN_POINTER( result );
728 729
}

730
static ArrayType  *
731 732 733 734 735 736 737 738 739 740
inner_int_union(ArrayType *a, ArrayType *b)
{
	ArrayType  *r = NULL;
	int			na,
				nb;
	int		   *da,
			   *db,
			   *dr;
	int			i,
				j;
741

Tom Lane's avatar
Tom Lane committed
742
	if (ARRISVOID(a) && ARRISVOID(b))
743
		return new_intArrayType(0);
Tom Lane's avatar
Tom Lane committed
744
	if (ARRISVOID(a))
745
		r = copy_intArrayType(b);
Tom Lane's avatar
Tom Lane committed
746
	if (ARRISVOID(b))
747 748 749 750 751 752 753 754 755 756
		r = copy_intArrayType(a);

	if (r)
		dr = ARRPTR(r);
	else
	{
		na = ARRNELEMS(a);
		nb = ARRNELEMS(b);
		da = ARRPTR(a);
		db = ARRPTR(b);
757

758 759
		r = new_intArrayType(na + nb);
		dr = ARRPTR(r);
760

761
		/* union */
762
		i = j = 0;
763 764
		while (i < na && j < nb)
			if (da[i] < db[j])
765 766 767 768
				*dr++ = da[i++];
			else
				*dr++ = db[j++];

769 770 771 772
		while (i < na)
			*dr++ = da[i++];
		while (j < nb)
			*dr++ = db[j++];
773

774 775 776 777
	}

	if (ARRNELEMS(r) > 1)
		r = _int_unique(r);
778 779 780 781 782

	return r;
}


783 784
Datum
_int_inter(PG_FUNCTION_ARGS)
785
{
786 787
	ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
	ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
788
	ArrayType  *result;
789

Tom Lane's avatar
Tom Lane committed
790
	if (ARRISVOID(a) || ARRISVOID(b))
791
		PG_RETURN_POINTER(new_intArrayType(0));
792

793 794
	SORT(a);
	SORT(b);
795

796
	result = inner_int_inter(a, b);
797

798 799
	pfree(a);
	pfree(b);
800

801
	PG_RETURN_POINTER( result );
802 803
}

804
static ArrayType  *
805 806 807 808 809 810 811 812 813 814
inner_int_inter(ArrayType *a, ArrayType *b)
{
	ArrayType  *r;
	int			na,
				nb;
	int		   *da,
			   *db,
			   *dr;
	int			i,
				j;
815

Tom Lane's avatar
Tom Lane committed
816
	if (ARRISVOID(a) || ARRISVOID(b))
817 818 819 820 821 822 823 824
		return new_intArrayType(0);

	na = ARRNELEMS(a);
	nb = ARRNELEMS(b);
	da = ARRPTR(a);
	db = ARRPTR(b);
	r = new_intArrayType(min(na, nb));
	dr = ARRPTR(r);
825 826

	i = j = 0;
827 828
	while (i < na && j < nb)
		if (da[i] < db[j])
829
			i++;
830 831 832
		else if (da[i] == db[j])
		{
			if (i + j == 0 || (i + j > 0 && *(dr - 1) != db[j]))
833
				*dr++ = db[j];
834 835 836 837
			i++;
			j++;
		}
		else
838 839
			j++;

840 841 842
	if ((dr - ARRPTR(r)) == 0)
	{
		pfree(r);
843
		return new_intArrayType(0);
844 845 846
	}
	else
		return resize_intArrayType(r, dr - ARRPTR(r));
847 848
}

849
static void
850 851
rt__int_size(ArrayType *a, float *size)
{
Tom Lane's avatar
Tom Lane committed
852
	*size = (float) ARRNELEMS(a);
853 854

	return;
855 856 857 858
}


/*****************************************************************************
859
 *				   Miscellaneous operators and functions
860 861 862
 *****************************************************************************/

/* len >= 2 */
863
static bool
864
isort(int4 *a, int len)
865
{
866
	int4			tmp,
867
				index;
868
	int4		   *cur,
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
			   *end;
	bool		r = FALSE;

	end = a + len;
	do
	{
		index = 0;
		cur = a + 1;
		while (cur < end)
		{
			if (*(cur - 1) > *cur)
			{
				tmp = *(cur - 1);
				*(cur - 1) = *cur;
				*cur = tmp;
				index = 1;
			}
			else if (!r && *(cur - 1) == *cur)
887
				r = TRUE;
888 889 890
			cur++;
		}
	} while (index);
891 892 893
	return r;
}

894 895 896 897 898 899 900
static ArrayType *
new_intArrayType(int num)
{
	ArrayType  *r;
	int			nbytes = ARR_OVERHEAD(NDIM) + sizeof(int) * num;

	r = (ArrayType *) palloc(nbytes);
901

902 903 904
	MemSet(r, 0, nbytes);
	r->size = nbytes;
	r->ndim = NDIM;
Tom Lane's avatar
Tom Lane committed
905
	r->flags &= ~LEAFKEY;
906 907 908 909 910 911 912 913 914 915
	*((int *) ARR_DIMS(r)) = num;
	*((int *) ARR_LBOUND(r)) = 1;

	return r;
}

static ArrayType *
resize_intArrayType(ArrayType *a, int num)
{
	int			nbytes = ARR_OVERHEAD(NDIM) + sizeof(int) * num;
916

917 918
	if (num == ARRNELEMS(a))
		return a;
919

920
	a = (ArrayType *) repalloc(a, nbytes);
921 922

	a->size = nbytes;
923
	*((int *) ARR_DIMS(a)) = num;
924 925 926
	return a;
}

927 928 929 930 931 932 933
static ArrayType *
copy_intArrayType(ArrayType *a)
{
	ArrayType  *r;

	r = new_intArrayType(ARRNELEMS(a));
	memmove(r, a, VARSIZE(a));
934 935 936 937
	return r;
}

/* num for compressed key */
938 939 940 941 942
static int
internal_size(int *a, int len)
{
	int			i,
				size = 0;
943

944 945 946
	for (i = 0; i < len; i += 2)
		if (!i || a[i] != a[i - 1])		/* do not count repeated range */
			size += a[i + 1] - a[i] + 1;
947

948
	return size;
949 950 951
}

/* r is sorted and size of r > 1 */
952 953 954 955 956 957 958 959 960 961 962
static ArrayType *
_int_unique(ArrayType *r)
{
	int		   *tmp,
			   *dr,
			   *data;
	int			num = ARRNELEMS(r);

	data = tmp = dr = ARRPTR(r);
	while (tmp - data < num)
		if (*tmp != *dr)
963
			*(++dr) = *tmp++;
964 965 966
		else
			tmp++;
	return resize_intArrayType(r, dr + 1 - ARRPTR(r));
967 968 969 970 971
}

/*********************************************************************
** intbig functions
*********************************************************************/
972 973 974 975 976 977 978 979
static void
gensign(BITVEC sign, int *a, int len)
{
	int			i;

	/* we assume that the sign vector is previously zeroed */
	for (i = 0; i < len; i++)
	{
980
		HASH(sign, *a);
981 982
		a++;
	}
983 984
}

985 986 987 988 989 990 991
static bool
_intbig_overlap(ArrayType *a, ArrayType *b)
{
	int			i;
	BITVECP		da,
				db;

992 993 994
	da = SIGPTR(a);
	db = SIGPTR(b);

995
	LOOPBYTE(if (da[i] & db[i]) return TRUE);
996 997 998
	return FALSE;
}

999 1000 1001 1002 1003 1004 1005
static bool
_intbig_contains(ArrayType *a, ArrayType *b)
{
	int			i;
	BITVECP		da,
				db;

1006 1007 1008
	da = SIGPTR(a);
	db = SIGPTR(b);

1009
	LOOPBYTE(if (db[i] & ~da[i]) return FALSE);
1010 1011 1012 1013

	return TRUE;
}

1014 1015 1016 1017 1018
static void
rt__intbig_size(ArrayType *a, float *sz)
{
	int			i,
				len = 0;
Tom Lane's avatar
Tom Lane committed
1019
	BITVECP		bv = SIGPTR(a);
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

	LOOPBYTE(
		len +=
			GETBITBYTE(bv,0) +
			GETBITBYTE(bv,1) +
			GETBITBYTE(bv,2) +
			GETBITBYTE(bv,3) +
			GETBITBYTE(bv,4) +
			GETBITBYTE(bv,5) +
			GETBITBYTE(bv,6) +
			GETBITBYTE(bv,7) ;
		bv = (BITVECP) ( ((char*)bv) + 1 );
	);
	
1034 1035 1036 1037
	*sz = (float) len;
	return;
}

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
static ArrayType *
_intbig_union(ArrayType *a, ArrayType *b)
{
	ArrayType  *r;
	BITVECP		da,
				db,
				dr;
	int			i;

	r = new_intArrayType(SIGLENINT);
1048 1049 1050 1051 1052 1053 1054

	da = SIGPTR(a);
	db = SIGPTR(b);
	dr = SIGPTR(r);

	LOOPBYTE(dr[i] = da[i] | db[i]);

1055 1056
	return r;
}
1057

1058 1059 1060 1061 1062 1063 1064 1065
static ArrayType *
_intbig_inter(ArrayType *a, ArrayType *b)
{
	ArrayType  *r;
	BITVECP		da,
				db,
				dr;
	int			i;
1066

1067
	r = new_intArrayType(SIGLENINT);
1068 1069 1070 1071 1072 1073 1074

	da = SIGPTR(a);
	db = SIGPTR(b);
	dr = SIGPTR(r);

	LOOPBYTE(dr[i] = da[i] & db[i]);

1075 1076
	return r;
}
1077

1078 1079
Datum
g_intbig_same(PG_FUNCTION_ARGS)
1080
{
1081 1082 1083
	ArrayType *a = (ArrayType *)PG_GETARG_POINTER(0);
	ArrayType *b = (ArrayType *)PG_GETARG_POINTER(1);
	bool *result = (bool *)PG_GETARG_POINTER(2);
1084 1085 1086
	BITVECP		da,
				db;
	int			i;
1087 1088 1089 1090 1091

	da = SIGPTR(a);
	db = SIGPTR(b);

	LOOPBYTE(
1092 1093 1094
	if (da[i] != db[i])
	{
		*result = FALSE;
1095
		PG_RETURN_POINTER( result );
1096
	}
1097 1098 1099
	);

	*result = TRUE;
1100
	PG_RETURN_POINTER( result );
1101 1102
}

1103 1104
Datum
g_intbig_compress(PG_FUNCTION_ARGS)
1105
{
1106
	GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
1107 1108 1109
	GISTENTRY  *retval;
	ArrayType  *r,
			   *in;
1110 1111
	bool maycompress = true;
	int i;
1112

1113 1114
	if (DatumGetPointer(entry->key) != NULL)
		in = (ArrayType *) PG_DETOAST_DATUM(entry->key);
1115
	else
1116 1117
		in = NULL;

1118
	if (!entry->leafkey) {
Tom Lane's avatar
Tom Lane committed
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
		LOOPBYTE( 
			if ( ( ((char*)ARRPTR(in))[i] & 0xff ) != 0xff ) {
				maycompress = false;
				break;
			}
		); 
		if ( maycompress ) {
			retval = palloc(sizeof(GISTENTRY));
			r = new_intArrayType(1);
			gistentryinit(*retval, PointerGetDatum(r), 
				entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
			PG_RETURN_POINTER( retval );
		}	
1132 1133
		PG_RETURN_POINTER( entry );
	}
1134

1135
	retval = palloc(sizeof(GISTENTRY));
Tom Lane's avatar
Tom Lane committed
1136
	r = new_intArrayType( SIGLENINT );
1137

Tom Lane's avatar
Tom Lane committed
1138
	if (ARRISVOID(in))
1139
	{
Tom Lane's avatar
Tom Lane committed
1140 1141 1142
		gistentryinit(*retval, PointerGetDatum(r),
			  entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
		if (in != (ArrayType *) DatumGetPointer(entry->key))
1143
				pfree(in);
1144
		PG_RETURN_POINTER (retval);
1145
	}
1146 1147 1148 1149 1150

	gensign(SIGPTR(r),
			ARRPTR(in),
			ARRNELEMS(in));

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
	LOOPBYTE( 
		if( ( ((char*)ARRPTR(in))[i] & 0xff ) != 0xff ) {
			maycompress = false;
			break;
		}
	); 

	if ( maycompress ) {
		pfree(r);
		r = new_intArrayType(1);
	}	

1163
	gistentryinit(*retval, PointerGetDatum(r), entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
1164

Tom Lane's avatar
Tom Lane committed
1165
	if ( in != (ArrayType *) DatumGetPointer(entry->key))
1166
			pfree(in);
1167

1168
	PG_RETURN_POINTER (retval);
1169 1170
}

1171 1172
Datum
g_intbig_decompress(PG_FUNCTION_ARGS)
1173
{
1174
	GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
1175 1176
	ArrayType  *key;

Tom Lane's avatar
Tom Lane committed
1177
	key = (ArrayType *) PG_DETOAST_DATUM(entry->key);
1178 1179

	if ( key != (ArrayType *) DatumGetPointer(entry->key))
1180 1181 1182
	{
		GISTENTRY  *retval;

1183 1184
		retval = palloc(sizeof(GISTENTRY));

Tom Lane's avatar
Tom Lane committed
1185 1186
		gistentryinit(*retval, PointerGetDatum(key), 
			entry->rel, entry->page, entry->offset, (key) ? VARSIZE(key) : 0, FALSE);
1187
		PG_RETURN_POINTER( retval );
1188
	}
Tom Lane's avatar
Tom Lane committed
1189 1190 1191
	if ( ARRNELEMS(key) == 1 ) {
		GISTENTRY  *retval;
		ArrayType  *newkey;
1192

Tom Lane's avatar
Tom Lane committed
1193 1194 1195
		retval = palloc(sizeof(GISTENTRY));
		newkey = new_intArrayType(SIGLENINT);
		MemSet( (void*)ARRPTR(newkey), 0xff, SIGLEN ); 
1196

Tom Lane's avatar
Tom Lane committed
1197 1198 1199 1200
		gistentryinit(*retval, PointerGetDatum(newkey), 
			entry->rel, entry->page, entry->offset, VARSIZE(newkey), FALSE);
		PG_RETURN_POINTER( retval );
	}
1201
	PG_RETURN_POINTER( entry );
1202 1203
}

1204 1205
Datum
g_intbig_picksplit(PG_FUNCTION_ARGS)
1206
{
1207 1208 1209 1210 1211 1212
	PG_RETURN_POINTER( _int_common_picksplit(
		(bytea *)PG_GETARG_POINTER(0), 
		(GIST_SPLITVEC *)PG_GETARG_POINTER(1),
		_intbig_union,
		_intbig_inter,
		rt__intbig_size,
Tom Lane's avatar
Tom Lane committed
1213
		0.1
1214
	) );
1215 1216
}

1217 1218
Datum
g_intbig_union(PG_FUNCTION_ARGS)
1219
{
1220 1221 1222 1223 1224
        PG_RETURN_POINTER( _int_common_union(
                (bytea *) PG_GETARG_POINTER(0),
                (int *) PG_GETARG_POINTER(1),
                _intbig_union
        ) );
1225 1226
}

1227 1228
Datum
g_intbig_penalty(PG_FUNCTION_ARGS)
1229
{
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
	PG_RETURN_POINTER( _int_common_penalty( 
		(GISTENTRY *)PG_GETARG_POINTER(0), 
		(GISTENTRY *)PG_GETARG_POINTER(1), 
		(float *)    PG_GETARG_POINTER(2), 
		_intbig_union, rt__intbig_size
	) );
}

Datum
g_intbig_consistent(PG_FUNCTION_ARGS) {
        GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
        ArrayType *query = ( ArrayType * )PG_GETARG_POINTER(1);
        StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
1243 1244
	bool		retval;
	ArrayType  *q;
1245

1246 1247 1248 1249 1250
	if ( strategy == BooleanSearchStrategy )
		PG_RETURN_BOOL(signconsistent( (QUERYTYPE*)query, 
						SIGPTR((ArrayType *) DatumGetPointer(entry->key)),
						false ) );
	
1251
	/* XXX what about toasted input? */
1252
	if (ARRISVOID(query))
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
		return FALSE;

	q = new_intArrayType(SIGLENINT);
	gensign(SIGPTR(q),
			ARRPTR(query),
			ARRNELEMS(query));

	switch (strategy)
	{
		case RTOverlapStrategyNumber:
1263
			retval = _intbig_overlap((ArrayType *) DatumGetPointer(entry->key), q);
1264 1265 1266
			break;
		case RTSameStrategyNumber:
		case RTContainsStrategyNumber:
1267
			retval = _intbig_contains((ArrayType *) DatumGetPointer(entry->key), q);
1268 1269
			break;
		case RTContainedByStrategyNumber:
1270
			retval = _intbig_overlap((ArrayType *) DatumGetPointer(entry->key), q);
1271 1272 1273 1274 1275
			break;
		default:
			retval = FALSE;
	}
	pfree(q);
1276
	PG_RETURN_BOOL(retval);
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
}

/*****************************************************************
** Common GiST Method
*****************************************************************/

/*
** The GiST Union method for _intments
** returns the minimal set that encloses all the entries in entryvec
*/
1287
static ArrayType  *
1288 1289 1290 1291 1292 1293 1294
_int_common_union(bytea *entryvec, int *sizep, formarray unionf)
{
	int			numranges,
				i;
	ArrayType  *out = (ArrayType *) NULL;
	ArrayType  *tmp;

1295
#ifdef GIST_DEBUG
1296
	elog(NOTICE, "_int_common_union in");
1297
#endif
1298 1299

	numranges = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
1300
	tmp = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[0].key);
1301 1302 1303 1304

	for (i = 1; i < numranges; i++)
	{
		out = (*unionf) (tmp, (ArrayType *)
1305
						 DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key));
1306 1307 1308 1309 1310
		if (i > 1 && tmp)
			pfree(tmp);
		tmp = out;
	}

Tom Lane's avatar
Tom Lane committed
1311
	out->flags &= ~LEAFKEY;
1312 1313 1314 1315
	*sizep = VARSIZE(out);
	if (*sizep == 0)
	{
		pfree(out);
1316
#ifdef GIST_DEBUG
1317
		elog(NOTICE, "_int_common_union out1");
1318
#endif
1319 1320
		return NULL;
	}
1321
#ifdef GIST_DEBUG
1322
	elog(NOTICE, "_int_common_union out");
1323
#endif
1324
	return (out);
1325 1326 1327

}

1328 1329 1330 1331
/*****************************************
 * The GiST Penalty method for _intments *
 *****************************************/

1332
static float *
1333
_int_common_penalty(GISTENTRY *origentry, GISTENTRY *newentry, float *result,
1334 1335
					formarray unionf,
					formfloat sizef)
1336
{
1337
	ArrayType  *ud;
1338 1339 1340
	float		tmp1,
				tmp2;

1341
#ifdef GIST_DEBUG
1342
	elog(NOTICE, "penalty");
1343
#endif
1344 1345 1346 1347
	ud = (*unionf) ((ArrayType *) DatumGetPointer(origentry->key),
					(ArrayType *) DatumGetPointer(newentry->key));
	(*sizef) (ud, &tmp1);
	(*sizef) ((ArrayType *) DatumGetPointer(origentry->key), &tmp2);
1348
	*result = tmp1 - tmp2;
1349
	pfree(ud);
1350 1351

#ifdef GIST_DEBUG
1352
	elog(NOTICE, "--penalty\t%g", *result);
1353 1354
#endif

1355
	return (result);
1356 1357
}

Tom Lane's avatar
Tom Lane committed
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
typedef struct {
	OffsetNumber	pos;
	float		cost;
} SPLITCOST;

static int 
comparecost( const void *a, const void *b ) {
	if ( ((SPLITCOST*)a)->cost == ((SPLITCOST*)b)->cost )
		return 0;
	else
		return ( ((SPLITCOST*)a)->cost > ((SPLITCOST*)b)->cost ) ? 1 : -1;
}

1371 1372
/*
** The GiST PickSplit method for _intments
1373
** We use Guttman's poly time split algorithm
1374
*/
1375
static GIST_SPLITVEC *
1376
_int_common_picksplit(bytea *entryvec,
1377 1378 1379 1380 1381
					  GIST_SPLITVEC *v,
					  formarray unionf,
					  formarray interf,
					  formfloat sizef,
					  float coef)
1382
{
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
	OffsetNumber i,
				j;
	ArrayType  *datum_alpha,
			   *datum_beta;
	ArrayType  *datum_l,
			   *datum_r;
	ArrayType  *union_d,
			   *union_dl,
			   *union_dr;
	ArrayType  *inter_d;
	bool		firsttime;
	float		size_alpha,
				size_beta,
				size_union,
				size_inter;
	float		size_waste,
				waste;
	float		size_l,
				size_r;
	int			nbytes;
	OffsetNumber seed_1 = 0,
				seed_2 = 0;
	OffsetNumber *left,
			   *right;
	OffsetNumber maxoff;
Tom Lane's avatar
Tom Lane committed
1408
	SPLITCOST	*costvector;
1409 1410

#ifdef GIST_DEBUG
1411
	elog(NOTICE, "--------picksplit %d", (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY));
1412 1413
#endif

1414 1415 1416 1417 1418 1419 1420 1421 1422
	maxoff = ((VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY)) - 2;
	nbytes = (maxoff + 2) * sizeof(OffsetNumber);
	v->spl_left = (OffsetNumber *) palloc(nbytes);
	v->spl_right = (OffsetNumber *) palloc(nbytes);

	firsttime = true;
	waste = 0.0;
	for (i = FirstOffsetNumber; i < maxoff; i = OffsetNumberNext(i))
	{
1423
		datum_alpha = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key);
1424 1425
		for (j = OffsetNumberNext(i); j <= maxoff; j = OffsetNumberNext(j))
		{
1426
			datum_beta = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[j].key);
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453

			/* compute the wasted space by unioning these guys */
			/* size_waste = size_union - size_inter; */
			union_d = (*unionf) (datum_alpha, datum_beta);
			(*sizef) (union_d, &size_union);
			inter_d = (*interf) (datum_alpha, datum_beta);
			(*sizef) (inter_d, &size_inter);
			size_waste = size_union - size_inter;

			pfree(union_d);

			if (inter_d != (ArrayType *) NULL)
				pfree(inter_d);

			/*
			 * are these a more promising split that what we've already
			 * seen?
			 */

			if (size_waste > waste || firsttime)
			{
				waste = size_waste;
				seed_1 = i;
				seed_2 = j;
				firsttime = false;
			}
		}
1454
	}
1455 1456 1457 1458 1459 1460

	left = v->spl_left;
	v->spl_nleft = 0;
	right = v->spl_right;
	v->spl_nright = 0;

1461
	datum_alpha = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[seed_1].key);
1462
	datum_l = copy_intArrayType(datum_alpha);
1463 1464
	(*sizef) (datum_l, &size_l);
	datum_beta = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[seed_2].key);
1465
	datum_r = copy_intArrayType(datum_beta);
1466
	(*sizef) (datum_r, &size_r);
1467

Tom Lane's avatar
Tom Lane committed
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
	maxoff = OffsetNumberNext(maxoff);
	/*
     	 * sort entries
	 */
	costvector=(SPLITCOST*)palloc( sizeof(SPLITCOST)*maxoff );
	for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) {
		costvector[i-1].pos = i;
		datum_alpha = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key);
		union_d = (*unionf)(datum_l, datum_alpha);
		(*sizef)(union_d, &size_alpha);
		pfree( union_d );
		union_d = (*unionf)(datum_r, datum_alpha);
		(*sizef)(union_d, &size_beta);
		pfree( union_d );
		costvector[i-1].cost = abs( (size_alpha - size_l) - (size_beta - size_r) );
	}
	qsort( (void*)costvector, maxoff, sizeof(SPLITCOST), comparecost );
 
1486
	/*
1487 1488 1489 1490 1491 1492 1493 1494 1495
	 * Now split up the regions between the two seeds.	An important
	 * property of this split algorithm is that the split vector v has the
	 * indices of items to be split in order in its left and right
	 * vectors.  We exploit this property by doing a merge in the code
	 * that actually splits the page.
	 *
	 * For efficiency, we also place the new index tuple in this loop. This
	 * is handled at the very end, when we have placed all the existing
	 * tuples and i == maxoff + 1.
1496
	 */
1497

Tom Lane's avatar
Tom Lane committed
1498 1499 1500
	
	for (j = 0; j < maxoff; j++) {
		i = costvector[j].pos;
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

		/*
		 * If we've already decided where to place this item, just put it
		 * on the right list.  Otherwise, we need to figure out which page
		 * needs the least enlargement in order to store the item.
		 */

		if (i == seed_1)
		{
			*left++ = i;
			v->spl_nleft++;
			continue;
		}
		else if (i == seed_2)
		{
			*right++ = i;
			v->spl_nright++;
			continue;
		}

		/* okay, which page needs least enlargement? */
1522 1523 1524 1525 1526
		datum_alpha = (ArrayType *) DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key);
		union_dl = (*unionf) (datum_l, datum_alpha);
		union_dr = (*unionf) (datum_r, datum_alpha);
		(*sizef) (union_dl, &size_alpha);
		(*sizef) (union_dr, &size_beta);
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550

		/* pick which page to add it to */
		if (size_alpha - size_l < size_beta - size_r + WISH_F(v->spl_nleft, v->spl_nright, coef))
		{
			if (datum_l)
				pfree(datum_l);
			if (union_dr)
				pfree(union_dr);
			datum_l = union_dl;
			size_l = size_alpha;
			*left++ = i;
			v->spl_nleft++;
		}
		else
		{
			if (datum_r)
				pfree(datum_r);
			if (union_dl)
				pfree(union_dl);
			datum_r = union_dr;
			size_r = size_beta;
			*right++ = i;
			v->spl_nright++;
		}
1551
	}
Tom Lane's avatar
Tom Lane committed
1552 1553
	pfree( costvector );
	*right = *left = FirstOffsetNumber;
1554

Tom Lane's avatar
Tom Lane committed
1555 1556
	datum_l->flags &= ~LEAFKEY;
	datum_r->flags &= ~LEAFKEY;
1557 1558
	v->spl_ldatum = PointerGetDatum(datum_l);
	v->spl_rdatum = PointerGetDatum(datum_r);
1559 1560

#ifdef GIST_DEBUG
1561
	elog(NOTICE, "--------ENDpicksplit %d %d", v->spl_nleft, v->spl_nright);
1562
#endif
1563
	return v;
1564
}
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747

/*****************************************************************************
 *	 	BoolSearch	
 *****************************************************************************/


#define END     0
#define ERR     1
#define VAL     2
#define OPR     3
#define OPEN    4
#define CLOSE   5

/* parser's states */
#define WAITOPERAND	1
#define WAITENDOPERAND	2
#define WAITOPERATOR	3

/*
 * node of query tree, also used
 * for storing polish notation in parser
 */
typedef struct NODE {
	int4	type;
	int4	val;
	struct NODE 	*next;
} NODE;

typedef struct {
	char *buf;
	int4	state;
	int4  count;
	/* reverse polish notation in list (for temprorary usage)*/
	NODE	*str;
	/* number in str */
	int4	num;
} WORKSTATE;

/*
 * get token from query string
 */
static int4 
gettoken( WORKSTATE* state, int4* val ) {
	char nnn[16], *curnnn;

	curnnn=nnn;
	while(1) {
		switch(state->state) {
			case WAITOPERAND:
				curnnn=nnn;
				if ( (*(state->buf)>='0' && *(state->buf)<='9') || 
						*(state->buf)=='-' ) {
					state->state = WAITENDOPERAND;
					*curnnn = *(state->buf);
					curnnn++;
				} else if ( *(state->buf) == '!' ) {
					(state->buf)++;
					*val = (int4)'!';
					return OPR;
				} else if ( *(state->buf) == '(' ) {
					state->count++;
					(state->buf)++;
					return OPEN;
				} else if ( *(state->buf) != ' ' ) 
					return ERR;
				break;
			case WAITENDOPERAND:
				if ( *(state->buf)>='0' && *(state->buf)<='9' ) {
					*curnnn = *(state->buf);
					curnnn++;
				} else {
					*curnnn = '\0';
					*val=(int4)atoi( nnn );
					state->state = WAITOPERATOR;
					return ( state->count && *(state->buf) == '\0' ) 
						? ERR : VAL;
				}
				break;
			case WAITOPERATOR:
				if ( *(state->buf) == '&' || *(state->buf) == '|' ) {
					state->state = WAITOPERAND;
					*val = (int4) *(state->buf);
	 				(state->buf)++;
					return OPR;
				} else if ( *(state->buf) == ')' ) {
					(state->buf)++;
					state->count--;
					return ( state->count <0 ) ? ERR : CLOSE;
				} else if ( *(state->buf) == '\0' ) {
					return ( state->count ) ? ERR : END;
				} else if ( *(state->buf) != ' ' )
					return ERR;
				break;
	   		default:
				return ERR;
				break;
	 	}
	 	(state->buf)++;
	}
	return END;
}

/*
 * push new one in polish notation reverse view
 */
static void
pushquery( WORKSTATE *state, int4 type, int4 val ) {
	NODE    *tmp = (NODE*)palloc(sizeof(NODE));
	tmp->type=type;
	tmp->val =val;
	tmp->next = state->str;
	state->str = tmp;
	state->num++;
}

#define STACKDEPTH	16

/*
 * make polish notaion of query
 */
static int4 
makepol(WORKSTATE *state) {
	int4 val,type;
	int4	stack[STACKDEPTH];
	int4	lenstack=0;

	while( (type=gettoken(state, &val))!=END ) {
		switch(type) {
			case VAL:
				pushquery(state, type, val);
				while ( lenstack && (stack[ lenstack-1 ] == (int4)'&' || 
						stack[ lenstack-1 ] == (int4)'!') ) {
					lenstack--;
					pushquery(state, OPR, stack[ lenstack ]);
				}
				break;
			case OPR:
				if ( lenstack && val == (int4) '|' ) {
					pushquery(state, OPR, val);
				} else { 
					if ( lenstack == STACKDEPTH )
						elog(ERROR,"Stack too short");
					stack[ lenstack ] = val;
					lenstack++;
				}
				break;
			case OPEN:
				if ( makepol( state ) == ERR ) return ERR;
				if ( lenstack && (stack[ lenstack-1 ] == (int4)'&' || 
						stack[ lenstack-1 ] == (int4)'!') ) {
					lenstack--;
					pushquery(state, OPR, stack[ lenstack ]);
				}
				break;
			case CLOSE:
				while ( lenstack ) {
					lenstack--;
					pushquery(state, OPR, stack[ lenstack ]);
				};
				return END;
				break;
			case ERR:
			default:
				elog(ERROR,"Syntax error");
				return ERR;
			
		}
	}

	while (lenstack) {
		lenstack--;
		pushquery(state, OPR, stack[ lenstack ]);
	};
	return END;
}

typedef struct {
	int4 *arrb;
	int4 *arre;
} CHKVAL;

/*
 * is there value 'val' in array or not ?
1748
 */
1749 1750
static bool
checkcondition_arr( void *checkval, int4 val ) {
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
	int4      *StopLow = ((CHKVAL*)checkval)->arrb;
	int4      *StopHigh = ((CHKVAL*)checkval)->arre;
	int4      *StopMiddle;

	/* Loop invariant: StopLow <= val < StopHigh */

	while (StopLow < StopHigh) {
		StopMiddle = StopLow + (StopHigh - StopLow) / 2;
		if (*StopMiddle == val)
			return (true);
		else if (*StopMiddle < val )
			StopLow = StopMiddle + 1;
		else
			StopHigh = StopMiddle;
1765
	}
1766
	return false;
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
}

static bool
checkcondition_bit( void *checkval, int4 val ) {
	return GETBIT( checkval, HASHVAL( val ) ); 	
}

/*
 * check for boolean condition
 */
static bool
execute( ITEM* curitem, void *checkval, bool calcnot, bool (*chkcond)(void *checkval, int4 val )) {

	if (  curitem->type == VAL ) {
		return (*chkcond)( checkval, curitem->val );
	} else if ( curitem->val == (int4)'!' ) {
		return ( calcnot ) ? 
			( ( execute(curitem - 1, checkval, calcnot, chkcond) ) ? false : true ) 
			: true;
	} else if ( curitem->val == (int4)'&' ) {
		if ( execute(curitem + curitem->left, checkval, calcnot, chkcond) )
			return execute(curitem - 1, checkval, calcnot, chkcond);
		else
			return false;
	} else { /* |-operator */
		if ( execute(curitem + curitem->left, checkval, calcnot, chkcond) )
			return true;
		else
			return execute(curitem - 1, checkval, calcnot, chkcond);
	}
	return false;
} 

/*
 * signconsistent & execconsistent called by *_consistent
 */
static bool 
signconsistent( QUERYTYPE *query, BITVEC sign, bool calcnot ) {
	return execute( 
		GETQUERY(query) + query->size-1 , 
		(void*)sign, calcnot, 
		checkcondition_bit 
	); 
}

static bool 
execconsistent( QUERYTYPE *query, ArrayType *array, bool calcnot ) {
	CHKVAL  chkval;

	chkval.arrb = ARRPTR(array);
1817
	chkval.arre = chkval.arrb + ARRNELEMS(array);
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
	return execute( 
		GETQUERY(query) + query->size-1 , 
		(void*)&chkval, calcnot, 
		checkcondition_arr 
	);
}

/*
 * boolean operations 
 */
Datum
rboolop(PG_FUNCTION_ARGS) {
	return DirectFunctionCall2(
		boolop,
		PG_GETARG_DATUM(1),
		PG_GETARG_DATUM(0)
	);
}

Datum
boolop(PG_FUNCTION_ARGS) {
	ArrayType *val = ( ArrayType * )PG_DETOAST_DATUM_COPY(PG_GETARG_POINTER(0));
	QUERYTYPE *query = ( QUERYTYPE * )PG_DETOAST_DATUM(PG_GETARG_POINTER(1));
	CHKVAL  chkval;
	bool result;
	
	if ( ARRISVOID( val ) ) {
		pfree(val);
		PG_FREE_IF_COPY(query,1);
		PG_RETURN_BOOL( false );
	}

	PREPAREARR(val);
	chkval.arrb = ARRPTR(val);
1852
	chkval.arre = chkval.arrb + ARRNELEMS(val);
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
	result = execute( 
		GETQUERY(query) + query->size-1 , 
		&chkval, true, 
		checkcondition_arr 
	);
	pfree(val);

	PG_FREE_IF_COPY(query,1);
	PG_RETURN_BOOL( result );
}

static void
findoprnd( ITEM *ptr, int4 *pos ) {
#ifdef BS_DEBUG
	elog(NOTICE, ( ptr[*pos].type == OPR ) ? 
		"%d  %c" : "%d  %d ", *pos, ptr[*pos].val );
#endif
	if ( ptr[*pos].type == VAL ) {
		ptr[*pos].left = 0;
		(*pos)--;
	} else if ( ptr[*pos].val == (int4)'!' ) {
		ptr[*pos].left = -1;
		(*pos)--;
		findoprnd( ptr, pos );
	} else {
		ITEM *curitem = &ptr[*pos];
		int4 tmp = *pos; 
		(*pos)--;
		findoprnd(ptr,pos);
		curitem->left = *pos - tmp;
		findoprnd(ptr,pos);
	}
}


/*
 * input
 */
Datum
bqarr_in(PG_FUNCTION_ARGS) {
	char *buf=(char*)PG_GETARG_POINTER(0);
	WORKSTATE state;
	int4 i;
	QUERYTYPE	*query;
	int4 commonlen;
	ITEM *ptr;
	NODE *tmp;
	int4 pos=0;
#ifdef BS_DEBUG
	char pbuf[16384],*cur;
#endif

	state.buf = buf;
	state.state = WAITOPERAND;
	state.count = 0;
	state.num = 0;
	state.str=NULL;

	/* make polish notation (postfix, but in reverse order) */
	makepol( &state );
	if (!state.num) 
		elog( ERROR,"Empty query");

	commonlen = COMPUTESIZE(state.num);
	query = (QUERYTYPE*) palloc( commonlen );
	query->len = commonlen;
	query->size = state.num;
	ptr = GETQUERY(query);

	for(i=state.num-1; i>=0; i-- ) {
		ptr[i].type = state.str->type; 
		ptr[i].val = state.str->val;
		tmp = state.str->next;
		pfree( state.str );
		state.str = tmp;
	}
	
	pos = query->size-1;
	findoprnd( ptr, &pos );
#ifdef BS_DEBUG
	cur = pbuf;
	*cur = '\0';
	for( i=0;i<query->size;i++ ) {
		if ( ptr[i].type == OPR ) 
			sprintf(cur, "%c(%d) ", ptr[i].val, ptr[i].left);
		else 
			sprintf(cur, "%d ", ptr[i].val );
		cur = strchr(cur,'\0');	
	}
	elog(NOTICE,"POR: %s", pbuf);
#endif

	PG_RETURN_POINTER( query );
}


/*
 * out function
 */
typedef struct {
	ITEM    *curpol;
	char *buf;
	char *cur;
	int4 buflen;
} INFIX;

#define RESIZEBUF(inf,addsize) while( ( inf->cur - inf->buf ) + addsize + 1 >= inf->buflen ) { \
	int4 len = inf->cur - inf->buf; \
	inf->buflen *= 2; \
	inf->buf = (char*) repalloc( (void*)inf->buf, inf->buflen ); \
	inf->cur = inf->buf + len; \
}

static void
infix(INFIX *in, bool first) {
	if ( in->curpol->type == VAL ) {
		RESIZEBUF(in, 11);
		sprintf(in->cur, "%d", in->curpol->val );
		in->cur = strchr( in->cur, '\0' );
		in->curpol--;
	} else if ( in->curpol->val == (int4)'!' ) {
		bool isopr = false;
		RESIZEBUF(in, 1);
		*(in->cur) = '!';
		in->cur++;
		*(in->cur) = '\0';
		in->curpol--;
		if ( in->curpol->type == OPR ) {
			isopr = true;
			RESIZEBUF(in, 2);
			sprintf(in->cur, "( ");
			in->cur = strchr( in->cur, '\0' );
		} 
		infix( in, isopr );
		if ( isopr ) {
			RESIZEBUF(in, 2);
			sprintf(in->cur, " )");
			in->cur = strchr( in->cur, '\0' );
		} 
	} else {
		int4 op = in->curpol->val;
		INFIX   nrm;
		
		in->curpol--;
		if ( op == (int4)'|' && ! first) {
			RESIZEBUF(in, 2);
			sprintf(in->cur, "( ");
			in->cur = strchr( in->cur, '\0' );
		}

		nrm.curpol = in->curpol;
		nrm.buflen = 16;
		nrm.cur = nrm.buf = (char*)palloc( sizeof(char) * nrm.buflen );
		
		/* get right operand */
		infix( &nrm, false );
		
		/* get & print left operand */
		in->curpol = nrm.curpol;
		infix( in, false );

		/* print operator & right operand*/
		RESIZEBUF(in, 3 + (nrm.cur - nrm.buf) );
		sprintf(in->cur, " %c %s", op, nrm.buf);
		in->cur = strchr( in->cur, '\0' );
		pfree( nrm.buf );

		if ( op == (int4)'|' && ! first) {
			RESIZEBUF(in, 2);
			sprintf(in->cur, " )");
			in->cur = strchr( in->cur, '\0' );
		}
	}
}


Datum
bqarr_out(PG_FUNCTION_ARGS) {
	QUERYTYPE       *query = (QUERYTYPE*)PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
	INFIX   nrm;

	if ( query->size == 0 )
		elog(ERROR,"Empty");	
	nrm.curpol = GETQUERY(query) + query->size - 1;
	nrm.buflen = 32;
	nrm.cur = nrm.buf = (char*)palloc( sizeof(char) * nrm.buflen );
	*(nrm.cur) = '\0';
	infix( &nrm, true );
	
	PG_FREE_IF_COPY(query,0);
	PG_RETURN_POINTER( nrm.buf );
}

static int4
countdroptree( ITEM *q, int4 pos ) {
	if ( q[pos].type == VAL ) {
		return 1;
	} else if ( q[pos].val == (int4)'!' ) {
		return 1+countdroptree(q, pos-1);
	} else {
		return 1 + countdroptree(q, pos-1) + countdroptree(q, pos + q[pos].left); 
	} 
}

/*
 * common algorithm:
 * result of all '!' will be = 'true', so 
 * we can modify query tree for clearing
 */
static int4 
shorterquery( ITEM *q, int4 len ) {
	int4 index,posnot,poscor;
	bool notisleft = false;
	int4 drop,i;

	/* out all '!' */
	do {
		index=0;
		drop=0;
		/* find ! */
		for(posnot=0; posnot < len; posnot++)
			if ( q[posnot].type == OPR  && q[posnot].val == (int4)'!') {
				index=1;
				break;
			}

		if ( posnot == len )
			return len;

		/* last operator is ! */
		if ( posnot == len-1 )
			return 0;

		/* find operator for this operand */
		for( poscor=posnot+1; poscor<len; poscor++) {
			if ( q[poscor].type == OPR ) {
				if ( poscor == posnot+1 ) {
					notisleft = false;
					break;
				} else if ( q[poscor].left + poscor == posnot ) { 
					notisleft = true;
					break;
				}
			}
		}
		if ( q[poscor].val == (int4)'!' ) {
			drop = countdroptree(q, poscor);
			q[poscor-1].type=VAL;
			for(i=poscor+1;i<len;i++)
				if ( q[i].type == OPR && q[i].left + i <= poscor )
					q[i].left += drop - 2; 
			memcpy( (void*)&q[poscor-drop+1], 
				(void*)&q[poscor-1], 
				sizeof(ITEM) * ( len - (poscor-1) ));
			len -= drop - 2;
		} else if ( q[poscor].val == (int4)'|' ) {
			drop = countdroptree(q, poscor);
			q[poscor-1].type=VAL;
			q[poscor].val=(int4)'!';
			q[poscor].left=-1;
			for(i=poscor+1;i<len;i++)
				if ( q[i].type == OPR && q[i].left + i < poscor )
					q[i].left += drop - 2; 
			memcpy( (void*)&q[poscor-drop+1], 
				(void*)&q[poscor-1], 
				sizeof(ITEM) * ( len - (poscor-1) ));
			len -= drop - 2;
		} else { /* &-operator */
			if ( 
					(notisleft && q[poscor-1].type == OPR && 
						q[poscor-1].val == (int4)'!' ) ||
					(!notisleft && q[poscor+q[poscor].left].type == OPR && 
						q[poscor+q[poscor].left].val == (int4)'!' )
				) { /* drop subtree */
				drop = countdroptree(q, poscor);
				q[poscor-1].type=VAL;
				q[poscor].val=(int4)'!';
				q[poscor].left=-1;
				for(i=poscor+1;i<len;i++)
					if ( q[i].type == OPR && q[i].left + i < poscor )
						q[i].left += drop - 2; 
				memcpy( (void*)&q[poscor-drop+1], 
					(void*)&q[poscor-1], 
					sizeof(ITEM) * ( len - (poscor-1) ));
				len -= drop - 2;
			} else { /* drop only operator */
				int4 subtreepos = ( notisleft ) ? 
					poscor-1 : poscor+q[poscor].left;
				int4 subtreelen = countdroptree( q, subtreepos );
				drop = countdroptree(q, poscor);
				for(i=poscor+1;i<len;i++)
					if ( q[i].type == OPR && q[i].left + i < poscor )
						q[i].left += drop - subtreelen; 
				memcpy( (void*)&q[ subtreepos+1 ], 
					(void*)&q[poscor+1], 
					sizeof(ITEM)*( len - (poscor-1) ) ); 
				memcpy( (void*)&q[ poscor-drop+1 ], 
					(void*)&q[subtreepos-subtreelen+1], 
					sizeof(ITEM)*( len - (drop-subtreelen) ) );
				len -= drop - subtreelen;  
			}
		}
	} while( index );
	return len;
}


Datum
querytree(PG_FUNCTION_ARGS) {
	QUERYTYPE       *query = (QUERYTYPE*)PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
	INFIX   nrm;
	text 	*res;
	ITEM	*q;
	int4	len;

	if ( query->size == 0 )
		elog(ERROR,"Empty");

	q = (ITEM*)palloc( sizeof(ITEM) * query->size );
	memcpy( (void*)q, GETQUERY(query), sizeof(ITEM) * query->size );
	len = shorterquery( q, query->size );
	PG_FREE_IF_COPY(query,0);

	if ( len == 0 ) {
		res = (text*) palloc( 1 + VARHDRSZ );
		VARATT_SIZEP(res) = 1 + VARHDRSZ;
		*((char*)VARDATA(res)) = 'T';
	} else {
		nrm.curpol = q + len - 1;
		nrm.buflen = 32;
		nrm.cur = nrm.buf = (char*)palloc( sizeof(char) * nrm.buflen );
		*(nrm.cur) = '\0';
		infix( &nrm, true );

		res = (text*) palloc( nrm.cur-nrm.buf + VARHDRSZ );
		VARATT_SIZEP(res) = nrm.cur-nrm.buf + VARHDRSZ;
		strncpy( VARDATA(res), nrm.buf, nrm.cur-nrm.buf );
	}
	pfree(q);

	PG_RETURN_POINTER( res );
}