pgindent run.
authorBruce Momjian <bruce@momjian.us>
Wed, 4 Sep 2002 20:31:48 +0000 (20:31 +0000)
committerBruce Momjian <bruce@momjian.us>
Wed, 4 Sep 2002 20:31:48 +0000 (20:31 +0000)
446 files changed:
contrib/btree_gist/btree_gist.c
contrib/cube/cube.c
contrib/dbase/dbf2pg.c
contrib/dblink/dblink.c
contrib/dblink/dblink.h
contrib/dbmirror/pending.c
contrib/dbsize/dbsize.c
contrib/findoidjoins/findoidjoins.c
contrib/intagg/int_aggregate.c
contrib/intarray/_int.c
contrib/ltree/_ltree_gist.c
contrib/ltree/_ltree_op.c
contrib/ltree/crc32.c
contrib/ltree/lquery_op.c
contrib/ltree/ltree.h
contrib/ltree/ltree_gist.c
contrib/ltree/ltree_io.c
contrib/ltree/ltree_op.c
contrib/ltree/ltxtquery_io.c
contrib/ltree/ltxtquery_op.c
contrib/mSQL-interface/mpgsql.c
contrib/pg_dumplo/lo_export.c
contrib/pg_dumplo/lo_import.c
contrib/pg_dumplo/main.c
contrib/pgbench/pgbench.c
contrib/pgstattuple/pgstattuple.c
contrib/rserv/rserv.c
contrib/rtree_gist/rtree_gist.c
contrib/spi/refint.c
contrib/spi/timetravel.c
contrib/tablefunc/tablefunc.c
contrib/tablefunc/tablefunc.h
contrib/tsearch/deflex.h
contrib/tsearch/gistidx.c
contrib/tsearch/morph.c
contrib/tsearch/query.c
contrib/tsearch/txtidx.c
contrib/vacuumlo/vacuumlo.c
src/backend/access/common/heaptuple.c
src/backend/access/common/indextuple.c
src/backend/access/common/printtup.c
src/backend/access/common/tupdesc.c
src/backend/access/gist/gist.c
src/backend/access/gist/gistget.c
src/backend/access/hash/hash.c
src/backend/access/hash/hashfunc.c
src/backend/access/hash/hashscan.c
src/backend/access/heap/heapam.c
src/backend/access/heap/tuptoaster.c
src/backend/access/index/genam.c
src/backend/access/index/indexam.c
src/backend/access/nbtree/nbtinsert.c
src/backend/access/nbtree/nbtree.c
src/backend/access/nbtree/nbtutils.c
src/backend/access/rtree/rtget.c
src/backend/access/rtree/rtree.c
src/backend/access/transam/transam.c
src/backend/access/transam/varsup.c
src/backend/access/transam/xact.c
src/backend/access/transam/xlog.c
src/backend/bootstrap/bootstrap.c
src/backend/catalog/aclchk.c
src/backend/catalog/catalog.c
src/backend/catalog/dependency.c
src/backend/catalog/heap.c
src/backend/catalog/index.c
src/backend/catalog/indexing.c
src/backend/catalog/namespace.c
src/backend/catalog/pg_aggregate.c
src/backend/catalog/pg_constraint.c
src/backend/catalog/pg_conversion.c
src/backend/catalog/pg_depend.c
src/backend/catalog/pg_operator.c
src/backend/catalog/pg_proc.c
src/backend/catalog/pg_type.c
src/backend/commands/aggregatecmds.c
src/backend/commands/analyze.c
src/backend/commands/cluster.c
src/backend/commands/comment.c
src/backend/commands/conversioncmds.c
src/backend/commands/copy.c
src/backend/commands/dbcommands.c
src/backend/commands/define.c
src/backend/commands/explain.c
src/backend/commands/functioncmds.c
src/backend/commands/indexcmds.c
src/backend/commands/lockcmds.c
src/backend/commands/opclasscmds.c
src/backend/commands/operatorcmds.c
src/backend/commands/portalcmds.c
src/backend/commands/prepare.c
src/backend/commands/proclang.c
src/backend/commands/schemacmds.c
src/backend/commands/sequence.c
src/backend/commands/tablecmds.c
src/backend/commands/trigger.c
src/backend/commands/typecmds.c
src/backend/commands/user.c
src/backend/commands/vacuum.c
src/backend/commands/vacuumlazy.c
src/backend/commands/variable.c
src/backend/commands/view.c
src/backend/executor/execJunk.c
src/backend/executor/execMain.c
src/backend/executor/execQual.c
src/backend/executor/execTuples.c
src/backend/executor/execUtils.c
src/backend/executor/functions.c
src/backend/executor/nodeAgg.c
src/backend/executor/nodeFunctionscan.c
src/backend/executor/nodeHash.c
src/backend/executor/nodeIndexscan.c
src/backend/executor/nodeMergejoin.c
src/backend/executor/nodeSeqscan.c
src/backend/executor/nodeTidscan.c
src/backend/executor/spi.c
src/backend/lib/stringinfo.c
src/backend/libpq/auth.c
src/backend/libpq/be-secure.c
src/backend/libpq/crypt.c
src/backend/libpq/hba.c
src/backend/libpq/md5.c
src/backend/libpq/pqcomm.c
src/backend/main/main.c
src/backend/nodes/copyfuncs.c
src/backend/nodes/makefuncs.c
src/backend/nodes/outfuncs.c
src/backend/nodes/print.c
src/backend/nodes/readfuncs.c
src/backend/optimizer/geqo/geqo_misc.c
src/backend/optimizer/path/allpaths.c
src/backend/optimizer/path/costsize.c
src/backend/optimizer/path/indxpath.c
src/backend/optimizer/path/joinpath.c
src/backend/optimizer/path/pathkeys.c
src/backend/optimizer/plan/createplan.c
src/backend/optimizer/plan/initsplan.c
src/backend/optimizer/plan/planner.c
src/backend/optimizer/plan/setrefs.c
src/backend/optimizer/plan/subselect.c
src/backend/optimizer/prep/preptlist.c
src/backend/optimizer/prep/prepunion.c
src/backend/optimizer/util/clauses.c
src/backend/optimizer/util/plancat.c
src/backend/optimizer/util/relnode.c
src/backend/optimizer/util/var.c
src/backend/parser/analyze.c
src/backend/parser/parse_clause.c
src/backend/parser/parse_coerce.c
src/backend/parser/parse_expr.c
src/backend/parser/parse_func.c
src/backend/parser/parse_node.c
src/backend/parser/parse_oper.c
src/backend/parser/parse_relation.c
src/backend/parser/parse_target.c
src/backend/parser/parse_type.c
src/backend/parser/parser.c
src/backend/port/dynloader/bsdi.h
src/backend/port/ipc_test.c
src/backend/port/posix_sema.c
src/backend/port/qnx4/tstsem.c
src/backend/port/sysv_sema.c
src/backend/port/sysv_shmem.c
src/backend/postmaster/pgstat.c
src/backend/postmaster/postmaster.c
src/backend/regex/regcomp.c
src/backend/rewrite/rewriteDefine.c
src/backend/rewrite/rewriteHandler.c
src/backend/rewrite/rewriteManip.c
src/backend/rewrite/rewriteRemove.c
src/backend/storage/buffer/buf_init.c
src/backend/storage/buffer/bufmgr.c
src/backend/storage/buffer/localbuf.c
src/backend/storage/freespace/freespace.c
src/backend/storage/ipc/ipc.c
src/backend/storage/ipc/shmem.c
src/backend/storage/ipc/sinval.c
src/backend/storage/lmgr/deadlock.c
src/backend/storage/lmgr/lock.c
src/backend/storage/lmgr/lwlock.c
src/backend/storage/lmgr/proc.c
src/backend/storage/lmgr/spin.c
src/backend/storage/page/bufpage.c
src/backend/storage/smgr/smgr.c
src/backend/tcop/postgres.c
src/backend/tcop/pquery.c
src/backend/tcop/utility.c
src/backend/utils/adt/acl.c
src/backend/utils/adt/arrayfuncs.c
src/backend/utils/adt/cash.c
src/backend/utils/adt/date.c
src/backend/utils/adt/datetime.c
src/backend/utils/adt/datum.c
src/backend/utils/adt/float.c
src/backend/utils/adt/format_type.c
src/backend/utils/adt/formatting.c
src/backend/utils/adt/geo_ops.c
src/backend/utils/adt/int8.c
src/backend/utils/adt/lockfuncs.c
src/backend/utils/adt/mac.c
src/backend/utils/adt/misc.c
src/backend/utils/adt/nabstime.c
src/backend/utils/adt/name.c
src/backend/utils/adt/not_in.c
src/backend/utils/adt/numeric.c
src/backend/utils/adt/numutils.c
src/backend/utils/adt/oracle_compat.c
src/backend/utils/adt/pg_locale.c
src/backend/utils/adt/pg_lzcompress.c
src/backend/utils/adt/pseudotypes.c
src/backend/utils/adt/regexp.c
src/backend/utils/adt/regproc.c
src/backend/utils/adt/ri_triggers.c
src/backend/utils/adt/ruleutils.c
src/backend/utils/adt/selfuncs.c
src/backend/utils/adt/sets.c
src/backend/utils/adt/tid.c
src/backend/utils/adt/timestamp.c
src/backend/utils/adt/varbit.c
src/backend/utils/adt/varchar.c
src/backend/utils/adt/varlena.c
src/backend/utils/cache/catcache.c
src/backend/utils/cache/inval.c
src/backend/utils/cache/lsyscache.c
src/backend/utils/cache/relcache.c
src/backend/utils/cache/syscache.c
src/backend/utils/error/assert.c
src/backend/utils/error/elog.c
src/backend/utils/fmgr/fmgr.c
src/backend/utils/fmgr/funcapi.c
src/backend/utils/init/findbe.c
src/backend/utils/init/globals.c
src/backend/utils/init/miscinit.c
src/backend/utils/init/postinit.c
src/backend/utils/mb/conv.c
src/backend/utils/mb/conversion_procs/ascii_and_mic/ascii_and_mic.c
src/backend/utils/mb/conversion_procs/cyrillic_and_mic/cyrillic_and_mic.c
src/backend/utils/mb/conversion_procs/euc_cn_and_mic/euc_cn_and_mic.c
src/backend/utils/mb/conversion_procs/euc_jp_and_sjis/euc_jp_and_sjis.c
src/backend/utils/mb/conversion_procs/euc_kr_and_mic/euc_kr_and_mic.c
src/backend/utils/mb/conversion_procs/euc_tw_and_big5/big5.c
src/backend/utils/mb/conversion_procs/euc_tw_and_big5/euc_tw_and_big5.c
src/backend/utils/mb/conversion_procs/latin2_and_win1250/latin2_and_win1250.c
src/backend/utils/mb/conversion_procs/latin_and_mic/latin_and_mic.c
src/backend/utils/mb/conversion_procs/utf8_and_ascii/utf8_and_ascii.c
src/backend/utils/mb/conversion_procs/utf8_and_big5/utf8_and_big5.c
src/backend/utils/mb/conversion_procs/utf8_and_cyrillic/utf8_and_cyrillic.c
src/backend/utils/mb/conversion_procs/utf8_and_euc_cn/utf8_and_euc_cn.c
src/backend/utils/mb/conversion_procs/utf8_and_euc_jp/utf8_and_euc_jp.c
src/backend/utils/mb/conversion_procs/utf8_and_euc_kr/utf8_and_euc_kr.c
src/backend/utils/mb/conversion_procs/utf8_and_euc_tw/utf8_and_euc_tw.c
src/backend/utils/mb/conversion_procs/utf8_and_gb18030/utf8_and_gb18030.c
src/backend/utils/mb/conversion_procs/utf8_and_gbk/utf8_and_gbk.c
src/backend/utils/mb/conversion_procs/utf8_and_iso8859/utf8_and_iso8859.c
src/backend/utils/mb/conversion_procs/utf8_and_iso8859_1/utf8_and_iso8859_1.c
src/backend/utils/mb/conversion_procs/utf8_and_johab/utf8_and_johab.c
src/backend/utils/mb/conversion_procs/utf8_and_sjis/utf8_and_sjis.c
src/backend/utils/mb/conversion_procs/utf8_and_tcvn/utf8_and_tcvn.c
src/backend/utils/mb/conversion_procs/utf8_and_uhc/utf8_and_uhc.c
src/backend/utils/mb/conversion_procs/utf8_and_win1250/utf8_and_win1250.c
src/backend/utils/mb/conversion_procs/utf8_and_win1256/utf8_and_win1256.c
src/backend/utils/mb/conversion_procs/utf8_and_win874/utf8_and_win874.c
src/backend/utils/mb/encnames.c
src/backend/utils/mb/mbutils.c
src/backend/utils/mb/wchar.c
src/backend/utils/misc/database.c
src/backend/utils/misc/guc.c
src/backend/utils/misc/ps_status.c
src/backend/utils/mmgr/aset.c
src/backend/utils/sort/tuplesort.c
src/backend/utils/time/tqual.c
src/bin/pg_controldata/pg_controldata.c
src/bin/pg_dump/common.c
src/bin/pg_dump/dumputils.c
src/bin/pg_dump/dumputils.h
src/bin/pg_dump/pg_backup.h
src/bin/pg_dump/pg_backup_archiver.c
src/bin/pg_dump/pg_backup_archiver.h
src/bin/pg_dump/pg_backup_custom.c
src/bin/pg_dump/pg_backup_db.c
src/bin/pg_dump/pg_backup_files.c
src/bin/pg_dump/pg_backup_null.c
src/bin/pg_dump/pg_backup_tar.c
src/bin/pg_dump/pg_dump.c
src/bin/pg_dump/pg_dump.h
src/bin/pg_dump/pg_dumpall.c
src/bin/pg_dump/pg_restore.c
src/bin/pg_dump/sprompt.c
src/bin/pg_resetxlog/pg_resetxlog.c
src/bin/psql/command.c
src/bin/psql/common.c
src/bin/psql/copy.c
src/bin/psql/describe.c
src/bin/psql/help.c
src/bin/psql/input.h
src/bin/psql/large_obj.c
src/bin/psql/mainloop.c
src/bin/psql/print.h
src/bin/psql/sprompt.c
src/bin/psql/startup.c
src/bin/psql/tab-complete.c
src/include/access/genam.h
src/include/access/heapam.h
src/include/access/htup.h
src/include/access/istrat.h
src/include/access/printtup.h
src/include/access/relscan.h
src/include/access/tupdesc.h
src/include/access/tuptoaster.h
src/include/access/valid.h
src/include/access/xlog.h
src/include/c.h
src/include/catalog/dependency.h
src/include/catalog/heap.h
src/include/catalog/indexing.h
src/include/catalog/namespace.h
src/include/catalog/pg_aggregate.h
src/include/catalog/pg_attribute.h
src/include/catalog/pg_cast.h
src/include/catalog/pg_class.h
src/include/catalog/pg_constraint.h
src/include/catalog/pg_control.h
src/include/catalog/pg_conversion.h
src/include/catalog/pg_language.h
src/include/catalog/pg_namespace.h
src/include/catalog/pg_opclass.h
src/include/catalog/pg_operator.h
src/include/catalog/pg_proc.h
src/include/catalog/pg_shadow.h
src/include/catalog/pg_statistic.h
src/include/catalog/pg_type.h
src/include/commands/conversioncmds.h
src/include/commands/copy.h
src/include/commands/defrem.h
src/include/commands/lockcmds.h
src/include/commands/portalcmds.h
src/include/commands/prepare.h
src/include/commands/schemacmds.h
src/include/commands/tablecmds.h
src/include/commands/trigger.h
src/include/commands/user.h
src/include/commands/variable.h
src/include/executor/execdesc.h
src/include/executor/executor.h
src/include/fmgr.h
src/include/funcapi.h
src/include/libpq/crypt.h
src/include/libpq/pqcomm.h
src/include/mb/pg_wchar.h
src/include/miscadmin.h
src/include/nodes/execnodes.h
src/include/nodes/makefuncs.h
src/include/nodes/parsenodes.h
src/include/nodes/plannodes.h
src/include/nodes/primnodes.h
src/include/nodes/print.h
src/include/nodes/relation.h
src/include/optimizer/cost.h
src/include/optimizer/geqo_misc.h
src/include/optimizer/planmain.h
src/include/parser/gramparse.h
src/include/parser/parse_coerce.h
src/include/parser/parse_func.h
src/include/parser/parse_oper.h
src/include/parser/parse_relation.h
src/include/parser/parse_target.h
src/include/parser/parsetree.h
src/include/port/hpux.h
src/include/postgres.h
src/include/regex/regex.h
src/include/rewrite/rewriteDefine.h
src/include/rewrite/rewriteRemove.h
src/include/storage/buf_internals.h
src/include/storage/bufmgr.h
src/include/storage/bufpage.h
src/include/storage/ipc.h
src/include/storage/lock.h
src/include/storage/pg_sema.h
src/include/storage/pg_shmem.h
src/include/storage/pmsignal.h
src/include/storage/proc.h
src/include/storage/sinval.h
src/include/tcop/dest.h
src/include/tcop/pquery.h
src/include/tcop/utility.h
src/include/utils/acl.h
src/include/utils/array.h
src/include/utils/builtins.h
src/include/utils/catcache.h
src/include/utils/date.h
src/include/utils/datetime.h
src/include/utils/elog.h
src/include/utils/guc.h
src/include/utils/inval.h
src/include/utils/lsyscache.h
src/include/utils/memutils.h
src/include/utils/pg_locale.h
src/include/utils/portal.h
src/include/utils/rel.h
src/include/utils/selfuncs.h
src/include/utils/syscache.h
src/include/utils/timestamp.h
src/include/utils/tqual.h
src/interfaces/cli/example1.c
src/interfaces/cli/example2.c
src/interfaces/cli/sqlcli.h
src/interfaces/ecpg/include/ecpgerrno.h
src/interfaces/ecpg/include/ecpglib.h
src/interfaces/ecpg/include/ecpgtype.h
src/interfaces/ecpg/lib/connect.c
src/interfaces/ecpg/lib/data.c
src/interfaces/ecpg/lib/descriptor.c
src/interfaces/ecpg/lib/error.c
src/interfaces/ecpg/lib/execute.c
src/interfaces/ecpg/lib/extern.h
src/interfaces/ecpg/lib/memory.c
src/interfaces/ecpg/lib/misc.c
src/interfaces/ecpg/preproc/ecpg.c
src/interfaces/ecpg/preproc/extern.h
src/interfaces/ecpg/preproc/type.c
src/interfaces/ecpg/preproc/type.h
src/interfaces/ecpg/preproc/variable.c
src/interfaces/libpgtcl/pgtcl.c
src/interfaces/libpgtcl/pgtclCmds.c
src/interfaces/libpgtcl/pgtclCmds.h
src/interfaces/libpgtcl/pgtclId.c
src/interfaces/libpq/fe-auth.c
src/interfaces/libpq/fe-connect.c
src/interfaces/libpq/fe-exec.c
src/interfaces/libpq/fe-misc.c
src/interfaces/libpq/fe-secure.c
src/interfaces/libpq/libpq-fe.h
src/interfaces/libpq/libpq-int.h
src/interfaces/libpq/win32.c
src/interfaces/python/pgmodule.c
src/pl/plperl/eloglvl.c
src/pl/plperl/eloglvl.h
src/pl/plperl/plperl.c
src/pl/plpgsql/src/pl_comp.c
src/pl/plpgsql/src/pl_exec.c
src/pl/plpgsql/src/pl_funcs.c
src/pl/plpgsql/src/plpgsql.h
src/pl/plpython/plpython.c
src/pl/tcl/pltcl.c
src/port/memcmp.c
src/port/qsort.c

index c4eb8522130f4c290d1a5930ad3ba7f2e749dcf4..ec84ec5a5b41666ded2ba5d1dcbb3d1200605a21 100644 (file)
@@ -299,11 +299,12 @@ gts_compress(PG_FUNCTION_ARGS)
    if (entry->leafkey)
    {
        TSKEY      *r = (TSKEY *) palloc(sizeof(TSKEY));
+
        retval = palloc(sizeof(GISTENTRY));
        r->lower = r->upper = *(Timestamp *) (entry->key);
        gistentryinit(*retval, PointerGetDatum(r),
-             entry->rel, entry->page,
-             entry->offset, sizeof(TSKEY), FALSE);
+                     entry->rel, entry->page,
+                     entry->offset, sizeof(TSKEY), FALSE);
    }
    else
        retval = entry;
@@ -398,8 +399,8 @@ gts_penalty(PG_FUNCTION_ARGS)
 
    intr = DatumGetIntervalP(DirectFunctionCall2(
                                                 timestamp_mi,
-                                     TimestampGetDatumFast(newentry->upper),
-                                  TimestampGetDatumFast(origentry->upper)));
+                                 TimestampGetDatumFast(newentry->upper),
+                              TimestampGetDatumFast(origentry->upper)));
 
    /* see interval_larger */
    *result = Max(intr->time + intr->month * (30.0 * 86400), 0);
@@ -407,8 +408,8 @@ gts_penalty(PG_FUNCTION_ARGS)
 
    intr = DatumGetIntervalP(DirectFunctionCall2(
                                                 timestamp_mi,
-                                    TimestampGetDatumFast(origentry->lower),
-                                   TimestampGetDatumFast(newentry->lower)));
+                                TimestampGetDatumFast(origentry->lower),
+                               TimestampGetDatumFast(newentry->lower)));
 
    /* see interval_larger */
    *result += Max(intr->time + intr->month * (30.0 * 86400), 0);
@@ -473,8 +474,8 @@ tskey_cmp(const void *a, const void *b)
    return DatumGetInt32(
                         DirectFunctionCall2(
                                             timestamp_cmp,
-                 TimestampGetDatumFast(((TSKEY *) (((RIX *) a)->r))->lower),
-                  TimestampGetDatumFast(((TSKEY *) (((RIX *) b)->r))->lower)
+             TimestampGetDatumFast(((TSKEY *) (((RIX *) a)->r))->lower),
+              TimestampGetDatumFast(((TSKEY *) (((RIX *) b)->r))->lower)
                                             )
        );
 }
index ddf6fb0fecf81f1470dbb3633623e21ab0fc493c..bf3dd8dfbf240bac014b5b52959525136e3f71bd 100644 (file)
@@ -73,11 +73,11 @@ bool        cube_right(NDBOX * a, NDBOX * b);
 bool       cube_lt(NDBOX * a, NDBOX * b);
 bool       cube_gt(NDBOX * a, NDBOX * b);
 double    *cube_distance(NDBOX * a, NDBOX * b);
-int    cube_dim(NDBOX *a);
-double *cube_ll_coord(NDBOX * a, int n);
-double *cube_ur_coord(NDBOX * a, int n);
-bool   cube_is_point(NDBOX * a);
-NDBOX     *cube_enlarge(NDBOX * a, double * r, int n);
+int            cube_dim(NDBOX * a);
+double    *cube_ll_coord(NDBOX * a, int n);
+double    *cube_ur_coord(NDBOX * a, int n);
+bool       cube_is_point(NDBOX * a);
+NDBOX     *cube_enlarge(NDBOX * a, double *r, int n);
 
 
 /*
@@ -111,11 +111,11 @@ NDBOX *
 cube(text *str)
 {
    return cube_in(DatumGetCString(DirectFunctionCall1(textout,
-           PointerGetDatum(str))));
+                                                PointerGetDatum(str))));
 }
 
 char *
-cube_out(NDBOX *cube)
+cube_out(NDBOX * cube)
 {
    StringInfoData buf;
    bool        equal = true;
@@ -542,14 +542,14 @@ cube_union(NDBOX * a, NDBOX * b)
    if (a->dim >= b->dim)
    {
        result = palloc(a->size);
-                memset(result, 0, a->size);
+       memset(result, 0, a->size);
        result->size = a->size;
        result->dim = a->dim;
    }
    else
    {
        result = palloc(b->size);
-                memset(result, 0, b->size);
+       memset(result, 0, b->size);
        result->size = b->size;
        result->dim = b->dim;
    }
@@ -580,12 +580,12 @@ cube_union(NDBOX * a, NDBOX * b)
 
    /* compute the union */
    for (i = 0; i < a->dim; i++)
-        {
+   {
        result->x[i] =
-                  min(min(a->x[i], a->x[i + a->dim]), result->x[i]);
+           min(min(a->x[i], a->x[i + a->dim]), result->x[i]);
        result->x[i + a->dim] = max(max(a->x[i],
-                  a->x[i + a->dim]), result->x[i + a->dim]);
-        }
+                              a->x[i + a->dim]), result->x[i + a->dim]);
+   }
 
    return (result);
 }
@@ -600,14 +600,14 @@ cube_inter(NDBOX * a, NDBOX * b)
    if (a->dim >= b->dim)
    {
        result = palloc(a->size);
-                memset(result, 0, a->size);
+       memset(result, 0, a->size);
        result->size = a->size;
        result->dim = a->dim;
    }
    else
    {
        result = palloc(b->size);
-                memset(result, 0, b->size);
+       memset(result, 0, b->size);
        result->size = b->size;
        result->dim = b->dim;
    }
@@ -638,12 +638,12 @@ cube_inter(NDBOX * a, NDBOX * b)
 
    /* compute the intersection */
    for (i = 0; i < a->dim; i++)
-        {
+   {
        result->x[i] =
-                  max(min(a->x[i], a->x[i + a->dim]), result->x[i]);
+           max(min(a->x[i], a->x[i + a->dim]), result->x[i]);
        result->x[i + a->dim] = min(max(a->x[i],
-                  a->x[i + a->dim]), result->x[i + a->dim]);
-        }
+                              a->x[i + a->dim]), result->x[i + a->dim]);
+   }
 
    /*
     * Is it OK to return a non-null intersection for non-overlapping
@@ -700,8 +700,8 @@ cube_over_left(NDBOX * a, NDBOX * b)
        return (FALSE);
 
    return (min(a->x[a->dim - 1], a->x[2 * a->dim - 1]) <=
-          min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
-          !cube_left(a, b) && !cube_right(a, b));
+           min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
+           !cube_left(a, b) && !cube_right(a, b));
 }
 
 /* is the left edge of (a) located to the right of
@@ -713,8 +713,8 @@ cube_over_right(NDBOX * a, NDBOX * b)
        return (FALSE);
 
    return (min(a->x[a->dim - 1], a->x[2 * a->dim - 1]) >=
-          min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
-          !cube_left(a, b) && !cube_right(a, b));
+           min(b->x[b->dim - 1], b->x[2 * b->dim - 1]) &&
+           !cube_left(a, b) && !cube_right(a, b));
 }
 
 
@@ -727,7 +727,7 @@ cube_left(NDBOX * a, NDBOX * b)
        return (FALSE);
 
    return (min(a->x[a->dim - 1], a->x[2 * a->dim - 1]) <
-          min(b->x[0], b->x[b->dim]));
+           min(b->x[0], b->x[b->dim]));
 }
 
 /* return 'true' if the projection of 'a' is
@@ -739,7 +739,7 @@ cube_right(NDBOX * a, NDBOX * b)
        return (FALSE);
 
    return (min(a->x[0], a->x[a->dim]) >
-          min(b->x[b->dim - 1], b->x[2 * b->dim - 1]));
+           min(b->x[b->dim - 1], b->x[2 * b->dim - 1]));
 }
 
 /* make up a metric in which one box will be 'lower' than the other
@@ -759,19 +759,19 @@ cube_lt(NDBOX * a, NDBOX * b)
    for (i = 0; i < dim; i++)
    {
        if (min(a->x[i], a->x[a->dim + i]) >
-                    min(b->x[i], b->x[b->dim + i]))
+           min(b->x[i], b->x[b->dim + i]))
            return (FALSE);
        if (min(a->x[i], a->x[a->dim + i]) <
-                    min(b->x[i], b->x[b->dim + i]))
+           min(b->x[i], b->x[b->dim + i]))
            return (TRUE);
    }
    for (i = 0; i < dim; i++)
    {
        if (max(a->x[i], a->x[a->dim + i]) >
-                    max(b->x[i], b->x[b->dim + i]))
+           max(b->x[i], b->x[b->dim + i]))
            return (FALSE);
        if (max(a->x[i], a->x[a->dim + i]) <
-                    max(b->x[i], b->x[b->dim + i]))
+           max(b->x[i], b->x[b->dim + i]))
            return (TRUE);
    }
 
@@ -792,11 +792,12 @@ cube_lt(NDBOX * a, NDBOX * b)
            if (max(a->x[i], a->x[a->dim + i]) < 0)
                return (TRUE);
        }
-           /*
-            * if all common dimensions are equal, the cube with more
-            * dimensions wins
-            */
-                return (FALSE);
+
+       /*
+        * if all common dimensions are equal, the cube with more
+        * dimensions wins
+        */
+       return (FALSE);
    }
    if (a->dim < b->dim)
    {
@@ -814,11 +815,12 @@ cube_lt(NDBOX * a, NDBOX * b)
            if (max(b->x[i], b->x[b->dim + i]) < 0)
                return (FALSE);
        }
-           /*
-            * if all common dimensions are equal, the cube with more
-            * dimensions wins
-            */
-                return (TRUE);
+
+       /*
+        * if all common dimensions are equal, the cube with more
+        * dimensions wins
+        */
+       return (TRUE);
    }
 
    return (FALSE);
@@ -840,19 +842,19 @@ cube_gt(NDBOX * a, NDBOX * b)
    for (i = 0; i < dim; i++)
    {
        if (min(a->x[i], a->x[a->dim + i]) <
-                    min(b->x[i], b->x[b->dim + i]))
+           min(b->x[i], b->x[b->dim + i]))
            return (FALSE);
        if (min(a->x[i], a->x[a->dim + i]) >
-                    min(b->x[i], b->x[b->dim + i]))
+           min(b->x[i], b->x[b->dim + i]))
            return (TRUE);
    }
    for (i = 0; i < dim; i++)
    {
        if (max(a->x[i], a->x[a->dim + i]) <
-                    max(b->x[i], b->x[b->dim + i]))
+           max(b->x[i], b->x[b->dim + i]))
            return (FALSE);
        if (max(a->x[i], a->x[a->dim + i]) >
-                    max(b->x[i], b->x[b->dim + i]))
+           max(b->x[i], b->x[b->dim + i]))
            return (TRUE);
    }
 
@@ -874,11 +876,12 @@ cube_gt(NDBOX * a, NDBOX * b)
            if (max(a->x[i], a->x[a->dim + i]) > 0)
                return (TRUE);
        }
-           /*
-            * if all common dimensions are equal, the cube with more
-            * dimensions wins
-            */
-                return (TRUE);
+
+       /*
+        * if all common dimensions are equal, the cube with more
+        * dimensions wins
+        */
+       return (TRUE);
    }
    if (a->dim < b->dim)
    {
@@ -896,11 +899,12 @@ cube_gt(NDBOX * a, NDBOX * b)
            if (max(b->x[i], b->x[b->dim + i]) > 0)
                return (FALSE);
        }
-           /*
-            * if all common dimensions are equal, the cube with more
-            * dimensions wins
-            */
-                return (FALSE);
+
+       /*
+        * if all common dimensions are equal, the cube with more
+        * dimensions wins
+        */
+       return (FALSE);
    }
 
    return (FALSE);
@@ -928,18 +932,18 @@ cube_same(NDBOX * a, NDBOX * b)
    for (i = 0; i < b->dim; i++)
    {
        if (min(a->x[i], a->x[a->dim + i]) !=
-                  min(b->x[i], b->x[b->dim + i]))
+           min(b->x[i], b->x[b->dim + i]))
            return (FALSE);
        if (max(a->x[i], a->x[a->dim + i]) !=
-                  max(b->x[i], b->x[b->dim + i]))
+           max(b->x[i], b->x[b->dim + i]))
            return (FALSE);
    }
 
    /*
     * all dimensions of (b) are compared to those of (a); instead of
-    * those in (a) absent in (b), compare (a) to zero
-         * Since both LL and UR coordinates are compared to zero, we can
-         * just check them all without worrying about which is which.
+    * those in (a) absent in (b), compare (a) to zero Since both LL and
+    * UR coordinates are compared to zero, we can just check them all
+    * without worrying about which is which.
     */
    for (i = b->dim; i < a->dim; i++)
    {
@@ -974,9 +978,9 @@ cube_contains(NDBOX * a, NDBOX * b)
    {
        /*
         * the further comparisons will make sense if the excess
-        * dimensions of (b) were zeroes
-                 * Since both UL and UR coordinates must be zero, we can
-                 * check them all without worrying about which is which.
+        * dimensions of (b) were zeroes Since both UL and UR coordinates
+        * must be zero, we can check them all without worrying about
+        * which is which.
         */
        for (i = a->dim; i < b->dim; i++)
        {
@@ -991,10 +995,10 @@ cube_contains(NDBOX * a, NDBOX * b)
    for (i = 0; i < min(a->dim, b->dim); i++)
    {
        if (min(a->x[i], a->x[a->dim + i]) >
-                  min(b->x[i], b->x[b->dim + i]))
+           min(b->x[i], b->x[b->dim + i]))
            return (FALSE);
        if (max(a->x[i], a->x[a->dim + i]) <
-                  max(b->x[i], b->x[b->dim + i]))
+           max(b->x[i], b->x[b->dim + i]))
            return (FALSE);
    }
 
@@ -1039,10 +1043,10 @@ cube_overlap(NDBOX * a, NDBOX * b)
    for (i = 0; i < b->dim; i++)
    {
        if (min(a->x[i], a->x[a->dim + i]) >
-                  max(b->x[i], b->x[b->dim + i]))
+           max(b->x[i], b->x[b->dim + i]))
            return (FALSE);
        if (max(a->x[i], a->x[a->dim + i]) <
-                  min(b->x[i], b->x[b->dim + i]))
+           min(b->x[i], b->x[b->dim + i]))
            return (FALSE);
    }
 
@@ -1122,87 +1126,94 @@ distance_1D(double a1, double a2, double b1, double b2)
 bool
 cube_is_point(NDBOX * a)
 {
-        int i,
-            j;
+   int         i,
+               j;
+
    for (i = 0, j = a->dim; i < a->dim; i++, j++)
-        {
-                if (a->x[i] != a->x[j]) return FALSE;
-        }
+   {
+       if (a->x[i] != a->x[j])
+           return FALSE;
+   }
 
-        return TRUE;
+   return TRUE;
 }
 
 /* Return dimensions in use in the data structure */
 int
 cube_dim(NDBOX * a)
 {
-        /* Other things will break before unsigned int doesn't fit. */
-        return a->dim;
+   /* Other things will break before unsigned int doesn't fit. */
+   return a->dim;
 }
 
 /* Return a specific normalized LL coordinate */
 double *
 cube_ll_coord(NDBOX * a, int n)
 {
-        double *result;
+   double     *result;
+
    result = (double *) palloc(sizeof(double));
-        *result = 0;
-        if (a->dim >= n && n > 0)
-               *result = min(a->x[n-1], a->x[a->dim + n-1]);
-        return result;
+   *result = 0;
+   if (a->dim >= n && n > 0)
+       *result = min(a->x[n - 1], a->x[a->dim + n - 1]);
+   return result;
 }
 
 /* Return a specific normalized UR coordinate */
 double *
 cube_ur_coord(NDBOX * a, int n)
 {
-        double *result;
+   double     *result;
+
    result = (double *) palloc(sizeof(double));
-        *result = 0;
-        if (a->dim >= n && n > 0)
-                *result = max(a->x[n-1], a->x[a->dim + n-1]);
-        return result;
+   *result = 0;
+   if (a->dim >= n && n > 0)
+       *result = max(a->x[n - 1], a->x[a->dim + n - 1]);
+   return result;
 }
 
 /* Increase or decrease box size by a radius in at least n dimensions. */
 NDBOX *
-cube_enlarge(NDBOX * a, double * r, int n)
+cube_enlarge(NDBOX * a, double *r, int n)
 {
-        NDBOX *result;
-        int dim = 0;
-        int size;
-        int i,
-            j;
-        if (*r > 0 && n > 0) dim = n;
-        if (a->dim > dim) dim = a->dim;
-        size = offsetof(NDBOX, x[0]) + sizeof(double) * dim * 2;
-        result = (NDBOX *) palloc(size);
-        memset(result, 0, size);
-        result->size = size;
-        result->dim = dim;
+   NDBOX      *result;
+   int         dim = 0;
+   int         size;
+   int         i,
+               j;
+
+   if (*r > 0 && n > 0)
+       dim = n;
+   if (a->dim > dim)
+       dim = a->dim;
+   size = offsetof(NDBOX, x[0]) + sizeof(double) * dim * 2;
+   result = (NDBOX *) palloc(size);
+   memset(result, 0, size);
+   result->size = size;
+   result->dim = dim;
    for (i = 0, j = dim; i < a->dim; i++, j++)
-        {
-                if (a->x[i] >= a->x[j])
-                {
-                        result->x[i] = a->x[j] - *r;
-                        result->x[j] = a->x[i] + *r;
-                }
-                else
-                {
-                        result->x[i] = a->x[i] - *r;
-                        result->x[j] = a->x[j] + *r;
-                }
-                if (result->x[i] > result->x[j])
-                {
-                        result->x[i] = (result->x[i] + result->x[j]) / 2;
-                        result->x[j] = result->x[i];
-                }
-        }
-        /* dim > a->dim only if r > 0 */
+   {
+       if (a->x[i] >= a->x[j])
+       {
+           result->x[i] = a->x[j] - *r;
+           result->x[j] = a->x[i] + *r;
+       }
+       else
+       {
+           result->x[i] = a->x[i] - *r;
+           result->x[j] = a->x[j] + *r;
+       }
+       if (result->x[i] > result->x[j])
+       {
+           result->x[i] = (result->x[i] + result->x[j]) / 2;
+           result->x[j] = result->x[i];
+       }
+   }
+   /* dim > a->dim only if r > 0 */
    for (; i < dim; i++, j++)
-        {
-                result->x[i] = -*r;
-                result->x[j] = *r;
-        }
-        return result;
+   {
+       result->x[i] = -*r;
+       result->x[j] = *r;
+   }
+   return result;
 }
index 4522368e06259bb60cfc96bb9bc32370280ae074..e179226cbe5755ad9250b6f0ef3228b08d75e269 100644 (file)
@@ -309,7 +309,7 @@ do_create(PGconn *conn, char *table, dbhead * dbh)
                {
                    strcat(query, " varchar");
                    snprintf(t, 20, "(%d)",
-                           dbh->db_fields[i].db_flen);
+                            dbh->db_fields[i].db_flen);
                    strcat(query, t);
                }
                else
@@ -468,8 +468,8 @@ do_inserts(PGconn *conn, char *table, dbhead * dbh)
                    if ((strlen(foo) == 8) && isinteger(foo))
                    {
                        snprintf(pgdate, 11, "%c%c%c%c-%c%c-%c%c",
-                               foo[0], foo[1], foo[2], foo[3],
-                               foo[4], foo[5], foo[6], foo[7]);
+                                foo[0], foo[1], foo[2], foo[3],
+                                foo[4], foo[5], foo[6], foo[7]);
                        strcat(query, pgdate);
                    }
                    else
index 44d5bf913486fe8c97fb7d6ee711c0163f38e758..899143adab344daee3fee73811c935c191f69947 100644 (file)
@@ -67,10 +67,10 @@ static char *quote_literal_cstr(char *rawstr);
 static char *quote_ident_cstr(char *rawstr);
 static int16 get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key);
 static HeapTuple get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals);
-static Oid get_relid_from_relname(text *relname_text);
+static Oid get_relid_from_relname(text *relname_text);
 static dblink_results *get_res_ptr(int32 res_id_index);
-static void append_res_ptr(dblink_results *results);
-static void remove_res_ptr(dblink_results *results);
+static void append_res_ptr(dblink_results * results);
+static void remove_res_ptr(dblink_results * results);
 static TupleDesc pgresultGetTupleDesc(PGresult *res);
 
 /* Global */
@@ -97,10 +97,10 @@ PG_FUNCTION_INFO_V1(dblink_connect);
 Datum
 dblink_connect(PG_FUNCTION_ARGS)
 {
-   char           *connstr = GET_STR(PG_GETARG_TEXT_P(0));
-   char           *msg;
-   text           *result_text;
-   MemoryContext   oldcontext;
+   char       *connstr = GET_STR(PG_GETARG_TEXT_P(0));
+   char       *msg;
+   text       *result_text;
+   MemoryContext oldcontext;
 
    if (persistent_conn != NULL)
        PQfinish(persistent_conn);
@@ -128,7 +128,7 @@ PG_FUNCTION_INFO_V1(dblink_disconnect);
 Datum
 dblink_disconnect(PG_FUNCTION_ARGS)
 {
-   text           *result_text;
+   text       *result_text;
 
    if (persistent_conn != NULL)
        PQfinish(persistent_conn);
@@ -146,13 +146,13 @@ PG_FUNCTION_INFO_V1(dblink_open);
 Datum
 dblink_open(PG_FUNCTION_ARGS)
 {
-   char           *msg;
-   PGresult       *res = NULL;
-   PGconn         *conn = NULL;
-   text           *result_text;
-   char           *curname = GET_STR(PG_GETARG_TEXT_P(0));
-   char           *sql = GET_STR(PG_GETARG_TEXT_P(1));
-   StringInfo      str = makeStringInfo();
+   char       *msg;
+   PGresult   *res = NULL;
+   PGconn     *conn = NULL;
+   text       *result_text;
+   char       *curname = GET_STR(PG_GETARG_TEXT_P(0));
+   char       *sql = GET_STR(PG_GETARG_TEXT_P(1));
+   StringInfo  str = makeStringInfo();
 
    if (persistent_conn != NULL)
        conn = persistent_conn;
@@ -199,12 +199,12 @@ PG_FUNCTION_INFO_V1(dblink_close);
 Datum
 dblink_close(PG_FUNCTION_ARGS)
 {
-   PGconn         *conn = NULL;
-   PGresult       *res = NULL;
-   char           *curname = GET_STR(PG_GETARG_TEXT_P(0));
-   StringInfo      str = makeStringInfo();
-   text           *result_text;
-   char           *msg;
+   PGconn     *conn = NULL;
+   PGresult   *res = NULL;
+   char       *curname = GET_STR(PG_GETARG_TEXT_P(0));
+   StringInfo  str = makeStringInfo();
+   text       *result_text;
+   char       *msg;
 
    if (persistent_conn != NULL)
        conn = persistent_conn;
@@ -215,7 +215,7 @@ dblink_close(PG_FUNCTION_ARGS)
 
    /* close the cursor */
    res = PQexec(conn, str->data);
-   if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
+   if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
    {
        msg = pstrdup(PQerrorMessage(conn));
        PQclear(res);
@@ -253,31 +253,34 @@ PG_FUNCTION_INFO_V1(dblink_fetch);
 Datum
 dblink_fetch(PG_FUNCTION_ARGS)
 {
-   FuncCallContext    *funcctx;
-   TupleDesc           tupdesc = NULL;
-   int                 call_cntr;
-   int                 max_calls;
-   TupleTableSlot     *slot;
-   AttInMetadata      *attinmeta;
-   char               *msg;
-   PGresult           *res = NULL;
-   MemoryContext       oldcontext;
+   FuncCallContext *funcctx;
+   TupleDesc   tupdesc = NULL;
+   int         call_cntr;
+   int         max_calls;
+   TupleTableSlot *slot;
+   AttInMetadata *attinmeta;
+   char       *msg;
+   PGresult   *res = NULL;
+   MemoryContext oldcontext;
 
    /* stuff done only on the first call of the function */
-   if(SRF_IS_FIRSTCALL())
-   {
-       Oid             functypeid;
-       char            functyptype;
-       Oid             funcid = fcinfo->flinfo->fn_oid;
-       PGconn         *conn = NULL;
-       StringInfo      str = makeStringInfo();
-       char           *curname = GET_STR(PG_GETARG_TEXT_P(0));
-       int             howmany = PG_GETARG_INT32(1);
+   if (SRF_IS_FIRSTCALL())
+   {
+       Oid         functypeid;
+       char        functyptype;
+       Oid         funcid = fcinfo->flinfo->fn_oid;
+       PGconn     *conn = NULL;
+       StringInfo  str = makeStringInfo();
+       char       *curname = GET_STR(PG_GETARG_TEXT_P(0));
+       int         howmany = PG_GETARG_INT32(1);
 
        /* create a function context for cross-call persistence */
-       funcctx = SRF_FIRSTCALL_INIT();
+       funcctx = SRF_FIRSTCALL_INIT();
 
-       /* switch to memory context appropriate for multiple function calls */
+       /*
+        * switch to memory context appropriate for multiple function
+        * calls
+        */
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
 
        if (persistent_conn != NULL)
@@ -314,7 +317,7 @@ dblink_fetch(PG_FUNCTION_ARGS)
 
        /* fast track when no results */
        if (funcctx->max_calls < 1)
-           SRF_RETURN_DONE(funcctx);
+           SRF_RETURN_DONE(funcctx);
 
        /* check typtype to see if we have a predetermined return type */
        functypeid = get_func_rettype(funcid);
@@ -336,10 +339,10 @@ dblink_fetch(PG_FUNCTION_ARGS)
        funcctx->attinmeta = attinmeta;
 
        MemoryContextSwitchTo(oldcontext);
-    }
+   }
 
    /* stuff done on every call of the function */
-   funcctx = SRF_PERCALL_SETUP();
+   funcctx = SRF_PERCALL_SETUP();
 
    /*
     * initialize per-call variables
@@ -354,12 +357,12 @@ dblink_fetch(PG_FUNCTION_ARGS)
    tupdesc = attinmeta->tupdesc;
 
    if (call_cntr < max_calls)  /* do when there is more left to send */
-   {
+   {
        char      **values;
        HeapTuple   tuple;
        Datum       result;
-       int     i;
-       int     nfields = PQnfields(res);
+       int         i;
+       int         nfields = PQnfields(res);
 
        values = (char **) palloc(nfields * sizeof(char *));
        for (i = 0; i < nfields; i++)
@@ -376,12 +379,13 @@ dblink_fetch(PG_FUNCTION_ARGS)
        /* make the tuple into a datum */
        result = TupleGetDatum(slot, tuple);
 
-       SRF_RETURN_NEXT(funcctx, result);
+       SRF_RETURN_NEXT(funcctx, result);
    }
-   else    /* do when there is no more left */
+   else
+/* do when there is no more left */
    {
        PQclear(res);
-       SRF_RETURN_DONE(funcctx);
+       SRF_RETURN_DONE(funcctx);
    }
 }
 
@@ -392,32 +396,35 @@ PG_FUNCTION_INFO_V1(dblink_record);
 Datum
 dblink_record(PG_FUNCTION_ARGS)
 {
-   FuncCallContext    *funcctx;
-   TupleDesc           tupdesc = NULL;
-   int                 call_cntr;
-   int                 max_calls;
-   TupleTableSlot     *slot;
-   AttInMetadata      *attinmeta;
-   char               *msg;
-   PGresult           *res = NULL;
-   bool                is_sql_cmd = false;
-   char               *sql_cmd_status = NULL;
-   MemoryContext       oldcontext;
+   FuncCallContext *funcctx;
+   TupleDesc   tupdesc = NULL;
+   int         call_cntr;
+   int         max_calls;
+   TupleTableSlot *slot;
+   AttInMetadata *attinmeta;
+   char       *msg;
+   PGresult   *res = NULL;
+   bool        is_sql_cmd = false;
+   char       *sql_cmd_status = NULL;
+   MemoryContext oldcontext;
 
    /* stuff done only on the first call of the function */
-   if(SRF_IS_FIRSTCALL())
-   {
-       Oid             functypeid;
-       char            functyptype;
-       Oid             funcid = fcinfo->flinfo->fn_oid;
-       PGconn         *conn = NULL;
-       char           *connstr = NULL;
-       char           *sql = NULL;
+   if (SRF_IS_FIRSTCALL())
+   {
+       Oid         functypeid;
+       char        functyptype;
+       Oid         funcid = fcinfo->flinfo->fn_oid;
+       PGconn     *conn = NULL;
+       char       *connstr = NULL;
+       char       *sql = NULL;
 
        /* create a function context for cross-call persistence */
-       funcctx = SRF_FIRSTCALL_INIT();
+       funcctx = SRF_FIRSTCALL_INIT();
 
-       /* switch to memory context appropriate for multiple function calls */
+       /*
+        * switch to memory context appropriate for multiple function
+        * calls
+        */
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
 
        if (fcinfo->nargs == 2)
@@ -487,7 +494,7 @@ dblink_record(PG_FUNCTION_ARGS)
 
        /* fast track when no results */
        if (funcctx->max_calls < 1)
-           SRF_RETURN_DONE(funcctx);
+           SRF_RETURN_DONE(funcctx);
 
        /* check typtype to see if we have a predetermined return type */
        functypeid = get_func_rettype(funcid);
@@ -512,10 +519,10 @@ dblink_record(PG_FUNCTION_ARGS)
        funcctx->attinmeta = attinmeta;
 
        MemoryContextSwitchTo(oldcontext);
-    }
+   }
 
    /* stuff done on every call of the function */
-   funcctx = SRF_PERCALL_SETUP();
+   funcctx = SRF_PERCALL_SETUP();
 
    /*
     * initialize per-call variables
@@ -530,15 +537,15 @@ dblink_record(PG_FUNCTION_ARGS)
    tupdesc = attinmeta->tupdesc;
 
    if (call_cntr < max_calls)  /* do when there is more left to send */
-   {
+   {
        char      **values;
        HeapTuple   tuple;
        Datum       result;
 
        if (!is_sql_cmd)
        {
-           int     i;
-           int     nfields = PQnfields(res);
+           int         i;
+           int         nfields = PQnfields(res);
 
            values = (char **) palloc(nfields * sizeof(char *));
            for (i = 0; i < nfields; i++)
@@ -561,12 +568,13 @@ dblink_record(PG_FUNCTION_ARGS)
        /* make the tuple into a datum */
        result = TupleGetDatum(slot, tuple);
 
-       SRF_RETURN_NEXT(funcctx, result);
+       SRF_RETURN_NEXT(funcctx, result);
    }
-   else    /* do when there is no more left */
+   else
+/* do when there is no more left */
    {
        PQclear(res);
-       SRF_RETURN_DONE(funcctx);
+       SRF_RETURN_DONE(funcctx);
    }
 }
 
@@ -577,14 +585,14 @@ PG_FUNCTION_INFO_V1(dblink_exec);
 Datum
 dblink_exec(PG_FUNCTION_ARGS)
 {
-   char           *msg;
-   PGresult       *res = NULL;
-   char           *sql_cmd_status = NULL;
-   TupleDesc       tupdesc = NULL;
-   text           *result_text;
-   PGconn         *conn = NULL;
-   char           *connstr = NULL;
-   char           *sql = NULL;
+   char       *msg;
+   PGresult   *res = NULL;
+   char       *sql_cmd_status = NULL;
+   TupleDesc   tupdesc = NULL;
+   text       *result_text;
+   PGconn     *conn = NULL;
+   char       *connstr = NULL;
+   char       *sql = NULL;
 
    if (fcinfo->nargs == 2)
    {
@@ -633,8 +641,8 @@ dblink_exec(PG_FUNCTION_ARGS)
                               TEXTOID, -1, 0, false);
 
            /*
-            * and save a copy of the command status string to return
-            * as our result tuple
+            * and save a copy of the command status string to return as
+            * our result tuple
             */
            sql_cmd_status = PQcmdStatus(res);
        }
@@ -659,15 +667,15 @@ PG_FUNCTION_INFO_V1(dblink);
 Datum
 dblink(PG_FUNCTION_ARGS)
 {
-   PGconn          *conn = NULL;
-   PGresult        *res = NULL;
-   dblink_results  *results;
-   char            *optstr;
-   char            *sqlstatement;
-   char            *execstatement;
-   char            *msg;
-   int             ntuples = 0;
-   ReturnSetInfo   *rsi;
+   PGconn     *conn = NULL;
+   PGresult   *res = NULL;
+   dblink_results *results;
+   char       *optstr;
+   char       *sqlstatement;
+   char       *execstatement;
+   char       *msg;
+   int         ntuples = 0;
+   ReturnSetInfo *rsi;
 
    if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo))
        elog(ERROR, "dblink: function called in context that does not accept a set result");
@@ -721,8 +729,8 @@ dblink(PG_FUNCTION_ARGS)
            results->res = res;
 
            /*
-            * Append node to res_id to hold pointer to results.
-            * Needed by dblink_tok to access the data
+            * Append node to res_id to hold pointer to results. Needed by
+            * dblink_tok to access the data
             */
            append_res_ptr(results);
 
@@ -797,11 +805,11 @@ Datum
 dblink_tok(PG_FUNCTION_ARGS)
 {
    dblink_results *results;
-   int             fldnum;
-   text            *result_text;
-   char            *result;
-   int             nfields = 0;
-   int             text_len = 0;
+   int         fldnum;
+   text       *result_text;
+   char       *result;
+   int         nfields = 0;
+   int         text_len = 0;
 
    results = get_res_ptr(PG_GETARG_INT32(0));
    if (results == NULL)
@@ -848,7 +856,7 @@ dblink_tok(PG_FUNCTION_ARGS)
 
 /*
  * dblink_get_pkey
- * 
+ *
  * Return list of primary key fields for the supplied relation,
  * or NULL if none exists.
  */
@@ -856,25 +864,28 @@ PG_FUNCTION_INFO_V1(dblink_get_pkey);
 Datum
 dblink_get_pkey(PG_FUNCTION_ARGS)
 {
-   int16               numatts;
-   Oid                 relid;
-   char              **results;
-   FuncCallContext    *funcctx;
-   int32               call_cntr;
-   int32               max_calls;
-   TupleTableSlot     *slot;
-   AttInMetadata      *attinmeta;
-   MemoryContext       oldcontext;
+   int16       numatts;
+   Oid         relid;
+   char      **results;
+   FuncCallContext *funcctx;
+   int32       call_cntr;
+   int32       max_calls;
+   TupleTableSlot *slot;
+   AttInMetadata *attinmeta;
+   MemoryContext oldcontext;
 
    /* stuff done only on the first call of the function */
-   if(SRF_IS_FIRSTCALL())
-   {
-       TupleDesc       tupdesc = NULL;
+   if (SRF_IS_FIRSTCALL())
+   {
+       TupleDesc   tupdesc = NULL;
 
        /* create a function context for cross-call persistence */
-       funcctx = SRF_FIRSTCALL_INIT();
+       funcctx = SRF_FIRSTCALL_INIT();
 
-       /* switch to memory context appropriate for multiple function calls */
+       /*
+        * switch to memory context appropriate for multiple function
+        * calls
+        */
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
 
        /* convert relname to rel Oid */
@@ -882,7 +893,10 @@ dblink_get_pkey(PG_FUNCTION_ARGS)
        if (!OidIsValid(relid))
            elog(ERROR, "dblink_get_pkey: relation does not exist");
 
-       /* need a tuple descriptor representing one INT and one TEXT column */
+       /*
+        * need a tuple descriptor representing one INT and one TEXT
+        * column
+        */
        tupdesc = CreateTemplateTupleDesc(2, false);
        TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
                           INT4OID, -1, 0, false);
@@ -896,8 +910,8 @@ dblink_get_pkey(PG_FUNCTION_ARGS)
        funcctx->slot = slot;
 
        /*
-        * Generate attribute metadata needed later to produce tuples from raw
-        * C strings
+        * Generate attribute metadata needed later to produce tuples from
+        * raw C strings
         */
        attinmeta = TupleDescGetAttInMetadata(tupdesc);
        funcctx->attinmeta = attinmeta;
@@ -912,14 +926,15 @@ dblink_get_pkey(PG_FUNCTION_ARGS)
            /* got results, keep track of them */
            funcctx->user_fctx = results;
        }
-       else    /* fast track when no results */
-           SRF_RETURN_DONE(funcctx);
+       else
+/* fast track when no results */
+           SRF_RETURN_DONE(funcctx);
 
        MemoryContextSwitchTo(oldcontext);
-    }
+   }
 
    /* stuff done on every call of the function */
-   funcctx = SRF_PERCALL_SETUP();
+   funcctx = SRF_PERCALL_SETUP();
 
    /*
     * initialize per-call variables
@@ -933,13 +948,13 @@ dblink_get_pkey(PG_FUNCTION_ARGS)
    attinmeta = funcctx->attinmeta;
 
    if (call_cntr < max_calls)  /* do when there is more left to send */
-   {
+   {
        char      **values;
        HeapTuple   tuple;
        Datum       result;
 
        values = (char **) palloc(2 * sizeof(char *));
-       values[0] = (char *) palloc(12);    /* sign, 10 digits, '\0' */
+       values[0] = (char *) palloc(12);        /* sign, 10 digits, '\0' */
 
        sprintf(values[0], "%d", call_cntr + 1);
 
@@ -951,10 +966,11 @@ dblink_get_pkey(PG_FUNCTION_ARGS)
        /* make the tuple into a datum */
        result = TupleGetDatum(slot, tuple);
 
-       SRF_RETURN_NEXT(funcctx, result);
+       SRF_RETURN_NEXT(funcctx, result);
    }
-   else    /* do when there is no more left */
-       SRF_RETURN_DONE(funcctx);
+   else
+/* do when there is no more left */
+       SRF_RETURN_DONE(funcctx);
 }
 
 /*
@@ -989,7 +1005,7 @@ dblink_last_oid(PG_FUNCTION_ARGS)
 
 /*
  * dblink_build_sql_insert
- * 
+ *
  * Used to generate an SQL insert statement
  * based on an existing tuple in a local relation.
  * This is useful for selectively replicating data
@@ -1022,7 +1038,7 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
    int        *src_dim;
    int         src_nitems;
    int         tgt_ndim;
-   int         *tgt_dim;
+   int        *tgt_dim;
    int         tgt_nitems;
    int         i;
    char       *ptr;
@@ -1043,6 +1059,7 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
 
    pkattnums = (int16 *) PG_GETARG_POINTER(1);
    pknumatts = PG_GETARG_INT16(2);
+
    /*
     * There should be at least one key attribute
     */
@@ -1053,8 +1070,8 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
    tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
 
    /*
-    * Source array is made up of key values that will be used to
-    * locate the tuple of interest from the local system.
+    * Source array is made up of key values that will be used to locate
+    * the tuple of interest from the local system.
     */
    src_ndim = ARR_NDIM(src_pkattvals_arry);
    src_dim = ARR_DIMS(src_pkattvals_arry);
@@ -1071,7 +1088,7 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
     */
    Assert(ARR_ELEMTYPE(src_pkattvals_arry) == TEXTOID);
    get_typlenbyvalalign(ARR_ELEMTYPE(src_pkattvals_arry),
-                                   &typlen, &typbyval, &typalign);
+                        &typlen, &typbyval, &typalign);
 
    src_pkattvals = (char **) palloc(src_nitems * sizeof(char *));
    ptr = ARR_DATA_PTR(src_pkattvals_arry);
@@ -1083,8 +1100,8 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
    }
 
    /*
-    * Target array is made up of key values that will be used to
-    * build the SQL string for use on the remote system.
+    * Target array is made up of key values that will be used to build
+    * the SQL string for use on the remote system.
     */
    tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
    tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
@@ -1101,7 +1118,7 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
     */
    Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
    get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
-                                   &typlen, &typbyval, &typalign);
+                        &typlen, &typbyval, &typalign);
 
    tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
    ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
@@ -1131,7 +1148,7 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
 
 /*
  * dblink_build_sql_delete
- * 
+ *
  * Used to generate an SQL delete statement.
  * This is useful for selectively replicating a
  * delete to another server via dblink.
@@ -1149,18 +1166,18 @@ Datum
 dblink_build_sql_delete(PG_FUNCTION_ARGS)
 {
    Oid         relid;
-   text        *relname_text;
-   int16       *pkattnums;
+   text       *relname_text;
+   int16      *pkattnums;
    int16       pknumatts;
-   char        **tgt_pkattvals;
-   ArrayType   *tgt_pkattvals_arry;
+   char      **tgt_pkattvals;
+   ArrayType  *tgt_pkattvals_arry;
    int         tgt_ndim;
-   int         *tgt_dim;
+   int        *tgt_dim;
    int         tgt_nitems;
    int         i;
-   char        *ptr;
-   char        *sql;
-   text        *sql_text;
+   char       *ptr;
+   char       *sql;
+   text       *sql_text;
    int16       typlen;
    bool        typbyval;
    char        typalign;
@@ -1176,6 +1193,7 @@ dblink_build_sql_delete(PG_FUNCTION_ARGS)
 
    pkattnums = (int16 *) PG_GETARG_POINTER(1);
    pknumatts = PG_GETARG_INT16(2);
+
    /*
     * There should be at least one key attribute
     */
@@ -1185,8 +1203,8 @@ dblink_build_sql_delete(PG_FUNCTION_ARGS)
    tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
 
    /*
-    * Target array is made up of key values that will be used to
-    * build the SQL string for use on the remote system.
+    * Target array is made up of key values that will be used to build
+    * the SQL string for use on the remote system.
     */
    tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
    tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
@@ -1203,7 +1221,7 @@ dblink_build_sql_delete(PG_FUNCTION_ARGS)
     */
    Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
    get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
-                                   &typlen, &typbyval, &typalign);
+                        &typlen, &typbyval, &typalign);
 
    tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
    ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
@@ -1233,7 +1251,7 @@ dblink_build_sql_delete(PG_FUNCTION_ARGS)
 
 /*
  * dblink_build_sql_update
- * 
+ *
  * Used to generate an SQL update statement
  * based on an existing tuple in a local relation.
  * This is useful for selectively replicating data
@@ -1255,23 +1273,23 @@ Datum
 dblink_build_sql_update(PG_FUNCTION_ARGS)
 {
    Oid         relid;
-   text        *relname_text;
-   int16       *pkattnums;
+   text       *relname_text;
+   int16      *pkattnums;
    int16       pknumatts;
-   char        **src_pkattvals;
-   char        **tgt_pkattvals;
-   ArrayType   *src_pkattvals_arry;
-   ArrayType   *tgt_pkattvals_arry;
+   char      **src_pkattvals;
+   char      **tgt_pkattvals;
+   ArrayType  *src_pkattvals_arry;
+   ArrayType  *tgt_pkattvals_arry;
    int         src_ndim;
-   int         *src_dim;
+   int        *src_dim;
    int         src_nitems;
    int         tgt_ndim;
-   int         *tgt_dim;
+   int        *tgt_dim;
    int         tgt_nitems;
    int         i;
-   char        *ptr;
-   char        *sql;
-   text        *sql_text;
+   char       *ptr;
+   char       *sql;
+   text       *sql_text;
    int16       typlen;
    bool        typbyval;
    char        typalign;
@@ -1287,6 +1305,7 @@ dblink_build_sql_update(PG_FUNCTION_ARGS)
 
    pkattnums = (int16 *) PG_GETARG_POINTER(1);
    pknumatts = PG_GETARG_INT16(2);
+
    /*
     * There should be one source array key values for each key attnum
     */
@@ -1297,8 +1316,8 @@ dblink_build_sql_update(PG_FUNCTION_ARGS)
    tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
 
    /*
-    * Source array is made up of key values that will be used to
-    * locate the tuple of interest from the local system.
+    * Source array is made up of key values that will be used to locate
+    * the tuple of interest from the local system.
     */
    src_ndim = ARR_NDIM(src_pkattvals_arry);
    src_dim = ARR_DIMS(src_pkattvals_arry);
@@ -1315,7 +1334,7 @@ dblink_build_sql_update(PG_FUNCTION_ARGS)
     */
    Assert(ARR_ELEMTYPE(src_pkattvals_arry) == TEXTOID);
    get_typlenbyvalalign(ARR_ELEMTYPE(src_pkattvals_arry),
-                                   &typlen, &typbyval, &typalign);
+                        &typlen, &typbyval, &typalign);
 
    src_pkattvals = (char **) palloc(src_nitems * sizeof(char *));
    ptr = ARR_DATA_PTR(src_pkattvals_arry);
@@ -1327,8 +1346,8 @@ dblink_build_sql_update(PG_FUNCTION_ARGS)
    }
 
    /*
-    * Target array is made up of key values that will be used to
-    * build the SQL string for use on the remote system.
+    * Target array is made up of key values that will be used to build
+    * the SQL string for use on the remote system.
     */
    tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
    tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
@@ -1345,7 +1364,7 @@ dblink_build_sql_update(PG_FUNCTION_ARGS)
     */
    Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
    get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
-                                   &typlen, &typbyval, &typalign);
+                        &typlen, &typbyval, &typalign);
 
    tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
    ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
@@ -1382,7 +1401,7 @@ PG_FUNCTION_INFO_V1(dblink_current_query);
 Datum
 dblink_current_query(PG_FUNCTION_ARGS)
 {
-   text        *result_text;
+   text       *result_text;
 
    result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(debug_query_string)));
    PG_RETURN_TEXT_P(result_text);
@@ -1410,7 +1429,7 @@ init_dblink_results(MemoryContext fn_mcxt)
    MemSet(retval, 0, sizeof(dblink_results));
 
    retval->tup_num = -1;
-   retval->res_id_index =-1;
+   retval->res_id_index = -1;
    retval->res = NULL;
 
    MemoryContextSwitchTo(oldcontext);
@@ -1420,21 +1439,21 @@ init_dblink_results(MemoryContext fn_mcxt)
 
 /*
  * get_pkey_attnames
- * 
+ *
  * Get the primary key attnames for the given relation.
  * Return NULL, and set numatts = 0, if no primary key exists.
  */
 static char **
 get_pkey_attnames(Oid relid, int16 *numatts)
 {
-   Relation        indexRelation;
-   ScanKeyData     entry;
-   HeapScanDesc    scan;
-   HeapTuple       indexTuple;
-   int             i;
-   char            **result = NULL;
-   Relation        rel;
-   TupleDesc       tupdesc;
+   Relation    indexRelation;
+   ScanKeyData entry;
+   HeapScanDesc scan;
+   HeapTuple   indexTuple;
+   int         i;
+   char      **result = NULL;
+   Relation    rel;
+   TupleDesc   tupdesc;
 
    /* open relation using relid, get tupdesc */
    rel = relation_open(relid, AccessShareLock);
@@ -1451,7 +1470,7 @@ get_pkey_attnames(Oid relid, int16 *numatts)
 
    while ((indexTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
    {
-       Form_pg_index   index = (Form_pg_index) GETSTRUCT(indexTuple);
+       Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
 
        /* we're only interested if it is the primary key */
        if (index->indisprimary == TRUE)
@@ -1480,23 +1499,23 @@ get_pkey_attnames(Oid relid, int16 *numatts)
 static char *
 get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 {
-   Relation        rel;
-   char            *relname;
-   HeapTuple       tuple;
-   TupleDesc       tupdesc;
-   int             natts;
-   StringInfo      str = makeStringInfo();
-   char            *sql;
-   char            *val;
-   int16           key;
-   int             i;
-   bool            needComma;
+   Relation    rel;
+   char       *relname;
+   HeapTuple   tuple;
+   TupleDesc   tupdesc;
+   int         natts;
+   StringInfo  str = makeStringInfo();
+   char       *sql;
+   char       *val;
+   int16       key;
+   int         i;
+   bool        needComma;
 
    /*
     * Open relation using relid
     */
    rel = relation_open(relid, AccessShareLock);
-   relname =  RelationGetRelationName(rel);
+   relname = RelationGetRelationName(rel);
    tupdesc = rel->rd_att;
    natts = tupdesc->natts;
 
@@ -1516,7 +1535,7 @@ get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattval
            appendStringInfo(str, ",");
 
        appendStringInfo(str, "%s",
-                        quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
+                 quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
        needComma = true;
    }
 
@@ -1566,33 +1585,33 @@ get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattval
 static char *
 get_sql_delete(Oid relid, int16 *pkattnums, int16 pknumatts, char **tgt_pkattvals)
 {
-   Relation        rel;
-   char            *relname;
-   TupleDesc       tupdesc;
-   int             natts;
-   StringInfo      str = makeStringInfo();
-   char            *sql;
-   char            *val;
-   int             i;
+   Relation    rel;
+   char       *relname;
+   TupleDesc   tupdesc;
+   int         natts;
+   StringInfo  str = makeStringInfo();
+   char       *sql;
+   char       *val;
+   int         i;
 
    /*
     * Open relation using relid
     */
    rel = relation_open(relid, AccessShareLock);
-   relname =  RelationGetRelationName(rel);
+   relname = RelationGetRelationName(rel);
    tupdesc = rel->rd_att;
    natts = tupdesc->natts;
 
    appendStringInfo(str, "DELETE FROM %s WHERE ", quote_ident_cstr(relname));
    for (i = 0; i < pknumatts; i++)
    {
-       int16   pkattnum = pkattnums[i];
+       int16       pkattnum = pkattnums[i];
 
        if (i > 0)
            appendStringInfo(str, " AND ");
 
        appendStringInfo(str, "%s",
-                        quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
+       quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
 
        if (tgt_pkattvals != NULL)
            val = pstrdup(tgt_pkattvals[i]);
@@ -1622,23 +1641,23 @@ get_sql_delete(Oid relid, int16 *pkattnums, int16 pknumatts, char **tgt_pkattval
 static char *
 get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 {
-   Relation        rel;
-   char            *relname;
-   HeapTuple       tuple;
-   TupleDesc       tupdesc;
-   int             natts;
-   StringInfo      str = makeStringInfo();
-   char            *sql;
-   char            *val;
-   int16           key;
-   int             i;
-   bool            needComma;
+   Relation    rel;
+   char       *relname;
+   HeapTuple   tuple;
+   TupleDesc   tupdesc;
+   int         natts;
+   StringInfo  str = makeStringInfo();
+   char       *sql;
+   char       *val;
+   int16       key;
+   int         i;
+   bool        needComma;
 
    /*
     * Open relation using relid
     */
    rel = relation_open(relid, AccessShareLock);
-   relname =  RelationGetRelationName(rel);
+   relname = RelationGetRelationName(rel);
    tupdesc = rel->rd_att;
    natts = tupdesc->natts;
 
@@ -1658,7 +1677,7 @@ get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattval
            appendStringInfo(str, ", ");
 
        appendStringInfo(str, "%s = ",
-                        quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
+                 quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
 
        if (tgt_pkattvals != NULL)
            key = get_attnum_pk_pos(pkattnums, pknumatts, i + 1);
@@ -1684,13 +1703,13 @@ get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattval
 
    for (i = 0; i < pknumatts; i++)
    {
-       int16   pkattnum = pkattnums[i];
+       int16       pkattnum = pkattnums[i];
 
        if (i > 0)
            appendStringInfo(str, " AND ");
 
        appendStringInfo(str, "%s",
-                        quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
+       quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
 
        if (tgt_pkattvals != NULL)
            val = pstrdup(tgt_pkattvals[i]);
@@ -1721,9 +1740,9 @@ get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattval
 static char *
 quote_literal_cstr(char *rawstr)
 {
-   text        *rawstr_text;
-   text        *result_text;
-   char        *result;
+   text       *rawstr_text;
+   text       *result_text;
+   char       *result;
 
    rawstr_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(rawstr)));
    result_text = DatumGetTextP(DirectFunctionCall1(quote_literal, PointerGetDatum(rawstr_text)));
@@ -1739,9 +1758,9 @@ quote_literal_cstr(char *rawstr)
 static char *
 quote_ident_cstr(char *rawstr)
 {
-   text        *rawstr_text;
-   text        *result_text;
-   char        *result;
+   text       *rawstr_text;
+   text       *result_text;
+   char       *result;
 
    rawstr_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(rawstr)));
    result_text = DatumGetTextP(DirectFunctionCall1(quote_ident, PointerGetDatum(rawstr_text)));
@@ -1753,11 +1772,10 @@ quote_ident_cstr(char *rawstr)
 static int16
 get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key)
 {
-   int     i;
+   int         i;
 
    /*
-    * Not likely a long list anyway, so just scan for
-    * the value
+    * Not likely a long list anyway, so just scan for the value
     */
    for (i = 0; i < pknumatts; i++)
        if (key == pkattnums[i])
@@ -1769,21 +1787,21 @@ get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key)
 static HeapTuple
 get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals)
 {
-   Relation        rel;
-   char            *relname;
-   TupleDesc       tupdesc;
-   StringInfo      str = makeStringInfo();
-   char            *sql = NULL;
-   int             ret;
-   HeapTuple       tuple;
-   int             i;
-   char            *val = NULL;
+   Relation    rel;
+   char       *relname;
+   TupleDesc   tupdesc;
+   StringInfo  str = makeStringInfo();
+   char       *sql = NULL;
+   int         ret;
+   HeapTuple   tuple;
+   int         i;
+   char       *val = NULL;
 
    /*
     * Open relation using relid
     */
    rel = relation_open(relid, AccessShareLock);
-   relname =  RelationGetRelationName(rel);
+   relname = RelationGetRelationName(rel);
    tupdesc = CreateTupleDescCopy(rel->rd_att);
    relation_close(rel, AccessShareLock);
 
@@ -1794,20 +1812,20 @@ get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_p
        elog(ERROR, "get_tuple_of_interest: SPI_connect returned %d", ret);
 
    /*
-    * Build sql statement to look up tuple of interest
-    * Use src_pkattvals as the criteria.
+    * Build sql statement to look up tuple of interest Use src_pkattvals
+    * as the criteria.
     */
    appendStringInfo(str, "SELECT * FROM %s WHERE ", quote_ident_cstr(relname));
 
    for (i = 0; i < pknumatts; i++)
    {
-       int16   pkattnum = pkattnums[i];
+       int16       pkattnum = pkattnums[i];
 
        if (i > 0)
            appendStringInfo(str, " AND ");
 
        appendStringInfo(str, "%s",
-                        quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
+       quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
 
        val = pstrdup(src_pkattvals[i]);
        if (val != NULL)
@@ -1822,6 +1840,7 @@ get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_p
    sql = pstrdup(str->data);
    pfree(str->data);
    pfree(str);
+
    /*
     * Retrieve the desired tuple
     */
@@ -1832,12 +1851,11 @@ get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_p
     * Only allow one qualifying tuple
     */
    if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
-   {
        elog(ERROR, "get_tuple_of_interest: Source criteria may not match more than one record.");
-   }
    else if (ret == SPI_OK_SELECT && SPI_processed == 1)
    {
        SPITupleTable *tuptable = SPI_tuptable;
+
        tuple = SPI_copytuple(tuptable->vals[0]);
 
        return tuple;
@@ -1871,15 +1889,15 @@ get_relid_from_relname(text *relname_text)
    return relid;
 }
 
-static dblink_results  *
+static dblink_results *
 get_res_ptr(int32 res_id_index)
 {
-   List    *ptr;
+   List       *ptr;
 
    /*
     * short circuit empty list
     */
-   if(res_id == NIL)
+   if (res_id == NIL)
        return NULL;
 
    /*
@@ -1887,7 +1905,8 @@ get_res_ptr(int32 res_id_index)
     */
    foreach(ptr, res_id)
    {
-       dblink_results  *this_res_id = (dblink_results *) lfirst(ptr);
+       dblink_results *this_res_id = (dblink_results *) lfirst(ptr);
+
        if (this_res_id->res_id_index == res_id_index)
            return this_res_id;
    }
@@ -1898,7 +1917,7 @@ get_res_ptr(int32 res_id_index)
  * Add node to global List res_id
  */
 static void
-append_res_ptr(dblink_results *results)
+append_res_ptr(dblink_results * results)
 {
    res_id = lappend(res_id, results);
 }
@@ -1908,7 +1927,7 @@ append_res_ptr(dblink_results *results)
  * using res_id_index
  */
 static void
-remove_res_ptr(dblink_results *results)
+remove_res_ptr(dblink_results * results)
 {
    res_id = lremove(results, res_id);
 
@@ -1919,15 +1938,15 @@ remove_res_ptr(dblink_results *results)
 static TupleDesc
 pgresultGetTupleDesc(PGresult *res)
 {
-   int             natts;
-   AttrNumber      attnum;
-   TupleDesc       desc;
-   char           *attname;
-   int32           atttypmod;
-   int             attdim;
-   bool            attisset;
-   Oid             atttypid;
-   int             i;
+   int         natts;
+   AttrNumber  attnum;
+   TupleDesc   desc;
+   char       *attname;
+   int32       atttypmod;
+   int         attdim;
+   bool        attisset;
+   Oid         atttypid;
+   int         i;
 
    /*
     * allocate a new tuple descriptor
@@ -1943,8 +1962,8 @@ pgresultGetTupleDesc(PGresult *res)
    for (i = 0; i < natts; i++)
    {
        /*
-        * for each field, get the name and type information from the query
-        * result and have TupleDescInitEntry fill in the attribute
+        * for each field, get the name and type information from the
+        * query result and have TupleDescInitEntry fill in the attribute
         * information we need.
         */
        attnum++;
@@ -1955,9 +1974,9 @@ pgresultGetTupleDesc(PGresult *res)
 
        if (PQfsize(res, i) != get_typlen(atttypid))
            elog(ERROR, "Size of remote field \"%s\" does not match size "
-               "of local type \"%s\"",
-               attname,
-               format_type_with_typemod(atttypid, atttypmod));
+                "of local type \"%s\"",
+                attname,
+                format_type_with_typemod(atttypid, atttypmod));
 
        attdim = 0;
        attisset = false;
index ddca6241c4a03e89e26b69e730249e8a83143365..09f9321bd6030c99c8fef6342e04977d16f62478 100644 (file)
@@ -74,6 +74,6 @@ extern Datum dblink_build_sql_delete(PG_FUNCTION_ARGS);
 extern Datum dblink_build_sql_update(PG_FUNCTION_ARGS);
 extern Datum dblink_current_query(PG_FUNCTION_ARGS);
 
-extern char    *debug_query_string;
+extern char *debug_query_string;
 
 #endif   /* DBLINK_H */
index a9027dbe502c8ffc8ef67d2762ab0f8f02c04152..82aaffa15e98185413a2d48d11a9cff197c987c6 100644 (file)
@@ -1,20 +1,20 @@
 /****************************************************************************
  * pending.c
- * $Id: pending.c,v 1.1 2002/06/23 21:58:08 momjian Exp $ 
+ * $Id: pending.c,v 1.2 2002/09/04 20:31:06 momjian Exp $
  *
  * This file contains a trigger for Postgresql-7.x to record changes to tables
  * to a pending table for mirroring.
  * All tables that should be mirrored should have this trigger hooked up to it.
  *
- *   Written by Steven Singer (ssinger@navtechinc.com)
- *   (c) 2001-2002 Navtech Systems Support Inc.
- *   Released under the GNU Public License version 2. See COPYING.
+ *  Written by Steven Singer (ssinger@navtechinc.com)
+ *  (c) 2001-2002 Navtech Systems Support Inc.
+ *  Released under the GNU Public License version 2. See COPYING.
  *
  *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
  *
  *
  ***************************************************************************/
 #include <commands/trigger.h>
 #include <postgres.h>
 
-enum FieldUsage  {PRIMARY=0,NONPRIMARY,ALL,NUM_FIELDUSAGE};
+enum FieldUsage
+{
+   PRIMARY = 0, NONPRIMARY, ALL, NUM_FIELDUSAGE
+};
 
-int storePending(char * cpTableName, HeapTuple  tBeforeTuple, 
-        HeapTuple tAfterTuple,
-         TupleDesc tTupdesc,
-        TriggerData * tpTrigdata,char cOp);
+int storePending(char *cpTableName, HeapTuple tBeforeTuple,
+            HeapTuple tAfterTuple,
+            TupleDesc tTupdesc,
+            TriggerData *tpTrigdata, char cOp);
 
-int storeKeyInfo(char * cpTableName, HeapTuple tTupleData, TupleDesc tTuplDesc,
-        TriggerData * tpTrigdata);
-int storeData(char * cpTableName,HeapTuple tTupleData,TupleDesc tTupleDesc,
-         TriggerData * tpTrigData,int iIncludeKeyData);
-     
-int2vector * getPrimaryKey(Oid tblOid);
+int storeKeyInfo(char *cpTableName, HeapTuple tTupleData, TupleDesc tTuplDesc,
+            TriggerData *tpTrigdata);
+int storeData(char *cpTableName, HeapTuple tTupleData, TupleDesc tTupleDesc,
+         TriggerData *tpTrigData, int iIncludeKeyData);
 
-char * packageData(HeapTuple tTupleData, TupleDesc tTupleDecs,
-          TriggerData * tTrigData,
-          enum FieldUsage eKeyUsage );
+int2vector *getPrimaryKey(Oid tblOid);
+
+char *packageData(HeapTuple tTupleData, TupleDesc tTupleDecs,
+           TriggerData *tTrigData,
+           enum FieldUsage eKeyUsage);
 
 #define BUFFER_SIZE 256
 #define MAX_OID_LEN 10
 
 
 extern Datum recordchange(PG_FUNCTION_ARGS);
+
 PG_FUNCTION_INFO_V1(recordchange);
 
 
@@ -54,394 +58,430 @@ PG_FUNCTION_INFO_V1(recordchange);
  * table the trigger was applied to.  If this name is incorrect so will the
  * mirroring.
  ****************************************************************************/
-Datum recordchange(PG_FUNCTION_ARGS) {
-  TriggerData * trigdata; 
-  TupleDesc tupdesc;
-  HeapTuple beforeTuple=NULL;
-  HeapTuple afterTuple=NULL;
-  HeapTuple retTuple=NULL;
-  char * tblname;
-  char op;
-  if(fcinfo->context!=NULL) {
-    
-    if(SPI_connect() < 0) {
-      elog(NOTICE,"storePending could not connect to SPI");
-      return -1;
-    }
-    trigdata = (TriggerData*)fcinfo->context;
-    /* Extract the table name */
-    tblname = SPI_getrelname(trigdata->tg_relation);
-    tupdesc = trigdata->tg_relation->rd_att;
-    if(TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) {
-      retTuple = trigdata->tg_newtuple;
-      beforeTuple = trigdata->tg_trigtuple;
-      afterTuple = trigdata->tg_newtuple;
-      op='u';
-
-    }
-    else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event)) {
-      retTuple = trigdata->tg_trigtuple;
-      afterTuple = trigdata->tg_trigtuple;
-      op = 'i';
-    }
-    else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) {
-      retTuple = trigdata->tg_trigtuple;
-      beforeTuple = trigdata->tg_trigtuple;
-      op = 'd';
-    }
-
-    if(storePending(tblname,beforeTuple,afterTuple,tupdesc,trigdata,op)) {
-      /* An error occoured. Skip the operation. */
-      elog(ERROR,"Operation could not be mirrored");
-      return PointerGetDatum(NULL);
-    
-    }
+Datum
+recordchange(PG_FUNCTION_ARGS)
+{
+   TriggerData *trigdata;
+   TupleDesc   tupdesc;
+   HeapTuple   beforeTuple = NULL;
+   HeapTuple   afterTuple = NULL;
+   HeapTuple   retTuple = NULL;
+   char       *tblname;
+   char        op;
+
+   if (fcinfo->context != NULL)
+   {
+
+       if (SPI_connect() < 0)
+       {
+           elog(NOTICE, "storePending could not connect to SPI");
+           return -1;
+       }
+       trigdata = (TriggerData *) fcinfo->context;
+       /* Extract the table name */
+       tblname = SPI_getrelname(trigdata->tg_relation);
+       tupdesc = trigdata->tg_relation->rd_att;
+       if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
+       {
+           retTuple = trigdata->tg_newtuple;
+           beforeTuple = trigdata->tg_trigtuple;
+           afterTuple = trigdata->tg_newtuple;
+           op = 'u';
+
+       }
+       else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
+       {
+           retTuple = trigdata->tg_trigtuple;
+           afterTuple = trigdata->tg_trigtuple;
+           op = 'i';
+       }
+       else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
+       {
+           retTuple = trigdata->tg_trigtuple;
+           beforeTuple = trigdata->tg_trigtuple;
+           op = 'd';
+       }
+
+       if (storePending(tblname, beforeTuple, afterTuple, tupdesc, trigdata, op))
+       {
+           /* An error occoured. Skip the operation. */
+           elog(ERROR, "Operation could not be mirrored");
+           return PointerGetDatum(NULL);
+
+       }
 #if defined DEBUG_OUTPUT
-    elog(NOTICE,"Returning on success");
+       elog(NOTICE, "Returning on success");
 #endif
-    SPI_finish();
-    return PointerGetDatum(retTuple);
-  }
-  else {
-    /*
-     * Not being called as a trigger.
-     */
-    return PointerGetDatum(NULL);
-  }
+       SPI_finish();
+       return PointerGetDatum(retTuple);
+   }
+   else
+   {
+       /*
+        * Not being called as a trigger.
+        */
+       return PointerGetDatum(NULL);
+   }
 }
 
 
 /*****************************************************************************
  * Constructs and executes an SQL query to write a record of this tuple change
- * to the pending table. 
+ * to the pending table.
  *****************************************************************************/
-int storePending(char * cpTableName, HeapTuple  tBeforeTuple, 
-        HeapTuple tAfterTuple,
-         TupleDesc tTupDesc,
-         TriggerData * tpTrigData,char cOp) {
-  char * cpQueryBase = "INSERT INTO \"Pending\" (\"TableName\",\"Op\",\"XID\") VALUES ($1,$2,$3)";
-
-  int iResult=0;
-  HeapTuple tCurTuple; // Points the current tuple(before or after)
-  Datum saPlanData[4];
-  Oid taPlanArgTypes[3] = {NAMEOID,CHAROID,INT4OID};
-  void * vpPlan;
-
-  tCurTuple = tBeforeTuple ? tBeforeTuple : tAfterTuple;
-
-  
-
-  
-  vpPlan = SPI_prepare(cpQueryBase,3,taPlanArgTypes);
-  if(vpPlan==NULL) {
-    elog(NOTICE,"Error creating plan");
-  }
-  //  SPI_saveplan(vpPlan);
-
-  saPlanData[0] = PointerGetDatum(cpTableName);
-  saPlanData[1] = CharGetDatum(cOp);
-  saPlanData[2] = Int32GetDatum(GetCurrentTransactionId());
-  
-  
-  iResult = SPI_execp(vpPlan,saPlanData,NULL,1);
-  if(iResult < 0) {
-    elog(NOTICE,"storedPending fired (%s) returned %d",cpQueryBase,iResult);
-  }
-  
+int
+storePending(char *cpTableName, HeapTuple tBeforeTuple,
+            HeapTuple tAfterTuple,
+            TupleDesc tTupDesc,
+            TriggerData *tpTrigData, char cOp)
+{
+   char       *cpQueryBase = "INSERT INTO \"Pending\" (\"TableName\",\"Op\",\"XID\") VALUES ($1,$2,$3)";
+
+   int         iResult = 0;
+   HeapTuple   tCurTuple;
+
+   //Points the current tuple(before or after)
+       Datum       saPlanData[4];
+   Oid         taPlanArgTypes[3] = {NAMEOID, CHAROID, INT4OID};
+   void       *vpPlan;
+
+   tCurTuple = tBeforeTuple ? tBeforeTuple : tAfterTuple;
+
+
+
+
+   vpPlan = SPI_prepare(cpQueryBase, 3, taPlanArgTypes);
+   if (vpPlan == NULL)
+       elog(NOTICE, "Error creating plan");
+   /* SPI_saveplan(vpPlan); */
+
+   saPlanData[0] = PointerGetDatum(cpTableName);
+   saPlanData[1] = CharGetDatum(cOp);
+   saPlanData[2] = Int32GetDatum(GetCurrentTransactionId());
+
+
+   iResult = SPI_execp(vpPlan, saPlanData, NULL, 1);
+   if (iResult < 0)
+       elog(NOTICE, "storedPending fired (%s) returned %d", cpQueryBase, iResult);
+
 
 #if defined DEBUG_OUTPUT
elog(NOTICE,"row successfully stored in pending table");
  elog(NOTICE, "row successfully stored in pending table");
 #endif
 
-  if(cOp=='d') {
-    /**
-     * This is a record of a delete operation.
-     * Just store the key data.
-     */
-    iResult = storeKeyInfo(cpTableName,tBeforeTuple,tTupDesc,tpTrigData);
-  }
-  else if (cOp=='i') {
-    /**
-     * An Insert operation.
-     * Store all data
-     */
-    iResult = storeData(cpTableName,tAfterTuple,tTupDesc,tpTrigData,TRUE);
-
-  }
-  else {
-    /* op must be an update. */
-    iResult = storeKeyInfo(cpTableName,tBeforeTuple,tTupDesc,tpTrigData);
-    iResult = iResult ? iResult : storeData(cpTableName,tAfterTuple,tTupDesc,
-                       tpTrigData,TRUE);
-  }
+   if (cOp == 'd')
+   {
+       /**
+        * This is a record of a delete operation.
+        * Just store the key data.
+        */
+       iResult = storeKeyInfo(cpTableName, tBeforeTuple, tTupDesc, tpTrigData);
+   }
+   else if (cOp == 'i')
+   {
+       /**
+        * An Insert operation.
+        * Store all data
+        */
+       iResult = storeData(cpTableName, tAfterTuple, tTupDesc, tpTrigData, TRUE);
+
+   }
+   else
+   {
+       /* op must be an update. */
+       iResult = storeKeyInfo(cpTableName, tBeforeTuple, tTupDesc, tpTrigData);
+       iResult = iResult ? iResult : storeData(cpTableName, tAfterTuple, tTupDesc,
+                                               tpTrigData, TRUE);
+   }
 
 #if defined DEBUG_OUTPUT
-  elog(NOTICE,"DOne storing keyinfo");
+   elog(NOTICE, "DOne storing keyinfo");
 #endif
-  return iResult;
+
+   return iResult;
 
 }
 
-int storeKeyInfo(char * cpTableName, HeapTuple tTupleData, 
-        TupleDesc tTupleDesc,
-        TriggerData * tpTrigData) {
-  Oid saPlanArgTypes[1] = {NAMEOID};
-  char * insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'t',$1)";
-  void * pplan;
-  Datum saPlanData[1];
-  char * cpKeyData;
-  int iRetCode;
-
-  pplan = SPI_prepare(insQuery,1,saPlanArgTypes);
-    if(pplan==NULL) {
-      elog(NOTICE,"Could not prepare INSERT plan");
-      return -1;
-    }
-    
-    //    pplan = SPI_saveplan(pplan);
-    cpKeyData = packageData(tTupleData, tTupleDesc,tpTrigData,PRIMARY);
+int
+storeKeyInfo(char *cpTableName, HeapTuple tTupleData,
+            TupleDesc tTupleDesc,
+            TriggerData *tpTrigData)
+{
+
+   Oid         saPlanArgTypes[1] = {NAMEOID};
+   char       *insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'t',$1)";
+   void       *pplan;
+   Datum       saPlanData[1];
+   char       *cpKeyData;
+   int         iRetCode;
+
+   pplan = SPI_prepare(insQuery, 1, saPlanArgTypes);
+   if (pplan == NULL)
+   {
+       elog(NOTICE, "Could not prepare INSERT plan");
+       return -1;
+   }
+
+   /* pplan = SPI_saveplan(pplan); */
+   cpKeyData = packageData(tTupleData, tTupleDesc, tpTrigData, PRIMARY);
 #if defined DEBUG_OUTPUT
-    elog(NOTICE,cpKeyData);
+   elog(NOTICE, cpKeyData);
 #endif
-    saPlanData[0] = PointerGetDatum(cpKeyData);
-    
-    iRetCode = SPI_execp(pplan,saPlanData,NULL,1);    
-
-    if(cpKeyData!=NULL) {
-      SPI_pfree(cpKeyData);
-    }
-
-    if(iRetCode != SPI_OK_INSERT ) {
-      elog(NOTICE,"Error inserting row in pendingDelete");
-      return -1;
-    }
+   saPlanData[0] = PointerGetDatum(cpKeyData);
+
+   iRetCode = SPI_execp(pplan, saPlanData, NULL, 1);
+
+   if (cpKeyData != NULL)
+       SPI_pfree(cpKeyData);
+
+   if (iRetCode != SPI_OK_INSERT)
+   {
+       elog(NOTICE, "Error inserting row in pendingDelete");
+       return -1;
+   }
 #if defined DEBUG_OUTPUT
-    elog(NOTICE,"INSERT SUCCESFULL");
+   elog(NOTICE, "INSERT SUCCESFULL");
 #endif
 
-    return 0;
-    
+   return 0;
+
 }
 
 
 
 
-int2vector * getPrimaryKey(Oid tblOid) {
-  char * queryBase;
-  char * query;
-  bool isNull;
-  int2vector * resultKey;
-  int2vector * tpResultKey;
-  HeapTuple resTuple;
-  Datum resDatum;
-  int ret;
-  queryBase = "SELECT indkey FROM pg_index WHERE indisprimary='t' AND indrelid=";
-  query = SPI_palloc(strlen(queryBase) + MAX_OID_LEN+1);
-  sprintf(query,"%s%d",queryBase,tblOid);
-  ret = SPI_exec(query,1);
-  if(ret != SPI_OK_SELECT || SPI_processed != 1 ) {
-    elog(NOTICE,"Could not select primary index key");
-    return NULL;
-  }
+int2vector *
+getPrimaryKey(Oid tblOid)
+{
+   char       *queryBase;
+   char       *query;
+   bool        isNull;
+   int2vector *resultKey;
+   int2vector *tpResultKey;
+   HeapTuple   resTuple;
+   Datum       resDatum;
+   int         ret;
+
+   queryBase = "SELECT indkey FROM pg_index WHERE indisprimary='t' AND indrelid=";
+   query = SPI_palloc(strlen(queryBase) + MAX_OID_LEN + 1);
+   sprintf(query, "%s%d", queryBase, tblOid);
+   ret = SPI_exec(query, 1);
+   if (ret != SPI_OK_SELECT || SPI_processed != 1)
+   {
+       elog(NOTICE, "Could not select primary index key");
+       return NULL;
+   }
 
-  resTuple = SPI_tuptable->vals[0];
-  resDatum = SPI_getbinval(resTuple,SPI_tuptable->tupdesc,1,&isNull);
+   resTuple = SPI_tuptable->vals[0];
+   resDatum = SPI_getbinval(resTuple, SPI_tuptable->tupdesc, 1, &isNull);
 
-  tpResultKey = (int2vector*) DatumGetPointer(resDatum);
-  resultKey = SPI_palloc(sizeof(int2vector));
-  memcpy(resultKey,tpResultKey,sizeof(int2vector));
+   tpResultKey = (int2vector *) DatumGetPointer(resDatum);
+   resultKey = SPI_palloc(sizeof(int2vector));
+   memcpy(resultKey, tpResultKey, sizeof(int2vector));
 
-  SPI_pfree(query);
-  return resultKey;
+   SPI_pfree(query);
+   return resultKey;
 }
 
 /******************************************************************************
  * Stores a copy of the non-key data for the row.
  *****************************************************************************/
-int storeData(char * cpTableName,HeapTuple tTupleData,TupleDesc tTupleDesc,
-            TriggerData * tpTrigData,int iIncludeKeyData) {
-
-  Oid planArgTypes[1] = {NAMEOID};
-  char * insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'f',$1)";
-  void * pplan;
-  Datum planData[1];
-  char * cpKeyData;
-  int iRetValue;
-
-  pplan = SPI_prepare(insQuery,1,planArgTypes);
-    if(pplan==NULL) {
-      elog(NOTICE,"Could not prepare INSERT plan");
-      return -1;
-    }
-    
-    //    pplan = SPI_saveplan(pplan);
-    if(iIncludeKeyData==0) {
-      cpKeyData = packageData(tTupleData, tTupleDesc,tpTrigData,NONPRIMARY); 
-    }
-    else {
-      cpKeyData = packageData(tTupleData,tTupleDesc,tpTrigData,ALL);
-    }
-    
-    planData[0] = PointerGetDatum(cpKeyData);
-    iRetValue = SPI_execp(pplan,planData,NULL,1);
-    
-    if(cpKeyData!=0) {
-      SPI_pfree(cpKeyData);
-    }
-
-    if(iRetValue != SPI_OK_INSERT ) {
-      elog(NOTICE,"Error inserting row in pendingDelete");
-      return -1;
-    }
+int
+storeData(char *cpTableName, HeapTuple tTupleData, TupleDesc tTupleDesc,
+         TriggerData *tpTrigData, int iIncludeKeyData)
+{
+
+   Oid         planArgTypes[1] = {NAMEOID};
+   char       *insQuery = "INSERT INTO \"PendingData\" (\"SeqId\",\"IsKey\",\"Data\") VALUES(currval('\"Pending_SeqId_seq\"'),'f',$1)";
+   void       *pplan;
+   Datum       planData[1];
+   char       *cpKeyData;
+   int         iRetValue;
+
+   pplan = SPI_prepare(insQuery, 1, planArgTypes);
+   if (pplan == NULL)
+   {
+       elog(NOTICE, "Could not prepare INSERT plan");
+       return -1;
+   }
+
+   /* pplan = SPI_saveplan(pplan); */
+   if (iIncludeKeyData == 0)
+       cpKeyData = packageData(tTupleData, tTupleDesc, tpTrigData, NONPRIMARY);
+   else
+       cpKeyData = packageData(tTupleData, tTupleDesc, tpTrigData, ALL);
+
+   planData[0] = PointerGetDatum(cpKeyData);
+   iRetValue = SPI_execp(pplan, planData, NULL, 1);
+
+   if (cpKeyData != 0)
+       SPI_pfree(cpKeyData);
+
+   if (iRetValue != SPI_OK_INSERT)
+   {
+       elog(NOTICE, "Error inserting row in pendingDelete");
+       return -1;
+   }
 #if defined DEBUG_OUTPUT
-    elog(NOTICE,"INSERT SUCCESFULL");
+   elog(NOTICE, "INSERT SUCCESFULL");
 #endif
 
-    return 0;  
-    
+   return 0;
+
 }
 
 /**
- * Packages the data in tTupleData into a string of the format 
+ * Packages the data in tTupleData into a string of the format
  * FieldName='value text'  where any quotes inside of value text
  * are escaped with a backslash and any backslashes in value text
  * are esacped by a second back slash.
  *
- * tTupleDesc should be a description of the tuple stored in 
- * tTupleData.  
+ * tTupleDesc should be a description of the tuple stored in
+ * tTupleData.
  *
  * eFieldUsage specifies which fields to use.
- *  PRIMARY implies include only primary key fields.
- *  NONPRIMARY implies include only non-primary key fields.
- *  ALL implies include all fields.
+ * PRIMARY implies include only primary key fields.
+ * NONPRIMARY implies include only non-primary key fields.
+ * ALL implies include all fields.
  */
-char * packageData(HeapTuple tTupleData, TupleDesc tTupleDesc,
-          TriggerData *  tpTrigData,
-          enum FieldUsage eKeyUsage ) {
-  int iNumCols;
-  int2vector * tpPKeys=NULL;
-  int iColumnCounter;
-  char * cpDataBlock;
-  int iDataBlockSize;
-  int  iUsedDataBlock;
-  
-  iNumCols = tTupleDesc->natts;
-
-  if(eKeyUsage!=ALL) {
-    tpPKeys = getPrimaryKey(tpTrigData->tg_relation->rd_id);
-    if(tpPKeys==NULL) {
-      return NULL;
-    }
-  }
-#if defined DEBUG_OUTPUT
-  if(tpPKeys!=NULL) {
-    elog(NOTICE,"Have primary keys");
-  }
-#endif 
-  cpDataBlock = SPI_palloc(BUFFER_SIZE);
-  iDataBlockSize = BUFFER_SIZE;
-  iUsedDataBlock = 0;                   /* To account for the null */
-
-  for(iColumnCounter=1; iColumnCounter <=iNumCols; iColumnCounter++) {
-    int iIsPrimaryKey;
-    int iPrimaryKeyIndex;
-    char * cpUnFormatedPtr;
-    char * cpFormatedPtr;
-
-    char * cpFieldName;
-    char * cpFieldData;
-    if(eKeyUsage!=ALL) {
-      //Determine if this is a primary key or not.
-      iIsPrimaryKey=0;
-      for(iPrimaryKeyIndex=0; (*tpPKeys)[iPrimaryKeyIndex]!=0;
-     iPrimaryKeyIndex++) {
-   if((*tpPKeys)[iPrimaryKeyIndex]==iColumnCounter) {  
-     iIsPrimaryKey=1;
-     break;
+char *
+packageData(HeapTuple tTupleData, TupleDesc tTupleDesc,
+           TriggerData *tpTrigData,
+           enum FieldUsage eKeyUsage)
+{
+   int         iNumCols;
+   int2vector *tpPKeys = NULL;
+   int         iColumnCounter;
+   char       *cpDataBlock;
+   int         iDataBlockSize;
+   int         iUsedDataBlock;
+
+   iNumCols = tTupleDesc->natts;
+
+   if (eKeyUsage != ALL)
+   {
+       tpPKeys = getPrimaryKey(tpTrigData->tg_relation->rd_id);
+       if (tpPKeys == NULL)
+           return NULL;
    }
-      }
-      if( iIsPrimaryKey ? (eKeyUsage!=PRIMARY) : (eKeyUsage!=NONPRIMARY)) {
-   /**
-    * Don't use.
-    */
 #if defined DEBUG_OUTPUT
-   elog(NOTICE,"Skipping column");
+   if (tpPKeys != NULL)
+       elog(NOTICE, "Have primary keys");
 #endif
-   continue;
-      }
-    }                                   /* KeyUsage!=ALL */
-    cpFieldName = DatumGetPointer(NameGetDatum(&tTupleDesc->attrs
-                          [iColumnCounter-1]->attname));
+   cpDataBlock = SPI_palloc(BUFFER_SIZE);
+   iDataBlockSize = BUFFER_SIZE;
+   iUsedDataBlock = 0;         /* To account for the null */
+
+   for (iColumnCounter = 1; iColumnCounter <= iNumCols; iColumnCounter++)
+   {
+       int         iIsPrimaryKey;
+       int         iPrimaryKeyIndex;
+       char       *cpUnFormatedPtr;
+       char       *cpFormatedPtr;
+
+       char       *cpFieldName;
+       char       *cpFieldData;
+
+       if (eKeyUsage != ALL)
+       {
+           /* Determine if this is a primary key or not. */
+           iIsPrimaryKey = 0;
+           for (iPrimaryKeyIndex = 0; (*tpPKeys)[iPrimaryKeyIndex] != 0;
+                iPrimaryKeyIndex++)
+           {
+               if ((*tpPKeys)[iPrimaryKeyIndex] == iColumnCounter)
+               {
+                   iIsPrimaryKey = 1;
+                   break;
+               }
+           }
+           if (iIsPrimaryKey ? (eKeyUsage != PRIMARY) : (eKeyUsage != NONPRIMARY))
+           {
+               /**
+                * Don't use.
+                */
 #if defined DEBUG_OUTPUT
-    elog(NOTICE,cpFieldName);
+               elog(NOTICE, "Skipping column");
 #endif
-    while(iDataBlockSize - iUsedDataBlock < strlen(cpFieldName) +4) {
-      cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize + BUFFER_SIZE);
-      iDataBlockSize = iDataBlockSize + BUFFER_SIZE;      
-    }
-    sprintf(cpDataBlock+iUsedDataBlock,"\"%s\"=",cpFieldName);
-    iUsedDataBlock = iUsedDataBlock + strlen(cpFieldName)+3;
-    cpFieldData=SPI_getvalue(tTupleData,tTupleDesc,iColumnCounter);
-    
-    cpUnFormatedPtr = cpFieldData;
-    cpFormatedPtr = cpDataBlock + iUsedDataBlock;
-    if(cpFieldData!=NULL) {
-      *cpFormatedPtr='\'';
-      iUsedDataBlock++;
-      cpFormatedPtr++;
-    }
-    else {
-      *cpFormatedPtr=' ';
-      iUsedDataBlock++;
-      cpFormatedPtr++;
-      continue;
-      
-    }
+               continue;
+           }
+       }                       /* KeyUsage!=ALL */
+       cpFieldName = DatumGetPointer(NameGetDatum(&tTupleDesc->attrs
+                                        [iColumnCounter - 1]->attname));
 #if defined DEBUG_OUTPUT
-    elog(NOTICE,cpFieldData);
-    elog(NOTICE,"Starting format loop");
+       elog(NOTICE, cpFieldName);
 #endif
-    while(*cpUnFormatedPtr!=0) {
-      while(iDataBlockSize - iUsedDataBlock < 2) {
-   cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize+BUFFER_SIZE);
-   iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
-   cpFormatedPtr = cpDataBlock + iUsedDataBlock;
-      }
-      if(*cpUnFormatedPtr=='\\' || *cpUnFormatedPtr=='\'') {
-   *cpFormatedPtr='\\';
-   cpFormatedPtr++;
-   iUsedDataBlock++;
-      }
-      *cpFormatedPtr=*cpUnFormatedPtr;
-      cpFormatedPtr++;
-      cpUnFormatedPtr++;
-      iUsedDataBlock++;
-    }
-
-    SPI_pfree(cpFieldData);
-
-    while(iDataBlockSize - iUsedDataBlock < 3) {
-      cpDataBlock = SPI_repalloc(cpDataBlock,iDataBlockSize+BUFFER_SIZE);
-      iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
-      cpFormatedPtr = cpDataBlock + iUsedDataBlock;
-    }
-    sprintf(cpFormatedPtr,"' ");
-    iUsedDataBlock = iUsedDataBlock +2;
+       while (iDataBlockSize - iUsedDataBlock < strlen(cpFieldName) + 4)
+       {
+           cpDataBlock = SPI_repalloc(cpDataBlock, iDataBlockSize + BUFFER_SIZE);
+           iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
+       }
+       sprintf(cpDataBlock + iUsedDataBlock, "\"%s\"=", cpFieldName);
+       iUsedDataBlock = iUsedDataBlock + strlen(cpFieldName) + 3;
+       cpFieldData = SPI_getvalue(tTupleData, tTupleDesc, iColumnCounter);
+
+       cpUnFormatedPtr = cpFieldData;
+       cpFormatedPtr = cpDataBlock + iUsedDataBlock;
+       if (cpFieldData != NULL)
+       {
+           *cpFormatedPtr = '\'';
+           iUsedDataBlock++;
+           cpFormatedPtr++;
+       }
+       else
+       {
+           *cpFormatedPtr = ' ';
+           iUsedDataBlock++;
+           cpFormatedPtr++;
+           continue;
+
+       }
 #if defined DEBUG_OUTPUT
-    elog(NOTICE,cpDataBlock);
+       elog(NOTICE, cpFieldData);
+       elog(NOTICE, "Starting format loop");
 #endif
-    
-  }                                     /*  for iColumnCounter  */
-  if(tpPKeys!=NULL) {
-    SPI_pfree(tpPKeys);    
-  }
+       while (*cpUnFormatedPtr != 0)
+       {
+           while (iDataBlockSize - iUsedDataBlock < 2)
+           {
+               cpDataBlock = SPI_repalloc(cpDataBlock, iDataBlockSize + BUFFER_SIZE);
+               iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
+               cpFormatedPtr = cpDataBlock + iUsedDataBlock;
+           }
+           if (*cpUnFormatedPtr == '\\' || *cpUnFormatedPtr == '\'')
+           {
+               *cpFormatedPtr = '\\';
+               cpFormatedPtr++;
+               iUsedDataBlock++;
+           }
+           *cpFormatedPtr = *cpUnFormatedPtr;
+           cpFormatedPtr++;
+           cpUnFormatedPtr++;
+           iUsedDataBlock++;
+       }
+
+       SPI_pfree(cpFieldData);
+
+       while (iDataBlockSize - iUsedDataBlock < 3)
+       {
+           cpDataBlock = SPI_repalloc(cpDataBlock, iDataBlockSize + BUFFER_SIZE);
+           iDataBlockSize = iDataBlockSize + BUFFER_SIZE;
+           cpFormatedPtr = cpDataBlock + iUsedDataBlock;
+       }
+       sprintf(cpFormatedPtr, "' ");
+       iUsedDataBlock = iUsedDataBlock + 2;
 #if defined DEBUG_OUTPUT
-  elog(NOTICE,"Returning");
+       elog(NOTICE, cpDataBlock);
 #endif
-  memset(cpDataBlock + iUsedDataBlock,0,iDataBlockSize - iUsedDataBlock);
 
-  return cpDataBlock;
-  
+   }                           /* for iColumnCounter  */
+   if (tpPKeys != NULL)
+       SPI_pfree(tpPKeys);
+#if defined DEBUG_OUTPUT
+   elog(NOTICE, "Returning");
+#endif
+   memset(cpDataBlock + iUsedDataBlock, 0, iDataBlockSize - iUsedDataBlock);
+
+   return cpDataBlock;
+
 }
index 8bc216bf7993c5588801b5697d599777e13e7ff4..f97e7876c86d070d2701d1a6cbabfbf2afa13d98 100644 (file)
@@ -37,7 +37,7 @@ psnprintf(size_t len, const char *fmt,...)
 
 PG_FUNCTION_INFO_V1(database_size);
 
-Datum database_size(PG_FUNCTION_ARGS);
+Datum      database_size(PG_FUNCTION_ARGS);
 
 Datum
 database_size(PG_FUNCTION_ARGS)
@@ -97,7 +97,7 @@ database_size(PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1(relation_size);
 
-Datum relation_size(PG_FUNCTION_ARGS);
+Datum      relation_size(PG_FUNCTION_ARGS);
 
 Datum
 relation_size(PG_FUNCTION_ARGS)
@@ -111,7 +111,7 @@ relation_size(PG_FUNCTION_ARGS)
    unsigned int segcount;
 
    relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname,
-                                                            "relation_size"));
+                                                      "relation_size"));
    relation = heap_openrv(relrv, AccessShareLock);
 
    relnode = relation->rd_rel->relfilenode;
index b3bef4d3cb327a0f882eb7743556481ccc45c7eb..f83e5da189337ecb942cb5ae4b7b27bc1975e292 100644 (file)
@@ -73,7 +73,7 @@ main(int argc, char **argv)
                    SELECT  count(*)::int4 \
                        FROM \"%s\" t1, \"%s\" t2 \
                    WHERE t1.\"%s\" = t2.oid ",
-                       relname, relname2, attname);
+                        relname, relname2, attname);
            else
                sprintf(query, 4000, "\
                    DECLARE c_matches BINARY CURSOR FOR \
index 820ec8dd08dff6cec68e14ea208cbade99a0abdf..b9c39d400b59bbd702307920f722e397b72e1220 100644 (file)
@@ -11,7 +11,7 @@
  * This file is the property of the Digital Music Network (DMN).
  * It is being made available to users of the PostgreSQL system
  * under the BSD license.
- * 
+ *
  * NOTE: This module requires sizeof(void *) to be the same as sizeof(int)
  */
 #include "postgres.h"
 
 typedef struct
 {
-   ArrayType a;
-   int     items;
-   int     lower;
-   int4    array[1];
-}PGARRAY;
+   ArrayType   a;
+   int         items;
+   int         lower;
+   int4        array[1];
+}  PGARRAY;
 
 /* This is used to keep track of our position during enumeration */
 typedef struct callContext
 {
-   PGARRAY *p;
-   int num;
-   int flags;
-}CTX;
+   PGARRAY    *p;
+   int         num;
+   int         flags;
+}  CTX;
 
 #define TOASTED        1
-#define START_NUM  8
+#define START_NUM  8
 #define PGARRAY_SIZE(n) (sizeof(PGARRAY) + ((n-1)*sizeof(int4)))
 
-static PGARRAY * GetPGArray(int4 state, int fAdd);
-static PGARRAY *ShrinkPGArray(PGARRAY *p);
+static PGARRAY *GetPGArray(int4 state, int fAdd);
+static PGARRAY *ShrinkPGArray(PGARRAY * p);
 
-Datum int_agg_state(PG_FUNCTION_ARGS);
-Datum int_agg_final_count(PG_FUNCTION_ARGS);
-Datum int_agg_final_array(PG_FUNCTION_ARGS);
-Datum int_enum(PG_FUNCTION_ARGS);
+Datum      int_agg_state(PG_FUNCTION_ARGS);
+Datum      int_agg_final_count(PG_FUNCTION_ARGS);
+Datum      int_agg_final_array(PG_FUNCTION_ARGS);
+Datum      int_enum(PG_FUNCTION_ARGS);
 
 PG_FUNCTION_INFO_V1(int_agg_state);
 PG_FUNCTION_INFO_V1(int_agg_final_count);
@@ -80,20 +80,21 @@ PG_FUNCTION_INFO_V1(int_enum);
  * Manage the aggregation state of the array
  * You need to specify the correct memory context, or it will vanish!
  */
-static PGARRAY * GetPGArray(int4 state, int fAdd)
+static PGARRAY *
+GetPGArray(int4 state, int fAdd)
 {
-   PGARRAY *p = (PGARRAY *) state;
+   PGARRAY    *p = (PGARRAY *) state;
 
-   if(!state)
+   if (!state)
    {
        /* New array */
-       int cb = PGARRAY_SIZE(START_NUM);
+       int         cb = PGARRAY_SIZE(START_NUM);
 
        p = (PGARRAY *) MemoryContextAlloc(TopTransactionContext, cb);
 
-       if(!p)
+       if (!p)
        {
-           elog(ERROR,"Integer aggregator, cant allocate TopTransactionContext memory");
+           elog(ERROR, "Integer aggregator, cant allocate TopTransactionContext memory");
            return 0;
        }
 
@@ -104,22 +105,22 @@ static PGARRAY * GetPGArray(int4 state, int fAdd)
        p->a.elemtype = INT4OID;
 #endif
        p->items = 0;
-       p->lower= START_NUM;
+       p->lower = START_NUM;
    }
-   else if(fAdd)
-   {   /* Ensure array has space */
-       if(p->items >= p->lower)
+   else if (fAdd)
+   {                           /* Ensure array has space */
+       if (p->items >= p->lower)
        {
-           PGARRAY *pn;
-           int n = p->lower + p->lower;
-           int cbNew = PGARRAY_SIZE(n);
+           PGARRAY    *pn;
+           int         n = p->lower + p->lower;
+           int         cbNew = PGARRAY_SIZE(n);
 
            pn = (PGARRAY *) repalloc(p, cbNew);
 
-           if(!pn)
-           {   /* Realloc failed! Reallocate new block. */
+           if (!pn)
+           {                   /* Realloc failed! Reallocate new block. */
                pn = (PGARRAY *) MemoryContextAlloc(TopTransactionContext, cbNew);
-               if(!pn)
+               if (!pn)
                {
                    elog(ERROR, "Integer aggregator, REALLY REALLY can't alloc memory");
                    return (PGARRAY *) NULL;
@@ -136,24 +137,29 @@ static PGARRAY * GetPGArray(int4 state, int fAdd)
 }
 
 /* Shrinks the array to its actual size and moves it into the standard
- * memory allocation context, frees working memory  */
-static PGARRAY *ShrinkPGArray(PGARRAY *p)
+ * memory allocation context, frees working memory */
+static PGARRAY *
+ShrinkPGArray(PGARRAY * p)
 {
-   PGARRAY *pnew=NULL;
-   if(p)
+   PGARRAY    *pnew = NULL;
+
+   if (p)
    {
        /* get target size */
-       int cb = PGARRAY_SIZE(p->items);
+       int         cb = PGARRAY_SIZE(p->items);
 
        /* use current transaction context */
        pnew = palloc(cb);
 
-       if(pnew)
+       if (pnew)
        {
-           /* Fix up the fields in the new structure, so Postgres understands */
+           /*
+            * Fix up the fields in the new structure, so Postgres
+            * understands
+            */
            memcpy(pnew, p, cb);
            pnew->a.size = cb;
-           pnew->a.ndim=1;
+           pnew->a.ndim = 1;
            pnew->a.flags = 0;
 #ifndef PG_7_2
            pnew->a.elemtype = INT4OID;
@@ -161,79 +167,72 @@ static PGARRAY *ShrinkPGArray(PGARRAY *p)
            pnew->lower = 0;
        }
        else
-       {
            elog(ERROR, "Integer aggregator, can't allocate memory");
-       }
        pfree(p);
    }
    return pnew;
 }
 
 /* Called for each iteration during an aggregate function */
-Datum int_agg_state(PG_FUNCTION_ARGS)
+Datum
+int_agg_state(PG_FUNCTION_ARGS)
 {
-   int4 state = PG_GETARG_INT32(0);
-   int4 value = PG_GETARG_INT32(1);
+   int4        state = PG_GETARG_INT32(0);
+   int4        value = PG_GETARG_INT32(1);
 
-   PGARRAY *p = GetPGArray(state, 1);
-   if(!p)
-   {
-       elog(ERROR,"No aggregate storage");
-   }
-   else if(p->items >= p->lower)
-   {
-       elog(ERROR,"aggregate storage too small");
-   }
+   PGARRAY    *p = GetPGArray(state, 1);
+
+   if (!p)
+       elog(ERROR, "No aggregate storage");
+   else if (p->items >= p->lower)
+       elog(ERROR, "aggregate storage too small");
    else
-   {
-       p->array[p->items++]= value;
-   }
+       p->array[p->items++] = value;
    PG_RETURN_INT32(p);
 }
 
 /* This is the final function used for the integer aggregator. It returns all the integers
  * collected as a one dimentional integer array */
-Datum int_agg_final_array(PG_FUNCTION_ARGS)
+Datum
+int_agg_final_array(PG_FUNCTION_ARGS)
 {
-   PGARRAY *pnew = ShrinkPGArray(GetPGArray(PG_GETARG_INT32(0),0));
-   if(pnew)
-   {
+   PGARRAY    *pnew = ShrinkPGArray(GetPGArray(PG_GETARG_INT32(0), 0));
+
+   if (pnew)
        PG_RETURN_POINTER(pnew);
-   }
    else
-   {
        PG_RETURN_NULL();
-   }
 }
 
 /* This function accepts an array, and returns one item for each entry in the array */
-Datum int_enum(PG_FUNCTION_ARGS)
+Datum
+int_enum(PG_FUNCTION_ARGS)
 {
-   PGARRAY *p = (PGARRAY *) PG_GETARG_POINTER(0);
-   CTX *pc;
-   ReturnSetInfo *rsi = (ReturnSetInfo *)fcinfo->resultinfo;
+   PGARRAY    *p = (PGARRAY *) PG_GETARG_POINTER(0);
+   CTX        *pc;
+   ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
 
    if (!rsi || !IsA(rsi, ReturnSetInfo))
        elog(ERROR, "No ReturnSetInfo sent! function must be declared returning a 'setof' integer");
 
-   if(!p)
+   if (!p)
    {
        elog(WARNING, "No data sent");
        PG_RETURN_NULL();
    }
 
-   if(!fcinfo->context)
+   if (!fcinfo->context)
    {
        /* Allocate a working context */
        pc = (CTX *) palloc(sizeof(CTX));
 
        /* Don't copy atribute if you don't need too */
-       if(VARATT_IS_EXTENDED(p) )
+       if (VARATT_IS_EXTENDED(p))
        {
            /* Toasted!!! */
            pc->p = (PGARRAY *) PG_DETOAST_DATUM_COPY(p);
            pc->flags = TOASTED;
-           if(!pc->p)
+           if (!pc->p)
            {
                elog(ERROR, "Error in toaster!!! no detoasting");
                PG_RETURN_NULL();
@@ -246,25 +245,26 @@ Datum int_enum(PG_FUNCTION_ARGS)
            pc->flags = 0;
        }
        fcinfo->context = (Node *) pc;
-       pc->num=0;
+       pc->num = 0;
    }
-   else /* use an existing one */
-   {
+   else
+/* use an existing one */
        pc = (CTX *) fcinfo->context;
-   }
    /* Are we done yet? */
-   if(pc->num >= pc->p->items)
+   if (pc->num >= pc->p->items)
    {
        /* We are done */
-       if(pc->flags & TOASTED)
+       if (pc->flags & TOASTED)
            pfree(pc->p);
        pfree(fcinfo->context);
        fcinfo->context = NULL;
-       rsi->isDone = ExprEndResult ;
+       rsi->isDone = ExprEndResult;
    }
-   else    /* nope, return the next value */
+   else
+/* nope, return the next value */
    {
-       int val = pc->p->array[pc->num++];
+       int         val = pc->p->array[pc->num++];
+
        rsi->isDone = ExprMultipleResult;
        PG_RETURN_INT32(val);
    }
index 75ebf5d8dda899a0ae042bd79847079f80f102e1..09590a28527f0ef13489f2728536255a816de000 100644 (file)
@@ -100,7 +100,7 @@ typedef char *BITVECP;
 static void
 printarr(ArrayType *a, int num)
 {
-   StringInfoData  bbb;
+   StringInfoData bbb;
    char       *cur;
    int         l;
    int        *d;
@@ -108,9 +108,7 @@ printarr(ArrayType *a, int num)
    d = ARRPTR(a);
    initStringInfo(&bbb);
    for (l = 0; l < min(num, ARRNELEMS(a)); l++)
-   {
        appendStringInfo(&bbb, "%d ", d[l]);
-   }
    elog(DEBUG3, "\t\t%s", bbb.data);
    pfree(bbb.data);
 }
@@ -125,7 +123,6 @@ printbitvec(BITVEC bv)
 
    elog(DEBUG3, "BV: %s", str);
 }
-
 #endif
 
 /*
@@ -163,78 +160,78 @@ static ArrayType *_int_common_union(bytea *entryvec,
 /*
 ** GiST support methods
 */
-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);
+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);
 
 
 /*
 ** R-tree support functions
 */
-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);
+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);
 
 /*
 ** _intbig methods
 */
-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);
+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);
 
 static bool _intbig_contains(ArrayType *a, ArrayType *b);
 static bool _intbig_overlap(ArrayType *a, ArrayType *b);
 static ArrayType *_intbig_union(ArrayType *a, ArrayType *b);
 
-static ArrayType * _intbig_inter(ArrayType *a, ArrayType *b);
+static ArrayType *_intbig_inter(ArrayType *a, ArrayType *b);
 static void rt__intbig_size(ArrayType *a, float *sz);
 
 
 
 /*****************************************************************************
- *         Boolean Search
+ *         Boolean Search
  *****************************************************************************/
 
 #define BooleanSearchStrategy  20
@@ -243,17 +240,19 @@ static void rt__intbig_size(ArrayType *a, float *sz);
  * 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;
+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) )
@@ -261,20 +260,20 @@ typedef struct {
 
 PG_FUNCTION_INFO_V1(bqarr_in);
 PG_FUNCTION_INFO_V1(bqarr_out);
-Datum   bqarr_in(PG_FUNCTION_ARGS);
-Datum   bqarr_out(PG_FUNCTION_ARGS);
+Datum      bqarr_in(PG_FUNCTION_ARGS);
+Datum      bqarr_out(PG_FUNCTION_ARGS);
 
 PG_FUNCTION_INFO_V1(boolop);
-Datum   boolop(PG_FUNCTION_ARGS);
+Datum      boolop(PG_FUNCTION_ARGS);
 
 PG_FUNCTION_INFO_V1(rboolop);
-Datum   rboolop(PG_FUNCTION_ARGS);
+Datum      rboolop(PG_FUNCTION_ARGS);
 
 PG_FUNCTION_INFO_V1(querytree);
-Datum   querytree(PG_FUNCTION_ARGS);
+Datum      querytree(PG_FUNCTION_ARGS);
 
-static bool signconsistent( QUERYTYPE *query, BITVEC sign, bool leaf );
-static bool execconsistent( QUERYTYPE *query, ArrayType *array, bool leaf );
+static bool signconsistent(QUERYTYPE * query, BITVEC sign, bool leaf);
+static bool execconsistent(QUERYTYPE * query, ArrayType *array, bool leaf);
 
 /*****************************************************************************
  *                        GiST functions
@@ -287,21 +286,22 @@ static bool execconsistent( QUERYTYPE *query, ArrayType *array, bool leaf );
 ** corresponding to strategy in the pg_amop table.
 */
 Datum
-g_int_consistent(PG_FUNCTION_ARGS) {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
-   ArrayType *query = ( ArrayType * )PG_GETARG_POINTER(1);
+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);
    bool        retval;
 
-   if ( strategy == BooleanSearchStrategy )
-       PG_RETURN_BOOL(execconsistent( (QUERYTYPE*)query,
-                       (ArrayType *) DatumGetPointer(entry->key),
-                       ISLEAFKEY( (ArrayType *) DatumGetPointer(entry->key) ) ) );
+   if (strategy == BooleanSearchStrategy)
+       PG_RETURN_BOOL(execconsistent((QUERYTYPE *) query,
+                              (ArrayType *) DatumGetPointer(entry->key),
+                 ISLEAFKEY((ArrayType *) DatumGetPointer(entry->key))));
 
    /* XXX are we sure it's safe to scribble on the query object here? */
    /* XXX what about toasted input? */
    /* sort query for fast search, key is already sorted */
-   if ( ARRISVOID( query ) )
+   if (ARRISVOID(query))
        PG_RETURN_BOOL(false);
    PREPAREARR(query);
 
@@ -312,28 +312,28 @@ g_int_consistent(PG_FUNCTION_ARGS) {
                                       query);
            break;
        case RTSameStrategyNumber:
-           if ( GIST_LEAF(entry) )
+           if (GIST_LEAF(entry))
                DirectFunctionCall3(
-                   g_int_same,
-                   entry->key,
-                   PointerGetDatum(query),
-                   PointerGetDatum(&retval)
-               );
+                                   g_int_same,
+                                   entry->key,
+                                   PointerGetDatum(query),
+                                   PointerGetDatum(&retval)
+                   );
            else
                retval = inner_int_contains((ArrayType *) DatumGetPointer(entry->key),
-                                       query);
+                                           query);
            break;
        case RTContainsStrategyNumber:
            retval = inner_int_contains((ArrayType *) DatumGetPointer(entry->key),
                                        query);
            break;
        case RTContainedByStrategyNumber:
-           if ( GIST_LEAF(entry) )
+           if (GIST_LEAF(entry))
                retval = inner_int_contains(query,
-                   (ArrayType *) DatumGetPointer(entry->key) );
+                             (ArrayType *) DatumGetPointer(entry->key));
            else
                retval = inner_int_overlap((ArrayType *) DatumGetPointer(entry->key),
-                                      query);
+                                          query);
            break;
        default:
            retval = FALSE;
@@ -344,11 +344,11 @@ g_int_consistent(PG_FUNCTION_ARGS) {
 Datum
 g_int_union(PG_FUNCTION_ARGS)
 {
-   PG_RETURN_POINTER( _int_common_union(
-       (bytea *) PG_GETARG_POINTER(0),
-       (int *) PG_GETARG_POINTER(1),
-       inner_int_union
-   );
+   PG_RETURN_POINTER(_int_common_union(
+                                       (bytea *) PG_GETARG_POINTER(0),
+                                       (int *) PG_GETARG_POINTER(1),
+                                       inner_int_union
+                                       ));
 }
 
 /*
@@ -357,7 +357,7 @@ g_int_union(PG_FUNCTION_ARGS)
 Datum
 g_int_compress(PG_FUNCTION_ARGS)
 {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
    GISTENTRY  *retval;
    ArrayType  *r;
    int         len;
@@ -366,26 +366,29 @@ g_int_compress(PG_FUNCTION_ARGS)
                min,
                cand;
 
-   if (entry->leafkey) {
+   if (entry->leafkey)
+   {
        r = (ArrayType *) PG_DETOAST_DATUM_COPY(entry->key);
        PREPAREARR(r);
        r->flags |= LEAFKEY;
        retval = palloc(sizeof(GISTENTRY));
        gistentryinit(*retval, PointerGetDatum(r),
-                 entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+             entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
 
        PG_RETURN_POINTER(retval);
    }
 
    r = (ArrayType *) PG_DETOAST_DATUM(entry->key);
-   if ( ISLEAFKEY( r ) || ARRISVOID(r) ) {
-       if ( r != (ArrayType*)DatumGetPointer(entry->key) )
+   if (ISLEAFKEY(r) || ARRISVOID(r))
+   {
+       if (r != (ArrayType *) DatumGetPointer(entry->key))
            pfree(r);
        PG_RETURN_POINTER(entry);
    }
 
-   if ( (len=ARRNELEMS(r)) >= 2 * MAXNUMRANGE) {   /* compress */
-       if ( r == (ArrayType*)DatumGetPointer( entry->key) )
+   if ((len = ARRNELEMS(r)) >= 2 * MAXNUMRANGE)
+   {                           /* compress */
+       if (r == (ArrayType *) DatumGetPointer(entry->key))
            r = (ArrayType *) PG_DETOAST_DATUM_COPY(entry->key);
        r = resize_intArrayType(r, 2 * (len));
 
@@ -411,11 +414,11 @@ g_int_compress(PG_FUNCTION_ARGS)
        r = resize_intArrayType(r, len);
        retval = palloc(sizeof(GISTENTRY));
        gistentryinit(*retval, PointerGetDatum(r),
-                 entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+             entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
        PG_RETURN_POINTER(retval);
-   } else {
-       PG_RETURN_POINTER(entry);
    }
+   else
+       PG_RETURN_POINTER(entry);
 
    PG_RETURN_POINTER(entry);
 }
@@ -423,7 +426,7 @@ g_int_compress(PG_FUNCTION_ARGS)
 Datum
 g_int_decompress(PG_FUNCTION_ARGS)
 {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
    GISTENTRY  *retval;
    ArrayType  *r;
    int        *dr,
@@ -436,17 +439,18 @@ g_int_decompress(PG_FUNCTION_ARGS)
 
    in = (ArrayType *) PG_DETOAST_DATUM(entry->key);
 
-   if ( ARRISVOID(in) ) {
+   if (ARRISVOID(in))
        PG_RETURN_POINTER(entry);
-   }
 
    lenin = ARRNELEMS(in);
 
-   if (lenin < 2 * MAXNUMRANGE || ISLEAFKEY( in ) ) { /* not comressed value */
-       if ( in != (ArrayType *) DatumGetPointer(entry->key)) {
+   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);
+            entry->rel, entry->page, entry->offset, VARSIZE(in), FALSE);
 
            PG_RETURN_POINTER(retval);
        }
@@ -468,7 +472,7 @@ g_int_decompress(PG_FUNCTION_ARGS)
        pfree(in);
    retval = palloc(sizeof(GISTENTRY));
    gistentryinit(*retval, PointerGetDatum(r),
-       entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+             entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
 
    PG_RETURN_POINTER(retval);
 }
@@ -479,26 +483,26 @@ g_int_decompress(PG_FUNCTION_ARGS)
 Datum
 g_int_penalty(PG_FUNCTION_ARGS)
 {
-   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
-   );
+   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
+                                         ));
 }
 
 
 Datum
 g_int_picksplit(PG_FUNCTION_ARGS)
 {
-   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,
-       0.01
-   );
+   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,
+                                           0.01
+                                           ));
 }
 
 /*
@@ -509,21 +513,24 @@ g_int_picksplit(PG_FUNCTION_ARGS)
 Datum
 g_int_same(PG_FUNCTION_ARGS)
 {
-   ArrayType   *a = (ArrayType*)PointerGetDatum(PG_GETARG_POINTER(0));
-   ArrayType   *b = (ArrayType*)PointerGetDatum(PG_GETARG_POINTER(1));
-   bool *result = (bool *)PG_GETARG_POINTER(2);
-   int4 n = ARRNELEMS(a);
-   int4 *da, *db;
+   ArrayType  *a = (ArrayType *) PointerGetDatum(PG_GETARG_POINTER(0));
+   ArrayType  *b = (ArrayType *) PointerGetDatum(PG_GETARG_POINTER(1));
+   bool       *result = (bool *) PG_GETARG_POINTER(2);
+   int4        n = ARRNELEMS(a);
+   int4       *da,
+              *db;
 
-   if ( n != ARRNELEMS(b) ) {
+   if (n != ARRNELEMS(b))
+   {
        *result = false;
        PG_RETURN_POINTER(result);
    }
    *result = TRUE;
    da = ARRPTR(a);
    db = ARRPTR(b);
-   while(n--)
-       if (*da++ != *db++) {
+   while (n--)
+       if (*da++ != *db++)
+       {
            *result = FALSE;
            break;
        }
@@ -534,20 +541,20 @@ g_int_same(PG_FUNCTION_ARGS)
 Datum
 _int_contained(PG_FUNCTION_ARGS)
 {
-   PG_RETURN_BOOL( DatumGetBool(
-       DirectFunctionCall2(
-           _int_contains,
-           PointerGetDatum(PG_GETARG_POINTER(1)),
-           PointerGetDatum(PG_GETARG_POINTER(0))
-       )
-   ));
+   PG_RETURN_BOOL(DatumGetBool(
+                               DirectFunctionCall2(
+                                                   _int_contains,
+                                  PointerGetDatum(PG_GETARG_POINTER(1)),
+                                   PointerGetDatum(PG_GETARG_POINTER(0))
+                                                   )
+                               ));
 }
 
 Datum
 _int_contains(PG_FUNCTION_ARGS)
 {
-   ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   ArrayType  *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
    bool        res;
 
    if (ARRISVOID(a) || ARRISVOID(b))
@@ -558,7 +565,7 @@ _int_contains(PG_FUNCTION_ARGS)
    res = inner_int_contains(a, b);
    pfree(a);
    pfree(b);
-   PG_RETURN_BOOL( res );
+   PG_RETURN_BOOL(res);
 }
 
 static bool
@@ -607,20 +614,20 @@ inner_int_contains(ArrayType *a, ArrayType *b)
 Datum
 _int_different(PG_FUNCTION_ARGS)
 {
-   PG_RETURN_BOOL( ! DatumGetBool(
-       DirectFunctionCall2(
-           _int_same,
-           PointerGetDatum(PG_GETARG_POINTER(0)),
-           PointerGetDatum(PG_GETARG_POINTER(1))
-       )
-   ));
+   PG_RETURN_BOOL(!DatumGetBool(
+                                DirectFunctionCall2(
+                                                    _int_same,
+                                  PointerGetDatum(PG_GETARG_POINTER(0)),
+                                   PointerGetDatum(PG_GETARG_POINTER(1))
+                                                    )
+                                ));
 }
 
 Datum
 _int_same(PG_FUNCTION_ARGS)
 {
-   ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   ArrayType  *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
    int         na,
                nb;
    int         n;
@@ -664,8 +671,8 @@ _int_same(PG_FUNCTION_ARGS)
 Datum
 _int_overlap(PG_FUNCTION_ARGS)
 {
-   ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   ArrayType  *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
    bool        result;
 
    if (ARRISVOID(a) || ARRISVOID(b))
@@ -679,7 +686,7 @@ _int_overlap(PG_FUNCTION_ARGS)
    pfree(a);
    pfree(b);
 
-   PG_RETURN_BOOL( result );
+   PG_RETURN_BOOL(result);
 }
 
 static bool
@@ -719,8 +726,8 @@ inner_int_overlap(ArrayType *a, ArrayType *b)
 Datum
 _int_union(PG_FUNCTION_ARGS)
 {
-   ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   ArrayType  *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
    ArrayType  *result;
 
    if (!ARRISVOID(a))
@@ -735,10 +742,10 @@ _int_union(PG_FUNCTION_ARGS)
    if (b)
        pfree(b);
 
-   PG_RETURN_POINTER( result );
+   PG_RETURN_POINTER(result);
 }
 
-static ArrayType  *
+static ArrayType *
 inner_int_union(ArrayType *a, ArrayType *b)
 {
    ArrayType  *r = NULL;
@@ -794,8 +801,8 @@ inner_int_union(ArrayType *a, ArrayType *b)
 Datum
 _int_inter(PG_FUNCTION_ARGS)
 {
-   ArrayType *a = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   ArrayType *b = (ArrayType *)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   ArrayType  *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
    ArrayType  *result;
 
    if (ARRISVOID(a) || ARRISVOID(b))
@@ -809,10 +816,10 @@ _int_inter(PG_FUNCTION_ARGS)
    pfree(a);
    pfree(b);
 
-   PG_RETURN_POINTER( result );
+   PG_RETURN_POINTER(result);
 }
 
-static ArrayType  *
+static ArrayType *
 inner_int_inter(ArrayType *a, ArrayType *b)
 {
    ArrayType  *r;
@@ -874,9 +881,9 @@ rt__int_size(ArrayType *a, float *size)
 static bool
 isort(int4 *a, int len)
 {
-   int4            tmp,
+   int4        tmp,
                index;
-   int4           *cur,
+   int4       *cur,
               *end;
    bool        r = FALSE;
 
@@ -1030,16 +1037,16 @@ rt__intbig_size(ArrayType *a, float *sz)
    BITVECP     bv = SIGPTR(a);
 
    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 );
+            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);
    );
 
    *sz = (float) len;
@@ -1089,9 +1096,9 @@ _intbig_inter(ArrayType *a, ArrayType *b)
 Datum
 g_intbig_same(PG_FUNCTION_ARGS)
 {
-   ArrayType *a = (ArrayType *)PG_GETARG_POINTER(0);
-   ArrayType *b = (ArrayType *)PG_GETARG_POINTER(1);
-   bool *result = (bool *)PG_GETARG_POINTER(2);
+   ArrayType  *a = (ArrayType *) PG_GETARG_POINTER(0);
+   ArrayType  *b = (ArrayType *) PG_GETARG_POINTER(1);
+   bool       *result = (bool *) PG_GETARG_POINTER(2);
    BITVECP     da,
                db;
    int         i;
@@ -1100,59 +1107,62 @@ g_intbig_same(PG_FUNCTION_ARGS)
    db = SIGPTR(b);
 
    LOOPBYTE(
-   if (da[i] != db[i])
-   {
+            if (da[i] != db[i])
+            {
        *result = FALSE;
-       PG_RETURN_POINTER( result );
+       PG_RETURN_POINTER(result);
    }
    );
 
    *result = TRUE;
-   PG_RETURN_POINTER( result );
+   PG_RETURN_POINTER(result);
 }
 
 Datum
 g_intbig_compress(PG_FUNCTION_ARGS)
 {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
    GISTENTRY  *retval;
    ArrayType  *r,
               *in;
-   bool maycompress = true;
-   int i;
+   bool        maycompress = true;
+   int         i;
 
    if (DatumGetPointer(entry->key) != NULL)
        in = (ArrayType *) PG_DETOAST_DATUM(entry->key);
    else
        in = NULL;
 
-   if (!entry->leafkey) {
+   if (!entry->leafkey)
+   {
        LOOPBYTE(
-           if ( ( ((char*)ARRPTR(in))[i] & 0xff ) != 0xff ) {
-               maycompress = false;
-               break;
-           }
+                if ((((char *) ARRPTR(in))[i] & 0xff) != 0xff)
+                {
+           maycompress = false;
+           break;
+       }
        );
-       if ( maycompress ) {
+       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 );
+             entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
+           PG_RETURN_POINTER(retval);
        }
-       PG_RETURN_POINTER( entry );
+       PG_RETURN_POINTER(entry);
    }
 
    retval = palloc(sizeof(GISTENTRY));
-   r = new_intArrayType( SIGLENINT );
+   r = new_intArrayType(SIGLENINT);
 
    if (ARRISVOID(in))
    {
        gistentryinit(*retval, PointerGetDatum(r),
              entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
        if (in != (ArrayType *) DatumGetPointer(entry->key))
-               pfree(in);
-       PG_RETURN_POINTER (retval);
+           pfree(in);
+       PG_RETURN_POINTER(retval);
    }
 
    gensign(SIGPTR(r),
@@ -1160,104 +1170,108 @@ g_intbig_compress(PG_FUNCTION_ARGS)
            ARRNELEMS(in));
 
    LOOPBYTE(
-       if( ( ((char*)ARRPTR(in))[i] & 0xff ) != 0xff ) {
-           maycompress = false;
-           break;
-       }
+            if ((((char *) ARRPTR(in))[i] & 0xff) != 0xff)
+            {
+       maycompress = false;
+       break;
+   }
    );
 
-   if ( maycompress ) {
+   if (maycompress)
+   {
        pfree(r);
        r = new_intArrayType(1);
    }
 
    gistentryinit(*retval, PointerGetDatum(r), entry->rel, entry->page, entry->offset, VARSIZE(r), FALSE);
 
-   if ( in != (ArrayType *) DatumGetPointer(entry->key))
-           pfree(in);
+   if (in != (ArrayType *) DatumGetPointer(entry->key))
+       pfree(in);
 
-   PG_RETURN_POINTER (retval);
+   PG_RETURN_POINTER(retval);
 }
 
 Datum
 g_intbig_decompress(PG_FUNCTION_ARGS)
 {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
    ArrayType  *key;
 
    key = (ArrayType *) PG_DETOAST_DATUM(entry->key);
 
-   if ( key != (ArrayType *) DatumGetPointer(entry->key))
+   if (key != (ArrayType *) DatumGetPointer(entry->key))
    {
        GISTENTRY  *retval;
 
        retval = palloc(sizeof(GISTENTRY));
 
        gistentryinit(*retval, PointerGetDatum(key),
-           entry->rel, entry->page, entry->offset, (key) ? VARSIZE(key) : 0, FALSE);
-       PG_RETURN_POINTER( retval );
+                     entry->rel, entry->page, entry->offset, (key) ? VARSIZE(key) : 0, FALSE);
+       PG_RETURN_POINTER(retval);
    }
-   if ( ARRNELEMS(key) == 1 ) {
+   if (ARRNELEMS(key) == 1)
+   {
        GISTENTRY  *retval;
        ArrayType  *newkey;
 
        retval = palloc(sizeof(GISTENTRY));
        newkey = new_intArrayType(SIGLENINT);
-       MemSet( (void*)ARRPTR(newkey), 0xff, SIGLEN );
+       MemSet((void *) ARRPTR(newkey), 0xff, SIGLEN);
 
        gistentryinit(*retval, PointerGetDatum(newkey),
-           entry->rel, entry->page, entry->offset, VARSIZE(newkey), FALSE);
-       PG_RETURN_POINTER( retval );
+        entry->rel, entry->page, entry->offset, VARSIZE(newkey), FALSE);
+       PG_RETURN_POINTER(retval);
    }
-   PG_RETURN_POINTER( entry );
+   PG_RETURN_POINTER(entry);
 }
 
 Datum
 g_intbig_picksplit(PG_FUNCTION_ARGS)
 {
-   PG_RETURN_POINTER( _int_common_picksplit(
-       (bytea *)PG_GETARG_POINTER(0),
-       (GIST_SPLITVEC *)PG_GETARG_POINTER(1),
-       _intbig_union,
-       _intbig_inter,
-       rt__intbig_size,
-       0.1
-   );
+   PG_RETURN_POINTER(_int_common_picksplit(
+                                         (bytea *) PG_GETARG_POINTER(0),
+                                 (GIST_SPLITVEC *) PG_GETARG_POINTER(1),
+                                           _intbig_union,
+                                           _intbig_inter,
+                                           rt__intbig_size,
+                                           0.1
+                                           ));
 }
 
 Datum
 g_intbig_union(PG_FUNCTION_ARGS)
 {
-       PG_RETURN_POINTER( _int_common_union(
-               (bytea *) PG_GETARG_POINTER(0),
-               (int *) PG_GETARG_POINTER(1),
-               _intbig_union
-       );
+   PG_RETURN_POINTER(_int_common_union(
+                                       (bytea *) PG_GETARG_POINTER(0),
+                                       (int *) PG_GETARG_POINTER(1),
+                                       _intbig_union
+                                       ));
 }
 
 Datum
 g_intbig_penalty(PG_FUNCTION_ARGS)
 {
-   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
-   );
+   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);
+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);
    bool        retval;
    ArrayType  *q;
 
-   if ( strategy == BooleanSearchStrategy )
-       PG_RETURN_BOOL(signconsistent( (QUERYTYPE*)query,
-                       SIGPTR((ArrayType *) DatumGetPointer(entry->key)),
-                       false ) );
+   if (strategy == BooleanSearchStrategy)
+       PG_RETURN_BOOL(signconsistent((QUERYTYPE *) query,
+                      SIGPTR((ArrayType *) DatumGetPointer(entry->key)),
+                                     false));
 
    /* XXX what about toasted input? */
    if (ARRISVOID(query))
@@ -1274,13 +1288,13 @@ g_intbig_consistent(PG_FUNCTION_ARGS) {
            retval = _intbig_overlap((ArrayType *) DatumGetPointer(entry->key), q);
            break;
        case RTSameStrategyNumber:
-           if ( GIST_LEAF(entry) )
+           if (GIST_LEAF(entry))
                DirectFunctionCall3(
-                   g_intbig_same,
-                   entry->key,
-                   PointerGetDatum(q),
-                   PointerGetDatum(&retval)
-               );
+                                   g_intbig_same,
+                                   entry->key,
+                                   PointerGetDatum(q),
+                                   PointerGetDatum(&retval)
+                   );
            else
                retval = _intbig_contains((ArrayType *) DatumGetPointer(entry->key), q);
            break;
@@ -1305,7 +1319,7 @@ g_intbig_consistent(PG_FUNCTION_ARGS) {
 ** The GiST Union method for _intments
 ** returns the minimal set that encloses all the entries in entryvec
 */
-static ArrayType  *
+static ArrayType *
 _int_common_union(bytea *entryvec, int *sizep, formarray unionf)
 {
    int         numranges,
@@ -1323,7 +1337,7 @@ _int_common_union(bytea *entryvec, int *sizep, formarray unionf)
    for (i = 1; i < numranges; i++)
    {
        out = (*unionf) (tmp, (ArrayType *)
-                        DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key));
+             DatumGetPointer(((GISTENTRY *) VARDATA(entryvec))[i].key));
        if (i > 1 && tmp)
            pfree(tmp);
        tmp = out;
@@ -1376,17 +1390,19 @@ _int_common_penalty(GISTENTRY *origentry, GISTENTRY *newentry, float *result,
    return (result);
 }
 
-typedef struct {
-   OffsetNumber    pos;
+typedef struct
+{
+   OffsetNumber pos;
    float       cost;
 } SPLITCOST;
 
 static int
-comparecost( const void *a, const void *b ) {
-   if ( ((SPLITCOST*)a)->cost == ((SPLITCOST*)b)->cost )
+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;
+       return (((SPLITCOST *) a)->cost > ((SPLITCOST *) b)->cost) ? 1 : -1;
 }
 
 /*
@@ -1426,7 +1442,7 @@ _int_common_picksplit(bytea *entryvec,
    OffsetNumber *left,
               *right;
    OffsetNumber maxoff;
-   SPLITCOST   *costvector;
+   SPLITCOST  *costvector;
 
 #ifdef GIST_DEBUG
    elog(DEBUG3, "--------picksplit %d", (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY));
@@ -1478,7 +1494,8 @@ _int_common_picksplit(bytea *entryvec,
    v->spl_nleft = 0;
    right = v->spl_right;
    v->spl_nright = 0;
-   if ( seed_1 == 0 || seed_2 == 0 ) {
+   if (seed_1 == 0 || seed_2 == 0)
+   {
        seed_1 = 1;
        seed_2 = 2;
    }
@@ -1491,22 +1508,24 @@ _int_common_picksplit(bytea *entryvec,
    (*sizef) (datum_r, &size_r);
 
    maxoff = OffsetNumberNext(maxoff);
+
    /*
-        * sort entries
+    * sort entries
     */
-   costvector=(SPLITCOST*)palloc( sizeof(SPLITCOST)*maxoff );
-   for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) {
-       costvector[i-1].pos = i;
+   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) );
+       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 );
+   qsort((void *) costvector, maxoff, sizeof(SPLITCOST), comparecost);
 
    /*
     * Now split up the regions between the two seeds.  An important
@@ -1521,7 +1540,8 @@ _int_common_picksplit(bytea *entryvec,
     */
 
 
-   for (j = 0; j < maxoff; j++) {
+   for (j = 0; j < maxoff; j++)
+   {
        i = costvector[j].pos;
 
        /*
@@ -1574,7 +1594,7 @@ _int_common_picksplit(bytea *entryvec,
            v->spl_nright++;
        }
    }
-   pfree( costvector );
+   pfree(costvector);
    *right = *left = FirstOffsetNumber;
 
    datum_l->flags &= ~LEAFKEY;
@@ -1589,19 +1609,19 @@ _int_common_picksplit(bytea *entryvec,
 }
 
 /*****************************************************************************
- *     BoolSearch
+ *     BoolSearch
  *****************************************************************************/
 
 
-#define END     0
-#define ERR     1
-#define VAL     2
-#define OPR     3
-#define OPEN    4
-#define CLOSE   5
+#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 WAITOPERAND 1
 #define WAITENDOPERAND 2
 #define WAITOPERATOR   3
 
@@ -1609,75 +1629,94 @@ _int_common_picksplit(bytea *entryvec,
  * 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;
+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;
+   int4        num;
+}  WORKSTATE;
 
 /*
  * get token from query string
  */
 static int4
-gettoken( WORKSTATE* state, int4* val ) {
-   char nnn[16], *curnnn;
+gettoken(WORKSTATE * state, int4 *val)
+{
+   char        nnn[16],
+              *curnnn;
 
-   curnnn=nnn;
-   while(1) {
-       switch(state->state) {
+   curnnn = nnn;
+   while (1)
+   {
+       switch (state->state)
+       {
            case WAITOPERAND:
-               curnnn=nnn;
-               if ( (*(state->buf)>='0' && *(state->buf)<='9') ||
-                       *(state->buf)=='-' ) {
+               curnnn = nnn;
+               if ((*(state->buf) >= '0' && *(state->buf) <= '9') ||
+                   *(state->buf) == '-')
+               {
                    state->state = WAITENDOPERAND;
                    *curnnn = *(state->buf);
                    curnnn++;
-               } else if ( *(state->buf) == '!' ) {
+               }
+               else if (*(state->buf) == '!')
+               {
                    (state->buf)++;
-                   *val = (int4)'!';
+                   *val = (int4) '!';
                    return OPR;
-               } else if ( *(state->buf) == '(' ) {
+               }
+               else if (*(state->buf) == '(')
+               {
                    state->count++;
                    (state->buf)++;
                    return OPEN;
-               } else if ( *(state->buf) != ' ' )
+               }
+               else if (*(state->buf) != ' ')
                    return ERR;
                break;
            case WAITENDOPERAND:
-               if ( *(state->buf)>='0' && *(state->buf)<='9' ) {
+               if (*(state->buf) >= '0' && *(state->buf) <= '9')
+               {
                    *curnnn = *(state->buf);
                    curnnn++;
-               } else {
+               }
+               else
+               {
                    *curnnn = '\0';
-                   *val=(int4)atoi( nnn );
+                   *val = (int4) atoi(nnn);
                    state->state = WAITOPERATOR;
-                   return ( state->count && *(state->buf) == '\0' )
+                   return (state->count && *(state->buf) == '\0')
                        ? ERR : VAL;
                }
                break;
            case WAITOPERATOR:
-               if ( *(state->buf) == '&' || *(state->buf) == '|' ) {
+               if (*(state->buf) == '&' || *(state->buf) == '|')
+               {
                    state->state = WAITOPERAND;
                    *val = (int4) *(state->buf);
                    (state->buf)++;
                    return OPR;
-               } else if ( *(state->buf) == ')' ) {
+               }
+               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 (state->count < 0) ? ERR : CLOSE;
+               }
+               else if (*(state->buf) == '\0')
+                   return (state->count) ? ERR : END;
+               else if (*(state->buf) != ' ')
                    return ERR;
                break;
            default:
@@ -1693,10 +1732,12 @@ gettoken( WORKSTATE* state, int4* val ) {
  * 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;
+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++;
@@ -1708,82 +1749,95 @@ pushquery( WORKSTATE *state, int4 type, int4 val ) {
  * make polish notaion of query
  */
 static int4
-makepol(WORKSTATE *state) {
-   int4 val,type;
-   int4    stack[STACKDEPTH];
-   int4    lenstack=0;
+makepol(WORKSTATE * state)
+{
+   int4        val,
+               type;
+   int4        stack[STACKDEPTH];
+   int4        lenstack = 0;
 
-   while( (type=gettoken(state, &val))!=END ) {
-       switch(type) {
+   while ((type = gettoken(state, &val)) != END)
+   {
+       switch (type)
+       {
            case VAL:
                pushquery(state, type, val);
-               while ( lenstack && (stack[ lenstack-1 ] == (int4)'&' ||
-                       stack[ lenstack-1 ] == (int4)'!') ) {
+               while (lenstack && (stack[lenstack - 1] == (int4) '&' ||
+                                   stack[lenstack - 1] == (int4) '!'))
+               {
                    lenstack--;
-                   pushquery(state, OPR, stack[ lenstack ]);
+                   pushquery(state, OPR, stack[lenstack]);
                }
                break;
            case OPR:
-               if ( lenstack && val == (int4) '|' ) {
+               if (lenstack && val == (int4) '|')
                    pushquery(state, OPR, val);
-               } else {
-                   if ( lenstack == STACKDEPTH )
-                       elog(ERROR,"Stack too short");
-                   stack[ lenstack ] = 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)'!') ) {
+               if (makepol(state) == ERR)
+                   return ERR;
+               if (lenstack && (stack[lenstack - 1] == (int4) '&' ||
+                                stack[lenstack - 1] == (int4) '!'))
+               {
                    lenstack--;
-                   pushquery(state, OPR, stack[ lenstack ]);
+                   pushquery(state, OPR, stack[lenstack]);
                }
                break;
            case CLOSE:
-               while ( lenstack ) {
+               while (lenstack)
+               {
                    lenstack--;
-                   pushquery(state, OPR, stack[ lenstack ]);
+                   pushquery(state, OPR, stack[lenstack]);
                };
                return END;
                break;
            case ERR:
            default:
-               elog(ERROR,"Syntax error");
+               elog(ERROR, "Syntax error");
                return ERR;
 
        }
    }
 
-   while (lenstack) {
+   while (lenstack)
+   {
        lenstack--;
-       pushquery(state, OPR, stack[ lenstack ]);
+       pushquery(state, OPR, stack[lenstack]);
    };
    return END;
 }
 
-typedef struct {
-   int4 *arrb;
-   int4 *arre;
-} CHKVAL;
+typedef struct
+{
+   int4       *arrb;
+   int4       *arre;
+}  CHKVAL;
 
 /*
  * is there value 'val' in array or not ?
  */
 static bool
-checkcondition_arr( void *checkval, int4 val ) {
-   int4      *StopLow = ((CHKVAL*)checkval)->arrb;
-   int4      *StopHigh = ((CHKVAL*)checkval)->arre;
-   int4      *StopMiddle;
+checkcondition_arr(void *checkval, int4 val)
+{
+   int4       *StopLow = ((CHKVAL *) checkval)->arrb;
+   int4       *StopHigh = ((CHKVAL *) checkval)->arre;
+   int4       *StopMiddle;
 
    /* Loop invariant: StopLow <= val < StopHigh */
 
-   while (StopLow < StopHigh) {
+   while (StopLow < StopHigh)
+   {
        StopMiddle = StopLow + (StopHigh - StopLow) / 2;
        if (*StopMiddle == val)
            return (true);
-       else if (*StopMiddle < val )
+       else if (*StopMiddle < val)
            StopLow = StopMiddle + 1;
        else
            StopHigh = StopMiddle;
@@ -1792,29 +1846,36 @@ checkcondition_arr( void *checkval, int4 val ) {
 }
 
 static bool
-checkcondition_bit( void *checkval, int4 val ) {
-   return GETBIT( checkval, HASHVAL( val ) );
+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 )) {
+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 )
+   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) )
+   }
+   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) )
+   }
+   else
+   {                           /* |-operator */
+       if (execute(curitem + curitem->left, checkval, calcnot, chkcond))
            return true;
        else
            return execute(curitem - 1, checkval, calcnot, chkcond);
@@ -1826,86 +1887,98 @@ execute( ITEM* curitem, void *checkval, bool calcnot, bool (*chkcond)(void *chec
  * signconsistent & execconsistent called by *_consistent
  */
 static bool
-signconsistent( QUERYTYPE *query, BITVEC sign, bool calcnot ) {
+signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot)
+{
    return execute(
-       GETQUERY(query) + query->size-1 ,
-       (void*)sign, calcnot,
-       checkcondition_bit
+                  GETQUERY(query) + query->size - 1,
+                  (void *) sign, calcnot,
+                  checkcondition_bit
    );
 }
 
 static bool
-execconsistent( QUERYTYPE *query, ArrayType *array, bool calcnot ) {
-   CHKVAL  chkval;
+execconsistent(QUERYTYPE * query, ArrayType *array, bool calcnot)
+{
+   CHKVAL      chkval;
 
    chkval.arrb = ARRPTR(array);
    chkval.arre = chkval.arrb + ARRNELEMS(array);
    return execute(
-       GETQUERY(query) + query->size-1 ,
-       (void*)&chkval, calcnot,
-       checkcondition_arr
-   );
+                  GETQUERY(query) + query->size - 1,
+                  (void *) &chkval, calcnot,
+                  checkcondition_arr
+       );
 }
 
 /*
  * boolean operations
  */
 Datum
-rboolop(PG_FUNCTION_ARGS) {
+rboolop(PG_FUNCTION_ARGS)
+{
    return DirectFunctionCall2(
-       boolop,
-       PG_GETARG_DATUM(1),
-       PG_GETARG_DATUM(0)
+                              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;
+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 ) ) {
+   if (ARRISVOID(val))
+   {
        pfree(val);
-       PG_FREE_IF_COPY(query,1);
-       PG_RETURN_BOOL( false );
+       PG_FREE_IF_COPY(query, 1);
+       PG_RETURN_BOOL(false);
    }
 
    PREPAREARR(val);
    chkval.arrb = ARRPTR(val);
    chkval.arre = chkval.arrb + ARRNELEMS(val);
    result = execute(
-       GETQUERY(query) + query->size-1 ,
-       &chkval, true,
-       checkcondition_arr
-   );
+                    GETQUERY(query) + query->size - 1,
+                    &chkval, true,
+                    checkcondition_arr
+       );
    pfree(val);
 
-   PG_FREE_IF_COPY(query,1);
-   PG_RETURN_BOOL( result );
+   PG_FREE_IF_COPY(query, 1);
+   PG_RETURN_BOOL(result);
 }
 
 static void
-findoprnd( ITEM *ptr, int4 *pos ) {
+findoprnd(ITEM * ptr, int4 *pos)
+{
 #ifdef BS_DEBUG
-   elog(DEBUG3, ( ptr[*pos].type == OPR ) ?
-       "%d  %c" : "%d  %d ", *pos, ptr[*pos].val );
+   elog(DEBUG3, (ptr[*pos].type == OPR) ?
+        "%d  %c" : "%d  %d ", *pos, ptr[*pos].val);
 #endif
-   if ( ptr[*pos].type == VAL ) {
+   if (ptr[*pos].type == VAL)
+   {
        ptr[*pos].left = 0;
        (*pos)--;
-   } else if ( ptr[*pos].val == (int4)'!' ) {
+   }
+   else if (ptr[*pos].val == (int4) '!')
+   {
        ptr[*pos].left = -1;
        (*pos)--;
-       findoprnd( ptr, pos );
-   } else {
-       ITEM *curitem = &ptr[*pos];
-       int4 tmp = *pos;
+       findoprnd(ptr, pos);
+   }
+   else
+   {
+       ITEM       *curitem = &ptr[*pos];
+       int4        tmp = *pos;
+
        (*pos)--;
-       findoprnd(ptr,pos);
+       findoprnd(ptr, pos);
        curitem->left = *pos - tmp;
-       findoprnd(ptr,pos);
+       findoprnd(ptr, pos);
    }
 }
 
@@ -1914,71 +1987,76 @@ findoprnd( ITEM *ptr, int4 *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;
+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
-   StringInfoData  pbuf;
+   StringInfoData pbuf;
 #endif
 
    state.buf = buf;
    state.state = WAITOPERAND;
    state.count = 0;
    state.num = 0;
-   state.str=NULL;
+   state.str = NULL;
 
    /* make polish notation (postfix, but in reverse order) */
-   makepol( &state );
+   makepol(&state);
    if (!state.num)
-       elog( ERROR,"Empty query");
+       elog(ERROR, "Empty query");
 
    commonlen = COMPUTESIZE(state.num);
-   query = (QUERYTYPE*) palloc( commonlen );
+   query = (QUERYTYPE *) palloc(commonlen);
    query->len = commonlen;
    query->size = state.num;
    ptr = GETQUERY(query);
 
-   for(i=state.num-1; i>=0; i-- ) {
+   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 );
+       pfree(state.str);
        state.str = tmp;
    }
 
-   pos = query->size-1;
-   findoprnd( ptr, &pos );
+   pos = query->size - 1;
+   findoprnd(ptr, &pos);
 #ifdef BS_DEBUG
    initStringInfo(&pbuf);
-   for( i=0;i<query->size;i++ ) {
-       if ( ptr[i].type == OPR )
+   for (i = 0; i < query->size; i++)
+   {
+       if (ptr[i].type == OPR)
            appendStringInfo(&pbuf, "%c(%d) ", ptr[i].val, ptr[i].left);
        else
-           appendStringInfo(&pbuf, "%d ", ptr[i].val );
+           appendStringInfo(&pbuf, "%d ", ptr[i].val);
    }
-   elog(DEBUG3,"POR: %s", pbuf.data);
+   elog(DEBUG3, "POR: %s", pbuf.data);
    pfree(pbuf.data);
 #endif
 
-   PG_RETURN_POINTER( query );
+   PG_RETURN_POINTER(query);
 }
 
 
 /*
  * out function
  */
-typedef struct {
-   ITEM    *curpol;
-   char *buf;
-   char *cur;
-   int4 buflen;
-} INFIX;
+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; \
@@ -1988,94 +2066,106 @@ typedef struct {
 }
 
 static void
-infix(INFIX *in, bool first) {
-   if ( in->curpol->type == VAL ) {
+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' );
+       sprintf(in->cur, "%d", in->curpol->val);
+       in->cur = strchr(in->cur, '\0');
        in->curpol--;
-   } else if ( in->curpol->val == (int4)'!' ) {
-       bool isopr = false;
+   }
+   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 ) {
+       if (in->curpol->type == OPR)
+       {
            isopr = true;
            RESIZEBUF(in, 2);
            sprintf(in->cur, "( ");
-           in->cur = strchr( in->cur, '\0' );
+           in->cur = strchr(in->cur, '\0');
        }
-       infix( in, isopr );
-       if ( isopr ) {
+       infix(in, isopr);
+       if (isopr)
+       {
            RESIZEBUF(in, 2);
            sprintf(in->cur, " )");
-           in->cur = strchr( in->cur, '\0' );
+           in->cur = strchr(in->cur, '\0');
        }
-   } else {
-       int4 op = in->curpol->val;
-       INFIX   nrm;
+   }
+   else
+   {
+       int4        op = in->curpol->val;
+       INFIX       nrm;
 
        in->curpol--;
-       if ( op == (int4)'|' && ! first) {
+       if (op == (int4) '|' && !first)
+       {
            RESIZEBUF(in, 2);
            sprintf(in->cur, "( ");
-           in->cur = strchr( in->cur, '\0' );
+           in->cur = strchr(in->cur, '\0');
        }
 
        nrm.curpol = in->curpol;
        nrm.buflen = 16;
-       nrm.cur = nrm.buf = (char*)palloc( sizeof(char) * nrm.buflen );
+       nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
 
        /* get right operand */
-       infix( &nrm, false );
+       infix(&nrm, false);
 
        /* get & print left operand */
        in->curpol = nrm.curpol;
-       infix( in, false );
+       infix(in, false);
 
-       /* print operator & right operand*/
-       RESIZEBUF(in, 3 + (nrm.cur - nrm.buf) );
+       /* 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 );
+       in->cur = strchr(in->cur, '\0');
+       pfree(nrm.buf);
 
-       if ( op == (int4)'|' && ! first) {
+       if (op == (int4) '|' && !first)
+       {
            RESIZEBUF(in, 2);
            sprintf(in->cur, " )");
-           in->cur = strchr( in->cur, '\0' );
+           in->cur = strchr(in->cur, '\0');
        }
    }
 }
 
 
 Datum
-bqarr_out(PG_FUNCTION_ARGS) {
-   QUERYTYPE       *query = (QUERYTYPE*)PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
-   INFIX   nrm;
+bqarr_out(PG_FUNCTION_ARGS)
+{
+   QUERYTYPE  *query = (QUERYTYPE *) PG_DETOAST_DATUM(PG_GETARG_POINTER(0));
+   INFIX       nrm;
 
-   if ( query->size == 0 )
-       elog(ERROR,"Empty");
+   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 = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
    *(nrm.cur) = '\0';
-   infix( &nrm, true );
+   infix(&nrm, true);
 
-   PG_FREE_IF_COPY(query,0);
-   PG_RETURN_POINTER( nrm.buf );
+   PG_FREE_IF_COPY(query, 0);
+   PG_RETURN_POINTER(nrm.buf);
 }
 
 static int4
-countdroptree( ITEM *q, int4 pos ) {
-   if ( q[pos].type == VAL ) {
+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);
-   }
+   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);
 }
 
 /*
@@ -2084,137 +2174,161 @@ countdroptree( ITEM *q, int4 pos ) {
  * we can modify query tree for clearing
  */
 static int4
-shorterquery( ITEM *q, int4 len ) {
-   int4 index,posnot,poscor;
-   bool notisleft = false;
-   int4 drop,i;
+shorterquery(ITEM * q, int4 len)
+{
+   int4        index,
+               posnot,
+               poscor;
+   bool        notisleft = false;
+   int4        drop,
+               i;
 
    /* out all '!' */
-   do {
-       index=0;
-       drop=0;
+   do
+   {
+       index = 0;
+       drop = 0;
        /* find ! */
-       for(posnot=0; posnot < len; posnot++)
-           if ( q[posnot].type == OPR  && q[posnot].val == (int4)'!') {
-               index=1;
+       for (posnot = 0; posnot < len; posnot++)
+           if (q[posnot].type == OPR && q[posnot].val == (int4) '!')
+           {
+               index = 1;
                break;
            }
 
-       if ( posnot == len )
+       if (posnot == len)
            return len;
 
        /* last operator is ! */
-       if ( posnot == len-1 )
+       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 ) {
+       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 ) {
+               }
+               else if (q[poscor].left + poscor == posnot)
+               {
                    notisleft = true;
                    break;
                }
            }
        }
-       if ( q[poscor].val == (int4)'!' ) {
+       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[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) ));
+           memcpy((void *) &q[poscor - drop + 1],
+                  (void *) &q[poscor - 1],
+                  sizeof(ITEM) * (len - (poscor - 1)));
            len -= drop - 2;
-       } else if ( q[poscor].val == (int4)'|' ) {
+       }
+       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[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) ));
+           memcpy((void *) &q[poscor - drop + 1],
+                  (void *) &q[poscor - 1],
+                  sizeof(ITEM) * (len - (poscor - 1)));
            len -= drop - 2;
-       } else { /* &-operator */
+       }
+       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 */
+               (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[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) ));
+               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 );
+           }
+           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 )
+               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) ) );
+               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 );
+   } 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 );
+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 {
+       *((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 = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen);
        *(nrm.cur) = '\0';
-       infix( &nrm, true );
+       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 );
+       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 );
+   PG_RETURN_POINTER(res);
 }
 
 /*
@@ -2225,72 +2339,84 @@ static ArrayType *intarray_add_elem(ArrayType *a, int32 elem);
 static ArrayType *intarray_concat_arrays(ArrayType *a, ArrayType *b);
 static ArrayType *int_to_intset(int32 elem);
 
-PG_FUNCTION_INFO_V1( intset );
-PG_FUNCTION_INFO_V1( icount );
-PG_FUNCTION_INFO_V1( sort );
-PG_FUNCTION_INFO_V1( sort_asc );
-PG_FUNCTION_INFO_V1( sort_desc );
-PG_FUNCTION_INFO_V1( uniq );
-PG_FUNCTION_INFO_V1( idx );
-PG_FUNCTION_INFO_V1( subarray );
-PG_FUNCTION_INFO_V1( intarray_push_elem );
-PG_FUNCTION_INFO_V1( intarray_push_array );
-PG_FUNCTION_INFO_V1( intarray_del_elem );
-PG_FUNCTION_INFO_V1( intset_union_elem );
-PG_FUNCTION_INFO_V1( intset_subtract );
-Datum intset(PG_FUNCTION_ARGS);
-Datum icount(PG_FUNCTION_ARGS);
-Datum sort(PG_FUNCTION_ARGS);
-Datum sort_asc(PG_FUNCTION_ARGS);
-Datum sort_desc(PG_FUNCTION_ARGS);
-Datum uniq(PG_FUNCTION_ARGS);
-Datum idx(PG_FUNCTION_ARGS);
-Datum subarray(PG_FUNCTION_ARGS);
-Datum intarray_push_elem(PG_FUNCTION_ARGS);
-Datum intarray_push_array(PG_FUNCTION_ARGS);
-Datum intarray_del_elem(PG_FUNCTION_ARGS);
-Datum intset_union_elem(PG_FUNCTION_ARGS);
-Datum intset_subtract(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(intset);
+PG_FUNCTION_INFO_V1(icount);
+PG_FUNCTION_INFO_V1(sort);
+PG_FUNCTION_INFO_V1(sort_asc);
+PG_FUNCTION_INFO_V1(sort_desc);
+PG_FUNCTION_INFO_V1(uniq);
+PG_FUNCTION_INFO_V1(idx);
+PG_FUNCTION_INFO_V1(subarray);
+PG_FUNCTION_INFO_V1(intarray_push_elem);
+PG_FUNCTION_INFO_V1(intarray_push_array);
+PG_FUNCTION_INFO_V1(intarray_del_elem);
+PG_FUNCTION_INFO_V1(intset_union_elem);
+PG_FUNCTION_INFO_V1(intset_subtract);
+Datum      intset(PG_FUNCTION_ARGS);
+Datum      icount(PG_FUNCTION_ARGS);
+Datum      sort(PG_FUNCTION_ARGS);
+Datum      sort_asc(PG_FUNCTION_ARGS);
+Datum      sort_desc(PG_FUNCTION_ARGS);
+Datum      uniq(PG_FUNCTION_ARGS);
+Datum      idx(PG_FUNCTION_ARGS);
+Datum      subarray(PG_FUNCTION_ARGS);
+Datum      intarray_push_elem(PG_FUNCTION_ARGS);
+Datum      intarray_push_array(PG_FUNCTION_ARGS);
+Datum      intarray_del_elem(PG_FUNCTION_ARGS);
+Datum      intset_union_elem(PG_FUNCTION_ARGS);
+Datum      intset_subtract(PG_FUNCTION_ARGS);
 
 static int32
-intarray_match_first(ArrayType *a, int32 elem) {
-   int32 *aa, c, i;
-   c  = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+intarray_match_first(ArrayType *a, int32 elem)
+{
+   int32      *aa,
+               c,
+               i;
+
+   c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
    aa = ARRPTR(a);
    for (i = 0; i < c; i++)
-       if (aa[i] == elem) return (i + 1);
+       if (aa[i] == elem)
+           return (i + 1);
    return 0;
 }
 
 static ArrayType *
-intarray_add_elem(ArrayType *a, int32 elem) {
-   ArrayType *result;
-   int32 *r;
-   int32 c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+intarray_add_elem(ArrayType *a, int32 elem)
+{
+   ArrayType  *result;
+   int32      *r;
+   int32       c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+
    result = new_intArrayType(c + 1);
    r = ARRPTR(result);
-   if (c > 0) memcpy(r, ARRPTR(a), c * sizeof(int32));
+   if (c > 0)
+       memcpy(r, ARRPTR(a), c * sizeof(int32));
    r[c] = elem;
    return result;
 }
 
 static ArrayType *
-intarray_concat_arrays(ArrayType *a, ArrayType *b) {
-   ArrayType *result;
-   int32 ac = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
-   int32 bc = (ARRISVOID(b)) ? 0 : ARRNELEMS(b);
-   result = new_intArrayType(ac+bc);
-   if ( ac )
+intarray_concat_arrays(ArrayType *a, ArrayType *b)
+{
+   ArrayType  *result;
+   int32       ac = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+   int32       bc = (ARRISVOID(b)) ? 0 : ARRNELEMS(b);
+
+   result = new_intArrayType(ac + bc);
+   if (ac)
        memcpy(ARRPTR(result), ARRPTR(a), ac * sizeof(int32));
-   if ( bc )
+   if (bc)
        memcpy(ARRPTR(result) + ac, ARRPTR(b), bc * sizeof(int32));
    return result;
 }
 
 static ArrayType *
-int_to_intset(int32 n) {
-   ArrayType *result;
-   int32 *aa;
+int_to_intset(int32 n)
+{
+   ArrayType  *result;
+   int32      *aa;
+
    result = new_intArrayType(1);
    aa = ARRPTR(result);
    aa[0] = n;
@@ -2298,67 +2424,82 @@ int_to_intset(int32 n) {
 }
 
 static int
-compASC(const void *a, const void *b) {
-   if ( *(int4*)a == *(int4*)b ) return 0;
-   return ( *(int4*)a > *(int4*)b ) ? 1 : -1;
+compASC(const void *a, const void *b)
+{
+   if (*(int4 *) a == *(int4 *) b)
+       return 0;
+   return (*(int4 *) a > *(int4 *) b) ? 1 : -1;
 }
 
 static int
-compDESC(const void *a, const void *b) {
-   if ( *(int4*)a == *(int4*)b ) return 0;
-   return ( *(int4*)a < *(int4*)b ) ? 1 : -1;
+compDESC(const void *a, const void *b)
+{
+   if (*(int4 *) a == *(int4 *) b)
+       return 0;
+   return (*(int4 *) a < *(int4 *) b) ? 1 : -1;
 }
 
-#define QSORT(a, direction)                    \
+#define QSORT(a, direction)                        \
 if (ARRNELEMS(a) > 1)                      \
-   qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4),  \
+   qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4),  \
        (direction) ? compASC : compDESC )
 
 #define UNIX_UNIQ(a) a = resize_intArrayType(a, unix_uniq(ARRPTR(a), ARRNELEMS(a)))
 
 static int32
-unix_uniq(int32 *array, int32 count) {
-   register int32 i, k = 0;
+unix_uniq(int32 *array, int32 count)
+{
+   register int32 i,
+               k = 0;
+
    for (i = 1; i < count; i++)
-       if (array[k] != array[i]) {
+       if (array[k] != array[i])
+       {
            k++;
-           if (i > k) array[k] = array[i];
+           if (i > k)
+               array[k] = array[i];
        }
-   return (k+1);
+   return (k + 1);
 }
 
 Datum
-intset(PG_FUNCTION_ARGS) {
-  PG_RETURN_POINTER(int_to_intset(PG_GETARG_INT32(0)));
+intset(PG_FUNCTION_ARGS)
+{
+   PG_RETURN_POINTER(int_to_intset(PG_GETARG_INT32(0)));
 }
 
 Datum
-icount(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
-   int32 count = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+icount(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+   int32       count = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+
    PG_FREE_IF_COPY(a, 0);
    PG_RETURN_INT32(count);
 }
 
 Datum
-sort(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   text *dirstr = ( fcinfo->nargs==2 ) ? PG_GETARG_TEXT_P(1) : NULL;
-   int32 dc = ( dirstr ) ? VARSIZE(dirstr)-VARHDRSZ : 0;
-   char *d = ( dirstr ) ? VARDATA(dirstr) : NULL;
-   int dir = -1;
-   if (ARRISVOID(a) || ARRNELEMS(a) < 2) PG_RETURN_POINTER(a);
-
-   if (dirstr==NULL || (dc == 3
-    && (d[0] == 'A' || d[0] == 'a')
-    && (d[1] == 'S' || d[1] == 's')
-    && (d[2] == 'C' || d[2] == 'c')))
+sort(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   text       *dirstr = (fcinfo->nargs == 2) ? PG_GETARG_TEXT_P(1) : NULL;
+   int32       dc = (dirstr) ? VARSIZE(dirstr) - VARHDRSZ : 0;
+   char       *d = (dirstr) ? VARDATA(dirstr) : NULL;
+   int         dir = -1;
+
+   if (ARRISVOID(a) || ARRNELEMS(a) < 2)
+       PG_RETURN_POINTER(a);
+
+   if (dirstr == NULL || (dc == 3
+                          && (d[0] == 'A' || d[0] == 'a')
+                          && (d[1] == 'S' || d[1] == 's')
+                          && (d[2] == 'C' || d[2] == 'c')))
        dir = 1;
    else if (dc == 4
-    && (d[0] == 'D' || d[0] == 'd')
-    && (d[1] == 'E' || d[1] == 'e')
-    && (d[2] == 'S' || d[2] == 's')
-    && (d[3] == 'C' || d[3] == 'c'))
+            && (d[0] == 'D' || d[0] == 'd')
+            && (d[1] == 'E' || d[1] == 'e')
+            && (d[2] == 'S' || d[2] == 's')
+            && (d[3] == 'C' || d[3] == 'c'))
        dir = 0;
    if (dir == -1)
        elog(ERROR, "Invalid second parameter in function sort. It must be 'ASC' or 'DESC'.");
@@ -2367,97 +2508,116 @@ sort(PG_FUNCTION_ARGS) {
 }
 
 Datum
-sort_asc(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   if (ARRISVOID(a)) PG_RETURN_POINTER(a);
+sort_asc(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+
+   if (ARRISVOID(a))
+       PG_RETURN_POINTER(a);
    QSORT(a, 1);
    PG_RETURN_POINTER(a);
 }
 
 Datum
-sort_desc(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   if (ARRISVOID(a)) PG_RETURN_POINTER(a);
+sort_desc(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+
+   if (ARRISVOID(a))
+       PG_RETURN_POINTER(a);
    QSORT(a, 0);
    PG_RETURN_POINTER(a);
 }
 
 Datum
-uniq(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   if (ARRISVOID(a) || ARRNELEMS(a) < 2) PG_RETURN_POINTER(a);
+uniq(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+
+   if (ARRISVOID(a) || ARRNELEMS(a) < 2)
+       PG_RETURN_POINTER(a);
    UNIX_UNIQ(a);
    PG_RETURN_POINTER(a);
 }
 
 Datum
-idx(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
-   int32 result = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
-   if (result) result = intarray_match_first(a, PG_GETARG_INT32(1));
+idx(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+   int32       result = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+
+   if (result)
+       result = intarray_match_first(a, PG_GETARG_INT32(1));
    PG_FREE_IF_COPY(a, 0);
    PG_RETURN_INT32(result);
 }
 
 Datum
-subarray(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
-   ArrayType *result;
-   int32 start = ( PG_GETARG_INT32(1) > 0 ) ? PG_GETARG_INT32(1)-1 : PG_GETARG_INT32(1);
-   int32 len = ( fcinfo->nargs==3 ) ? PG_GETARG_INT32(2) : 0;
-   int32 end = 0;
-   int32 c;
-
-   if ( ARRISVOID(a) ) {
+subarray(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+   ArrayType  *result;
+   int32       start = (PG_GETARG_INT32(1) > 0) ? PG_GETARG_INT32(1) - 1 : PG_GETARG_INT32(1);
+   int32       len = (fcinfo->nargs == 3) ? PG_GETARG_INT32(2) : 0;
+   int32       end = 0;
+   int32       c;
+
+   if (ARRISVOID(a))
+   {
        PG_FREE_IF_COPY(a, 0);
-       PG_RETURN_POINTER( new_intArrayType(0) );
+       PG_RETURN_POINTER(new_intArrayType(0));
    }
 
    c = ARRNELEMS(a);
-   
-   if ( start < 0 )
+
+   if (start < 0)
        start = c + start;
 
-   if ( len < 0 )
+   if (len < 0)
        end = c + len;
-   else if ( len == 0 )
+   else if (len == 0)
        end = c;
    else
        end = start + len;
 
-   if ( end > c )
-       end = c; 
+   if (end > c)
+       end = c;
 
-   if ( start < 0 )
+   if (start < 0)
        start = 0;
 
-   if ( start >= end || end <= 0 ) { 
+   if (start >= end || end <= 0)
+   {
        PG_FREE_IF_COPY(a, 0);
-       PG_RETURN_POINTER( new_intArrayType(0) );
+       PG_RETURN_POINTER(new_intArrayType(0));
    }
 
 
-   result = new_intArrayType(end-start);
-   if (end-start > 0) 
-       memcpy(ARRPTR(result), ARRPTR(a) + start, (end-start) * sizeof(int32));
+   result = new_intArrayType(end - start);
+   if (end - start > 0)
+       memcpy(ARRPTR(result), ARRPTR(a) + start, (end - start) * sizeof(int32));
    PG_FREE_IF_COPY(a, 0);
    PG_RETURN_POINTER(result);
 }
 
 Datum
-intarray_push_elem(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
-   ArrayType *result;
+intarray_push_elem(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+   ArrayType  *result;
+
    result = intarray_add_elem(a, PG_GETARG_INT32(1));
    PG_FREE_IF_COPY(a, 0);
    PG_RETURN_POINTER(result);
 }
 
 Datum
-intarray_push_array(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
-   ArrayType *b = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(1)));
-   ArrayType *result;
+intarray_push_array(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+   ArrayType  *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(1)));
+   ArrayType  *result;
+
    result = intarray_concat_arrays(a, b);
    PG_FREE_IF_COPY(a, 0);
    PG_FREE_IF_COPY(b, 1);
@@ -2465,25 +2625,34 @@ intarray_push_array(PG_FUNCTION_ARGS) {
 }
 
 Datum
-intarray_del_elem(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   int32 c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
-   int32 *aa = ARRPTR(a);
-   int32 n = 0, i;
-   int32 elem = PG_GETARG_INT32(1);
+intarray_del_elem(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   int32       c = (ARRISVOID(a)) ? 0 : ARRNELEMS(a);
+   int32      *aa = ARRPTR(a);
+   int32       n = 0,
+               i;
+   int32       elem = PG_GETARG_INT32(1);
+
    for (i = 0; i < c; i++)
-       if (aa[i] != elem) {
-           if (i > n) aa[n++] = aa[i];
-           else n++;
+       if (aa[i] != elem)
+       {
+           if (i > n)
+               aa[n++] = aa[i];
+           else
+               n++;
        }
-   if (c > 0) a = resize_intArrayType(a, n);
+   if (c > 0)
+       a = resize_intArrayType(a, n);
    PG_RETURN_POINTER(a);
 }
 
 Datum
-intset_union_elem(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
-   ArrayType *result;
+intset_union_elem(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(0)));
+   ArrayType  *result;
+
    result = intarray_add_elem(a, PG_GETARG_INT32(1));
    PG_FREE_IF_COPY(a, 0);
    QSORT(result, 1);
@@ -2492,27 +2661,44 @@ intset_union_elem(PG_FUNCTION_ARGS) {
 }
 
 Datum
-intset_subtract(PG_FUNCTION_ARGS) {
-   ArrayType *a = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
-   ArrayType *b = (ArrayType*)DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
-   ArrayType *result;
-   int32 ca = ARRISVOID(a);
-   int32 cb = ARRISVOID(b);
-   int32 *aa, *bb, *r;
-   int32 n = 0, i = 0, k = 0;
-   QSORT(a, 1); UNIX_UNIQ(a); ca = ARRNELEMS(a);
-   QSORT(b, 1); UNIX_UNIQ(b); cb = ARRNELEMS(b);
+intset_subtract(PG_FUNCTION_ARGS)
+{
+   ArrayType  *a = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0)));
+   ArrayType  *b = (ArrayType *) DatumGetPointer(PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(1)));
+   ArrayType  *result;
+   int32       ca = ARRISVOID(a);
+   int32       cb = ARRISVOID(b);
+   int32      *aa,
+              *bb,
+              *r;
+   int32       n = 0,
+               i = 0,
+               k = 0;
+
+   QSORT(a, 1);
+   UNIX_UNIQ(a);
+   ca = ARRNELEMS(a);
+   QSORT(b, 1);
+   UNIX_UNIQ(b);
+   cb = ARRNELEMS(b);
    result = new_intArrayType(ca);
    aa = ARRPTR(a);
    bb = ARRPTR(b);
    r = ARRPTR(result);
-   while (i < ca) {
-       if (k == cb || aa[i] < bb[k]) r[n++] = aa[i++];
-       else if (aa[i] == bb[k]) { i++; k++; }
-       else k++;
+   while (i < ca)
+   {
+       if (k == cb || aa[i] < bb[k])
+           r[n++] = aa[i++];
+       else if (aa[i] == bb[k])
+       {
+           i++;
+           k++;
+       }
+       else
+           k++;
    }
    result = resize_intArrayType(result, n);
-   pfree(a); pfree(b);
+   pfree(a);
+   pfree(b);
    PG_RETURN_POINTER(result);
 }
-
index 27bd057a567103f87815464d4ae8f73aaa30158c..d8efd8096d0f1e063f6b8efb07c55cb3cb855d91 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * GiST support for ltree[] 
+ * GiST support for ltree[]
  * Teodor Sigaev <teodor@stack.net>
  */
 
 
 #include "crc32.h"
 
-PG_FUNCTION_INFO_V1( _ltree_compress );
-Datum   _ltree_compress(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_same );
-Datum   _ltree_same(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_union );
-Datum   _ltree_union(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_penalty );
-Datum   _ltree_penalty(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_picksplit );
-Datum   _ltree_picksplit(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( _ltree_consistent );
-Datum   _ltree_consistent(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(_ltree_compress);
+Datum      _ltree_compress(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_same);
+Datum      _ltree_same(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_union);
+Datum      _ltree_union(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_penalty);
+Datum      _ltree_penalty(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_picksplit);
+Datum      _ltree_picksplit(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(_ltree_consistent);
+Datum      _ltree_consistent(PG_FUNCTION_ARGS);
 
 #define GETENTRY(vec,pos) ((ltree_gist *) DatumGetPointer(((GISTENTRY *) VARDATA(vec))[(pos)].key))
 #define NEXTVAL(x) ( (ltree*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) )
-#define SUMBIT(val) (        \
+#define SUMBIT(val) (       \
    GETBITBYTE(val,0) + \
    GETBITBYTE(val,1) + \
    GETBITBYTE(val,2) + \
@@ -34,235 +39,280 @@ Datum   _ltree_consistent(PG_FUNCTION_ARGS);
    GETBITBYTE(val,4) + \
    GETBITBYTE(val,5) + \
    GETBITBYTE(val,6) + \
-   GETBITBYTE(val,7)   \
+   GETBITBYTE(val,7)   \
 )
 #define WISH_F(a,b,c) (double)( -(double)(((a)-(b))*((a)-(b))*((a)-(b)))*(c) )
 
 static void
-hashing(BITVECP sign, ltree *t) {
-   int tlen = t->numlevel;
+hashing(BITVECP sign, ltree * t)
+{
+   int         tlen = t->numlevel;
    ltree_level *cur = LTREE_FIRST(t);
-   int  hash;
+   int         hash;
 
-   while(tlen > 0) {
-       hash = ltree_crc32_sz( cur->name, cur->len );
-       AHASH( sign, hash );
+   while (tlen > 0)
+   {
+       hash = ltree_crc32_sz(cur->name, cur->len);
+       AHASH(sign, hash);
        cur = LEVEL_NEXT(cur);
        tlen--;
    }
 }
 
-Datum   
-_ltree_compress(PG_FUNCTION_ARGS) {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+Datum
+_ltree_compress(PG_FUNCTION_ARGS)
+{
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
    GISTENTRY  *retval = entry;
 
-   if ( entry->leafkey ) { /* ltree */
-       ltree_gist  *key;
-       ArrayType   *val = DatumGetArrayTypeP(entry->key);
-       int4 len = LTG_HDRSIZE + ASIGLEN;
-       int num=ArrayGetNItems( ARR_NDIM(val), ARR_DIMS(val) );
-       ltree   *item = (ltree*)ARR_DATA_PTR(val);
+   if (entry->leafkey)
+   {                           /* ltree */
+       ltree_gist *key;
+       ArrayType  *val = DatumGetArrayTypeP(entry->key);
+       int4        len = LTG_HDRSIZE + ASIGLEN;
+       int         num = ArrayGetNItems(ARR_NDIM(val), ARR_DIMS(val));
+       ltree      *item = (ltree *) ARR_DATA_PTR(val);
 
-       if ( ARR_NDIM(val) != 1 )
-            elog(ERROR,"Dimension of array != 1");
+       if (ARR_NDIM(val) != 1)
+           elog(ERROR, "Dimension of array != 1");
 
-       key = (ltree_gist*)palloc( len );
+       key = (ltree_gist *) palloc(len);
        key->len = len;
        key->flag = 0;
 
-       MemSet( LTG_SIGN(key), 0, sizeof(ASIGLEN) );
-       while( num>0 ) {
+       MemSet(LTG_SIGN(key), 0, sizeof(ASIGLEN));
+       while (num > 0)
+       {
            hashing(LTG_SIGN(key), item);
            num--;
            item = NEXTVAL(item);
        }
 
-       if ( PointerGetDatum(val) != entry->key )
+       if (PointerGetDatum(val) != entry->key)
            pfree(val);
 
-       retval = (GISTENTRY*)palloc( sizeof(GISTENTRY) );
+       retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
        gistentryinit(*retval, PointerGetDatum(key),
-           entry->rel, entry->page,
-           entry->offset, key->len, FALSE);
-   } else {
-       int4 i,len;
-       ltree_gist  *key;
+                     entry->rel, entry->page,
+                     entry->offset, key->len, FALSE);
+   }
+   else
+   {
+       int4        i,
+                   len;
+       ltree_gist *key;
 
-       BITVECP sign = LTG_SIGN(DatumGetPointer( entry->key ) );
+       BITVECP     sign = LTG_SIGN(DatumGetPointer(entry->key));
 
        ALOOPBYTE(
-           if ( sign[i] != 0xff )
-               PG_RETURN_POINTER(retval);
+                 if (sign[i] != 0xff)
+                 PG_RETURN_POINTER(retval);
        );
 
-       len = LTG_HDRSIZE; 
-       key = (ltree_gist*)palloc( len );
+       len = LTG_HDRSIZE;
+       key = (ltree_gist *) palloc(len);
        key->len = len;
        key->flag = LTG_ALLTRUE;
 
-       retval = (GISTENTRY*)palloc( sizeof(GISTENTRY) );
+       retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
        gistentryinit(*retval, PointerGetDatum(key),
-           entry->rel, entry->page,
-           entry->offset, key->len, FALSE);
+                     entry->rel, entry->page,
+                     entry->offset, key->len, FALSE);
    }
    PG_RETURN_POINTER(retval);
 }
 
-Datum   
-_ltree_same(PG_FUNCTION_ARGS) {
-   ltree_gist* a=(ltree_gist*)PG_GETARG_POINTER(0);
-   ltree_gist* b=(ltree_gist*)PG_GETARG_POINTER(1);
-   bool *result = (bool *)PG_GETARG_POINTER(2);
+Datum
+_ltree_same(PG_FUNCTION_ARGS)
+{
+   ltree_gist *a = (ltree_gist *) PG_GETARG_POINTER(0);
+   ltree_gist *b = (ltree_gist *) PG_GETARG_POINTER(1);
+   bool       *result = (bool *) PG_GETARG_POINTER(2);
 
-   if ( LTG_ISALLTRUE(a) && LTG_ISALLTRUE(b) ) {
+   if (LTG_ISALLTRUE(a) && LTG_ISALLTRUE(b))
        *result = true;
-   } else if ( LTG_ISALLTRUE(a) ) {
+   else if (LTG_ISALLTRUE(a))
        *result = false;
-   } else if ( LTG_ISALLTRUE(b) ) {
+   else if (LTG_ISALLTRUE(b))
        *result = false;
-   } else {
-       int4 i;
-       BITVECP sa=LTG_SIGN(a), sb=LTG_SIGN(b);
+   else
+   {
+       int4        i;
+       BITVECP     sa = LTG_SIGN(a),
+                   sb = LTG_SIGN(b);
+
        *result = true;
        ALOOPBYTE(
-           if ( sa[i] != sb[i] ) {
-               *result = false;
-               break;
-           }
+                 if (sa[i] != sb[i])
+                 {
+           *result = false;
+           break;
+       }
        );
-   } 
-   PG_RETURN_POINTER(result); 
+   }
+   PG_RETURN_POINTER(result);
 }
 
-static int4 
-unionkey( BITVECP sbase, ltree_gist *add ) {
-   int4    i;
-   BITVECP sadd = LTG_SIGN( add );
+static int4
+unionkey(BITVECP sbase, ltree_gist * add)
+{
+   int4        i;
+   BITVECP     sadd = LTG_SIGN(add);
 
-   if ( LTG_ISALLTRUE(add) )
+   if (LTG_ISALLTRUE(add))
        return 1;
 
    ALOOPBYTE(
-       sbase[i] |= sadd[i];
+             sbase[i] |= sadd[i];
    );
    return 0;
 }
 
-Datum   
-_ltree_union(PG_FUNCTION_ARGS) {
-   bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
-   int *size = (int *) PG_GETARG_POINTER(1);
-   ABITVEC base;
-   int4 len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
-   int4 i;
-   int4 flag = 0;
-   ltree_gist  *result;
-
-   MemSet( (void*)base, 0, sizeof(ABITVEC) );
-   for(i=0;i<len;i++) {
-       if ( unionkey( base, GETENTRY(entryvec, i) ) ) {
+Datum
+_ltree_union(PG_FUNCTION_ARGS)
+{
+   bytea      *entryvec = (bytea *) PG_GETARG_POINTER(0);
+   int        *size = (int *) PG_GETARG_POINTER(1);
+   ABITVEC     base;
+   int4        len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
+   int4        i;
+   int4        flag = 0;
+   ltree_gist *result;
+
+   MemSet((void *) base, 0, sizeof(ABITVEC));
+   for (i = 0; i < len; i++)
+   {
+       if (unionkey(base, GETENTRY(entryvec, i)))
+       {
            flag = LTG_ALLTRUE;
            break;
        }
    }
 
-   len = LTG_HDRSIZE + ( ( flag & LTG_ALLTRUE ) ? 0 : ASIGLEN );
-   result = (ltree_gist*)palloc( len );
+   len = LTG_HDRSIZE + ((flag & LTG_ALLTRUE) ? 0 : ASIGLEN);
+   result = (ltree_gist *) palloc(len);
    *size = result->len = len;
    result->flag = flag;
-   if ( ! LTG_ISALLTRUE(result) )
-       memcpy((void*)LTG_SIGN(result), (void*)base, sizeof( ABITVEC ) );
+   if (!LTG_ISALLTRUE(result))
+       memcpy((void *) LTG_SIGN(result), (void *) base, sizeof(ABITVEC));
 
-   PG_RETURN_POINTER(result);  
+   PG_RETURN_POINTER(result);
 }
 
 static int4
-sizebitvec( BITVECP sign ) {
-   int4 size=0, i;
+sizebitvec(BITVECP sign)
+{
+   int4        size = 0,
+               i;
+
    ALOOPBYTE(
-       size += SUMBIT(*(char*)sign);
-       sign = (BITVECP) ( ((char*)sign) + 1 );
+             size += SUMBIT(*(char *) sign);
+   sign = (BITVECP) (((char *) sign) + 1);
    );
    return size;
 }
 
-Datum   
-_ltree_penalty(PG_FUNCTION_ARGS) {
-   ltree_gist *origval = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(0) )->key );
-   ltree_gist *newval  = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(1) )->key );
-   float  *penalty = (float *)    PG_GETARG_POINTER(2);
-   BITVECP orig = LTG_SIGN(origval);
+Datum
+_ltree_penalty(PG_FUNCTION_ARGS)
+{
+   ltree_gist *origval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
+   ltree_gist *newval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
+   float      *penalty = (float *) PG_GETARG_POINTER(2);
+   BITVECP     orig = LTG_SIGN(origval);
 
-   if ( LTG_ISALLTRUE(origval) ) {
+   if (LTG_ISALLTRUE(origval))
+   {
        *penalty = 0.0;
-       PG_RETURN_POINTER( penalty );
+       PG_RETURN_POINTER(penalty);
    }
 
-   if ( LTG_ISALLTRUE(newval) ) {
-       *penalty = (float) (ASIGLENBIT - sizebitvec( orig ) );
-   } else {
+   if (LTG_ISALLTRUE(newval))
+       *penalty = (float) (ASIGLENBIT - sizebitvec(orig));
+   else
+   {
        unsigned char valtmp;
-       BITVECP nval = LTG_SIGN(newval);
-       int4 i, unionsize=0;
+       BITVECP     nval = LTG_SIGN(newval);
+       int4        i,
+                   unionsize = 0;
 
        ALOOPBYTE(
-           valtmp = nval[i] | orig[i];
-           unionsize += SUMBIT(valtmp) - SUMBIT(orig[i]);
+                 valtmp = nval[i] | orig[i];
+       unionsize += SUMBIT(valtmp) - SUMBIT(orig[i]);
        );
-       *penalty = (float)unionsize;
+       *penalty = (float) unionsize;
    }
-   PG_RETURN_POINTER( penalty );
+   PG_RETURN_POINTER(penalty);
 }
 
-typedef struct {
-   OffsetNumber    pos;
-   int4           cost;
+typedef struct
+{
+   OffsetNumber pos;
+   int4        cost;
 } SPLITCOST;
 
 static int
-comparecost( const void *a, const void *b ) {
-   return ((SPLITCOST*)a)->cost - ((SPLITCOST*)b)->cost;
+comparecost(const void *a, const void *b)
+{
+   return ((SPLITCOST *) a)->cost - ((SPLITCOST *) b)->cost;
 }
 
-Datum   
-_ltree_picksplit(PG_FUNCTION_ARGS) {
-   bytea *entryvec = (bytea*) PG_GETARG_POINTER(0);
-   GIST_SPLITVEC *v = (GIST_SPLITVEC*) PG_GETARG_POINTER(1);
-   OffsetNumber k,j;
-   ltree_gist  *datum_l, *datum_r;
-   ABITVEC union_l, union_r;
-   bool            firsttime = true;
-   int4    size_alpha,size_beta,sizeu,sizei;
-   int4    size_waste, waste = 0.0;
-   int4    size_l, size_r;
-   int4    nbytes;
-   OffsetNumber seed_1=0, seed_2=0;
-   OffsetNumber    *left, *right;
+Datum
+_ltree_picksplit(PG_FUNCTION_ARGS)
+{
+   bytea      *entryvec = (bytea *) PG_GETARG_POINTER(0);
+   GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
+   OffsetNumber k,
+               j;
+   ltree_gist *datum_l,
+              *datum_r;
+   ABITVEC     union_l,
+               union_r;
+   bool        firsttime = true;
+   int4        size_alpha,
+               size_beta,
+               sizeu,
+               sizei;
+   int4        size_waste,
+               waste = 0.0;
+   int4        size_l,
+               size_r;
+   int4        nbytes;
+   OffsetNumber seed_1 = 0,
+               seed_2 = 0;
+   OffsetNumber *left,
+              *right;
    OffsetNumber maxoff;
-   BITVECP ptra, ptrb, ptrc;
-   int i;
-   unsigned char    valtmp;
-   SPLITCOST       *costvector;
-   ltree_gist  *_k, *_j;
+   BITVECP     ptra,
+               ptrb,
+               ptrc;
+   int         i;
+   unsigned char valtmp;
+   SPLITCOST  *costvector;
+   ltree_gist *_k,
+              *_j;
 
    maxoff = ((VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY)) - 2;
    nbytes = (maxoff + 2) * sizeof(OffsetNumber);
    v->spl_left = (OffsetNumber *) palloc(nbytes);
    v->spl_right = (OffsetNumber *) palloc(nbytes);
 
-   for (k = FirstOffsetNumber; k < maxoff; k = OffsetNumberNext(k)) {
-       _k = GETENTRY(entryvec,k); 
-       for (j = OffsetNumberNext(k); j <= maxoff; j = OffsetNumberNext(j)) {
-           _j = GETENTRY(entryvec,j);
-           if ( LTG_ISALLTRUE(_k) || LTG_ISALLTRUE(_j) ) {
+   for (k = FirstOffsetNumber; k < maxoff; k = OffsetNumberNext(k))
+   {
+       _k = GETENTRY(entryvec, k);
+       for (j = OffsetNumberNext(k); j <= maxoff; j = OffsetNumberNext(j))
+       {
+           _j = GETENTRY(entryvec, j);
+           if (LTG_ISALLTRUE(_k) || LTG_ISALLTRUE(_j))
+           {
                sizeu = ASIGLENBIT;
-               if ( LTG_ISALLTRUE(_k) && LTG_ISALLTRUE(_j) )
+               if (LTG_ISALLTRUE(_k) && LTG_ISALLTRUE(_j))
                    sizei = ASIGLENBIT;
                else
-                   sizei = ( LTG_ISALLTRUE(_k) ) ? 
-                       sizebitvec( LTG_SIGN(_j) ) : sizebitvec( LTG_SIGN(_k) ); 
-           } else {
+                   sizei = (LTG_ISALLTRUE(_k)) ?
+                       sizebitvec(LTG_SIGN(_j)) : sizebitvec(LTG_SIGN(_k));
+           }
+           else
+           {
                sizeu = sizei = 0;
                ptra = LTG_SIGN(_j);
                ptrb = LTG_SIGN(_k);
@@ -278,20 +328,21 @@ _ltree_picksplit(PG_FUNCTION_ARGS) {
 } while(0)
 
                ALOOPBYTE(
-                   COUNT(0);
-                   COUNT(1);
-                   COUNT(2);
-                   COUNT(3);
-                   COUNT(4);
-                   COUNT(5);
-                   COUNT(6);
-                   COUNT(7);
-                   ptra = (BITVECP) ( ((char*)ptra) + 1 );
-                   ptrb = (BITVECP) ( ((char*)ptrb) + 1 );
+                         COUNT(0);
+               COUNT(1);
+               COUNT(2);
+               COUNT(3);
+               COUNT(4);
+               COUNT(5);
+               COUNT(6);
+               COUNT(7);
+               ptra = (BITVECP) (((char *) ptra) + 1);
+               ptrb = (BITVECP) (((char *) ptrb) + 1);
                );
            }
            size_waste = sizeu - sizei;
-           if (size_waste > waste || firsttime) {
+           if (size_waste > waste || firsttime)
+           {
                waste = size_waste;
                seed_1 = k;
                seed_2 = j;
@@ -305,129 +356,166 @@ _ltree_picksplit(PG_FUNCTION_ARGS) {
    right = v->spl_right;
    v->spl_nright = 0;
 
-   if ( seed_1 == 0 || seed_2 == 0 ) {
+   if (seed_1 == 0 || seed_2 == 0)
+   {
        seed_1 = 1;
        seed_2 = 2;
    }
 
    /* form initial .. */
-   if ( LTG_ISALLTRUE(GETENTRY(entryvec,seed_1)) ) {
-       datum_l = (ltree_gist*)palloc( LTG_HDRSIZE );
-       datum_l->len = LTG_HDRSIZE; datum_l->flag = LTG_ALLTRUE;
+   if (LTG_ISALLTRUE(GETENTRY(entryvec, seed_1)))
+   {
+       datum_l = (ltree_gist *) palloc(LTG_HDRSIZE);
+       datum_l->len = LTG_HDRSIZE;
+       datum_l->flag = LTG_ALLTRUE;
        size_l = ASIGLENBIT;
-   } else {
-       datum_l = (ltree_gist*)palloc( LTG_HDRSIZE + ASIGLEN );
-       datum_l->len = LTG_HDRSIZE + ASIGLEN; datum_l->flag = 0;
-       memcpy((void*)LTG_SIGN(datum_l), (void*)LTG_SIGN(GETENTRY(entryvec,seed_1)), sizeof(ABITVEC));
-       size_l = sizebitvec( LTG_SIGN(datum_l) );
    }
-   if ( LTG_ISALLTRUE(GETENTRY(entryvec,seed_2)) ) {
-       datum_r = (ltree_gist*)palloc( LTG_HDRSIZE );
-       datum_r->len = LTG_HDRSIZE; datum_r->flag = LTG_ALLTRUE;
+   else
+   {
+       datum_l = (ltree_gist *) palloc(LTG_HDRSIZE + ASIGLEN);
+       datum_l->len = LTG_HDRSIZE + ASIGLEN;
+       datum_l->flag = 0;
+       memcpy((void *) LTG_SIGN(datum_l), (void *) LTG_SIGN(GETENTRY(entryvec, seed_1)), sizeof(ABITVEC));
+       size_l = sizebitvec(LTG_SIGN(datum_l));
+   }
+   if (LTG_ISALLTRUE(GETENTRY(entryvec, seed_2)))
+   {
+       datum_r = (ltree_gist *) palloc(LTG_HDRSIZE);
+       datum_r->len = LTG_HDRSIZE;
+       datum_r->flag = LTG_ALLTRUE;
        size_r = ASIGLENBIT;
-   } else {
-       datum_r = (ltree_gist*)palloc( LTG_HDRSIZE + ASIGLEN );
-       datum_r->len = LTG_HDRSIZE + ASIGLEN; datum_r->flag = 0;
-       memcpy((void*)LTG_SIGN(datum_r), (void*)LTG_SIGN(GETENTRY(entryvec,seed_2)), sizeof(ABITVEC));
-       size_r = sizebitvec( LTG_SIGN(datum_r) );
+   }
+   else
+   {
+       datum_r = (ltree_gist *) palloc(LTG_HDRSIZE + ASIGLEN);
+       datum_r->len = LTG_HDRSIZE + ASIGLEN;
+       datum_r->flag = 0;
+       memcpy((void *) LTG_SIGN(datum_r), (void *) LTG_SIGN(GETENTRY(entryvec, seed_2)), sizeof(ABITVEC));
+       size_r = sizebitvec(LTG_SIGN(datum_r));
    }
 
    maxoff = OffsetNumberNext(maxoff);
    /* sort before ... */
-   costvector=(SPLITCOST*)palloc( sizeof(SPLITCOST)*maxoff );
-   for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j)) {
-       costvector[j-1].pos = j;
-       _j = GETENTRY(entryvec,j);
-       if ( LTG_ISALLTRUE(_j) ) {
+   costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
+   for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
+   {
+       costvector[j - 1].pos = j;
+       _j = GETENTRY(entryvec, j);
+       if (LTG_ISALLTRUE(_j))
+       {
            size_alpha = ASIGLENBIT - size_l;
-           size_beta  = ASIGLENBIT - size_r;
-       } else {
-           ptra = LTG_SIGN( datum_l );
-           ptrb = LTG_SIGN( datum_r );
-           ptrc = LTG_SIGN( _j );
+           size_beta = ASIGLENBIT - size_r;
+       }
+       else
+       {
+           ptra = LTG_SIGN(datum_l);
+           ptrb = LTG_SIGN(datum_r);
+           ptrc = LTG_SIGN(_j);
            size_beta = size_alpha = 0;
-           if ( LTG_ISALLTRUE(datum_l) ) {
-               if ( !LTG_ISALLTRUE(datum_r) ) {
+           if (LTG_ISALLTRUE(datum_l))
+           {
+               if (!LTG_ISALLTRUE(datum_r))
+               {
                    ALOOPBIT(
-                       if ( GETBIT(ptrc,i) && ! GETBIT(ptrb,i) )
-                           size_beta++;
+                            if (GETBIT(ptrc, i) && !GETBIT(ptrb, i))
+                            size_beta++;
                    );
                }
-           } else if ( LTG_ISALLTRUE(datum_r) ) {
-               if ( !LTG_ISALLTRUE(datum_l) ) {
+           }
+           else if (LTG_ISALLTRUE(datum_r))
+           {
+               if (!LTG_ISALLTRUE(datum_l))
+               {
                    ALOOPBIT(
-                        if ( GETBIT(ptrc,i) && ! GETBIT(ptra,i) )
-                           size_alpha++;
+                            if (GETBIT(ptrc, i) && !GETBIT(ptra, i))
+                            size_alpha++;
                    );
                }
-           } else {
+           }
+           else
+           {
                ALOOPBIT(
-                   if ( GETBIT(ptrc,i) && ! GETBIT(ptra,i) )
-                       size_alpha++;
-                   if ( GETBIT(ptrc,i) && ! GETBIT(ptrb,i) )
-                       size_beta++;
+                        if (GETBIT(ptrc, i) && !GETBIT(ptra, i))
+                        size_alpha++;
+               if (GETBIT(ptrc, i) && !GETBIT(ptrb, i))
+                   size_beta++;
                );
            }
        }
-       costvector[j-1].cost = abs( size_alpha - size_beta );
+       costvector[j - 1].cost = abs(size_alpha - size_beta);
    }
-   qsort( (void*)costvector, maxoff, sizeof(SPLITCOST), comparecost );
+   qsort((void *) costvector, maxoff, sizeof(SPLITCOST), comparecost);
 
-   for (k = 0; k < maxoff; k++) {
+   for (k = 0; k < maxoff; k++)
+   {
        j = costvector[k].pos;
-       _j = GETENTRY(entryvec,j);
-       if ( j == seed_1 ) {
+       _j = GETENTRY(entryvec, j);
+       if (j == seed_1)
+       {
            *left++ = j;
            v->spl_nleft++;
            continue;
-       } else if ( j == seed_2 ) {
+       }
+       else if (j == seed_2)
+       {
            *right++ = j;
            v->spl_nright++;
            continue;
        }
 
-       if ( LTG_ISALLTRUE(datum_l) || LTG_ISALLTRUE(_j) ) {
+       if (LTG_ISALLTRUE(datum_l) || LTG_ISALLTRUE(_j))
            size_alpha = ASIGLENBIT;
-       } else {
+       else
+       {
            ptra = LTG_SIGN(_j);
            ptrb = LTG_SIGN(datum_l);
            size_alpha = 0;
            ALOOPBYTE(
-               valtmp = union_l[i] = ptra[i] | ptrb[i];
-               size_alpha += SUMBIT( valtmp );
+                     valtmp = union_l[i] = ptra[i] | ptrb[i];
+           size_alpha += SUMBIT(valtmp);
            );
        }
 
-       if ( LTG_ISALLTRUE(datum_r) || LTG_ISALLTRUE(_j) ) {
+       if (LTG_ISALLTRUE(datum_r) || LTG_ISALLTRUE(_j))
            size_beta = ASIGLENBIT;
-       } else {
+       else
+       {
            ptra = LTG_SIGN(_j);
            ptrb = LTG_SIGN(datum_r);
            size_beta = 0;
            ALOOPBYTE(
-               valtmp = union_r[i] = ptra[i] | ptrb[i];
-               size_beta += SUMBIT( valtmp );
+                     valtmp = union_r[i] = ptra[i] | ptrb[i];
+           size_beta += SUMBIT(valtmp);
            );
        }
 
-       if (size_alpha - size_l < size_beta - size_r + WISH_F(v->spl_nleft, v->spl_nright, 0.1)) {
-           if ( ! LTG_ISALLTRUE( datum_l ) ) {
-               if ( size_alpha == ASIGLENBIT ) {
-                   if ( size_alpha != size_l )
-                       MemSet( (void*)LTG_SIGN(datum_l),0xff, sizeof(ABITVEC));
-               } else
-                   memcpy( (void*)LTG_SIGN(datum_l), (void*)union_l, sizeof(ABITVEC) );
+       if (size_alpha - size_l < size_beta - size_r + WISH_F(v->spl_nleft, v->spl_nright, 0.1))
+       {
+           if (!LTG_ISALLTRUE(datum_l))
+           {
+               if (size_alpha == ASIGLENBIT)
+               {
+                   if (size_alpha != size_l)
+                       MemSet((void *) LTG_SIGN(datum_l), 0xff, sizeof(ABITVEC));
+               }
+               else
+                   memcpy((void *) LTG_SIGN(datum_l), (void *) union_l, sizeof(ABITVEC));
            }
            size_l = size_alpha;
            *left++ = j;
            v->spl_nleft++;
-       } else {
-           if ( ! LTG_ISALLTRUE( datum_r ) ) {
-               if ( size_beta == ASIGLENBIT ) {
-                   if ( size_beta != size_r )
-                       MemSet( (void*)LTG_SIGN(datum_r),0xff, sizeof(ABITVEC));
-               } else
-                   memcpy( (void*)LTG_SIGN(datum_r), (void*)union_r, sizeof(ABITVEC) );
+       }
+       else
+       {
+           if (!LTG_ISALLTRUE(datum_r))
+           {
+               if (size_beta == ASIGLENBIT)
+               {
+                   if (size_beta != size_r)
+                       MemSet((void *) LTG_SIGN(datum_r), 0xff, sizeof(ABITVEC));
+               }
+               else
+                   memcpy((void *) LTG_SIGN(datum_r), (void *) union_r, sizeof(ABITVEC));
            }
            size_r = size_beta;
            *right++ = j;
@@ -441,23 +529,25 @@ _ltree_picksplit(PG_FUNCTION_ARGS) {
    v->spl_ldatum = PointerGetDatum(datum_l);
    v->spl_rdatum = PointerGetDatum(datum_r);
 
-   PG_RETURN_POINTER( v );
+   PG_RETURN_POINTER(v);
 }
 
 static bool
-gist_te(ltree_gist *key, ltree* query) {
-   ltree_level    *curq = LTREE_FIRST(query);
-   BITVECP sign = LTG_SIGN(key);
-   int     qlen = query->numlevel;
+gist_te(ltree_gist * key, ltree * query)
+{
+   ltree_level *curq = LTREE_FIRST(query);
+   BITVECP     sign = LTG_SIGN(key);
+   int         qlen = query->numlevel;
    unsigned int hv;
 
-   if ( LTG_ISALLTRUE(key) )
+   if (LTG_ISALLTRUE(key))
        return true;
 
-   while( qlen>0 ) {
-       hv = ltree_crc32_sz(curq->name,curq->len);
-       if ( ! GETBIT( sign, AHASHVAL(hv) ) )
-           return false; 
+   while (qlen > 0)
+   {
+       hv = ltree_crc32_sz(curq->name, curq->len);
+       if (!GETBIT(sign, AHASHVAL(hv)))
+           return false;
        curq = LEVEL_NEXT(curq);
        qlen--;
    }
@@ -466,48 +556,56 @@ gist_te(ltree_gist *key, ltree* query) {
 }
 
 static bool
-checkcondition_bit(void *checkval, ITEM* val ) {
-   return ( FLG_CANLOOKSIGN(val->flag) ) ? GETBIT( checkval, AHASHVAL( val->val ) ) : true;
+checkcondition_bit(void *checkval, ITEM * val)
+{
+   return (FLG_CANLOOKSIGN(val->flag)) ? GETBIT(checkval, AHASHVAL(val->val)) : true;
 }
 
 static bool
-gist_qtxt(ltree_gist *key, ltxtquery* query) {
-   if ( LTG_ISALLTRUE(key) )
+gist_qtxt(ltree_gist * key, ltxtquery * query)
+{
+   if (LTG_ISALLTRUE(key))
        return true;
-            
+
    return ltree_execute(
-       GETQUERY(query),
-       (void*)LTG_SIGN(key), false,
-       checkcondition_bit
-   );
+                        GETQUERY(query),
+                        (void *) LTG_SIGN(key), false,
+                        checkcondition_bit
+       );
 }
 
 static bool
-gist_qe(ltree_gist *key, lquery* query) {
-   lquery_level    *curq = LQUERY_FIRST(query);
-   BITVECP sign = LTG_SIGN(key);
-   int     qlen = query->numlevel;
-                    
-   if ( LTG_ISALLTRUE(key) )
+gist_qe(ltree_gist * key, lquery * query)
+{
+   lquery_level *curq = LQUERY_FIRST(query);
+   BITVECP     sign = LTG_SIGN(key);
+   int         qlen = query->numlevel;
+
+   if (LTG_ISALLTRUE(key))
        return true;
-               
-   while( qlen>0 ) {
-       if ( curq->numvar && LQL_CANLOOKSIGN(curq) ) {
-           bool isexist=false;
-           int vlen = curq->numvar;
+
+   while (qlen > 0)
+   {
+       if (curq->numvar && LQL_CANLOOKSIGN(curq))
+       {
+           bool        isexist = false;
+           int         vlen = curq->numvar;
            lquery_variant *curv = LQL_FIRST(curq);
-           while( vlen>0 ) {
-               if ( GETBIT( sign, AHASHVAL( curv->val ) ) ) {
-                   isexist=true;
+
+           while (vlen > 0)
+           {
+               if (GETBIT(sign, AHASHVAL(curv->val)))
+               {
+                   isexist = true;
                    break;
                }
                curv = LVAR_NEXT(curv);
                vlen--;
            }
-           if ( !isexist )
+           if (!isexist)
                return false;
        }
+
        curq = LQL_NEXT(curq);
        qlen--;
    }
@@ -516,34 +614,35 @@ gist_qe(ltree_gist *key, lquery* query) {
 }
 
 
-Datum   
-_ltree_consistent(PG_FUNCTION_ARGS) {
-   GISTENTRY *entry = (GISTENTRY*)PG_GETARG_POINTER(0);
-   char *query = (char*)DatumGetPointer( PG_DETOAST_DATUM(PG_GETARG_DATUM(1)) );
-   ltree_gist *key = (ltree_gist*)DatumGetPointer( entry->key );
+Datum
+_ltree_consistent(PG_FUNCTION_ARGS)
+{
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+   char       *query = (char *) DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(1)));
+   ltree_gist *key = (ltree_gist *) DatumGetPointer(entry->key);
    StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
-   bool res = false;
+   bool        res = false;
 
-#ifndef assert_enabled 
+#ifndef assert_enabled
 #define assert_enabled 0
 #endif
-   
-   switch( strategy ) {
+
+   switch (strategy)
+   {
        case 10:
        case 11:
-           res =  gist_te(key, (ltree*)query);
+           res = gist_te(key, (ltree *) query);
            break;
        case 12:
        case 13:
-           res =  gist_qe(key, (lquery*)query);
-           break; 
+           res = gist_qe(key, (lquery *) query);
+           break;
        case 14:
        case 15:
-           res = gist_qtxt(key, (ltxtquery*)query);
-           break;  
+           res = gist_qtxt(key, (ltxtquery *) query);
+           break;
        default:
-           elog(ERROR,"Unknown StrategyNumber: %d", strategy);
+           elog(ERROR, "Unknown StrategyNumber: %d", strategy);
    }
    PG_RETURN_BOOL(res);
 }
-
index 336b83820cf0351476e2fa78f8037364f62c6496..59de0a51e4a77a7410718313c70e37985787fe21 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * op function for ltree[] 
+ * op function for ltree[]
  * Teodor Sigaev <teodor@stack.net>
  */
 
@@ -16,223 +16,253 @@ PG_FUNCTION_INFO_V1(_ltq_rregex);
 PG_FUNCTION_INFO_V1(_ltxtq_exec);
 PG_FUNCTION_INFO_V1(_ltxtq_rexec);
 
-Datum _ltree_r_isparent(PG_FUNCTION_ARGS);
-Datum _ltree_r_risparent(PG_FUNCTION_ARGS);
+Datum      _ltree_r_isparent(PG_FUNCTION_ARGS);
+Datum      _ltree_r_risparent(PG_FUNCTION_ARGS);
 
 PG_FUNCTION_INFO_V1(_ltree_extract_isparent);
 PG_FUNCTION_INFO_V1(_ltree_extract_risparent);
 PG_FUNCTION_INFO_V1(_ltq_extract_regex);
 PG_FUNCTION_INFO_V1(_ltxtq_extract_exec);
-Datum _ltree_extract_isparent(PG_FUNCTION_ARGS);
-Datum _ltree_extract_risparent(PG_FUNCTION_ARGS);
-Datum _ltq_extract_regex(PG_FUNCTION_ARGS);
-Datum _ltxtq_extract_exec(PG_FUNCTION_ARGS);
+Datum      _ltree_extract_isparent(PG_FUNCTION_ARGS);
+Datum      _ltree_extract_risparent(PG_FUNCTION_ARGS);
+Datum      _ltq_extract_regex(PG_FUNCTION_ARGS);
+Datum      _ltxtq_extract_exec(PG_FUNCTION_ARGS);
 
 PG_FUNCTION_INFO_V1(_lca);
-Datum _lca(PG_FUNCTION_ARGS);
+Datum      _lca(PG_FUNCTION_ARGS);
+
+typedef Datum (*PGCALL2) (PG_FUNCTION_ARGS);
 
-typedef Datum (*PGCALL2)(PG_FUNCTION_ARGS);
 #define NEXTVAL(x) ( (ltree*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) )
 
 static bool
-array_iterator( ArrayType *la, PGCALL2 callback, void* param, ltree ** found) {
-   int num=ArrayGetNItems( ARR_NDIM(la), ARR_DIMS(la));
-   ltree   *item = (ltree*)ARR_DATA_PTR(la);
-
-   if ( ARR_NDIM(la) !=1 )
-       elog(ERROR,"Dimension of array != 1");
-
-   if ( found )
-       *found=NULL;
-   while( num>0 ) {
-       if ( DatumGetBool( DirectFunctionCall2( callback, 
-           PointerGetDatum(item), PointerGetDatum(param) ) ) ) {
-
-           if ( found )
+array_iterator(ArrayType *la, PGCALL2 callback, void *param, ltree ** found)
+{
+   int         num = ArrayGetNItems(ARR_NDIM(la), ARR_DIMS(la));
+   ltree      *item = (ltree *) ARR_DATA_PTR(la);
+
+   if (ARR_NDIM(la) != 1)
+       elog(ERROR, "Dimension of array != 1");
+
+   if (found)
+       *found = NULL;
+   while (num > 0)
+   {
+       if (DatumGetBool(DirectFunctionCall2(callback,
+                        PointerGetDatum(item), PointerGetDatum(param))))
+       {
+
+           if (found)
                *found = item;
            return true;
        }
        num--;
-       item = NEXTVAL(item); 
+       item = NEXTVAL(item);
    }
 
    return false;
 }
 
 Datum
-_ltree_isparent(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   ltree       *query = PG_GETARG_LTREE(1);
-   bool res = array_iterator( la, ltree_isparent, (void*)query, NULL );
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+_ltree_isparent(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   ltree      *query = PG_GETARG_LTREE(1);
+   bool        res = array_iterator(la, ltree_isparent, (void *) query, NULL);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_BOOL(res);
 }
 
 Datum
-_ltree_r_isparent(PG_FUNCTION_ARGS) {
-   PG_RETURN_DATUM( DirectFunctionCall2( _ltree_isparent,
-       PG_GETARG_DATUM(1),
-       PG_GETARG_DATUM(0)
-   ) );
+_ltree_r_isparent(PG_FUNCTION_ARGS)
+{
+   PG_RETURN_DATUM(DirectFunctionCall2(_ltree_isparent,
+                                       PG_GETARG_DATUM(1),
+                                       PG_GETARG_DATUM(0)
+                                       ));
 }
 
 Datum
-_ltree_risparent(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   ltree       *query = PG_GETARG_LTREE(1);
-   bool res = array_iterator( la, ltree_risparent, (void*)query, NULL );
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+_ltree_risparent(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   ltree      *query = PG_GETARG_LTREE(1);
+   bool        res = array_iterator(la, ltree_risparent, (void *) query, NULL);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_BOOL(res);
 }
 
 Datum
-_ltree_r_risparent(PG_FUNCTION_ARGS) {
-   PG_RETURN_DATUM( DirectFunctionCall2( _ltree_risparent,
-       PG_GETARG_DATUM(1),
-       PG_GETARG_DATUM(0)
-   ) );
+_ltree_r_risparent(PG_FUNCTION_ARGS)
+{
+   PG_RETURN_DATUM(DirectFunctionCall2(_ltree_risparent,
+                                       PG_GETARG_DATUM(1),
+                                       PG_GETARG_DATUM(0)
+                                       ));
 }
 
 Datum
-_ltq_regex(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   lquery      *query = PG_GETARG_LQUERY(1);
-   bool res = array_iterator( la, ltq_regex, (void*)query, NULL );
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+_ltq_regex(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   lquery     *query = PG_GETARG_LQUERY(1);
+   bool        res = array_iterator(la, ltq_regex, (void *) query, NULL);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_BOOL(res);
 }
 
 Datum
-_ltq_rregex(PG_FUNCTION_ARGS) {
-   PG_RETURN_DATUM( DirectFunctionCall2( _ltq_regex,
-       PG_GETARG_DATUM(1),
-       PG_GETARG_DATUM(0)
-   ) );
+_ltq_rregex(PG_FUNCTION_ARGS)
+{
+   PG_RETURN_DATUM(DirectFunctionCall2(_ltq_regex,
+                                       PG_GETARG_DATUM(1),
+                                       PG_GETARG_DATUM(0)
+                                       ));
 }
 
-Datum   
-_ltxtq_exec(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   ltxtquery   *query = PG_GETARG_LTXTQUERY(1);
-   bool res = array_iterator( la, ltxtq_exec, (void*)query, NULL );
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+Datum
+_ltxtq_exec(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   ltxtquery  *query = PG_GETARG_LTXTQUERY(1);
+   bool        res = array_iterator(la, ltxtq_exec, (void *) query, NULL);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_BOOL(res);
 }
 
 Datum
-_ltxtq_rexec(PG_FUNCTION_ARGS) {
-   PG_RETURN_DATUM( DirectFunctionCall2( _ltxtq_exec,
-       PG_GETARG_DATUM(1),
-       PG_GETARG_DATUM(0)
-   ) );
+_ltxtq_rexec(PG_FUNCTION_ARGS)
+{
+   PG_RETURN_DATUM(DirectFunctionCall2(_ltxtq_exec,
+                                       PG_GETARG_DATUM(1),
+                                       PG_GETARG_DATUM(0)
+                                       ));
 }
 
 
-Datum 
-_ltree_extract_isparent(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   ltree       *query = PG_GETARG_LTREE(1);
-   ltree       *found,*item;
-
-   if ( !array_iterator( la, ltree_isparent, (void*)query, &found )  ) {
-       PG_FREE_IF_COPY(la,0);
-       PG_FREE_IF_COPY(query,1);
+Datum
+_ltree_extract_isparent(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   ltree      *query = PG_GETARG_LTREE(1);
+   ltree      *found,
+              *item;
+
+   if (!array_iterator(la, ltree_isparent, (void *) query, &found))
+   {
+       PG_FREE_IF_COPY(la, 0);
+       PG_FREE_IF_COPY(query, 1);
        PG_RETURN_NULL();
    }
 
-   item = (ltree*)palloc( found->len );
-   memcpy( item, found, found->len );  
-   
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+   item = (ltree *) palloc(found->len);
+   memcpy(item, found, found->len);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_POINTER(item);
 }
 
-Datum 
-_ltree_extract_risparent(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   ltree       *query = PG_GETARG_LTREE(1);
-   ltree       *found,*item;
-
-   if ( !array_iterator( la, ltree_risparent, (void*)query, &found )  ) {
-       PG_FREE_IF_COPY(la,0);
-       PG_FREE_IF_COPY(query,1);
+Datum
+_ltree_extract_risparent(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   ltree      *query = PG_GETARG_LTREE(1);
+   ltree      *found,
+              *item;
+
+   if (!array_iterator(la, ltree_risparent, (void *) query, &found))
+   {
+       PG_FREE_IF_COPY(la, 0);
+       PG_FREE_IF_COPY(query, 1);
        PG_RETURN_NULL();
    }
 
-   item = (ltree*)palloc( found->len );
-   memcpy( item, found, found->len );  
-   
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+   item = (ltree *) palloc(found->len);
+   memcpy(item, found, found->len);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_POINTER(item);
 }
 
-Datum 
-_ltq_extract_regex(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   lquery      *query = PG_GETARG_LQUERY(1);
-   ltree       *found,*item;
-
-   if ( !array_iterator( la, ltq_regex, (void*)query, &found )  ) {
-       PG_FREE_IF_COPY(la,0);
-       PG_FREE_IF_COPY(query,1);
+Datum
+_ltq_extract_regex(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   lquery     *query = PG_GETARG_LQUERY(1);
+   ltree      *found,
+              *item;
+
+   if (!array_iterator(la, ltq_regex, (void *) query, &found))
+   {
+       PG_FREE_IF_COPY(la, 0);
+       PG_FREE_IF_COPY(query, 1);
        PG_RETURN_NULL();
    }
 
-   item = (ltree*)palloc( found->len );
-   memcpy( item, found, found->len );  
-   
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+   item = (ltree *) palloc(found->len);
+   memcpy(item, found, found->len);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_POINTER(item);
 }
 
-Datum 
-_ltxtq_extract_exec(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   ltxtquery   *query = PG_GETARG_LTXTQUERY(1);
-   ltree       *found,*item;
-
-   if ( !array_iterator( la, ltxtq_exec, (void*)query, &found )  ) {
-       PG_FREE_IF_COPY(la,0);
-       PG_FREE_IF_COPY(query,1);
+Datum
+_ltxtq_extract_exec(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   ltxtquery  *query = PG_GETARG_LTXTQUERY(1);
+   ltree      *found,
+              *item;
+
+   if (!array_iterator(la, ltxtq_exec, (void *) query, &found))
+   {
+       PG_FREE_IF_COPY(la, 0);
+       PG_FREE_IF_COPY(query, 1);
        PG_RETURN_NULL();
    }
 
-   item = (ltree*)palloc( found->len );
-   memcpy( item, found, found->len );  
-   
-   PG_FREE_IF_COPY(la,0);
-   PG_FREE_IF_COPY(query,1);
+   item = (ltree *) palloc(found->len);
+   memcpy(item, found, found->len);
+
+   PG_FREE_IF_COPY(la, 0);
+   PG_FREE_IF_COPY(query, 1);
    PG_RETURN_POINTER(item);
 }
 
 Datum
-_lca(PG_FUNCTION_ARGS) {
-   ArrayType   *la = PG_GETARG_ARRAYTYPE_P(0);
-   int num=ArrayGetNItems( ARR_NDIM(la), ARR_DIMS(la));
-   ltree   *item = (ltree*)ARR_DATA_PTR(la);
-        ltree **a,*res;
-
-        a=(ltree**)palloc( sizeof(ltree*) * num );
-   while( num>0 ) {
+_lca(PG_FUNCTION_ARGS)
+{
+   ArrayType  *la = PG_GETARG_ARRAYTYPE_P(0);
+   int         num = ArrayGetNItems(ARR_NDIM(la), ARR_DIMS(la));
+   ltree      *item = (ltree *) ARR_DATA_PTR(la);
+   ltree     **a,
+              *res;
+
+   a = (ltree **) palloc(sizeof(ltree *) * num);
+   while (num > 0)
+   {
        num--;
        a[num] = item;
        item = NEXTVAL(item);
    }
-        res = lca_inner(a, ArrayGetNItems( ARR_NDIM(la), ARR_DIMS(la)));
+   res = lca_inner(a, ArrayGetNItems(ARR_NDIM(la), ARR_DIMS(la)));
    pfree(a);
 
-   PG_FREE_IF_COPY(la,0);
+   PG_FREE_IF_COPY(la, 0);
 
-        if ( res )
-                PG_RETURN_POINTER(res);
-        else
-                PG_RETURN_NULL();
+   if (res)
+       PG_RETURN_POINTER(res);
+   else
+       PG_RETURN_NULL();
 }
-
index 5cbde4135bf1aa2d6d3202db1ae89b355a43b0e7..8a4f27b30666e5dfd44988af3ce1eb35a978a712 100644 (file)
@@ -105,6 +105,6 @@ ltree_crc32_sz(char *buf, int size)
    len = 0;
    nr = size;
    for (len += nr, p = buf; nr--; ++p)
-       _CRC32_(crc, TOLOWER((unsigned int)*p));
+       _CRC32_(crc, TOLOWER((unsigned int) *p));
    return ~crc;
 }
index 83b380d97ae2227747abb6578d6cabd784a626e0..e24cc8559fcc16c6773ce6f0e1b28fe85159854c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * op function for ltree and lquery 
+ * op function for ltree and lquery
  * Teodor Sigaev <teodor@stack.net>
  */
 
@@ -9,27 +9,29 @@
 PG_FUNCTION_INFO_V1(ltq_regex);
 PG_FUNCTION_INFO_V1(ltq_rregex);
 
-typedef struct {
-   lquery_level    *q;
-   int     nq;
-   ltree_level *t;
-   int     nt;
-   int     posq;
-   int     post;
-} FieldNot;
+typedef struct
+{
+   lquery_level *q;
+   int         nq;
+   ltree_level *t;
+   int         nt;
+   int         posq;
+   int         post;
+}  FieldNot;
 
 static char *
-getlexem(char *start, char *end, int *len) {
-   char *ptr;
-   
-   while( start<end && *start == '_' )
+getlexem(char *start, char *end, int *len)
+{
+   char       *ptr;
+
+   while (start < end && *start == '_')
        start++;
 
    ptr = start;
-   if ( ptr == end )
+   if (ptr == end)
        return NULL;
 
-   while( ptr < end && *ptr != '_') 
+   while (ptr < end && *ptr != '_')
        ptr++;
 
    *len = ptr - start;
@@ -37,31 +39,36 @@ getlexem(char *start, char *end, int *len) {
 }
 
 bool
-compare_subnode( ltree_level *t, char *qn, int len, int (*cmpptr)(const char *,const char *,size_t), bool anyend ) {
-   char *endt = t->name + t->len;
-   char *endq = qn + len;
-   char *tn;
-   int lent,lenq;
-   bool    isok;
-
-   while( (qn=getlexem(qn,endq,&lenq)) != NULL ) {
-       tn=t->name;
+           compare_subnode(ltree_level * t, char *qn, int len, int (*cmpptr) (const char *, const char *, size_t), bool anyend)
+{
+   char       *endt = t->name + t->len;
+   char       *endq = qn + len;
+   char       *tn;
+   int         lent,
+               lenq;
+   bool        isok;
+
+   while ((qn = getlexem(qn, endq, &lenq)) != NULL)
+   {
+       tn = t->name;
        isok = false;
-       while( (tn=getlexem(tn,endt,&lent)) != NULL ) {
-           if ( 
+       while ((tn = getlexem(tn, endt, &lent)) != NULL)
+       {
+           if (
                (
-                   lent == lenq ||
-                   ( lent > lenq && anyend )
-               ) &&
-               (*cmpptr)(qn,tn,lenq) == 0 ) {
-       
-               isok = true;    
+                lent == lenq ||
+                (lent > lenq && anyend)
+                ) &&
+               (*cmpptr) (qn, tn, lenq) == 0)
+           {
+
+               isok = true;
                break;
            }
            tn += lent;
        }
 
-       if ( !isok )
+       if (!isok)
            return false;
        qn += lenq;
    }
@@ -70,27 +77,32 @@ compare_subnode( ltree_level *t, char *qn, int len, int (*cmpptr)(const char *,c
 }
 
 static bool
-checkLevel( lquery_level *curq, ltree_level *curt ) {
-   int (*cmpptr)(const char *,const char *,size_t);
+checkLevel(lquery_level * curq, ltree_level * curt)
+{
+   int         (*cmpptr) (const char *, const char *, size_t);
    lquery_variant *curvar = LQL_FIRST(curq);
-   int i;
-   
-   for(i=0;i<curq->numvar;i++) {
-       cmpptr = ( curvar->flag & LVAR_INCASE ) ? strncasecmp : strncmp;
+   int         i;
 
-       if ( curvar->flag & LVAR_SUBLEXEM ) {
-           if ( compare_subnode(curt, curvar->name, curvar->len, cmpptr, (curvar->flag & LVAR_ANYEND) ) )
+   for (i = 0; i < curq->numvar; i++)
+   {
+       cmpptr = (curvar->flag & LVAR_INCASE) ? strncasecmp : strncmp;
+
+       if (curvar->flag & LVAR_SUBLEXEM)
+       {
+           if (compare_subnode(curt, curvar->name, curvar->len, cmpptr, (curvar->flag & LVAR_ANYEND)))
                return true;
-       } else if ( 
-           ( 
-               curvar->len == curt->len || 
-               ( curt->len > curvar->len && (curvar->flag & LVAR_ANYEND) )  
-           ) && 
-           (*cmpptr)( curvar->name, curt->name, curvar->len) == 0 ) {
+       }
+       else if (
+                (
+                 curvar->len == curt->len ||
+               (curt->len > curvar->len && (curvar->flag & LVAR_ANYEND))
+                 ) &&
+                (*cmpptr) (curvar->name, curt->name, curvar->len) == 0)
+       {
 
            return true;
        }
-       curvar = LVAR_NEXT(curvar); 
+       curvar = LVAR_NEXT(curvar);
    }
    return false;
 }
@@ -102,78 +114,97 @@ printFieldNot(FieldNot *fn ) {
        elog(NOTICE,"posQ:%d lenQ:%d posT:%d lenT:%d", fn->posq,fn->nq,fn->post,fn->nt);
        fn++;
    }
-} 
+}
 */
 
 static bool
-checkCond( lquery_level *curq, int query_numlevel, ltree_level *curt, int tree_numlevel, FieldNot *ptr ) {
-   uint32 low_pos=0,high_pos=0,cur_tpos=0;
-   int tlen = tree_numlevel, qlen = query_numlevel;
-   int isok;
-   lquery_level *prevq=NULL;
-   ltree_level  *prevt=NULL;
-
-   while( tlen >0 && qlen>0 ) {
-       if ( curq->numvar ) {
+checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_numlevel, FieldNot * ptr)
+{
+   uint32      low_pos = 0,
+               high_pos = 0,
+               cur_tpos = 0;
+   int         tlen = tree_numlevel,
+               qlen = query_numlevel;
+   int         isok;
+   lquery_level *prevq = NULL;
+   ltree_level *prevt = NULL;
+
+   while (tlen > 0 && qlen > 0)
+   {
+       if (curq->numvar)
+       {
            prevt = curt;
-           while ( cur_tpos < low_pos ) {
+           while (cur_tpos < low_pos)
+           {
                curt = LEVEL_NEXT(curt);
                tlen--;
                cur_tpos++;
-               if ( tlen==0 )
+               if (tlen == 0)
                    return false;
-               if ( ptr && ptr->q )
+               if (ptr && ptr->q)
                    ptr->nt++;
            }
-           
-           if ( ptr && curq->flag & LQL_NOT ) {
-               if ( !(prevq && prevq->numvar == 0) )
+
+           if (ptr && curq->flag & LQL_NOT)
+           {
+               if (!(prevq && prevq->numvar == 0))
                    prevq = curq;
-               if ( ptr->q == NULL ) {
+               if (ptr->q == NULL)
+               {
                    ptr->t = prevt;
                    ptr->q = prevq;
-                   ptr->nt=1;
-                   ptr->nq=1 + ( (prevq==curq) ? 0 : 1 );
-                   ptr->posq = query_numlevel - qlen - ( (prevq==curq) ? 0 : 1 ); 
+                   ptr->nt = 1;
+                   ptr->nq = 1 + ((prevq == curq) ? 0 : 1);
+                   ptr->posq = query_numlevel - qlen - ((prevq == curq) ? 0 : 1);
                    ptr->post = cur_tpos;
-               } else {
+               }
+               else
+               {
                    ptr->nt++;
                    ptr->nq++;
                }
 
-               if ( qlen == 1 && ptr->q->numvar==0 )
-                   ptr->nt = tree_numlevel - ptr->post; 
+               if (qlen == 1 && ptr->q->numvar == 0)
+                   ptr->nt = tree_numlevel - ptr->post;
                curt = LEVEL_NEXT(curt);
                tlen--;
                cur_tpos++;
-               if ( high_pos < cur_tpos )
+               if (high_pos < cur_tpos)
                    high_pos++;
-           } else { 
+           }
+           else
+           {
                isok = false;
-               while( cur_tpos <= high_pos && tlen > 0 && !isok) {
+               while (cur_tpos <= high_pos && tlen > 0 && !isok)
+               {
                    isok = checkLevel(curq, curt);
                    curt = LEVEL_NEXT(curt);
                    tlen--;
                    cur_tpos++;
-                   if ( !isok && ptr )
+                   if (!isok && ptr)
                        ptr->nt++;
                }
-               if ( !isok )
+               if (!isok)
                    return false;
 
-               if (ptr && ptr->q) {
-                   if ( checkCond(ptr->q,ptr->nq,ptr->t,ptr->nt,NULL) )
+               if (ptr && ptr->q)
+               {
+                   if (checkCond(ptr->q, ptr->nq, ptr->t, ptr->nt, NULL))
                        return false;
                    ptr->q = NULL;
                }
-               low_pos=cur_tpos; high_pos=cur_tpos;
+               low_pos = cur_tpos;
+               high_pos = cur_tpos;
            }
-       } else {
+       }
+       else
+       {
            low_pos = cur_tpos + curq->low;
            high_pos = cur_tpos + curq->high;
-           if ( ptr && ptr->q ) {
+           if (ptr && ptr->q)
+           {
                ptr->nq++;
-               if ( qlen==1 )
+               if (qlen == 1)
                    ptr->nt = tree_numlevel - ptr->post;
            }
        }
@@ -181,16 +212,20 @@ checkCond( lquery_level *curq, int query_numlevel, ltree_level *curt, int tree_n
        prevq = curq;
        curq = LQL_NEXT(curq);
        qlen--;
-   }   
+   }
 
-   if ( low_pos > tree_numlevel || tree_numlevel > high_pos )
+   if (low_pos > tree_numlevel || tree_numlevel > high_pos)
        return false;
 
-   while( qlen>0 ) {
-       if ( curq->numvar ) {
-           if ( ! (curq->flag & LQL_NOT) )
+   while (qlen > 0)
+   {
+       if (curq->numvar)
+       {
+           if (!(curq->flag & LQL_NOT))
                return false;
-       } else {
+       }
+       else
+       {
            low_pos = cur_tpos + curq->low;
            high_pos = cur_tpos + curq->high;
        }
@@ -199,42 +234,47 @@ checkCond( lquery_level *curq, int query_numlevel, ltree_level *curt, int tree_n
        qlen--;
    }
 
-   if ( low_pos > tree_numlevel || tree_numlevel > high_pos )
+   if (low_pos > tree_numlevel || tree_numlevel > high_pos)
        return false;
-   
-   if ( ptr && ptr->q && checkCond(ptr->q,ptr->nq,ptr->t,ptr->nt,NULL) )
+
+   if (ptr && ptr->q && checkCond(ptr->q, ptr->nq, ptr->t, ptr->nt, NULL))
        return false;
-   
+
    return true;
 }
 
 Datum
-ltq_regex(PG_FUNCTION_ARGS) {
-   ltree *tree = PG_GETARG_LTREE(0);
-   lquery *query = PG_GETARG_LQUERY(1);
-   bool res= false;
+ltq_regex(PG_FUNCTION_ARGS)
+{
+   ltree      *tree = PG_GETARG_LTREE(0);
+   lquery     *query = PG_GETARG_LQUERY(1);
+   bool        res = false;
 
-   if ( query->flag & LQUERY_HASNOT ) {
+   if (query->flag & LQUERY_HASNOT)
+   {
        FieldNot    fn;
 
-       fn.q=NULL;
+       fn.q = NULL;
 
-       res = checkCond( LQUERY_FIRST(query), query->numlevel, 
-           LTREE_FIRST(tree), tree->numlevel, &fn );
-   } else {
-       res = checkCond( LQUERY_FIRST(query), query->numlevel, 
-           LTREE_FIRST(tree), tree->numlevel, NULL ); 
+       res = checkCond(LQUERY_FIRST(query), query->numlevel,
+                       LTREE_FIRST(tree), tree->numlevel, &fn);
+   }
+   else
+   {
+       res = checkCond(LQUERY_FIRST(query), query->numlevel,
+                       LTREE_FIRST(tree), tree->numlevel, NULL);
    }
 
-        PG_FREE_IF_COPY(tree,0);
-        PG_FREE_IF_COPY(query,1);
-        PG_RETURN_BOOL(res);
+   PG_FREE_IF_COPY(tree, 0);
+   PG_FREE_IF_COPY(query, 1);
+   PG_RETURN_BOOL(res);
 }
 
-Datum 
-ltq_rregex(PG_FUNCTION_ARGS) {
-   PG_RETURN_DATUM( DirectFunctionCall2( ltq_regex,
-       PG_GETARG_DATUM(1),
-       PG_GETARG_DATUM(0)
-   ) );
+Datum
+ltq_rregex(PG_FUNCTION_ARGS)
+{
+   PG_RETURN_DATUM(DirectFunctionCall2(ltq_regex,
+                                       PG_GETARG_DATUM(1),
+                                       PG_GETARG_DATUM(0)
+                                       ));
 }
index 0c92deeea4aa9271c1cbfffcb045c05495db7bf8..606b3e3a74756d67079c8d24122abc9c34fe24ba 100644 (file)
@@ -6,19 +6,21 @@
 #include "utils/palloc.h"
 #include "utils/builtins.h"
 
-typedef struct {
-   uint8   len;
-   char    name[1];
-} ltree_level;
+typedef struct
+{
+   uint8       len;
+   char        name[1];
+}  ltree_level;
 
-#define LEVEL_HDRSIZE   (sizeof(uint8))
+#define LEVEL_HDRSIZE  (sizeof(uint8))
 #define LEVEL_NEXT(x)  ( (ltree_level*)( ((char*)(x)) + MAXALIGN(((ltree_level*)(x))->len + LEVEL_HDRSIZE) ) )
 
-typedef struct {
-   int32   len;
-   uint16  numlevel;
-   char    data[1];
-} ltree;
+typedef struct
+{
+   int32       len;
+   uint16      numlevel;
+   char        data[1];
+}  ltree;
 
 #define LTREE_HDRSIZE  MAXALIGN( sizeof(int32) + sizeof(uint16) )
 #define LTREE_FIRST(x) ( (ltree_level*)( ((char*)(x))+LTREE_HDRSIZE ) )
@@ -26,31 +28,33 @@ typedef struct {
 
 /* lquery */
 
-typedef struct {
-   int4    val;    
-   uint8   len;
-   uint8   flag;
-   char    name[1];
-} lquery_variant;
+typedef struct
+{
+   int4        val;
+   uint8       len;
+   uint8       flag;
+   char        name[1];
+}  lquery_variant;
 
 #define LVAR_HDRSIZE   MAXALIGN(sizeof(uint8)*2 + sizeof(int4))
 #define LVAR_NEXT(x)   ( (lquery_variant*)( ((char*)(x)) + MAXALIGN(((lquery_variant*)(x))->len) + LVAR_HDRSIZE ) )
 
-#define LVAR_ANYEND    0x01
-#define LVAR_INCASE    0x02
+#define LVAR_ANYEND 0x01
+#define LVAR_INCASE 0x02
 #define LVAR_SUBLEXEM  0x04
 
-typedef struct {
-   uint16  totallen;
-   uint16  flag;
-   uint16  numvar;
-   uint16  low;
-   uint16  high;
-   char    variants[1];
-} lquery_level;
-
-#define LQL_HDRSIZE    MAXALIGN( sizeof(uint16)*5 )
-#define LQL_NEXT(x)    ( (lquery_level*)( ((char*)(x)) + MAXALIGN(((lquery_level*)(x))->totallen) ) )
+typedef struct
+{
+   uint16      totallen;
+   uint16      flag;
+   uint16      numvar;
+   uint16      low;
+   uint16      high;
+   char        variants[1];
+}  lquery_level;
+
+#define LQL_HDRSIZE MAXALIGN( sizeof(uint16)*5 )
+#define LQL_NEXT(x) ( (lquery_level*)( ((char*)(x)) + MAXALIGN(((lquery_level*)(x))->totallen) ) )
 #define LQL_FIRST(x)   ( (lquery_variant*)( ((char*)(x))+LQL_HDRSIZE ) )
 
 #define LQL_NOT        0x10
@@ -59,29 +63,30 @@ typedef struct {
 #else
 #define FLG_CANLOOKSIGN(x) ( ( (x) & ( LQL_NOT | LVAR_ANYEND | LVAR_SUBLEXEM | LVAR_INCASE ) ) == 0 )
 #endif
-#define LQL_CANLOOKSIGN(x) FLG_CANLOOKSIGN( ((lquery_level*)(x))->flag ) 
-
-typedef struct {
-   int32   len;
-   uint16  numlevel;
-   uint16  firstgood;
-   uint16  flag;
-   char    data[1];
-} lquery; 
+#define LQL_CANLOOKSIGN(x) FLG_CANLOOKSIGN( ((lquery_level*)(x))->flag )
 
-#define LQUERY_HDRSIZE   MAXALIGN( sizeof(int32) + 3*sizeof(uint16) )
+typedef struct
+{
+   int32       len;
+   uint16      numlevel;
+   uint16      firstgood;
+   uint16      flag;
+   char        data[1];
+}  lquery;
+
+#define LQUERY_HDRSIZE  MAXALIGN( sizeof(int32) + 3*sizeof(uint16) )
 #define LQUERY_FIRST(x)   ( (lquery_level*)( ((char*)(x))+LQUERY_HDRSIZE ) )
 
 #define LQUERY_HASNOT      0x01
 
-#ifndef max  
-#define max(a,b)                ((a) >  (b) ? (a) : (b))
+#ifndef max
+#define max(a,b)               ((a) >  (b) ? (a) : (b))
 #endif
 #ifndef min
-#define min(a,b)                ((a) <= (b) ? (a) : (b))
+#define min(a,b)               ((a) <= (b) ? (a) : (b))
 #endif
 #ifndef abs
-#define abs(a)                  ((a) <  (0) ? -(a) : (a))
+#define abs(a)                 ((a) <  (0) ? -(a) : (a))
 #endif
 #define ISALNUM(x) ( isalnum((unsigned int)(x)) || (x) == '_' )
 
@@ -93,75 +98,75 @@ typedef struct {
  */
 typedef struct ITEM
 {
-        int2            type;
-        int2            left;
-        int4            val;
+   int2        type;
+   int2        left;
+   int4        val;
    uint8       flag;
-        /* user-friendly value */
-        uint8          length;
-        uint16          distance;
-}       ITEM;
+   /* user-friendly value */
+   uint8       length;
+   uint16      distance;
+}  ITEM;
 
 /*
  *Storage:
- *      (len)(size)(array of ITEM)(array of operand in user-friendly form)
+ *     (len)(size)(array of ITEM)(array of operand in user-friendly form)
  */
 typedef struct
 {
-        int4            len;
-        int4            size;
-        char            data[1];
-}       ltxtquery;
+   int4        len;
+   int4        size;
+   char        data[1];
+}  ltxtquery;
 
-#define HDRSIZEQT       MAXALIGN( 2*sizeof(int4) )
-#define COMPUTESIZE(size,lenofoperand)  ( HDRSIZEQT + size * sizeof(ITEM) + lenofoperand )
+#define HDRSIZEQT      MAXALIGN( 2*sizeof(int4) )
+#define COMPUTESIZE(size,lenofoperand) ( HDRSIZEQT + size * sizeof(ITEM) + lenofoperand )
 #define GETQUERY(x)  (ITEM*)( (char*)(x)+HDRSIZEQT )
-#define GETOPERAND(x)   ( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )
+#define GETOPERAND(x)  ( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )
 
 #define ISOPERATOR(x) ( (x)=='!' || (x)=='&' || (x)=='|' || (x)=='(' || (x)==')' )
 
-#define END                     0
-#define ERR                     1
-#define VAL                     2
-#define OPR                     3
-#define OPEN                    4
-#define CLOSE                   5
-#define VALTRUE                 6               /* for stop words */
-#define VALFALSE                7
+#define END                        0
+#define ERR                        1
+#define VAL                        2
+#define OPR                        3
+#define OPEN                   4
+#define CLOSE                  5
+#define VALTRUE                    6       /* for stop words */
+#define VALFALSE               7
 
 
 /* use in array iterator */
-Datum   ltree_isparent(PG_FUNCTION_ARGS);
-Datum   ltree_risparent(PG_FUNCTION_ARGS);
-Datum ltq_regex(PG_FUNCTION_ARGS);
-Datum ltq_rregex(PG_FUNCTION_ARGS);
-Datum      ltxtq_exec(PG_FUNCTION_ARGS);
-Datum      ltxtq_rexec(PG_FUNCTION_ARGS);
-Datum   _ltq_regex(PG_FUNCTION_ARGS);
-Datum   _ltq_rregex(PG_FUNCTION_ARGS);
-Datum   _ltxtq_exec(PG_FUNCTION_ARGS);
-Datum   _ltxtq_rexec(PG_FUNCTION_ARGS);
-Datum   _ltree_isparent(PG_FUNCTION_ARGS);
-Datum   _ltree_risparent(PG_FUNCTION_ARGS);
+Datum      ltree_isparent(PG_FUNCTION_ARGS);
+Datum      ltree_risparent(PG_FUNCTION_ARGS);
+Datum      ltq_regex(PG_FUNCTION_ARGS);
+Datum      ltq_rregex(PG_FUNCTION_ARGS);
+Datum      ltxtq_exec(PG_FUNCTION_ARGS);
+Datum      ltxtq_rexec(PG_FUNCTION_ARGS);
+Datum      _ltq_regex(PG_FUNCTION_ARGS);
+Datum      _ltq_rregex(PG_FUNCTION_ARGS);
+Datum      _ltxtq_exec(PG_FUNCTION_ARGS);
+Datum      _ltxtq_rexec(PG_FUNCTION_ARGS);
+Datum      _ltree_isparent(PG_FUNCTION_ARGS);
+Datum      _ltree_risparent(PG_FUNCTION_ARGS);
 
 /* Concatenation functions */
-Datum   ltree_addltree(PG_FUNCTION_ARGS);
-Datum   ltree_addtext(PG_FUNCTION_ARGS);
-Datum   ltree_textadd(PG_FUNCTION_ARGS);
+Datum      ltree_addltree(PG_FUNCTION_ARGS);
+Datum      ltree_addtext(PG_FUNCTION_ARGS);
+Datum      ltree_textadd(PG_FUNCTION_ARGS);
 
 /* Util function */
-Datum ltree_in(PG_FUNCTION_ARGS);
+Datum      ltree_in(PG_FUNCTION_ARGS);
 
 bool ltree_execute(ITEM * curitem, void *checkval,
-                bool calcnot, bool (*chkcond) (void *checkval, ITEM * val));
+             bool calcnot, bool (*chkcond) (void *checkval, ITEM * val));
 
-int ltree_compare(const ltree *a, const ltree *b);
-bool inner_isparent(const ltree *c, const ltree *p);
-bool compare_subnode( ltree_level *t, char *q, int len, 
-   int (*cmpptr)(const char *,const char *,size_t), bool anyend );
-ltree* lca_inner(ltree** a, int len);
+int            ltree_compare(const ltree * a, const ltree * b);
+bool       inner_isparent(const ltree * c, const ltree * p);
+bool compare_subnode(ltree_level * t, char *q, int len,
+       int (*cmpptr) (const char *, const char *, size_t), bool anyend);
+ltree     *lca_inner(ltree ** a, int len);
 
-#define PG_GETARG_LTREE(x)  ((ltree*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
+#define PG_GETARG_LTREE(x) ((ltree*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
 #define PG_GETARG_LQUERY(x) ((lquery*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
 #define PG_GETARG_LTXTQUERY(x) ((ltxtquery*)DatumGetPointer(PG_DETOAST_DATUM(PG_GETARG_DATUM(x))))
 
@@ -169,7 +174,7 @@ ltree* lca_inner(ltree** a, int len);
 
 #define BITBYTE 8
 #define SIGLENINT  8
-#define SIGLEN  ( sizeof(int4)*SIGLENINT )
+#define SIGLEN ( sizeof(int4)*SIGLENINT )
 #define SIGLENBIT (SIGLEN*BITBYTE)
 typedef unsigned char BITVEC[SIGLEN];
 typedef unsigned char *BITVECP;
@@ -195,43 +200,44 @@ typedef unsigned char *BITVECP;
 /*
  * type of index key for ltree. Tree are combined B-Tree and R-Tree
  * Storage:
- *     Leaf pages 
+ * Leaf pages
  *     (len)(flag)(ltree)
  * Non-Leaf
- *              (len)(flag)(sign)(left_ltree)(right_ltree)
+ *              (len)(flag)(sign)(left_ltree)(right_ltree)
  *     ALLTRUE: (len)(flag)(left_ltree)(right_ltree)
- * 
+ *
  */
 
-typedef struct {
-   int4 len;
-   uint32  flag;
-   char    data[1];
-} ltree_gist;
-
-#define    LTG_ONENODE 0x01
-#define    LTG_ALLTRUE 0x02
-#define    LTG_NORIGHT 0x04
-
-#define LTG_HDRSIZE    MAXALIGN( sizeof(int4) + sizeof(uint32) )
-#define LTG_SIGN(x)    ( (BITVECP)( ((char*)(x))+LTG_HDRSIZE ) ) 
-#define LTG_NODE(x)    ( (ltree*)( ((char*)(x))+LTG_HDRSIZE ) )
-#define LTG_ISONENODE(x) ( ((ltree_gist*)(x))->flag & LTG_ONENODE ) 
-#define LTG_ISALLTRUE(x) ( ((ltree_gist*)(x))->flag & LTG_ALLTRUE ) 
-#define LTG_ISNORIGHT(x) ( ((ltree_gist*)(x))->flag & LTG_NORIGHT ) 
+typedef struct
+{
+   int4        len;
+   uint32      flag;
+   char        data[1];
+}  ltree_gist;
+
+#define LTG_ONENODE 0x01
+#define LTG_ALLTRUE 0x02
+#define LTG_NORIGHT 0x04
+
+#define LTG_HDRSIZE MAXALIGN( sizeof(int4) + sizeof(uint32) )
+#define LTG_SIGN(x) ( (BITVECP)( ((char*)(x))+LTG_HDRSIZE ) )
+#define LTG_NODE(x) ( (ltree*)( ((char*)(x))+LTG_HDRSIZE ) )
+#define LTG_ISONENODE(x) ( ((ltree_gist*)(x))->flag & LTG_ONENODE )
+#define LTG_ISALLTRUE(x) ( ((ltree_gist*)(x))->flag & LTG_ALLTRUE )
+#define LTG_ISNORIGHT(x) ( ((ltree_gist*)(x))->flag & LTG_NORIGHT )
 #define LTG_LNODE(x)   ( (ltree*)( ( ((char*)(x))+LTG_HDRSIZE ) + ( LTG_ISALLTRUE(x) ? 0 : SIGLEN ) ) )
 #define LTG_RENODE(x)  ( (ltree*)( ((char*)LTG_LNODE(x)) + LTG_LNODE(x)->len) )
 #define LTG_RNODE(x)   ( LTG_ISNORIGHT(x) ? LTG_LNODE(x) : LTG_RENODE(x) )
 
-#define LTG_GETLNODE(x)    ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_LNODE(x) ) 
-#define LTG_GETRNODE(x)    ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_RNODE(x) ) 
+#define LTG_GETLNODE(x) ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_LNODE(x) )
+#define LTG_GETRNODE(x) ( LTG_ISONENODE(x) ? LTG_NODE(x) : LTG_RNODE(x) )
 
 
 /* GiST support for ltree[] */
 
-#define ASIGLENINT     (2*SIGLENINT)
+#define ASIGLENINT (2*SIGLENINT)
 #define ASIGLEN        (sizeof(int4)*ASIGLENINT)
-#define    ASIGLENBIT (ASIGLEN*BITBYTE)
+#define ASIGLENBIT (ASIGLEN*BITBYTE)
 typedef unsigned char ABITVEC[ASIGLEN];
 
 #define ALOOPBYTE(a) \
@@ -249,4 +255,3 @@ typedef unsigned char ABITVEC[ASIGLEN];
 /* type of key is the same to ltree_gist */
 
 #endif
-
index 5a4c7bbf5177b3e0b994df12ea23bdef2e11236d..5c5f4c7d6dc669f92de595af0145efa5bfc5093a 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * GiST support for ltree 
+ * GiST support for ltree
  * Teodor Sigaev <teodor@stack.net>
  */
 
 
 #include "crc32.h"
 
-PG_FUNCTION_INFO_V1( ltree_gist_in );
-Datum   ltree_gist_in(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_gist_out );
-Datum   ltree_gist_out(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(ltree_gist_in);
+Datum      ltree_gist_in(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_gist_out);
+Datum      ltree_gist_out(PG_FUNCTION_ARGS);
 
 Datum
-ltree_gist_in(PG_FUNCTION_ARGS) {
-   elog(ERROR,"Unimplemented");
+ltree_gist_in(PG_FUNCTION_ARGS)
+{
+   elog(ERROR, "Unimplemented");
    PG_RETURN_DATUM(0);
 }
 
 Datum
-ltree_gist_out(PG_FUNCTION_ARGS) {
-   elog(ERROR,"Unimplemented");
+ltree_gist_out(PG_FUNCTION_ARGS)
+{
+   elog(ERROR, "Unimplemented");
    PG_RETURN_DATUM(0);
 }
 
-PG_FUNCTION_INFO_V1( ltree_compress );
-Datum   ltree_compress(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_decompress );
-Datum   ltree_decompress(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_same );
-Datum   ltree_same(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_union );
-Datum   ltree_union(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_penalty );
-Datum   ltree_penalty(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_picksplit );
-Datum   ltree_picksplit(PG_FUNCTION_ARGS);
-PG_FUNCTION_INFO_V1( ltree_consistent );
-Datum   ltree_consistent(PG_FUNCTION_ARGS);
+PG_FUNCTION_INFO_V1(ltree_compress);
+Datum      ltree_compress(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_decompress);
+Datum      ltree_decompress(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_same);
+Datum      ltree_same(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_union);
+Datum      ltree_union(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_penalty);
+Datum      ltree_penalty(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_picksplit);
+Datum      ltree_picksplit(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ltree_consistent);
+Datum      ltree_consistent(PG_FUNCTION_ARGS);
 
 #define ISEQ(a,b)  ( (a)->numlevel == (b)->numlevel && ltree_compare(a,b)==0 )
 #define GETENTRY(vec,pos) ((ltree_gist *) DatumGetPointer(((GISTENTRY *) VARDATA(vec))[(pos)].key))
 
-Datum   
-ltree_compress(PG_FUNCTION_ARGS) {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
+Datum
+ltree_compress(PG_FUNCTION_ARGS)
+{
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
    GISTENTRY  *retval = entry;
 
-   if ( entry->leafkey ) { /* ltree */
-       ltree_gist  *key;
-       ltree   *val = (ltree*)DatumGetPointer(PG_DETOAST_DATUM(entry->key));
-       int4 len = LTG_HDRSIZE + val->len;
+   if (entry->leafkey)
+   {                           /* ltree */
+       ltree_gist *key;
+       ltree      *val = (ltree *) DatumGetPointer(PG_DETOAST_DATUM(entry->key));
+       int4        len = LTG_HDRSIZE + val->len;
 
-       key = (ltree_gist*)palloc( len );
+       key = (ltree_gist *) palloc(len);
        key->len = len;
        key->flag = LTG_ONENODE;
-       memcpy( (void*)LTG_NODE(key), (void*)val, val->len);
+       memcpy((void *) LTG_NODE(key), (void *) val, val->len);
 
-       if ( PointerGetDatum(val) != entry->key )
+       if (PointerGetDatum(val) != entry->key)
            pfree(val);
 
-       retval = (GISTENTRY*)palloc( sizeof(GISTENTRY) );
+       retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
        gistentryinit(*retval, PointerGetDatum(key),
-           entry->rel, entry->page,
-           entry->offset, key->len, FALSE);
+                     entry->rel, entry->page,
+                     entry->offset, key->len, FALSE);
    }
    PG_RETURN_POINTER(retval);
 }
 
-Datum   
-ltree_decompress(PG_FUNCTION_ARGS) {
-   GISTENTRY *entry = (GISTENTRY *)PG_GETARG_POINTER(0);
-   ltree_gist *key = (ltree_gist*)DatumGetPointer( PG_DETOAST_DATUM(entry->key) );
+Datum
+ltree_decompress(PG_FUNCTION_ARGS)
+{
+   GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+   ltree_gist *key = (ltree_gist *) DatumGetPointer(PG_DETOAST_DATUM(entry->key));
+
+   if (PointerGetDatum(key) != entry->key)
+   {
+       GISTENTRY  *retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
 
-   if ( PointerGetDatum(key) != entry->key ) {
-       GISTENTRY *retval = (GISTENTRY*)palloc(sizeof(GISTENTRY));
        gistentryinit(*retval, PointerGetDatum(key),
-           entry->rel, entry->page,
-           entry->offset, key->len, FALSE);
+                     entry->rel, entry->page,
+                     entry->offset, key->len, FALSE);
        PG_RETURN_POINTER(retval);
    }
-    PG_RETURN_POINTER(entry);
+   PG_RETURN_POINTER(entry);
 }
 
-Datum   
-ltree_same(PG_FUNCTION_ARGS) {
-   ltree_gist* a=(ltree_gist*)PG_GETARG_POINTER(0);
-   ltree_gist* b=(ltree_gist*)PG_GETARG_POINTER(1);
-   bool *result = (bool *)PG_GETARG_POINTER(2);
+Datum
+ltree_same(PG_FUNCTION_ARGS)
+{
+   ltree_gist *a = (ltree_gist *) PG_GETARG_POINTER(0);
+   ltree_gist *b = (ltree_gist *) PG_GETARG_POINTER(1);
+   bool       *result = (bool *) PG_GETARG_POINTER(2);
 
    *result = false;
-   if ( LTG_ISONENODE(a) != LTG_ISONENODE(b) )
-       PG_RETURN_POINTER(result); 
-       
-   if ( LTG_ISONENODE(a) ) {
-       *result = ( ISEQ(LTG_NODE(a), LTG_NODE(b)) ) ? true : false;
-   } else {
-       int4 i;
-       BITVECP sa=LTG_SIGN(a), sb=LTG_SIGN(b);
-       if ( LTG_ISALLTRUE(a) != LTG_ISALLTRUE(b) ) 
-            PG_RETURN_POINTER(result);
-
-       if ( !ISEQ(LTG_LNODE(a), LTG_LNODE(b)) ) 
-           PG_RETURN_POINTER(result); 
-       if ( !ISEQ(LTG_RNODE(a), LTG_RNODE(b)) ) 
+   if (LTG_ISONENODE(a) != LTG_ISONENODE(b))
+       PG_RETURN_POINTER(result);
+
+   if (LTG_ISONENODE(a))
+       *result = (ISEQ(LTG_NODE(a), LTG_NODE(b))) ? true : false;
+   else
+   {
+       int4        i;
+       BITVECP     sa = LTG_SIGN(a),
+                   sb = LTG_SIGN(b);
+
+       if (LTG_ISALLTRUE(a) != LTG_ISALLTRUE(b))
+           PG_RETURN_POINTER(result);
+
+       if (!ISEQ(LTG_LNODE(a), LTG_LNODE(b)))
+           PG_RETURN_POINTER(result);
+       if (!ISEQ(LTG_RNODE(a), LTG_RNODE(b)))
            PG_RETURN_POINTER(result);
 
        *result = true;
-       if ( !LTG_ISALLTRUE(a) )
+       if (!LTG_ISALLTRUE(a))
            LOOPBYTE(
-               if ( sa[i] != sb[i] ) {
-                   *result = false;
-                   break;
-               }
-           );
+                    if (sa[i] != sb[i])
+                    {
+               *result = false;
+               break;
+           }
+       );
    }
-   PG_RETURN_POINTER(result); 
+
+   PG_RETURN_POINTER(result);
 }
 
 static void
-hashing(BITVECP sign, ltree *t) {
-   int tlen = t->numlevel;
+hashing(BITVECP sign, ltree * t)
+{
+   int         tlen = t->numlevel;
    ltree_level *cur = LTREE_FIRST(t);
-   int  hash;
+   int         hash;
 
-   while(tlen > 0) {
-       hash = ltree_crc32_sz( cur->name, cur->len );
-       HASH( sign, hash );
+   while (tlen > 0)
+   {
+       hash = ltree_crc32_sz(cur->name, cur->len);
+       HASH(sign, hash);
        cur = LEVEL_NEXT(cur);
        tlen--;
    }
 }
 
-Datum   
-ltree_union(PG_FUNCTION_ARGS) {
-   bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
-   int *size = (int *) PG_GETARG_POINTER(1);
-   BITVEC base;
-   int4 len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
-   int4 i,j;
-   ltree_gist  *result,*cur;
-   ltree   *left=NULL, *right=NULL, *curtree;
-   bool    isalltrue = false;
-   bool    isleqr;
-
-   MemSet( (void*)base, 0, sizeof(BITVEC) );
-   for(j=0;j<len;j++) {
+Datum
+ltree_union(PG_FUNCTION_ARGS)
+{
+   bytea      *entryvec = (bytea *) PG_GETARG_POINTER(0);
+   int        *size = (int *) PG_GETARG_POINTER(1);
+   BITVEC      base;
+   int4        len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
+   int4        i,
+               j;
+   ltree_gist *result,
+              *cur;
+   ltree      *left = NULL,
+              *right = NULL,
+              *curtree;
+   bool        isalltrue = false;
+   bool        isleqr;
+
+   MemSet((void *) base, 0, sizeof(BITVEC));
+   for (j = 0; j < len; j++)
+   {
        cur = GETENTRY(entryvec, j);
-       if ( LTG_ISONENODE(cur) ) {
+       if (LTG_ISONENODE(cur))
+       {
            curtree = LTG_NODE(cur);
-           hashing(base,curtree);
-           if ( !left || ltree_compare( left, curtree ) > 0 )
-               left =  curtree;
-           if ( !right || ltree_compare( right, curtree ) < 0 ) 
+           hashing(base, curtree);
+           if (!left || ltree_compare(left, curtree) > 0)
+               left = curtree;
+           if (!right || ltree_compare(right, curtree) < 0)
                right = curtree;
-       } else {
-           if ( isalltrue || LTG_ISALLTRUE(cur) ) 
+       }
+       else
+       {
+           if (isalltrue || LTG_ISALLTRUE(cur))
                isalltrue = true;
-           else { 
-               BITVECP sc=LTG_SIGN(cur);
+           else
+           {
+               BITVECP     sc = LTG_SIGN(cur);
+
                LOOPBYTE(
-                   ((unsigned char*)base)[i] |= sc[i];
+                        ((unsigned char *) base)[i] |= sc[i];
                );
            }
 
            curtree = LTG_LNODE(cur);
-           if ( !left || ltree_compare( left, curtree ) > 0 )
-               left =  curtree;
+           if (!left || ltree_compare(left, curtree) > 0)
+               left = curtree;
            curtree = LTG_RNODE(cur);
-           if ( !right || ltree_compare( right, curtree ) < 0 ) 
+           if (!right || ltree_compare(right, curtree) < 0)
                right = curtree;
-       } 
+       }
    }
-   
-   if ( isalltrue == false ) {
+
+   if (isalltrue == false)
+   {
        isalltrue = true;
        LOOPBYTE(
-           if ( ((unsigned char*)base)[i] != 0xff ) {
-               isalltrue = false;
-               break;
-           }
-       ); 
+                if (((unsigned char *) base)[i] != 0xff)
+                {
+           isalltrue = false;
+           break;
+       }
+       );
    }
 
-   isleqr = ( left==right || ISEQ(left,right) ) ? true : false; 
-   *size = LTG_HDRSIZE + ( (isalltrue) ? 0 : SIGLEN ) + left->len + ( (isleqr) ? 0 : right->len );
+   isleqr = (left == right || ISEQ(left, right)) ? true : false;
+   *size = LTG_HDRSIZE + ((isalltrue) ? 0 : SIGLEN) + left->len + ((isleqr) ? 0 : right->len);
 
-   result = (ltree_gist*)palloc( *size );
+   result = (ltree_gist *) palloc(*size);
    result->len = *size;
    result->flag = 0;
 
-   if ( isalltrue )
+   if (isalltrue)
        result->flag |= LTG_ALLTRUE;
    else
-       memcpy( (void*)LTG_SIGN(result), base, SIGLEN );
+       memcpy((void *) LTG_SIGN(result), base, SIGLEN);
 
-   memcpy( (void*)LTG_LNODE(result), (void*)left, left->len );
-   if ( isleqr )
+   memcpy((void *) LTG_LNODE(result), (void *) left, left->len);
+   if (isleqr)
        result->flag |= LTG_NORIGHT;
    else
-       memcpy( (void*)LTG_RNODE(result), (void*)right, right->len );
+       memcpy((void *) LTG_RNODE(result), (void *) right, right->len);
 
-   PG_RETURN_POINTER(result);  
+   PG_RETURN_POINTER(result);
 }
 
-Datum   
-ltree_penalty(PG_FUNCTION_ARGS) {
-   ltree_gist *origval = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(0) )->key );
-   ltree_gist *newval  = (ltree_gist*)DatumGetPointer( ( (GISTENTRY *)PG_GETARG_POINTER(1) )->key );
-   float  *penalty = (float *)    PG_GETARG_POINTER(2);
-   int4 cmpr,cmpl;
+Datum
+ltree_penalty(PG_FUNCTION_ARGS)
+{
+   ltree_gist *origval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
+   ltree_gist *newval = (ltree_gist *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
+   float      *penalty = (float *) PG_GETARG_POINTER(2);
+   int4        cmpr,
+               cmpl;
 
-   cmpl = ltree_compare( LTG_GETLNODE(origval), LTG_GETLNODE(newval) );
-   cmpr = ltree_compare( LTG_GETRNODE(newval),  LTG_GETRNODE(origval));
+   cmpl = ltree_compare(LTG_GETLNODE(origval), LTG_GETLNODE(newval));
+   cmpr = ltree_compare(LTG_GETRNODE(newval), LTG_GETRNODE(origval));
 
-   *penalty = max( cmpl, 0 ) + max( cmpr, 0 );
+   *penalty = max(cmpl, 0) + max(cmpr, 0);
 
    PG_RETURN_POINTER(penalty);
 }
 
 /* used for sorting */
-typedef struct rix {
-        int         index;
-        ltree       *r;
-}       RIX;
+typedef struct rix
+{
+   int         index;
+   ltree      *r;
+}  RIX;
 
 static int
-treekey_cmp(const void *a, const void *b) {
+treekey_cmp(const void *a, const void *b)
+{
    return ltree_compare(
-       ((RIX *) a)->r,
-       ((RIX *) b)->r
+                        ((RIX *) a)->r,
+                        ((RIX *) b)->r
    );
 }
 
 
-Datum   
-ltree_picksplit(PG_FUNCTION_ARGS) {
-   bytea *entryvec = (bytea*) PG_GETARG_POINTER(0);
-   GIST_SPLITVEC *v = (GIST_SPLITVEC*) PG_GETARG_POINTER(1);
+Datum
+ltree_picksplit(PG_FUNCTION_ARGS)
+{
+   bytea      *entryvec = (bytea *) PG_GETARG_POINTER(0);
+   GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
    OffsetNumber j;
-   int4 i;
-   RIX *array;
+   int4        i;
+   RIX        *array;
    OffsetNumber maxoff;
-   int     nbytes;
-   int    size;
-   ltree   *lu_l,*lu_r, *ru_l, *ru_r;
-   ltree_gist   *lu, *ru;
-   BITVEC  ls,rs;
-   bool    lisat=false, risat=false, isleqr;
-   
-   memset( (void*)ls,0,sizeof(BITVEC) );   
-   memset( (void*)rs,0,sizeof(BITVEC) );   
+   int         nbytes;
+   int         size;
+   ltree      *lu_l,
+              *lu_r,
+              *ru_l,
+              *ru_r;
+   ltree_gist *lu,
+              *ru;
+   BITVEC      ls,
+               rs;
+   bool        lisat = false,
+               risat = false,
+               isleqr;
+
+   memset((void *) ls, 0, sizeof(BITVEC));
+   memset((void *) rs, 0, sizeof(BITVEC));
    maxoff = ((VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY)) - 1;
    nbytes = (maxoff + 2) * sizeof(OffsetNumber);
    v->spl_left = (OffsetNumber *) palloc(nbytes);
@@ -263,109 +308,124 @@ ltree_picksplit(PG_FUNCTION_ARGS) {
    v->spl_nleft = 0;
    v->spl_nright = 0;
    array = (RIX *) palloc(sizeof(RIX) * (maxoff + 1));
-   
+
    /* copy the data into RIXes, and sort the RIXes */
-   for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j)) {
+   for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
+   {
        array[j].index = j;
-       lu = GETENTRY( entryvec, j ); /* use as tmp val */
+       lu = GETENTRY(entryvec, j);     /* use as tmp val */
        array[j].r = LTG_GETLNODE(lu);
    }
 
    qsort((void *) &array[FirstOffsetNumber], maxoff - FirstOffsetNumber + 1,
-       sizeof(RIX), treekey_cmp);
+         sizeof(RIX), treekey_cmp);
 
    lu_l = lu_r = ru_l = ru_r = NULL;
-   for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j)) {
-       lu = GETENTRY( entryvec, array[j].index ); /* use as tmp val */
-       if (j <= (maxoff - FirstOffsetNumber + 1) / 2) {
+   for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
+   {
+       lu = GETENTRY(entryvec, array[j].index);        /* use as tmp val */
+       if (j <= (maxoff - FirstOffsetNumber + 1) / 2)
+       {
            v->spl_left[v->spl_nleft] = array[j].index;
            v->spl_nleft++;
-           if ( lu_r==NULL || ltree_compare( LTG_GETRNODE(lu), lu_r ) > 0 )
+           if (lu_r == NULL || ltree_compare(LTG_GETRNODE(lu), lu_r) > 0)
                lu_r = LTG_GETRNODE(lu);
-           if ( LTG_ISONENODE(lu) )
-               hashing(ls,LTG_NODE(lu));
-           else { 
-               if ( lisat || LTG_ISALLTRUE(lu) ) 
+           if (LTG_ISONENODE(lu))
+               hashing(ls, LTG_NODE(lu));
+           else
+           {
+               if (lisat || LTG_ISALLTRUE(lu))
                    lisat = true;
-               else { 
-                   BITVECP sc=LTG_SIGN(lu);
+               else
+               {
+                   BITVECP     sc = LTG_SIGN(lu);
+
                    LOOPBYTE(
-                       ((unsigned char*)ls)[i] |= sc[i];
+                            ((unsigned char *) ls)[i] |= sc[i];
                    );
                }
            }
-       } else {
+       }
+       else
+       {
            v->spl_right[v->spl_nright] = array[j].index;
            v->spl_nright++;
-           if ( ru_r==NULL || ltree_compare( LTG_GETRNODE(lu), ru_r ) > 0 )
+           if (ru_r == NULL || ltree_compare(LTG_GETRNODE(lu), ru_r) > 0)
                ru_r = LTG_GETRNODE(lu);
-           if ( LTG_ISONENODE(lu) )
-               hashing(rs,LTG_NODE(lu));
-           else { 
-               if ( risat || LTG_ISALLTRUE(lu) ) 
+           if (LTG_ISONENODE(lu))
+               hashing(rs, LTG_NODE(lu));
+           else
+           {
+               if (risat || LTG_ISALLTRUE(lu))
                    risat = true;
-               else { 
-                   BITVECP sc=LTG_SIGN(lu);
+               else
+               {
+                   BITVECP     sc = LTG_SIGN(lu);
+
                    LOOPBYTE(
-                       ((unsigned char*)rs)[i] |= sc[i];
+                            ((unsigned char *) rs)[i] |= sc[i];
                    );
                }
            }
        }
    }
-   
-   if ( lisat == false ) {
+
+   if (lisat == false)
+   {
        lisat = true;
        LOOPBYTE(
-           if ( ((unsigned char*)ls)[i] != 0xff ) {
-               lisat = false;
-               break;
-           }
-       ); 
+                if (((unsigned char *) ls)[i] != 0xff)
+                {
+           lisat = false;
+           break;
+       }
+       );
    }
 
-   if ( risat == false ) {
+   if (risat == false)
+   {
        risat = true;
        LOOPBYTE(
-           if ( ((unsigned char*)rs)[i] != 0xff ) {
-               risat = false;
-               break;
-           }
-       ); 
+                if (((unsigned char *) rs)[i] != 0xff)
+                {
+           risat = false;
+           break;
+       }
+       );
    }
 
-   lu_l = LTG_GETLNODE( GETENTRY( entryvec, array[FirstOffsetNumber].index ) );
-   isleqr = ( lu_l==lu_r || ISEQ(lu_l,lu_r) ) ? true : false; 
-   size = LTG_HDRSIZE + ( (lisat) ? 0 : SIGLEN ) + lu_l->len + ( (isleqr) ? 0 : lu_r->len );
-   lu = (ltree_gist*)palloc( size );
+   lu_l = LTG_GETLNODE(GETENTRY(entryvec, array[FirstOffsetNumber].index));
+   isleqr = (lu_l == lu_r || ISEQ(lu_l, lu_r)) ? true : false;
+   size = LTG_HDRSIZE + ((lisat) ? 0 : SIGLEN) + lu_l->len + ((isleqr) ? 0 : lu_r->len);
+   lu = (ltree_gist *) palloc(size);
    lu->len = size;
    lu->flag = 0;
-   if ( lisat )
+   if (lisat)
        lu->flag |= LTG_ALLTRUE;
    else
-       memcpy( (void*)LTG_SIGN(lu), ls, SIGLEN );
-   memcpy( (void*)LTG_LNODE(lu), (void*)lu_l, lu_l->len );
-   if ( isleqr )
+       memcpy((void *) LTG_SIGN(lu), ls, SIGLEN);
+   memcpy((void *) LTG_LNODE(lu), (void *) lu_l, lu_l->len);
+   if (isleqr)
        lu->flag |= LTG_NORIGHT;
    else
-       memcpy( (void*)LTG_RNODE(lu), (void*)lu_r, lu_r->len );
+       memcpy((void *) LTG_RNODE(lu), (void *) lu_r, lu_r->len);
 
 
-   ru_l = LTG_GETLNODE( GETENTRY( entryvec, array[ 1 + ((maxoff - FirstOffsetNumber + 1) / 2) ].index ) );
-   isleqr = ( ru_l==ru_r || ISEQ(ru_l,ru_r) ) ? true : false;
-   size = LTG_HDRSIZE + ( (risat) ? 0 : SIGLEN ) + ru_l->len + ( (isleqr) ? 0 : ru_r->len ); 
-   ru = (ltree_gist*)palloc( size );
+   ru_l = LTG_GETLNODE(GETENTRY(entryvec, array[1 + ((maxoff - FirstOffsetNumber + 1) / 2)].index));
+   isleqr = (ru_l == ru_r || ISEQ(ru_l, ru_r)) ? true : false;
+   size = LTG_HDRSIZE + ((risat) ? 0 : SIGLEN) + ru_l->len + ((isleqr) ? 0 : ru_r->len);
+   ru = (ltree_gist *) palloc(size);
    ru->len = size;
    ru->flag = 0;
-   if ( risat )
+   if (risat)
        ru->flag |= LTG_ALLTRUE;
    else
-       memcpy( (void*)LTG_SIGN(ru), rs, SIGLEN );
-   memcpy( (void*)LTG_LNODE(ru), (void*)ru_l, ru_l->len );
-   if ( isleqr )
+       memcpy((void *) LTG_SIGN(ru), rs, SIGLEN);
+   memcpy((void *) LTG_LNODE(ru), (void *) ru_l, ru_l->len);
+   if (isleqr)
        ru->flag |= LTG_NORIGHT;
    else
-       memcpy( (void*)LTG_RNODE(ru), (void*)ru_r, ru_r->len );
+       memcpy((void *) LTG_RNODE(ru), (void *) ru_r, ru_r->len);
 
    pfree(array);
    v->spl_ldatum = PointerGetDatum(lu);
@@ -375,13 +435,16 @@ ltree_picksplit(PG_FUNCTION_ARGS) {
 }
 
 static bool
-gist_isparent(ltree_gist *key, ltree *query) {
-   int4    numlevel = query->numlevel;
-   int i;
-
-   for(i=query->numlevel;i>=0;i--) {
-       query->numlevel=i;
-       if ( ltree_compare(query,LTG_GETLNODE(key)) >=0 && ltree_compare(query,LTG_GETRNODE(key)) <= 0 ) {
+gist_isparent(ltree_gist * key, ltree * query)
+{
+   int4        numlevel = query->numlevel;
+   int         i;
+
+   for (i = query->numlevel; i >= 0; i--)
+   {
+       query->numlevel = i;
+       if (ltree_compare(query, LTG_GETLNODE(key)) >= 0 && ltree_compare(query, LTG_GETRNODE(key)) <= 0)
+       {
            query->numlevel = numlevel;
            return true;
        }
@@ -392,23 +455,24 @@ gist_isparent(ltree_gist *key, ltree *query) {
 }
 
 static bool
-gist_ischild(ltree_gist *key, ltree *query) {
-   ltree   *left = LTG_GETLNODE(key);
-   ltree   *right = LTG_GETRNODE(key);
-   int4    numlevelL = left->numlevel;
-   int4    numlevelR = right->numlevel;
-   bool res = true;
-
-   if ( numlevelL > query->numlevel )
+gist_ischild(ltree_gist * key, ltree * query)
+{
+   ltree      *left = LTG_GETLNODE(key);
+   ltree      *right = LTG_GETRNODE(key);
+   int4        numlevelL = left->numlevel;
+   int4        numlevelR = right->numlevel;
+   bool        res = true;
+
+   if (numlevelL > query->numlevel)
        left->numlevel = query->numlevel;
 
-   if ( ltree_compare(query,left) < 0 )
+   if (ltree_compare(query, left) < 0)
        res = false;
 
-   if ( numlevelR > query->numlevel )
+   if (numlevelR > query->numlevel)
        right->numlevel = query->numlevel;
 
-   if ( res && ltree_compare(query,right) > 0 )
+   if (res && ltree_compare(query, right) > 0)
        res = false;
 
    left->numlevel = numlevelL;
@@ -417,29 +481,35 @@ gist_ischild(ltree_gist *key, ltree *query) {
 }
 
 static bool
-gist_qe(ltree_gist *key, lquery* query) {
-   lquery_level    *curq = LQUERY_FIRST(query);
-   BITVECP sign = LTG_SIGN(key);
-   int qlen = query->numlevel;
+gist_qe(ltree_gist * key, lquery * query)
+{
+   lquery_level *curq = LQUERY_FIRST(query);
+   BITVECP     sign = LTG_SIGN(key);
+   int         qlen = query->numlevel;
 
-   if ( LTG_ISALLTRUE(key) )
+   if (LTG_ISALLTRUE(key))
        return true;
 
-   while( qlen>0 ) {
-       if ( curq->numvar && LQL_CANLOOKSIGN(curq) ) {
-           bool isexist=false;
-           int vlen = curq->numvar;
+   while (qlen > 0)
+   {
+       if (curq->numvar && LQL_CANLOOKSIGN(curq))
+       {
+           bool        isexist = false;
+           int         vlen = curq->numvar;
            lquery_variant *curv = LQL_FIRST(curq);
-           while( vlen>0 ) {
-               if ( GETBIT( sign, HASHVAL( curv->val ) ) ) {
-                   isexist=true;
+
+           while (vlen > 0)
+           {
+               if (GETBIT(sign, HASHVAL(curv->val)))
+               {
+                   isexist = true;
                    break;
                }
                curv = LVAR_NEXT(curv);
                vlen--;
            }
-           if ( !isexist )
-               return false;   
+           if (!isexist)
+               return false;
        }
 
        curq = LQL_NEXT(curq);
@@ -450,22 +520,27 @@ gist_qe(ltree_gist *key, lquery* query) {
 }
 
 static int
-gist_tqcmp(ltree* t, lquery* q) {
+gist_tqcmp(ltree * t, lquery * q)
+{
    ltree_level *al = LTREE_FIRST(t);
    lquery_level *ql = LQUERY_FIRST(q);
    lquery_variant *bl;
-   int     an = t->numlevel;
-   int     bn = q->firstgood;
-   int     res = 0;
+   int         an = t->numlevel;
+   int         bn = q->firstgood;
+   int         res = 0;
 
-   while( an>0 && bn>0 ) {
+   while (an > 0 && bn > 0)
+   {
        bl = LQL_FIRST(ql);
-       if ( (res = strncmp( al->name, bl->name, min(al->len, bl->len))) == 0 ) {
-           if ( al->len != bl->len )
+       if ((res = strncmp(al->name, bl->name, min(al->len, bl->len))) == 0)
+       {
+           if (al->len != bl->len)
                return al->len - bl->len;
-       } else
+       }
+       else
           &n