pgindent run.
authorBruce Momjian <bruce@momjian.us>
Mon, 4 Aug 2003 00:43:34 +0000 (00:43 +0000)
committerBruce Momjian <bruce@momjian.us>
Mon, 4 Aug 2003 00:43:34 +0000 (00:43 +0000)
554 files changed:
contrib/btree_gist/btree_common.c
contrib/btree_gist/btree_gist.h
contrib/cube/cube.c
contrib/dbase/dbf2pg.c
contrib/dblink/dblink.c
contrib/dbmirror/pending.c
contrib/dbsize/dbsize.c
contrib/earthdistance/earthdistance.c
contrib/findoidjoins/findoidjoins.c
contrib/fulltextindex/fti.c
contrib/fuzzystrmatch/fuzzystrmatch.c
contrib/intagg/int_aggregate.c
contrib/intarray/_int.h
contrib/intarray/_int_bool.c
contrib/intarray/_int_gist.c
contrib/intarray/_int_tool.c
contrib/ltree/_ltree_op.c
contrib/ltree/lquery_op.c
contrib/ltree/ltree_io.c
contrib/ltree/ltree_op.c
contrib/oid2name/oid2name.c
contrib/pg_autovacuum/pg_autovacuum.c
contrib/pg_autovacuum/pg_autovacuum.h
contrib/pg_dumplo/main.c
contrib/pgbench/pgbench.c
contrib/pgcrypto/openssl.c
contrib/pgcrypto/pgcrypto.c
contrib/pgstattuple/pgstattuple.c
contrib/spi/autoinc.c
contrib/spi/insert_username.c
contrib/spi/moddatetime.c
contrib/spi/refint.c
contrib/spi/timetravel.c
contrib/tablefunc/tablefunc.c
contrib/tsearch/morph.c
contrib/tsearch2/common.c
contrib/tsearch2/common.h
contrib/tsearch2/dict.c
contrib/tsearch2/dict.h
contrib/tsearch2/dict_ex.c
contrib/tsearch2/dict_ispell.c
contrib/tsearch2/dict_snowball.c
contrib/tsearch2/dict_syn.c
contrib/tsearch2/ispell/spell.c
contrib/tsearch2/ispell/spell.h
contrib/tsearch2/prs_dcfg.c
contrib/tsearch2/query.c
contrib/tsearch2/query.h
contrib/tsearch2/rank.c
contrib/tsearch2/snmap.c
contrib/tsearch2/snmap.h
contrib/tsearch2/snowball/api.c
contrib/tsearch2/snowball/api.h
contrib/tsearch2/snowball/english_stem.c
contrib/tsearch2/snowball/english_stem.h
contrib/tsearch2/snowball/header.h
contrib/tsearch2/snowball/russian_stem.c
contrib/tsearch2/snowball/russian_stem.h
contrib/tsearch2/snowball/utilities.c
contrib/tsearch2/stopword.c
contrib/tsearch2/ts_cfg.c
contrib/tsearch2/ts_cfg.h
contrib/tsearch2/ts_stat.c
contrib/tsearch2/ts_stat.h
contrib/tsearch2/tsvector.c
contrib/tsearch2/tsvector.h
contrib/tsearch2/tsvector_op.c
contrib/tsearch2/wordparser/deflex.c
contrib/tsearch2/wparser.c
contrib/tsearch2/wparser.h
contrib/tsearch2/wparser_def.c
contrib/xml/pgxml_dom.c
src/backend/access/common/heaptuple.c
src/backend/access/common/indextuple.c
src/backend/access/common/printtup.c
src/backend/access/gist/gistscan.c
src/backend/access/hash/hashfunc.c
src/backend/access/hash/hashovfl.c
src/backend/access/heap/heapam.c
src/backend/access/index/indexam.c
src/backend/access/nbtree/nbtinsert.c
src/backend/access/nbtree/nbtpage.c
src/backend/access/nbtree/nbtree.c
src/backend/access/nbtree/nbtsearch.c
src/backend/access/nbtree/nbtsort.c
src/backend/access/nbtree/nbtxlog.c
src/backend/access/rtree/rtscan.c
src/backend/access/transam/clog.c
src/backend/access/transam/rmgr.c
src/backend/access/transam/slru.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/dependency.c
src/backend/catalog/heap.c
src/backend/catalog/index.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_operator.c
src/backend/catalog/pg_proc.c
src/backend/catalog/pg_type.c
src/backend/commands/aggregatecmds.c
src/backend/commands/alter.c
src/backend/commands/analyze.c
src/backend/commands/async.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/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/execAmi.c
src/backend/executor/execGrouping.c
src/backend/executor/execMain.c
src/backend/executor/execProcnode.c
src/backend/executor/execQual.c
src/backend/executor/execScan.c
src/backend/executor/execTuples.c
src/backend/executor/execUtils.c
src/backend/executor/functions.c
src/backend/executor/nodeAgg.c
src/backend/executor/nodeAppend.c
src/backend/executor/nodeHash.c
src/backend/executor/nodeHashjoin.c
src/backend/executor/nodeIndexscan.c
src/backend/executor/nodeLimit.c
src/backend/executor/nodeMaterial.c
src/backend/executor/nodeMergejoin.c
src/backend/executor/nodeNestloop.c
src/backend/executor/nodeResult.c
src/backend/executor/nodeSeqscan.c
src/backend/executor/nodeSubplan.c
src/backend/executor/nodeSubqueryscan.c
src/backend/executor/nodeUnique.c
src/backend/executor/spi.c
src/backend/executor/tstoreReceiver.c
src/backend/lib/stringinfo.c
src/backend/libpq/auth.c
src/backend/libpq/be-fsstubs.c
src/backend/libpq/be-secure.c
src/backend/libpq/crypt.c
src/backend/libpq/hba.c
src/backend/libpq/ip.c
src/backend/libpq/md5.c
src/backend/libpq/pqcomm.c
src/backend/libpq/pqformat.c
src/backend/main/main.c
src/backend/nodes/bitmapset.c
src/backend/nodes/copyfuncs.c
src/backend/nodes/equalfuncs.c
src/backend/nodes/list.c
src/backend/nodes/nodes.c
src/backend/nodes/outfuncs.c
src/backend/nodes/readfuncs.c
src/backend/optimizer/geqo/geqo_eval.c
src/backend/optimizer/geqo/geqo_main.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/joinrels.c
src/backend/optimizer/path/orindxpath.c
src/backend/optimizer/path/pathkeys.c
src/backend/optimizer/path/tidpath.c
src/backend/optimizer/plan/createplan.c
src/backend/optimizer/plan/initsplan.c
src/backend/optimizer/plan/planmain.c
src/backend/optimizer/plan/planner.c
src/backend/optimizer/plan/setrefs.c
src/backend/optimizer/plan/subselect.c
src/backend/optimizer/prep/prepjointree.c
src/backend/optimizer/prep/prepqual.c
src/backend/optimizer/prep/preptlist.c
src/backend/optimizer/prep/prepunion.c
src/backend/optimizer/util/clauses.c
src/backend/optimizer/util/joininfo.c
src/backend/optimizer/util/pathnode.c
src/backend/optimizer/util/plancat.c
src/backend/optimizer/util/relnode.c
src/backend/optimizer/util/restrictinfo.c
src/backend/optimizer/util/tlist.c
src/backend/optimizer/util/var.c
src/backend/parser/analyze.c
src/backend/parser/parse_agg.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/port/beos/sem.c
src/backend/port/dynloader/darwin.c
src/backend/port/dynloader/linux.c
src/backend/port/dynloader/linux.h
src/backend/port/dynloader/win32.c
src/backend/port/ipc_test.c
src/backend/port/posix_sema.c
src/backend/port/sysv_sema.c
src/backend/port/sysv_shmem.c
src/backend/port/win32/sema.c
src/backend/postmaster/pgstat.c
src/backend/postmaster/postmaster.c
src/backend/regex/regc_color.c
src/backend/regex/regc_cvec.c
src/backend/regex/regc_lex.c
src/backend/regex/regc_locale.c
src/backend/regex/regc_nfa.c
src/backend/regex/regcomp.c
src/backend/regex/rege_dfa.c
src/backend/regex/regerror.c
src/backend/regex/regexec.c
src/backend/regex/regfree.c
src/backend/rewrite/rewriteDefine.c
src/backend/rewrite/rewriteHandler.c
src/backend/rewrite/rewriteManip.c
src/backend/storage/buffer/bufmgr.c
src/backend/storage/file/fd.c
src/backend/storage/freespace/freespace.c
src/backend/storage/ipc/ipc.c
src/backend/storage/ipc/ipci.c
src/backend/storage/ipc/sinval.c
src/backend/storage/lmgr/deadlock.c
src/backend/storage/lmgr/lock.c
src/backend/storage/lmgr/proc.c
src/backend/storage/page/bufpage.c
src/backend/storage/smgr/md.c
src/backend/tcop/dest.c
src/backend/tcop/fastpath.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/array_userfuncs.c
src/backend/utils/adt/arrayfuncs.c
src/backend/utils/adt/ascii.c
src/backend/utils/adt/char.c
src/backend/utils/adt/date.c
src/backend/utils/adt/datetime.c
src/backend/utils/adt/float.c
src/backend/utils/adt/formatting.c
src/backend/utils/adt/geo_ops.c
src/backend/utils/adt/inet_net_ntop.c
src/backend/utils/adt/inet_net_pton.c
src/backend/utils/adt/int.c
src/backend/utils/adt/int8.c
src/backend/utils/adt/like.c
src/backend/utils/adt/like_match.c
src/backend/utils/adt/mac.c
src/backend/utils/adt/nabstime.c
src/backend/utils/adt/name.c
src/backend/utils/adt/network.c
src/backend/utils/adt/not_in.c
src/backend/utils/adt/numeric.c
src/backend/utils/adt/numutils.c
src/backend/utils/adt/oid.c
src/backend/utils/adt/oracle_compat.c
src/backend/utils/adt/pg_locale.c
src/backend/utils/adt/pgstatfuncs.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/timestamp.c
src/backend/utils/adt/varbit.c
src/backend/utils/adt/varchar.c
src/backend/utils/adt/varlena.c
src/backend/utils/adt/xid.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/error/elog.c
src/backend/utils/fmgr/dfmgr.c
src/backend/utils/fmgr/fmgr.c
src/backend/utils/init/findbe.c
src/backend/utils/init/miscinit.c
src/backend/utils/init/postinit.c
src/backend/utils/mb/conv.c
src/backend/utils/mb/mbutils.c
src/backend/utils/mb/wchar.c
src/backend/utils/misc/guc.c
src/backend/utils/misc/help_config.c
src/backend/utils/mmgr/aset.c
src/backend/utils/mmgr/mcxt.c
src/backend/utils/mmgr/portalmem.c
src/backend/utils/sort/logtape.c
src/backend/utils/sort/tuplesort.c
src/backend/utils/sort/tuplestore.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_archiver.c
src/bin/pg_dump/pg_backup_archiver.h
src/bin/pg_dump/pg_backup_custom.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_encoding/pg_encoding.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.c
src/bin/psql/large_obj.c
src/bin/psql/mainloop.c
src/bin/psql/mbprint.c
src/bin/psql/print.c
src/bin/psql/print.h
src/bin/psql/prompt.c
src/bin/psql/sprompt.c
src/bin/psql/startup.c
src/bin/psql/stringutils.c
src/bin/psql/tab-complete.c
src/bin/psql/variables.c
src/bin/psql/variables.h
src/bin/scripts/clusterdb.c
src/bin/scripts/common.c
src/bin/scripts/common.h
src/bin/scripts/createdb.c
src/bin/scripts/createlang.c
src/bin/scripts/createuser.c
src/bin/scripts/dropdb.c
src/bin/scripts/droplang.c
src/bin/scripts/vacuumdb.c
src/include/access/genam.h
src/include/access/heapam.h
src/include/access/nbtree.h
src/include/access/printtup.h
src/include/access/relscan.h
src/include/access/slru.h
src/include/access/xact.h
src/include/access/xlog.h
src/include/c.h
src/include/catalog/catversion.h
src/include/catalog/dependency.h
src/include/catalog/pg_am.h
src/include/catalog/pg_amproc.h
src/include/catalog/pg_attribute.h
src/include/catalog/pg_cast.h
src/include/catalog/pg_constraint.h
src/include/catalog/pg_opclass.h
src/include/catalog/pg_operator.h
src/include/catalog/pg_proc.h
src/include/catalog/pg_statistic.h
src/include/catalog/pg_type.h
src/include/commands/alter.h
src/include/commands/dbcommands.h
src/include/commands/explain.h
src/include/commands/portalcmds.h
src/include/commands/prepare.h
src/include/commands/sequence.h
src/include/commands/trigger.h
src/include/commands/typecmds.h
src/include/executor/execdesc.h
src/include/executor/executor.h
src/include/executor/hashjoin.h
src/include/executor/nodeHash.h
src/include/executor/nodeSeqscan.h
src/include/executor/nodeSubplan.h
src/include/executor/spi.h
src/include/executor/spi_priv.h
src/include/executor/tstoreReceiver.h
src/include/getaddrinfo.h
src/include/getopt_long.h
src/include/lib/stringinfo.h
src/include/libpq/crypt.h
src/include/libpq/ip.h
src/include/libpq/libpq-be.h
src/include/libpq/libpq.h
src/include/libpq/pqcomm.h
src/include/libpq/pqformat.h
src/include/mb/pg_wchar.h
src/include/miscadmin.h
src/include/nodes/bitmapset.h
src/include/nodes/execnodes.h
src/include/nodes/makefuncs.h
src/include/nodes/nodes.h
src/include/nodes/params.h
src/include/nodes/parsenodes.h
src/include/nodes/pg_list.h
src/include/nodes/plannodes.h
src/include/nodes/primnodes.h
src/include/nodes/relation.h
src/include/optimizer/clauses.h
src/include/optimizer/cost.h
src/include/optimizer/geqo_misc.h
src/include/optimizer/joininfo.h
src/include/optimizer/pathnode.h
src/include/optimizer/paths.h
src/include/optimizer/plancat.h
src/include/optimizer/planmain.h
src/include/optimizer/prep.h
src/include/optimizer/restrictinfo.h
src/include/optimizer/tlist.h
src/include/parser/analyze.h
src/include/parser/parse_agg.h
src/include/parser/parse_clause.h
src/include/parser/parse_coerce.h
src/include/parser/parse_func.h
src/include/parser/parse_node.h
src/include/parser/parse_oper.h
src/include/pg_config_manual.h
src/include/pgstat.h
src/include/port.h
src/include/port/bsdi.h
src/include/port/cygwin.h
src/include/port/freebsd.h
src/include/port/hpux.h
src/include/port/netbsd.h
src/include/port/openbsd.h
src/include/port/win32.h
src/include/port/win32/dlfcn.h
src/include/port/win32/grp.h
src/include/port/win32/netdb.h
src/include/port/win32/netinet/in.h
src/include/port/win32/pwd.h
src/include/port/win32/sys/socket.h
src/include/port/win32/sys/wait.h
src/include/postgres.h
src/include/regex/regcustom.h
src/include/regex/regerrs.h
src/include/regex/regex.h
src/include/regex/regguts.h
src/include/storage/bufmgr.h
src/include/storage/freespace.h
src/include/storage/lock.h
src/include/tcop/dest.h
src/include/tcop/pquery.h
src/include/tcop/tcopprot.h
src/include/utils/acl.h
src/include/utils/array.h
src/include/utils/builtins.h
src/include/utils/datetime.h
src/include/utils/elog.h
src/include/utils/errcodes.h
src/include/utils/guc.h
src/include/utils/guc_tables.h
src/include/utils/help_config.h
src/include/utils/inet.h
src/include/utils/lsyscache.h
src/include/utils/memutils.h
src/include/utils/palloc.h
src/include/utils/portal.h
src/include/utils/rel.h
src/include/utils/selfuncs.h
src/include/utils/tuplestore.h
src/interfaces/ecpg/compatlib/informix.c
src/interfaces/ecpg/ecpglib/connect.c
src/interfaces/ecpg/ecpglib/data.c
src/interfaces/ecpg/ecpglib/descriptor.c
src/interfaces/ecpg/ecpglib/error.c
src/interfaces/ecpg/ecpglib/execute.c
src/interfaces/ecpg/ecpglib/extern.h
src/interfaces/ecpg/ecpglib/misc.c
src/interfaces/ecpg/ecpglib/prepare.c
src/interfaces/ecpg/include/datetime.h
src/interfaces/ecpg/include/decimal.h
src/interfaces/ecpg/include/ecpg_informix.h
src/interfaces/ecpg/include/ecpgerrno.h
src/interfaces/ecpg/include/ecpglib.h
src/interfaces/ecpg/include/ecpgtype.h
src/interfaces/ecpg/include/pgtypes_date.h
src/interfaces/ecpg/include/pgtypes_error.h
src/interfaces/ecpg/include/pgtypes_interval.h
src/interfaces/ecpg/include/pgtypes_numeric.h
src/interfaces/ecpg/include/pgtypes_timestamp.h
src/interfaces/ecpg/include/sqlca.h
src/interfaces/ecpg/include/sqlda.h
src/interfaces/ecpg/include/sqltypes.h
src/interfaces/ecpg/pgtypeslib/common.c
src/interfaces/ecpg/pgtypeslib/datetime.c
src/interfaces/ecpg/pgtypeslib/dt.h
src/interfaces/ecpg/pgtypeslib/dt_common.c
src/interfaces/ecpg/pgtypeslib/extern.h
src/interfaces/ecpg/pgtypeslib/interval.c
src/interfaces/ecpg/pgtypeslib/numeric.c
src/interfaces/ecpg/pgtypeslib/timestamp.c
src/interfaces/ecpg/preproc/c_keywords.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/pgtclCmds.c
src/interfaces/libpgtcl/pgtclCmds.h
src/interfaces/libpgtcl/pgtclId.c
src/interfaces/libpgtcl/pgtclId.h
src/interfaces/libpq/fe-auth.c
src/interfaces/libpq/fe-connect.c
src/interfaces/libpq/fe-exec.c
src/interfaces/libpq/fe-lobj.c
src/interfaces/libpq/fe-misc.c
src/interfaces/libpq/fe-protocol2.c
src/interfaces/libpq/fe-protocol3.c
src/interfaces/libpq/fe-secure.c
src/interfaces/libpq/libpq-fe.h
src/interfaces/libpq/libpq-int.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/pl_handler.c
src/pl/plpgsql/src/plpgsql.h
src/pl/plpython/plpython.c
src/pl/tcl/pltcl.c
src/port/copydir.c
src/port/crypt.c
src/port/dirmod.c
src/port/fseeko.c
src/port/getaddrinfo.c
src/port/getopt.c
src/port/getopt_long.c
src/port/gettimeofday.c
src/port/path.c
src/port/threads.c
src/test/examples/testlibpq.c
src/test/examples/testlibpq2.c
src/test/examples/testlibpq3.c
src/test/regress/regress.c
src/tutorial/complex.c

index 9873af911c3bac2c7998ef9f67cd56d89e72de06..9306076e0aed94434980f1bfdb8377b7c68455c0 100644 (file)
@@ -1,7 +1,7 @@
 #include "btree_gist.h"
 
 PG_FUNCTION_INFO_V1(btree_decompress);
-Datum   btree_decompress(PG_FUNCTION_ARGS);
+Datum      btree_decompress(PG_FUNCTION_ARGS);
 
 /*
 ** GiST DeCompress methods
index ebcecf4cc53fd354e6e4f1fc3916d7480595fd87..ecbabc2dbb34e1017c31d5f7881cb5135433a348 100644 (file)
@@ -23,4 +23,3 @@ typedef struct rix
 
 extern GIST_SPLITVEC *btree_picksplit(bytea *entryvec, GIST_SPLITVEC *v,
                BINARY_UNION bu, CMPFUNC cmp);
-
index 5d8bcf75b5d74fa216ca0fd2c3a975f263b6caa1..396253261d95f57d4c4205f14720dc5b7a0a7cfa 100644 (file)
@@ -28,11 +28,11 @@ extern int  cube_yyparse();
 NDBOX     *cube_in(char *str);
 NDBOX     *cube(text *str);
 char      *cube_out(NDBOX * cube);
-NDBOX      *cube_f8(double *);
-NDBOX      *cube_f8_f8(double *, double *);
-NDBOX      *cube_c_f8(NDBOX *, double *);
-NDBOX      *cube_c_f8_f8(NDBOX *, double *, double *);
-int4           cube_dim(NDBOX * a);
+NDBOX     *cube_f8(double *);
+NDBOX     *cube_f8_f8(double *, double *);
+NDBOX     *cube_c_f8(NDBOX *, double *);
+NDBOX     *cube_c_f8_f8(NDBOX *, double *, double *);
+int4       cube_dim(NDBOX * a);
 double    *cube_ll_coord(NDBOX * a, int4 n);
 double    *cube_ur_coord(NDBOX * a, int4 n);
 
@@ -123,7 +123,7 @@ cube_out(NDBOX * cube)
    bool        equal = true;
    int         dim = cube->dim;
    int         i;
-   int     ndig;
+   int         ndig;
 
    initStringInfo(&buf);
 
@@ -131,7 +131,8 @@ cube_out(NDBOX * cube)
     * Get the number of digits to display.
     */
    ndig = DBL_DIG + extra_float_digits;
-   if (ndig < 1) ndig = 1;
+   if (ndig < 1)
+       ndig = 1;
 
    /*
     * while printing the first (LL) corner, check if it is equal to the
@@ -1192,7 +1193,8 @@ cube_enlarge(NDBOX * a, double *r, int4 n)
                j,
                k;
 
-   if (n > CUBE_MAX_DIM) n = CUBE_MAX_DIM;
+   if (n > CUBE_MAX_DIM)
+       n = CUBE_MAX_DIM;
    if (*r > 0 && n > 0)
        dim = n;
    if (a->dim > dim)
@@ -1234,14 +1236,15 @@ NDBOX *
 cube_f8(double *x1)
 {
    NDBOX      *result;
-        int        size;
+   int         size;
+
    size = offsetof(NDBOX, x[0]) + sizeof(double) * 2;
    result = (NDBOX *) palloc(size);
    memset(result, 0, size);
    result->size = size;
    result->dim = 1;
-        result->x[0] = *x1;
-        result->x[1] = *x1;
+   result->x[0] = *x1;
+   result->x[1] = *x1;
    return result;
 }
 
@@ -1250,56 +1253,61 @@ NDBOX *
 cube_f8_f8(double *x1, double *x2)
 {
    NDBOX      *result;
-        int        size;
+   int         size;
+
    size = offsetof(NDBOX, x[0]) + sizeof(double) * 2;
    result = (NDBOX *) palloc(size);
    memset(result, 0, size);
    result->size = size;
    result->dim = 1;
-        result->x[0] = *x1;
-        result->x[1] = *x2;
+   result->x[0] = *x1;
+   result->x[1] = *x2;
    return result;
 }
 
 /* Add a dimension to an existing cube with the same values for the new
    coordinate */
 NDBOX *
-cube_c_f8(NDBOX *c, double *x1)
+cube_c_f8(NDBOX * c, double *x1)
 {
    NDBOX      *result;
-        int        size;
-        int        i;
-   size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) * 2;
+   int         size;
+   int         i;
+
+   size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) *2;
    result = (NDBOX *) palloc(size);
    memset(result, 0, size);
    result->size = size;
    result->dim = c->dim + 1;
-        for (i = 0; i < c->dim; i++) {
-            result->x[i] = c->x[i];
-            result->x[result->dim + i] = c->x[c->dim + i];
-        }
-        result->x[result->dim - 1] = *x1;
-        result->x[2 * result->dim - 1] = *x1;
+   for (i = 0; i < c->dim; i++)
+   {
+       result->x[i] = c->x[i];
+       result->x[result->dim + i] = c->x[c->dim + i];
+   }
+   result->x[result->dim - 1] = *x1;
+   result->x[2 * result->dim - 1] = *x1;
    return result;
 }
 
 /* Add a dimension to an existing cube */
 NDBOX *
-cube_c_f8_f8(NDBOX *c, double *x1, double *x2)
+cube_c_f8_f8(NDBOX * c, double *x1, double *x2)
 {
    NDBOX      *result;
-        int        size;
-        int        i;
-   size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) * 2;
+   int         size;
+   int         i;
+
+   size = offsetof(NDBOX, x[0]) + sizeof(double) * (c->dim + 1) *2;
    result = (NDBOX *) palloc(size);
    memset(result, 0, size);
    result->size = size;
    result->dim = c->dim + 1;
-        for (i = 0; i < c->dim; i++) {
-            result->x[i] = c->x[i];
-            result->x[result->dim + i] = c->x[c->dim + i];
-        }
-        result->x[result->dim - 1] = *x1;
-        result->x[2 * result->dim - 1] = *x2;
+   for (i = 0; i < c->dim; i++)
+   {
+       result->x[i] = c->x[i];
+       result->x[result->dim + i] = c->x[c->dim + i];
+   }
+   result->x[result->dim - 1] = *x1;
+   result->x[2 * result->dim - 1] = *x2;
    return result;
 }
index 0ae53cd126d48a51426dcd134c590d98cd9d3655..d679eed1ad895652ad49a75f6787abcbc7c395cc 100644 (file)
@@ -443,17 +443,15 @@ do_inserts(PGconn *conn, char *table, dbhead * dbh)
        if (result == DBF_VALID)
        {
            query[0] = '\0';
-           j = 0; /* counter for fields in the output */
+           j = 0;              /* counter for fields in the output */
            for (h = 0; h < dbh->db_nfields; h++)
            {
-               if (!strlen(fields[h].db_name)) /* When the new fieldname is empty, the field is skipped */
-               {
+               if (!strlen(fields[h].db_name)) /* When the new fieldname
+                                                * is empty, the field is
+                                                * skipped */
                    continue;
-               }
                else
-               {
                    j++;
-               }
 
                if (j > 1)      /* not for the first field! */
                    strcat(query, "\t");        /* COPY statement field
index 158942a4c046af2d2f31f230ecb083b7f75bbb1b..629f93f1c64b0a5e05fcbb537f672f7d88d294ef 100644 (file)
 
 typedef struct remoteConn
 {
-   PGconn *con;            /* Hold the remote connection */
-   bool remoteTrFlag;      /* Indicates whether or not a transaction
-                            * on remote database is in progress*/
-} remoteConn;
+   PGconn     *con;            /* Hold the remote connection */
+   bool        remoteTrFlag;   /* Indicates whether or not a transaction
+                                * on remote database is in progress */
+}  remoteConn;
 
 /*
  * Internal declarations
  */
 static remoteConn *getConnectionByName(const char *name);
 static HTAB *createConnHash(void);
-static void createNewConnection(const char *name,remoteConn *con);
+static void createNewConnection(const char *name, remoteConn * con);
 static void deleteConnection(const char *name);
 static char **get_pkey_attnames(Oid relid, int16 *numatts);
 static char *get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals);
@@ -86,15 +86,15 @@ static TupleDesc pgresultGetTupleDesc(PGresult *res);
 static char *generate_relation_name(Oid relid);
 
 /* Global */
-List   *res_id = NIL;
-int        res_id_index = 0;
-PGconn *persistent_conn = NULL;
-static HTAB *remoteConnHash=NULL;
+List      *res_id = NIL;
+int            res_id_index = 0;
+PGconn    *persistent_conn = NULL;
+static HTAB *remoteConnHash = NULL;
 
-/* 
+/*
 Following is list that holds multiple remote connections.
 Calling convention of each dblink function changes to accept
-connection name as the first parameter. The connection list is 
+connection name as the first parameter. The connection list is
 much like ecpg e.g. a mapping between a name and a PGconn object.
 */
 
@@ -102,7 +102,7 @@ typedef struct remoteConnHashEnt
 {
    char        name[NAMEDATALEN];
    remoteConn *rcon;
-} remoteConnHashEnt;
+}  remoteConnHashEnt;
 
 /* initial number of connection hashes */
 #define NUMCONN 16
@@ -186,18 +186,18 @@ dblink_connect(PG_FUNCTION_ARGS)
    PGconn     *conn = NULL;
    remoteConn *rcon = NULL;
 
-   if(PG_NARGS()==2)
+   if (PG_NARGS() == 2)
    {
        connstr = GET_STR(PG_GETARG_TEXT_P(1));
        connname = GET_STR(PG_GETARG_TEXT_P(0));
    }
-   else if(PG_NARGS()==1)
+   else if (PG_NARGS() == 1)
        connstr = GET_STR(PG_GETARG_TEXT_P(0));
 
    oldcontext = MemoryContextSwitchTo(TopMemoryContext);
 
-   if(connname)
-       rcon=(remoteConn *) palloc(sizeof(remoteConn));
+   if (connname)
+       rcon = (remoteConn *) palloc(sizeof(remoteConn));
    conn = PQconnectdb(connstr);
 
    MemoryContextSwitchTo(oldcontext);
@@ -206,16 +206,16 @@ dblink_connect(PG_FUNCTION_ARGS)
    {
        msg = pstrdup(PQerrorMessage(conn));
        PQfinish(conn);
-       if(rcon)
+       if (rcon)
            pfree(rcon);
 
        ereport(ERROR,
-               (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
-                errmsg("could not establish connection"),
-                errdetail("%s", msg)));
+          (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
+           errmsg("could not establish connection"),
+           errdetail("%s", msg)));
    }
 
-   if(connname)
+   if (connname)
    {
        rcon->con = conn;
        createNewConnection(connname, rcon);
@@ -237,7 +237,7 @@ dblink_disconnect(PG_FUNCTION_ARGS)
    remoteConn *rcon = NULL;
    PGconn     *conn = NULL;
 
-   if (PG_NARGS() ==)
+   if (PG_NARGS() == 1)
    {
        conname = GET_STR(PG_GETARG_TEXT_P(0));
        rcon = getConnectionByName(conname);
@@ -276,13 +276,13 @@ dblink_open(PG_FUNCTION_ARGS)
    StringInfo  str = makeStringInfo();
    remoteConn *rcon = NULL;
 
-   if(PG_NARGS() == 2)
+   if (PG_NARGS() == 2)
    {
        curname = GET_STR(PG_GETARG_TEXT_P(0));
        sql = GET_STR(PG_GETARG_TEXT_P(1));
        conn = persistent_conn;
    }
-   else if(PG_NARGS() == 3)
+   else if (PG_NARGS() == 3)
    {
        conname = GET_STR(PG_GETARG_TEXT_P(0));
        curname = GET_STR(PG_GETARG_TEXT_P(1));
@@ -333,12 +333,12 @@ dblink_close(PG_FUNCTION_ARGS)
        curname = GET_STR(PG_GETARG_TEXT_P(0));
        conn = persistent_conn;
    }
-   else if (PG_NARGS()==2)
+   else if (PG_NARGS() == 2)
    {
        conname = GET_STR(PG_GETARG_TEXT_P(0));
        curname = GET_STR(PG_GETARG_TEXT_P(1));
        rcon = getConnectionByName(conname);
-       if(rcon)
+       if (rcon)
            conn = rcon->con;
    }
 
@@ -381,7 +381,7 @@ dblink_fetch(PG_FUNCTION_ARGS)
    PGresult   *res = NULL;
    MemoryContext oldcontext;
    char       *conname = NULL;
-   remoteConn *rcon=NULL;
+   remoteConn *rcon = NULL;
 
    /* stuff done only on the first call of the function */
    if (SRF_IS_FIRSTCALL())
@@ -401,7 +401,7 @@ dblink_fetch(PG_FUNCTION_ARGS)
            howmany = PG_GETARG_INT32(2);
 
            rcon = getConnectionByName(conname);
-           if(rcon)
+           if (rcon)
                conn = rcon->con;
        }
        else if (PG_NARGS() == 2)
@@ -411,7 +411,7 @@ dblink_fetch(PG_FUNCTION_ARGS)
            conn = persistent_conn;
        }
 
-       if(!conn)
+       if (!conn)
            DBLINK_CONN_NOT_AVAIL;
 
        /* create a function context for cross-call persistence */
@@ -429,9 +429,7 @@ dblink_fetch(PG_FUNCTION_ARGS)
        if (!res ||
            (PQresultStatus(res) != PGRES_COMMAND_OK &&
             PQresultStatus(res) != PGRES_TUPLES_OK))
-       {
            DBLINK_RES_ERROR("sql error");
-       }
        else if (PQresultStatus(res) == PGRES_COMMAND_OK)
        {
            /* cursor does not exist - closed already or bad name */
@@ -549,7 +547,7 @@ dblink_record(PG_FUNCTION_ARGS)
        char       *connstr = NULL;
        char       *sql = NULL;
        char       *conname = NULL;
-       remoteConn *rcon=NULL;
+       remoteConn *rcon = NULL;
 
        /* create a function context for cross-call persistence */
        funcctx = SRF_FIRSTCALL_INIT();
@@ -574,7 +572,7 @@ dblink_record(PG_FUNCTION_ARGS)
            /* shouldn't happen */
            elog(ERROR, "wrong number of arguments");
 
-       if(!conn)
+       if (!conn)
            DBLINK_CONN_NOT_AVAIL;
 
        res = PQexec(conn, sql);
@@ -591,8 +589,8 @@ dblink_record(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);
            funcctx->max_calls = 1;
@@ -707,7 +705,7 @@ dblink_exec(PG_FUNCTION_ARGS)
    char       *connstr = NULL;
    char       *sql = NULL;
    char       *conname = NULL;
-   remoteConn *rcon=NULL;
+   remoteConn *rcon = NULL;
    bool        freeconn = true;
 
    if (PG_NARGS() == 2)
@@ -724,7 +722,7 @@ dblink_exec(PG_FUNCTION_ARGS)
        /* shouldn't happen */
        elog(ERROR, "wrong number of arguments");
 
-   if(!conn)
+   if (!conn)
        DBLINK_CONN_NOT_AVAIL;
 
    res = PQexec(conn, sql);
@@ -741,15 +739,15 @@ 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 = GET_TEXT(PQcmdStatus(res));
    }
    else
        ereport(ERROR,
-               (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
-                errmsg("statement returning results not allowed")));
+             (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
+              errmsg("statement returning results not allowed")));
 
    PQclear(res);
 
@@ -802,6 +800,7 @@ dblink_get_pkey(PG_FUNCTION_ARGS)
                    (errcode(ERRCODE_UNDEFINED_TABLE),
                     errmsg("relation \"%s\" does not exist",
                            GET_STR(PG_GETARG_TEXT_P(0)))));
+
        /*
         * need a tuple descriptor representing one INT and one TEXT
         * column
@@ -980,8 +979,8 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
    if (src_nitems != pknumatts)
        ereport(ERROR,
                (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
-                errmsg("source key array length must match number of key " \
-                       "attributes")));
+            errmsg("source key array length must match number of key " \
+                   "attributes")));
 
    /*
     * get array of pointers to c-strings from the input source array
@@ -1013,8 +1012,8 @@ dblink_build_sql_insert(PG_FUNCTION_ARGS)
    if (tgt_nitems != pknumatts)
        ereport(ERROR,
                (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
-                errmsg("target key array length must match number of key " \
-                       "attributes")));
+            errmsg("target key array length must match number of key " \
+                   "attributes")));
 
    /*
     * get array of pointers to c-strings from the input target array
@@ -1126,8 +1125,8 @@ dblink_build_sql_delete(PG_FUNCTION_ARGS)
    if (tgt_nitems != pknumatts)
        ereport(ERROR,
                (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
-                errmsg("target key array length must match number of key " \
-                       "attributes")));
+            errmsg("target key array length must match number of key " \
+                   "attributes")));
 
    /*
     * get array of pointers to c-strings from the input target array
@@ -1249,8 +1248,8 @@ dblink_build_sql_update(PG_FUNCTION_ARGS)
    if (src_nitems != pknumatts)
        ereport(ERROR,
                (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
-                errmsg("source key array length must match number of key " \
-                       "attributes")));
+            errmsg("source key array length must match number of key " \
+                   "attributes")));
 
    /*
     * get array of pointers to c-strings from the input source array
@@ -1282,8 +1281,8 @@ dblink_build_sql_update(PG_FUNCTION_ARGS)
    if (tgt_nitems != pknumatts)
        ereport(ERROR,
                (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
-                errmsg("target key array length must match number of key " \
-                       "attributes")));
+            errmsg("target key array length must match number of key " \
+                   "attributes")));
 
    /*
     * get array of pointers to c-strings from the input target array
@@ -1839,10 +1838,10 @@ pgresultGetTupleDesc(PGresult *res)
            ereport(ERROR,
                    (errcode(ERRCODE_MOST_SPECIFIC_TYPE_MISMATCH),
                     errmsg("field size mismatch"),
-                    errdetail("Size of remote field \"%s\" does not match " \
-                               "size of local type \"%s\".", attname,
-                               format_type_with_typemod(atttypid,
-                                                        atttypmod))));
+               errdetail("Size of remote field \"%s\" does not match " \
+                         "size of local type \"%s\".", attname,
+                         format_type_with_typemod(atttypid,
+                                                  atttypmod))));
 
        attdim = 0;
        attisset = false;
@@ -1893,50 +1892,50 @@ generate_relation_name(Oid relid)
 static remoteConn *
 getConnectionByName(const char *name)
 {
-   remoteConnHashEnt  *hentry;
-   char                key[NAMEDATALEN];
+   remoteConnHashEnt *hentry;
+   char        key[NAMEDATALEN];
 
-   if(!remoteConnHash)
-       remoteConnHash=createConnHash();
+   if (!remoteConnHash)
+       remoteConnHash = createConnHash();
 
    MemSet(key, 0, NAMEDATALEN);
    snprintf(key, NAMEDATALEN - 1, "%s", name);
-   hentry = (remoteConnHashEnt*) hash_search(remoteConnHash,
-                                             key, HASH_FIND, NULL);
+   hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
+                                              key, HASH_FIND, NULL);
 
-   if(hentry)
-       return(hentry->rcon);
+   if (hentry)
+       return (hentry->rcon);
 
-   return(NULL);
+   return (NULL);
 }
 
 static HTAB *
 createConnHash(void)
 {
-   HASHCTL ctl;
-   HTAB   *ptr;
+   HASHCTL     ctl;
+   HTAB       *ptr;
 
    ctl.keysize = NAMEDATALEN;
    ctl.entrysize = sizeof(remoteConnHashEnt);
 
-   ptr=hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
+   ptr = hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
 
-   if(!ptr)
+   if (!ptr)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
 
-   return(ptr);
+   return (ptr);
 }
 
 static void
-createNewConnection(const char *name, remoteConn *con)
+createNewConnection(const char *name, remoteConn * con)
 {
-   remoteConnHashEnt  *hentry;
-   bool                found;
-   char                key[NAMEDATALEN];
+   remoteConnHashEnt *hentry;
+   bool        found;
+   char        key[NAMEDATALEN];
 
-   if(!remoteConnHash)
+   if (!remoteConnHash)
        remoteConnHash = createConnHash();
 
    MemSet(key, 0, NAMEDATALEN);
@@ -1944,12 +1943,12 @@ createNewConnection(const char *name, remoteConn *con)
    hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
                                               HASH_ENTER, &found);
 
-   if(!hentry)
+   if (!hentry)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
 
-   if(found)
+   if (found)
        ereport(ERROR,
                (errcode(ERRCODE_DUPLICATE_OBJECT),
                 errmsg("duplicate connection name")));
@@ -1961,12 +1960,12 @@ createNewConnection(const char *name, remoteConn *con)
 static void
 deleteConnection(const char *name)
 {
-   remoteConnHashEnt  *hentry;
-   bool                found;
-   char                key[NAMEDATALEN];
+   remoteConnHashEnt *hentry;
+   bool        found;
+   char        key[NAMEDATALEN];
 
-   if(!remoteConnHash)
-       remoteConnHash=createConnHash();
+   if (!remoteConnHash)
+       remoteConnHash = createConnHash();
 
    MemSet(key, 0, NAMEDATALEN);
    snprintf(key, NAMEDATALEN - 1, "%s", name);
@@ -1974,7 +1973,7 @@ deleteConnection(const char *name)
    hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
                                               key, HASH_REMOVE, &found);
 
-   if(!hentry)
+   if (!hentry)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_OBJECT),
                 errmsg("undefined connection name")));
index 5eebd1a1ba0bd32cd9b6f52b8f6cb26d5e9c3ed4..cf00276a8f176f3ff35cbf60c7bdebac9296a9ea 100644 (file)
@@ -1,6 +1,6 @@
 /****************************************************************************
  * pending.c
- * $Id: pending.c,v 1.12 2003/07/24 17:52:20 tgl Exp $
+ * $Id: pending.c,v 1.13 2003/08/04 00:43:10 momjian Exp $
  *
  * This file contains a trigger for Postgresql-7.x to record changes to tables
  * to a pending table for mirroring.
@@ -8,7 +8,7 @@
  *
  *  Written by Steven Singer (ssinger@navtechinc.com)
  *  (c) 2001-2002 Navtech Systems Support Inc.
- *       ALL RIGHTS RESERVED
+ *      ALL RIGHTS RESERVED
  *
  * Permission to use, copy, modify, and distribute this software and its
  * documentation for any purpose, without fee, and without a written agreement
@@ -79,8 +79,9 @@ recordchange(PG_FUNCTION_ARGS)
    HeapTuple   retTuple = NULL;
    char       *tblname;
    char        op = 0;
-   char       *schemaname;
+   char       *schemaname;
    char       *fullyqualtblname;
+
    if (fcinfo->context != NULL)
    {
 
@@ -94,13 +95,13 @@ recordchange(PG_FUNCTION_ARGS)
        tblname = SPI_getrelname(trigdata->tg_relation);
 #ifndef NOSCHEMAS
        schemaname = get_namespace_name(RelationGetNamespace(trigdata->tg_relation));
-       fullyqualtblname = SPI_palloc(strlen(tblname) + 
-                         strlen(schemaname) + 6);
-       sprintf(fullyqualtblname,"\"%s\".\"%s\"",
-           schemaname,tblname);
+       fullyqualtblname = SPI_palloc(strlen(tblname) +
+                                     strlen(schemaname) + 6);
+       sprintf(fullyqualtblname, "\"%s\".\"%s\"",
+               schemaname, tblname);
 #else
        fullyqualtblname = SPI_palloc(strlen(tblname) + 3);
-       sprintf(fullyqualtblname,"\"%s\"",tblname);
+       sprintf(fullyqualtblname, "\"%s\"", tblname);
 #endif
        tupdesc = trigdata->tg_relation->rd_att;
        if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
@@ -166,8 +167,8 @@ storePending(char *cpTableName, HeapTuple tBeforeTuple,
    int         iResult = 0;
    HeapTuple   tCurTuple;
 
-   //Points the current tuple(before or after)
-       Datum       saPlanData[4];
+   /* Points the current tuple(before or after) */
+   Datum       saPlanData[4];
    Oid         taPlanArgTypes[3] = {NAMEOID, CHAROID, INT4OID};
    void       *vpPlan;
 
@@ -253,7 +254,7 @@ storeKeyInfo(char *cpTableName, HeapTuple tTupleData,
    if (cpKeyData == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_OBJECT),
-                /* cpTableName already contains quotes... */
+       /* cpTableName already contains quotes... */
                 errmsg("there is no PRIMARY KEY for table %s",
                        cpTableName)));
 
@@ -460,7 +461,7 @@ packageData(HeapTuple tTupleData, TupleDesc tTupleDesc,
        }
        else
        {
-           sprintf(cpFormatedPtr," ");
+           sprintf(cpFormatedPtr, " ");
            iUsedDataBlock++;
            cpFormatedPtr++;
            continue;
@@ -508,8 +509,8 @@ packageData(HeapTuple tTupleData, TupleDesc tTupleDesc,
    if (tpPKeys != NULL)
        SPI_pfree(tpPKeys);
 #if defined DEBUG_OUTPUT
-   elog(NOTICE, "returning DataBlockSize:%d iUsedDataBlock:%d",iDataBlockSize,
-           iUsedDataBlock);
+   elog(NOTICE, "returning DataBlockSize:%d iUsedDataBlock:%d", iDataBlockSize,
+        iUsedDataBlock);
 #endif
    memset(cpDataBlock + iUsedDataBlock, 0, iDataBlockSize - iUsedDataBlock);
 
index c474930ca9592a6a47ddb8d760a64bc00760a284..0037c14e706da940d266d5dd4499d0e07584a051 100644 (file)
@@ -54,7 +54,7 @@ database_size(PG_FUNCTION_ARGS)
    if (!OidIsValid(dbid))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_DATABASE),
-                errmsg("database \"%s\" does not exist", NameStr(*dbname))));
+           errmsg("database \"%s\" does not exist", NameStr(*dbname))));
 
    dbpath = GetDatabasePath(dbid);
 
index 19c81a5783fc2842149bf4f65317a335bd0ba115..28ce40378cfafd0046cb3e2debf946ec27bf6ee0 100644 (file)
@@ -6,8 +6,8 @@
 
 
 /* Earth's radius is in statute miles. */
-const double   EARTH_RADIUS = 3958.747716;
-const double   TWO_PI = 2.0 * M_PI;
+const double EARTH_RADIUS = 3958.747716;
+const double TWO_PI = 2.0 * M_PI;
 
 double    *geo_distance(Point *pt1, Point *pt2);
 
@@ -66,10 +66,11 @@ geo_distance(Point *pt1, Point *pt2)
    if (longdiff > M_PI)
        longdiff = TWO_PI - longdiff;
 
-        sino = sqrt(sin(fabs(lat1-lat2)/2.)*sin(fabs(lat1-lat2)/2.) +
-                cos(lat1) * cos(lat2) * sin(longdiff/2.)*sin(longdiff/2.));
-        if (sino > 1.) sino = 1.;
-        *resultp = 2. * EARTH_RADIUS * asin(sino);
+   sino = sqrt(sin(fabs(lat1 - lat2) / 2.) * sin(fabs(lat1 - lat2) / 2.) +
+       cos(lat1) * cos(lat2) * sin(longdiff / 2.) * sin(longdiff / 2.));
+   if (sino > 1.)
+       sino = 1.;
+   *resultp = 2. * EARTH_RADIUS * asin(sino);
 
    return resultp;
 }
index 8eb27e42a5145ef163738fc2abaf7a240f34e0cd..4843c1f3e5dec7bd5288e751ae7ebe11d0e4b854 100644 (file)
@@ -3,7 +3,7 @@
  *
  * Copyright 2002 by PostgreSQL Global Development Group
  *
- * $Header: /cvsroot/pgsql/contrib/findoidjoins/Attic/findoidjoins.c,v 1.20 2003/05/14 03:25:56 tgl Exp $
+ * $Header: /cvsroot/pgsql/contrib/findoidjoins/Attic/findoidjoins.c,v 1.21 2003/08/04 00:43:10 momjian Exp $
  */
 #include "postgres_fe.h"
 
 int
 main(int argc, char **argv)
 {
-   PGconn             *conn;
-   PQExpBufferData     sql;
-   PGresult           *res;
-   PGresult           *pkrel_res;
-   PGresult           *fkrel_res;
-   char               *fk_relname;
-   char               *fk_nspname;
-   char               *fk_attname;
-   char               *pk_relname;
-   char               *pk_nspname;
-   int                 fk, pk;     /* loop counters */
+   PGconn     *conn;
+   PQExpBufferData sql;
+   PGresult   *res;
+   PGresult   *pkrel_res;
+   PGresult   *fkrel_res;
+   char       *fk_relname;
+   char       *fk_nspname;
+   char       *fk_attname;
+   char       *pk_relname;
+   char       *pk_nspname;
+   int         fk,
+               pk;             /* loop counters */
 
    if (argc != 2)
    {
        fprintf(stderr, "Usage:  %s database\n", argv[0]);
        exit(EXIT_FAILURE);
-   }       
+   }
 
    initPQExpBuffer(&sql);
 
@@ -48,13 +49,13 @@ main(int argc, char **argv)
    resetPQExpBuffer(&sql);
 
    appendPQExpBuffer(&sql, "%s",
-       "SET search_path = public;"
-       "SELECT c.relname, (SELECT nspname FROM "
-       "pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname "
-       "FROM pg_catalog.pg_class c "
-       "WHERE c.relkind = 'r' "
-       "AND c.relhasoids "
-       "ORDER BY nspname, c.relname"
+                     "SET search_path = public;"
+                     "SELECT c.relname, (SELECT nspname FROM "
+   "pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname "
+                     "FROM pg_catalog.pg_class c "
+                     "WHERE c.relkind = 'r' "
+                     "AND c.relhasoids "
+                     "ORDER BY nspname, c.relname"
        );
 
    res = PQexec(conn, sql.data);
@@ -70,20 +71,20 @@ main(int argc, char **argv)
    resetPQExpBuffer(&sql);
 
    appendPQExpBuffer(&sql, "%s",
-       "SELECT c.relname, "
-       "(SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname, "
-       "a.attname "
-       "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
-       "WHERE a.attnum > 0 AND c.relkind = 'r' "
-       "AND a.attrelid = c.oid "
-       "AND a.atttypid IN ('pg_catalog.oid'::regtype, "
-       " 'pg_catalog.regclass'::regtype, "
-       " 'pg_catalog.regoper'::regtype, "
-       " 'pg_catalog.regoperator'::regtype, "
-       " 'pg_catalog.regproc'::regtype, "
-       " 'pg_catalog.regprocedure'::regtype, "
-       " 'pg_catalog.regtype'::regtype) "
-       "ORDER BY nspname, c.relname, a.attnum"
+                     "SELECT c.relname, "
+                     "(SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname, "
+                     "a.attname "
+                "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
+                     "WHERE a.attnum > 0 AND c.relkind = 'r' "
+                     "AND a.attrelid = c.oid "
+                     "AND a.atttypid IN ('pg_catalog.oid'::regtype, "
+                     " 'pg_catalog.regclass'::regtype, "
+                     " 'pg_catalog.regoper'::regtype, "
+                     " 'pg_catalog.regoperator'::regtype, "
+                     " 'pg_catalog.regproc'::regtype, "
+                     " 'pg_catalog.regprocedure'::regtype, "
+                     " 'pg_catalog.regtype'::regtype) "
+                     "ORDER BY nspname, c.relname, a.attnum"
        );
 
    res = PQexec(conn, sql.data);
@@ -95,8 +96,8 @@ main(int argc, char **argv)
    fkrel_res = res;
 
    /*
-    * For each column and each relation-having-OIDs, look to see if
-    * the column contains any values matching entries in the relation.
+    * For each column and each relation-having-OIDs, look to see if the
+    * column contains any values matching entries in the relation.
     */
 
    for (fk = 0; fk < PQntuples(fkrel_res); fk++)
@@ -113,12 +114,12 @@ main(int argc, char **argv)
            resetPQExpBuffer(&sql);
 
            appendPQExpBuffer(&sql,
-               "SELECT 1 "
-               "FROM \"%s\".\"%s\" t1, "
-               "\"%s\".\"%s\" t2 "
-               "WHERE t1.\"%s\"::pg_catalog.oid = t2.oid "
-               "LIMIT 1",
-               fk_nspname, fk_relname, pk_nspname, pk_relname, fk_attname);
+                             "SELECT   1 "
+                             "FROM \"%s\".\"%s\" t1, "
+                             "\"%s\".\"%s\" t2 "
+                             "WHERE t1.\"%s\"::pg_catalog.oid = t2.oid "
+                             "LIMIT 1",
+            fk_nspname, fk_relname, pk_nspname, pk_relname, fk_attname);
 
            res = PQexec(conn, sql.data);
            if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
index 38dba1ce30ee69598cf7932f9222e4abc1521e26..e5095ff1a1d69159ca08217b277f18f27f0102c7 100644 (file)
@@ -304,7 +304,7 @@ fti(PG_FUNCTION_ARGS)
                ereport(ERROR,
                        (errcode(ERRCODE_UNDEFINED_COLUMN),
                         errmsg("column \"%s\" of \"%s\" does not exist",
-                        args[i + 1], indexname)));
+                               args[i + 1], indexname)));
 
            /* Get the char* representation of the column */
            column = SPI_getvalue(rettuple, tupdesc, colnum);
@@ -339,8 +339,8 @@ fti(PG_FUNCTION_ARGS)
                    ret = SPI_execp(*(plan->splan), values, NULL, 0);
                    if (ret != SPI_OK_INSERT)
                        ereport(ERROR,
-                               (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
-                                errmsg("error executing insert")));
+                           (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
+                            errmsg("error executing insert")));
                }
                pfree(buff);
                pfree(data);
index 3f869180b86a0f54be12dcf63810133bad1d7d9a..cc4be6af1de9dc24623297791bf7b439aa49271a 100644 (file)
@@ -87,7 +87,7 @@ levenshtein(PG_FUNCTION_ARGS)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("argument exceeds max length: %d",
-                        MAX_LEVENSHTEIN_STRLEN)));
+                       MAX_LEVENSHTEIN_STRLEN)));
 
    /*
     * If either rows or cols is 0, the answer is the other value. This
@@ -220,7 +220,7 @@ metaphone(PG_FUNCTION_ARGS)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("argument exceeds max length: %d",
-                        MAX_METAPHONE_STRLEN)));
+                       MAX_METAPHONE_STRLEN)));
 
    if (!(str_i_len > 0))
        ereport(ERROR,
@@ -232,7 +232,7 @@ metaphone(PG_FUNCTION_ARGS)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("output length exceeds max length: %d",
-                        MAX_METAPHONE_STRLEN)));
+                       MAX_METAPHONE_STRLEN)));
 
    if (!(reqlen > 0))
        ereport(ERROR,
index 4614b669a7a0cf2dbc852d1f6df924e3972becb8..2bb06ff73a4a81c51cf6bd6d3ebccbf9789b5808 100644 (file)
@@ -132,9 +132,9 @@ ShrinkPGArray(PGARRAY * p)
 
        /* use current transaction context */
        pnew = palloc(cb);
+
        /*
-        * 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;
@@ -194,7 +194,7 @@ int_enum(PG_FUNCTION_ARGS)
    if (!rsi || !IsA(rsi, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                errmsg("int_enum called in context that cannot accept a set")));
+        errmsg("int_enum called in context that cannot accept a set")));
 
    if (!p)
    {
index 5decd969e169c248eb0a8a190a6b7a6d6a243fcf..3e702ca1afedf31993f9f08f53fbabf09676e371 100644 (file)
@@ -91,19 +91,19 @@ typedef char *BITVECP;
  */
 typedef struct
 {
-        int4            len;
-        int4            flag;
-        char            data[1];
-}       GISTTYPE;
+   int4        len;
+   int4        flag;
+   char        data[1];
+}  GISTTYPE;
 
-#define ALLISTRUE       0x04
+#define ALLISTRUE      0x04
 
-#define ISALLTRUE(x)    ( ((GISTTYPE*)x)->flag & ALLISTRUE )
+#define ISALLTRUE(x)   ( ((GISTTYPE*)x)->flag & ALLISTRUE )
 
-#define GTHDRSIZE       ( sizeof(int4)*2  )
+#define GTHDRSIZE      ( sizeof(int4)*2  )
 #define CALCGTSIZE(flag) ( GTHDRSIZE+(((flag) & ALLISTRUE) ? 0 : SIGLEN) )
 
-#define GETSIGN(x)      ( (BITVECP)( (char*)x+GTHDRSIZE ) )
+#define GETSIGN(x)     ( (BITVECP)( (char*)x+GTHDRSIZE ) )
 
 /*
 ** types for functions
@@ -114,22 +114,22 @@ typedef void (*formfloat) (ArrayType *, float *);
 /*
 ** useful function
 */
-bool isort(int4 *a, const int len);
-ArrayType *new_intArrayType(int num);
-ArrayType *copy_intArrayType(ArrayType *a);
-ArrayType *resize_intArrayType(ArrayType *a, int num);
-int    internal_size(int *a, int len);
-ArrayType *_int_unique(ArrayType *a);
-int32 intarray_match_first(ArrayType *a, int32 elem);
-ArrayType *intarray_add_elem(ArrayType *a, int32 elem);
-ArrayType *intarray_concat_arrays(ArrayType *a, ArrayType *b);
-ArrayType *int_to_intset(int32 elem);
-bool inner_int_overlap(ArrayType *a, ArrayType *b);
-bool inner_int_contains(ArrayType *a, ArrayType *b);
-ArrayType inner_int_union(ArrayType *a, ArrayType *b);
-ArrayType inner_int_inter(ArrayType *a, ArrayType *b);
-void rt__int_size(ArrayType *a, float *size);
-void gensign(BITVEC sign, int *a, int len);
+bool       isort(int4 *a, const int len);
+ArrayType  *new_intArrayType(int num);
+ArrayType  *copy_intArrayType(ArrayType *a);
+ArrayType  *resize_intArrayType(ArrayType *a, int num);
+int            internal_size(int *a, int len);
+ArrayType  *_int_unique(ArrayType *a);
+int32      intarray_match_first(ArrayType *a, int32 elem);
+ArrayType  *intarray_add_elem(ArrayType *a, int32 elem);
+ArrayType  *intarray_concat_arrays(ArrayType *a, ArrayType *b);
+ArrayType  *int_to_intset(int32 elem);
+bool       inner_int_overlap(ArrayType *a, ArrayType *b);
+bool       inner_int_contains(ArrayType *a, ArrayType *b);
+ArrayType  *inner_int_union(ArrayType *a, ArrayType *b);
+ArrayType  *inner_int_inter(ArrayType *a, ArrayType *b);
+void       rt__int_size(ArrayType *a, float *size);
+void       gensign(BITVEC sign, int *a, int len);
 
 
 /*****************************************************************************
@@ -160,18 +160,16 @@ typedef struct
 #define COMPUTESIZE(size)  ( HDRSIZEQT + size * sizeof(ITEM) )
 #define GETQUERY(x)  (ITEM*)( (char*)(x)+HDRSIZEQT )
 
-bool signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot);
-bool execconsistent(QUERYTYPE * query, ArrayType *array, bool calcnot);
-
-
+bool       signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot);
+bool       execconsistent(QUERYTYPE * query, ArrayType *array, bool calcnot);
 
-int compASC(const void *a, const void *b);
 
-int compDESC(const void *a, const void *b);
 
-#define QSORT(a, direction)                                     \
-if (ARRNELEMS(a) > 1)                                           \
-        qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4),      \
-                (direction) ? compASC : compDESC )
+int            compASC(const void *a, const void *b);
 
+int            compDESC(const void *a, const void *b);
 
+#define QSORT(a, direction)                                        \
+if (ARRNELEMS(a) > 1)                                          \
+       qsort((void*)ARRPTR(a), ARRNELEMS(a),sizeof(int4),      \
+               (direction) ? compASC : compDESC )
index 35d6e6e2c002e09105abafae3b81a1965aae3b4b..d57a94e8709e3e8cbed0c5c6a833fe8a926f3339 100644 (file)
@@ -299,7 +299,7 @@ signconsistent(QUERYTYPE * query, BITVEC sign, bool calcnot)
                   GETQUERY(query) + query->size - 1,
                   (void *) sign, calcnot,
                   checkcondition_bit
-   );
+       );
 }
 
 bool
@@ -326,7 +326,7 @@ rboolop(PG_FUNCTION_ARGS)
                               boolop,
                               PG_GETARG_DATUM(1),
                               PG_GETARG_DATUM(0)
-   );
+       );
 }
 
 Datum
@@ -743,4 +743,3 @@ querytree(PG_FUNCTION_ARGS)
 
    PG_RETURN_POINTER(res);
 }
-
index fa6d502e891cf2424c2f732d632c2d62035c10ef..39c9679adddfb490b27afad9da03d286b09c88be 100644 (file)
@@ -85,27 +85,31 @@ g_int_consistent(PG_FUNCTION_ARGS)
 }
 
 Datum
-g_int_union(PG_FUNCTION_ARGS) {
-   bytea      *entryvec = (bytea *) PG_GETARG_POINTER(0);
-   int                *size = (int *) PG_GETARG_POINTER(1);
-   int4            i,len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
-   ArrayType   *res;
-   int totlen=0,*ptr;
+g_int_union(PG_FUNCTION_ARGS)
+{
+   bytea      *entryvec = (bytea *) PG_GETARG_POINTER(0);
+   int        *size = (int *) PG_GETARG_POINTER(1);
+   int4        i,
+               len = (VARSIZE(entryvec) - VARHDRSZ) / sizeof(GISTENTRY);
+   ArrayType  *res;
+   int         totlen = 0,
+              *ptr;
 
    for (i = 0; i < len; i++)
-       totlen+=ARRNELEMS( GETENTRY(entryvec,i) );
+       totlen += ARRNELEMS(GETENTRY(entryvec, i));
 
-   res=new_intArrayType(totlen);
-   ptr=ARRPTR(res);
+   res = new_intArrayType(totlen);
+   ptr = ARRPTR(res);
 
-   for (i = 0; i < len; i++) {
-       memcpy(ptr, ARRPTR( GETENTRY(entryvec,i) ), ARRNELEMS( GETENTRY(entryvec,i) )*sizeof(int4) );
-       ptr+=ARRNELEMS( GETENTRY(entryvec,i) );
+   for (i = 0; i < len; i++)
+   {
+       memcpy(ptr, ARRPTR(GETENTRY(entryvec, i)), ARRNELEMS(GETENTRY(entryvec, i)) * sizeof(int4));
+       ptr += ARRNELEMS(GETENTRY(entryvec, i));
    }
 
-   QSORT(res,1);
-   res=_int_unique(res);
-   *size = VARSIZE(res);   
+   QSORT(res, 1);
+   res = _int_unique(res);
+   *size = VARSIZE(res);
    PG_RETURN_POINTER(res);
 }
 
@@ -239,22 +243,23 @@ g_int_decompress(PG_FUNCTION_ARGS)
 ** The GiST Penalty method for _intments
 */
 Datum
-g_int_penalty(PG_FUNCTION_ARGS) {
-   GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0);
-   GISTENTRY *newentry  = (GISTENTRY *) PG_GETARG_POINTER(1);
-   float *result = (float *) PG_GETARG_POINTER(2);
+g_int_penalty(PG_FUNCTION_ARGS)
+{
+   GISTENTRY  *origentry = (GISTENTRY *) PG_GETARG_POINTER(0);
+   GISTENTRY  *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
+   float      *result = (float *) PG_GETARG_POINTER(2);
    ArrayType  *ud;
    float       tmp1,
                tmp2;
 
    ud = inner_int_union((ArrayType *) DatumGetPointer(origentry->key),
-                   (ArrayType *) DatumGetPointer(newentry->key));
+                        (ArrayType *) DatumGetPointer(newentry->key));
    rt__int_size(ud, &tmp1);
    rt__int_size((ArrayType *) DatumGetPointer(origentry->key), &tmp2);
    *result = tmp1 - tmp2;
    pfree(ud);
 
-   PG_RETURN_POINTER (result);
+   PG_RETURN_POINTER(result);
 }
 
 
@@ -311,8 +316,9 @@ comparecost(const void *a, const void *b)
 ** We use Guttman's poly time split algorithm
 */
 Datum
-g_int_picksplit(PG_FUNCTION_ARGS) {
-   bytea *entryvec = (bytea *) PG_GETARG_POINTER(0);
+g_int_picksplit(PG_FUNCTION_ARGS)
+{
+   bytea      *entryvec = (bytea *) PG_GETARG_POINTER(0);
    GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
    OffsetNumber i,
                j;
@@ -501,4 +507,3 @@ g_int_picksplit(PG_FUNCTION_ARGS) {
 
    PG_RETURN_POINTER(v);
 }
-
index 04ff5e436b6874b6f37fe71c23f87bdeeecdff16..d5f169f7c82680228cc6eb682ca88464ef03919f 100644 (file)
@@ -270,7 +270,7 @@ _int_unique(ArrayType *r)
               *data;
    int         num = ARRNELEMS(r);
 
-   if ( num<2 )
+   if (num < 2)
        return r;
 
    data = tmp = dr = ARRPTR(r);
@@ -367,4 +367,3 @@ compDESC(const void *a, const void *b)
        return 0;
    return (*(int4 *) a < *(int4 *) b) ? 1 : -1;
 }
-
index f55434d3876aa0c40464390b83adfc12d525d077..3890769ce1a5531f6e5f51187ff6be51a3bc5c29 100644 (file)
@@ -45,8 +45,8 @@ array_iterator(ArrayType *la, PGCALL2 callback, void *param, ltree ** found)
 
    if (ARR_NDIM(la) != 1)
        ereport(ERROR,
-           (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
-            errmsg("array must be one-dimensional")));
+               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                errmsg("array must be one-dimensional")));
 
    if (found)
        *found = NULL;
@@ -133,38 +133,40 @@ _ltq_rregex(PG_FUNCTION_ARGS)
 Datum
 _lt_q_regex(PG_FUNCTION_ARGS)
 {
-        ArrayType      *_tree = PG_GETARG_ARRAYTYPE_P(0);
-        ArrayType   *_query =  PG_GETARG_ARRAYTYPE_P(1);
-        lquery  *query = (lquery *) ARR_DATA_PTR(_query);
-        bool    res = false;
-        int     num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query));
-
-        if (ARR_NDIM(_query) != 1)
-           ereport(ERROR,
+   ArrayType  *_tree = PG_GETARG_ARRAYTYPE_P(0);
+   ArrayType  *_query = PG_GETARG_ARRAYTYPE_P(1);
+   lquery     *query = (lquery *) ARR_DATA_PTR(_query);
+   bool        res = false;
+   int         num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query));
+
+   if (ARR_NDIM(_query) != 1)
+       ereport(ERROR,
                (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                 errmsg("array must be one-dimensional")));
 
-        while (num > 0) {
-       if ( array_iterator(_tree, ltq_regex, (void*)query, NULL) ) {
-                        res = true;
-                        break;
-                }
-                num--;
-                query = (lquery*)NEXTVAL(query);
-        }
-
-        PG_FREE_IF_COPY(_tree, 0);
-        PG_FREE_IF_COPY(_query, 1);
-        PG_RETURN_BOOL(res);
+   while (num > 0)
+   {
+       if (array_iterator(_tree, ltq_regex, (void *) query, NULL))
+       {
+           res = true;
+           break;
+       }
+       num--;
+       query = (lquery *) NEXTVAL(query);
+   }
+
+   PG_FREE_IF_COPY(_tree, 0);
+   PG_FREE_IF_COPY(_query, 1);
+   PG_RETURN_BOOL(res);
 }
 
 Datum
 _lt_q_rregex(PG_FUNCTION_ARGS)
 {
-        PG_RETURN_DATUM(DirectFunctionCall2(_lt_q_regex,
-                                                                                PG_GETARG_DATUM(1),
-                                                                                PG_GETARG_DATUM(0)
-                                                                                ));
+   PG_RETURN_DATUM(DirectFunctionCall2(_lt_q_regex,
+                                       PG_GETARG_DATUM(1),
+                                       PG_GETARG_DATUM(0)
+                                       ));
 }
 
 
index 72fd968d59586775d01828475c1d16ebe23b7c73..2328fcd238670a1804948f6ac1ef19030c3d5cae 100644 (file)
@@ -45,7 +45,7 @@ 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)
+           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;
@@ -123,10 +123,15 @@ printFieldNot(FieldNot *fn ) {
 }
 */
 
-static struct {
-   bool muse;
-   uint32  high_pos;
-} SomeStack = {false,0,};
+static struct
+{
+   bool        muse;
+   uint32      high_pos;
+}  SomeStack =
+
+{
+   false, 0,
+};
 
 static bool
 checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_numlevel, FieldNot * ptr)
@@ -140,7 +145,8 @@ checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_
    lquery_level *prevq = NULL;
    ltree_level *prevt = NULL;
 
-   if ( SomeStack.muse ) {
+   if (SomeStack.muse)
+   {
        high_pos = SomeStack.high_pos;
        qlen--;
        prevq = curq;
@@ -200,13 +206,15 @@ checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_
                    curt = LEVEL_NEXT(curt);
                    tlen--;
                    cur_tpos++;
-                   if ( isok && prevq && prevq->numvar==0 && tlen>0 && cur_tpos <= high_pos ) {
-                       FieldNot tmpptr;
-                       if ( ptr )
-                           memcpy(&tmpptr,ptr,sizeof(FieldNot));
-                       SomeStack.high_pos = high_pos-cur_tpos;
+                   if (isok && prevq && prevq->numvar == 0 && tlen > 0 && cur_tpos <= high_pos)
+                   {
+                       FieldNot    tmpptr;
+
+                       if (ptr)
+                           memcpy(&tmpptr, ptr, sizeof(FieldNot));
+                       SomeStack.high_pos = high_pos - cur_tpos;
                        SomeStack.muse = true;
-                       if ( checkCond(prevq, qlen+1, curt, tlen, (ptr) ? &tmpptr : NULL) )
+                       if (checkCond(prevq, qlen + 1, curt, tlen, (ptr) ? &tmpptr : NULL))
                            return true;
                    }
                    if (!isok && ptr)
@@ -311,19 +319,21 @@ Datum
 lt_q_regex(PG_FUNCTION_ARGS)
 {
    ltree      *tree = PG_GETARG_LTREE(0);
-   ArrayType   *_query =  PG_GETARG_ARRAYTYPE_P(1);
-   lquery  *query = (lquery *) ARR_DATA_PTR(_query);   
-   bool    res = false;
-        int     num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query));
+   ArrayType  *_query = PG_GETARG_ARRAYTYPE_P(1);
+   lquery     *query = (lquery *) ARR_DATA_PTR(_query);
+   bool        res = false;
+   int         num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query));
 
-        if (ARR_NDIM(_query) != 1)
-           ereport(ERROR,
+   if (ARR_NDIM(_query) != 1)
+       ereport(ERROR,
                (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
                 errmsg("array must be one-dimensional")));
 
-   while (num > 0) {
+   while (num > 0)
+   {
        if (DatumGetBool(DirectFunctionCall2(ltq_regex,
-               PointerGetDatum(tree), PointerGetDatum(query)))) {
+                        PointerGetDatum(tree), PointerGetDatum(query))))
+       {
 
            res = true;
            break;
@@ -345,5 +355,3 @@ lt_q_rregex(PG_FUNCTION_ARGS)
                                        PG_GETARG_DATUM(0)
                                        ));
 }
-
-
index 24116b024248d0a9ecd3432420eebe03313de9c1..62c033cc5df61a63fc078a7e67503571d7a501ad 100644 (file)
@@ -22,7 +22,7 @@ Datum     lquery_out(PG_FUNCTION_ARGS);
 
 #define UNCHAR ereport(ERROR, \
                       (errcode(ERRCODE_SYNTAX_ERROR), \
-                       errmsg("syntax error at position %d near \"%c\"", \
+                       errmsg("syntax error at position %d near \"%c\"", \
                        (int)(ptr-buf), *ptr)));
 
 
@@ -81,8 +81,8 @@ ltree_in(PG_FUNCTION_ARGS)
                            (errcode(ERRCODE_NAME_TOO_LONG),
                             errmsg("name of level is too long"),
                             errdetail("name length is %d, must " \
-                                   "be < 256, in position %d",
-                                   lptr->len, (int) (lptr->start - buf))));
+                                      "be < 256, in position %d",
+                                lptr->len, (int) (lptr->start - buf))));
 
                totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
                lptr++;
@@ -105,8 +105,8 @@ ltree_in(PG_FUNCTION_ARGS)
                    (errcode(ERRCODE_NAME_TOO_LONG),
                     errmsg("name of level is too long"),
                     errdetail("name length is %d, must " \
-                               "be < 256, in position %d",
-                               lptr->len, (int) (lptr->start - buf))));
+                              "be < 256, in position %d",
+                              lptr->len, (int) (lptr->start - buf))));
 
        totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE);
        lptr++;
@@ -283,8 +283,8 @@ lquery_in(PG_FUNCTION_ARGS)
                            (errcode(ERRCODE_NAME_TOO_LONG),
                             errmsg("name of level is too long"),
                             errdetail("name length is %d, must " \
-                                       "be < 256, in position %d",
-                                       lptr->len, (int) (lptr->start - buf))));
+                                      "be < 256, in position %d",
+                                lptr->len, (int) (lptr->start - buf))));
 
                state = LQPRS_WAITVAR;
            }
@@ -299,8 +299,8 @@ lquery_in(PG_FUNCTION_ARGS)
                            (errcode(ERRCODE_NAME_TOO_LONG),
                             errmsg("name of level is too long"),
                             errdetail("name length is %d, must " \
-                                       "be < 256, in position %d",
-                                       lptr->len, (int) (lptr->start - buf))));
+                                      "be < 256, in position %d",
+                                lptr->len, (int) (lptr->start - buf))));
 
                state = LQPRS_WAITLEVEL;
                curqlevel = NEXTLEV(curqlevel);
@@ -412,8 +412,8 @@ lquery_in(PG_FUNCTION_ARGS)
                    (errcode(ERRCODE_NAME_TOO_LONG),
                     errmsg("name of level is too long"),
                     errdetail("name length is %d, must " \
-                           "be < 256, in position %d",
-                           lptr->len, (int) (lptr->start - buf))));
+                              "be < 256, in position %d",
+                              lptr->len, (int) (lptr->start - buf))));
    }
    else if (state == LQPRS_WAITOPEN)
        curqlevel->high = 0xffff;
@@ -442,7 +442,7 @@ lquery_in(PG_FUNCTION_ARGS)
                    (errcode(ERRCODE_SYNTAX_ERROR),
                     errmsg("syntax error"),
                     errdetail("Low limit(%d) is greater than upper(%d).",
-                               curqlevel->low, curqlevel->high)));
+                              curqlevel->low, curqlevel->high)));
 
        curqlevel = NEXTLEV(curqlevel);
    }
index 1b3c80b726669999aef4d653527d5297431210b4..4dcb558fe48299cfdc28ac5713ba4ab2357800e9 100644 (file)
@@ -83,49 +83,49 @@ Datum
 ltree_cmp(PG_FUNCTION_ARGS)
 {
    RUNCMP
-   PG_RETURN_INT32(res);
+       PG_RETURN_INT32(res);
 }
 
 Datum
 ltree_lt(PG_FUNCTION_ARGS)
 {
    RUNCMP
-   PG_RETURN_BOOL((res < 0) ? true : false);
+       PG_RETURN_BOOL((res < 0) ? true : false);
 }
 
 Datum
 ltree_le(PG_FUNCTION_ARGS)
 {
    RUNCMP
-   PG_RETURN_BOOL((res <= 0) ? true : false);
+       PG_RETURN_BOOL((res <= 0) ? true : false);
 }
 
 Datum
 ltree_eq(PG_FUNCTION_ARGS)
 {
    RUNCMP
-   PG_RETURN_BOOL((res == 0) ? true : false);
+       PG_RETURN_BOOL((res == 0) ? true : false);
 }
 
 Datum
 ltree_ge(PG_FUNCTION_ARGS)
 {
    RUNCMP
-   PG_RETURN_BOOL((res >= 0) ? true : false);
+       PG_RETURN_BOOL((res >= 0) ? true : false);
 }
 
 Datum
 ltree_gt(PG_FUNCTION_ARGS)
 {
    RUNCMP
-   PG_RETURN_BOOL((res > 0) ? true : false);
+       PG_RETURN_BOOL((res > 0) ? true : false);
 }
 
 Datum
 ltree_ne(PG_FUNCTION_ARGS)
 {
    RUNCMP
-   PG_RETURN_BOOL((res != 0) ? true : false);
+       PG_RETURN_BOOL((res != 0) ? true : false);
 }
 
 Datum
@@ -331,46 +331,55 @@ ltree_index(PG_FUNCTION_ARGS)
 {
    ltree      *a = PG_GETARG_LTREE(0);
    ltree      *b = PG_GETARG_LTREE(1);
-   int start=(fcinfo->nargs == 3) ? PG_GETARG_INT32(2) : 0;
-   int i,j;
-   ltree_level *startptr, *aptr, *bptr;
-   bool found=false;
-
-   if ( start < 0 ) {
-       if ( -start >= a->numlevel ) 
-           start=0;
-       else 
-           start = (int)(a->numlevel)+start;
+   int         start = (fcinfo->nargs == 3) ? PG_GETARG_INT32(2) : 0;
+   int         i,
+               j;
+   ltree_level *startptr,
+              *aptr,
+              *bptr;
+   bool        found = false;
+
+   if (start < 0)
+   {
+       if (-start >= a->numlevel)
+           start = 0;
+       else
+           start = (int) (a->numlevel) + start;
    }
 
-   if ( a->numlevel - start < b->numlevel || a->numlevel==0 || b->numlevel==0 ) {
+   if (a->numlevel - start < b->numlevel || a->numlevel == 0 || b->numlevel == 0)
+   {
        PG_FREE_IF_COPY(a, 0);
        PG_FREE_IF_COPY(b, 1);
        PG_RETURN_INT32(-1);
    }
 
-   startptr=LTREE_FIRST(a);
-   for(i=0; i<=a->numlevel-b->numlevel; i++) {
-       if ( i>=start ) {
-           aptr=startptr;
-           bptr=LTREE_FIRST(b);
-           for(j=0;j<b->numlevel;j++) {
-               if ( !(aptr->len==bptr->len && strncmp(aptr->name,bptr->name, aptr->len)==0) )
-                   break; 
-               aptr=LEVEL_NEXT(aptr);
-               bptr=LEVEL_NEXT(bptr);
+   startptr = LTREE_FIRST(a);
+   for (i = 0; i <= a->numlevel - b->numlevel; i++)
+   {
+       if (i >= start)
+       {
+           aptr = startptr;
+           bptr = LTREE_FIRST(b);
+           for (j = 0; j < b->numlevel; j++)
+           {
+               if (!(aptr->len == bptr->len && strncmp(aptr->name, bptr->name, aptr->len) == 0))
+                   break;
+               aptr = LEVEL_NEXT(aptr);
+               bptr = LEVEL_NEXT(bptr);
            }
-   
-           if ( j==b->numlevel ) {
-               found=true;
+
+           if (j == b->numlevel)
+           {
+               found = true;
                break;
            }
        }
-       startptr=LEVEL_NEXT(startptr);  
+       startptr = LEVEL_NEXT(startptr);
    }
-   
-   if ( !found ) 
-       i=-1;
+
+   if (!found)
+       i = -1;
 
    PG_FREE_IF_COPY(a, 0);
    PG_FREE_IF_COPY(b, 1);
@@ -496,18 +505,18 @@ Datum
 text2ltree(PG_FUNCTION_ARGS)
 {
    text       *in = PG_GETARG_TEXT_P(0);
-   char *s = (char *) palloc(VARSIZE(in) - VARHDRSZ + 1);
-   ltree *out;
+   char       *s = (char *) palloc(VARSIZE(in) - VARHDRSZ + 1);
+   ltree      *out;
 
    memcpy(s, VARDATA(in), VARSIZE(in) - VARHDRSZ);
    s[VARSIZE(in) - VARHDRSZ] = '\0';
 
    out = (ltree *) DatumGetPointer(DirectFunctionCall1(
-               ltree_in,
-               PointerGetDatum(s)
-           ));
+                                                       ltree_in,
+                                                       PointerGetDatum(s)
+                                                       ));
    pfree(s);
-   PG_FREE_IF_COPY(in,0);
+   PG_FREE_IF_COPY(in, 0);
    PG_RETURN_POINTER(out);
 }
 
@@ -516,16 +525,18 @@ Datum
 ltree2text(PG_FUNCTION_ARGS)
 {
    ltree      *in = PG_GETARG_LTREE(0);
-   char       *ptr;
-   int                     i;
+   char       *ptr;
+   int         i;
    ltree_level *curlevel;
-   text    *out;
-                    
-   out=(text*)palloc(in->len+VARHDRSZ);
-   ptr = VARDATA(out); 
+   text       *out;
+
+   out = (text *) palloc(in->len + VARHDRSZ);
+   ptr = VARDATA(out);
    curlevel = LTREE_FIRST(in);
-   for (i = 0; i < in->numlevel; i++) {
-       if (i != 0) {
+   for (i = 0; i < in->numlevel; i++)
+   {
+       if (i != 0)
+       {
            *ptr = '.';
            ptr++;
        }
@@ -533,13 +544,9 @@ ltree2text(PG_FUNCTION_ARGS)
        ptr += curlevel->len;
        curlevel = LEVEL_NEXT(curlevel);
    }
-               
-   VARATT_SIZEP(out) = VARHDRSZ + (ptr-VARDATA(out)); 
+
+   VARATT_SIZEP(out) = VARHDRSZ + (ptr - VARDATA(out));
    PG_FREE_IF_COPY(in, 0);
-        
+
    PG_RETURN_POINTER(out);
 }
-
-   
-
-
index e2e2907267f3ee5b60fc3c2c502063b6c8aabeae..76369fd13cb6ef40dbc5a4ffa7403a1ee62bdac4 100644 (file)
@@ -356,8 +356,8 @@ sql_exec_dumptable(PGconn *conn, int systables)
        snprintf(todo, 1024, "select relfilenode,relname from pg_class order by relname");
    else
        snprintf(todo, 1024, "select relfilenode,relname from pg_class "
-                           "where relkind not in ('v','s', 'c') and "
-                           "relname not like 'pg_%%' order by relname");
+                "where relkind not in ('v','s', 'c') and "
+                "relname not like 'pg_%%' order by relname");
 
    sql_exec(conn, todo, 0);
 }
index dce065d7b6f13f71a2117468051f62bf0553f55d..01d22dbc6b19a7330189ebfb4752d3ea2fe9d581 100644 (file)
 
 #include "pg_autovacuum.h"
 #define TIMEBUFF 256
-FILE *LOGOUTPUT;
-char timebuffer[TIMEBUFF];
-char logbuffer[4096];
+FILE      *LOGOUTPUT;
+char       timebuffer[TIMEBUFF];
+char       logbuffer[4096];
 
 void
-log_entry (const char *logentry)
+log_entry(const char *logentry)
 {
-  time_t curtime;
-  struct tm *loctime;
-  curtime = time (NULL);
-  loctime = localtime (&curtime);
-  strftime (timebuffer, TIMEBUFF, "%Y-%m-%d %r", loctime);  /* cbb - %F is not always available */
-  fprintf (LOGOUTPUT, "[%s] %s\n", timebuffer, logentry);
+   time_t      curtime;
+   struct tm  *loctime;
+
+   curtime = time(NULL);
+   loctime = localtime(&curtime);
+   strftime(timebuffer, TIMEBUFF, "%Y-%m-%d %r", loctime);     /* cbb - %F is not
+                                                                * always available */
+   fprintf(LOGOUTPUT, "[%s] %s\n", timebuffer, logentry);
 }
 
 /* Function used to detatch the pg_autovacuum daemon from the tty and go into the background *
-*     This code is mostly ripped directly from pm_dameonize in postmaster.c               *
-*     with unneeded code removed.                                                         */
-void daemonize ()
+*    This code is mostly ripped directly from pm_dameonize in postmaster.c               *
+*    with unneeded code removed.                                                         */
+void
+daemonize()
 {
-  pid_t pid;
-
-  pid = fork();
-  if (pid == (pid_t) -1)
-  {
-    log_entry("Error: cannot disassociate from controlling TTY");
-    fflush(LOGOUTPUT);
-    _exit(1);
-  }
-  else if (pid)
-  {  /* parent */
-     /* Parent should just exit, without doing any atexit cleanup */
-    _exit(0);
-  }
+   pid_t       pid;
+
+   pid = fork();
+   if (pid == (pid_t) -1)
+   {
+       log_entry("Error: cannot disassociate from controlling TTY");
+       fflush(LOGOUTPUT);
+       _exit(1);
+   }
+   else if (pid)
+   {                           /* parent */
+       /* Parent should just exit, without doing any atexit cleanup */
+       _exit(0);
+   }
 
 /* GH: If there's no setsid(), we hopefully don't need silent mode.
  * Until there's a better solution.  */
 #ifdef HAVE_SETSID
-  if (setsid() < 0)
-  {
-    log_entry("Error: cannot disassociate from controlling TTY");
-    fflush(LOGOUTPUT);
-    _exit(1);
-  }
+   if (setsid() < 0)
+   {
+       log_entry("Error: cannot disassociate from controlling TTY");
+       fflush(LOGOUTPUT);
+       _exit(1);
+   }
 #endif
 
 }
 
 /* Create and return tbl_info struct with initialized to values from row or res */
 tbl_info *
-init_table_info (PGresult * res, int row, db_info *dbi)
+init_table_info(PGresult *res, int row, db_info * dbi)
 {
-  tbl_info *new_tbl = (tbl_info *) malloc (sizeof (tbl_info));
-
-  if (!new_tbl) {
-    log_entry ("init_table_info: Cannot get memory");
-    fflush (LOGOUTPUT);
-    return NULL;
-  }
-
-  if (NULL == res)
-    return NULL;
-
-  new_tbl->dbi = dbi;    /* set pointer to db */
-
-  new_tbl->schema_name = (char *)
-    malloc (strlen (PQgetvalue (res, row, PQfnumber (res, "schemaname"))) + 1);
-  if (!new_tbl->schema_name) {
-    log_entry ("init_table_info: malloc failed on new_tbl->schema_name");
-    fflush (LOGOUTPUT);
-    return NULL;
-  }
-  strcpy (new_tbl->schema_name,
-    PQgetvalue (res, row, PQfnumber (res, "schemaname")));
-
-  new_tbl->table_name = (char *)
-    malloc (strlen (PQgetvalue (res, row, PQfnumber (res, "relname"))) +
-    strlen (new_tbl->schema_name) + 2);
-  if (!new_tbl->table_name) {
-    log_entry ("init_table_info: malloc failed on new_tbl->table_name");
-    fflush (LOGOUTPUT);
-    return NULL;
-  }
-  strcpy (new_tbl->table_name, new_tbl->schema_name);
-  strcat (new_tbl->table_name, ".");
-  strcat (new_tbl->table_name, PQgetvalue (res, row, PQfnumber (res, "relname")));
-
-  new_tbl->CountAtLastAnalyze =
-    (atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_ins"))) +
-     atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_upd"))));
-  new_tbl->curr_analyze_count = new_tbl->CountAtLastAnalyze;
-
-  new_tbl->CountAtLastVacuum =
-    (atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_del"))) +
-     atol (PQgetvalue (res, row, PQfnumber (res, "n_tup_upd"))));
-  new_tbl->curr_vacuum_count = new_tbl->CountAtLastVacuum;
-
-  new_tbl->relfilenode = atoi (PQgetvalue (res, row, PQfnumber (res, "relfilenode")));
-  new_tbl->reltuples =   atoi (PQgetvalue (res, row, PQfnumber (res, "reltuples")));
-  new_tbl->relpages =    atoi (PQgetvalue (res, row, PQfnumber (res, "relpages")));
-
-  new_tbl->analyze_threshold =
-    args->analyze_base_threshold + args->analyze_scaling_factor * new_tbl->reltuples;
-  new_tbl->vacuum_threshold =
-    args->vacuum_base_threshold + args->vacuum_scaling_factor * new_tbl->reltuples;
-
-  if (args->debug >= 2) {
-    print_table_info (new_tbl);
-  }
-
-  return new_tbl;
+   tbl_info   *new_tbl = (tbl_info *) malloc(sizeof(tbl_info));
+
+   if (!new_tbl)
+   {
+       log_entry("init_table_info: Cannot get memory");
+       fflush(LOGOUTPUT);
+       return NULL;
+   }
+
+   if (NULL == res)
+       return NULL;
+
+   new_tbl->dbi = dbi;         /* set pointer to db */
+
+   new_tbl->schema_name = (char *)
+       malloc(strlen(PQgetvalue(res, row, PQfnumber(res, "schemaname"))) + 1);
+   if (!new_tbl->schema_name)
+   {
+       log_entry("init_table_info: malloc failed on new_tbl->schema_name");
+       fflush(LOGOUTPUT);
+       return NULL;
+   }
+   strcpy(new_tbl->schema_name,
+          PQgetvalue(res, row, PQfnumber(res, "schemaname")));
+
+   new_tbl->table_name = (char *)
+       malloc(strlen(PQgetvalue(res, row, PQfnumber(res, "relname"))) +
+              strlen(new_tbl->schema_name) + 2);
+   if (!new_tbl->table_name)
+   {
+       log_entry("init_table_info: malloc failed on new_tbl->table_name");
+       fflush(LOGOUTPUT);
+       return NULL;
+   }
+   strcpy(new_tbl->table_name, new_tbl->schema_name);
+   strcat(new_tbl->table_name, ".");
+   strcat(new_tbl->table_name, PQgetvalue(res, row, PQfnumber(res, "relname")));
+
+   new_tbl->CountAtLastAnalyze =
+       (atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_ins"))) +
+        atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_upd"))));
+   new_tbl->curr_analyze_count = new_tbl->CountAtLastAnalyze;
+
+   new_tbl->CountAtLastVacuum =
+       (atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_del"))) +
+        atol(PQgetvalue(res, row, PQfnumber(res, "n_tup_upd"))));
+   new_tbl->curr_vacuum_count = new_tbl->CountAtLastVacuum;
+
+   new_tbl->relfilenode = atoi(PQgetvalue(res, row, PQfnumber(res, "relfilenode")));
+   new_tbl->reltuples = atoi(PQgetvalue(res, row, PQfnumber(res, "reltuples")));
+   new_tbl->relpages = atoi(PQgetvalue(res, row, PQfnumber(res, "relpages")));
+
+   new_tbl->analyze_threshold =
+       args->analyze_base_threshold + args->analyze_scaling_factor * new_tbl->reltuples;
+   new_tbl->vacuum_threshold =
+       args->vacuum_base_threshold + args->vacuum_scaling_factor * new_tbl->reltuples;
+
+   if (args->debug >= 2)
+       print_table_info(new_tbl);
+
+   return new_tbl;
 }
 
 /* Set thresholds = base_value + scaling_factor * reltuples
    Should be called after a vacuum since vacuum updates values in pg_class */
 void
-update_table_thresholds (db_info * dbi, tbl_info * tbl,int vacuum_type)
+update_table_thresholds(db_info * dbi, tbl_info * tbl, int vacuum_type)
 {
-  PGresult *res = NULL;
-  int disconnect = 0;
-  char query[128];
-
-  if (NULL == dbi->conn) {
-    dbi->conn = db_connect (dbi);
-    disconnect = 1;
-  }
-
-  if (NULL != dbi->conn) {
-    snprintf (query, sizeof (query), PAGES_QUERY, tbl->relfilenode);
-    res = send_query (query, dbi);
-    if (NULL != res) {
-      tbl->reltuples =
-        atoi (PQgetvalue (res, 0, PQfnumber (res, "reltuples")));
-      tbl->relpages = atoi (PQgetvalue (res, 0, PQfnumber (res, "relpages")));
-
-      /* update vacuum thresholds only of we just did a vacuum analyze */
-      if(VACUUM_ANALYZE == vacuum_type)
-      {
-        tbl->vacuum_threshold =
-          (args->vacuum_base_threshold + args->vacuum_scaling_factor * tbl->reltuples);
-        tbl->CountAtLastVacuum  = tbl->curr_vacuum_count;
-      }
-
-      /* update analyze thresholds */
-      tbl->analyze_threshold =
-        (args->analyze_base_threshold + args->analyze_scaling_factor * tbl->reltuples);
-      tbl->CountAtLastAnalyze = tbl->curr_analyze_count;
-
-      PQclear (res);
-
-      /* If the stats collector is reporting fewer updates then we have on record
-         then the stats were probably reset, so we need to reset also */
-      if ((tbl->curr_analyze_count < tbl->CountAtLastAnalyze) ||
-          (tbl->curr_vacuum_count < tbl->CountAtLastVacuum))
-      {
-        tbl->CountAtLastAnalyze = tbl->curr_analyze_count;
-        tbl->CountAtLastVacuum = tbl->curr_vacuum_count;
-      }
-    }
-  }
-  if (disconnect)
-    db_disconnect (dbi);
+   PGresult   *res = NULL;
+   int         disconnect = 0;
+   char        query[128];
+
+   if (NULL == dbi->conn)
+   {
+       dbi->conn = db_connect(dbi);
+       disconnect = 1;
+   }
+
+   if (NULL != dbi->conn)
+   {
+       snprintf(query, sizeof(query), PAGES_QUERY, tbl->relfilenode);
+       res = send_query(query, dbi);
+       if (NULL != res)
+       {
+           tbl->reltuples =
+               atoi(PQgetvalue(res, 0, PQfnumber(res, "reltuples")));
+           tbl->relpages = atoi(PQgetvalue(res, 0, PQfnumber(res, "relpages")));
+
+           /*
+            * update vacuum thresholds only of we just did a vacuum
+            * analyze
+            */
+           if (VACUUM_ANALYZE == vacuum_type)
+           {
+               tbl->vacuum_threshold =
+                   (args->vacuum_base_threshold + args->vacuum_scaling_factor * tbl->reltuples);
+               tbl->CountAtLastVacuum = tbl->curr_vacuum_count;
+           }
+
+           /* update analyze thresholds */
+           tbl->analyze_threshold =
+               (args->analyze_base_threshold + args->analyze_scaling_factor * tbl->reltuples);
+           tbl->CountAtLastAnalyze = tbl->curr_analyze_count;
+
+           PQclear(res);
+
+           /*
+            * If the stats collector is reporting fewer updates then we
+            * have on record then the stats were probably reset, so we
+            * need to reset also
+            */
+           if ((tbl->curr_analyze_count < tbl->CountAtLastAnalyze) ||
+               (tbl->curr_vacuum_count < tbl->CountAtLastVacuum))
+           {
+               tbl->CountAtLastAnalyze = tbl->curr_analyze_count;
+               tbl->CountAtLastVacuum = tbl->curr_vacuum_count;
+           }
+       }
+   }
+   if (disconnect)
+       db_disconnect(dbi);
 }
 
 void
-update_table_list (db_info * dbi)
+update_table_list(db_info * dbi)
 {
-  int disconnect = 0;
-  PGresult *res = NULL;
-  tbl_info *tbl = NULL;
-  Dlelem *tbl_elem = DLGetHead (dbi->table_list);
-  int i = 0, t = 0, found_match = 0;
-
-  if (NULL == dbi->conn) {
-    dbi->conn = db_connect (dbi);
-    disconnect = 1;
-  }
-
-  if (NULL != dbi->conn) {
-    /* Get a result set that has all the information
-       we will need to both remove tables from the list
-       that no longer exist and add tables to the list
-       that are new */
-    res = send_query (query_table_stats (dbi), dbi);
-    t = PQntuples (res);
-
-    /* First: use the tbl_list as the outer loop and
-       the result set as the inner loop, this will
-       determine what tables should be removed */
-    while (NULL != tbl_elem) {
-      tbl = ((tbl_info *) DLE_VAL (tbl_elem));
-      found_match = 0;
-
-      for (i = 0; i < t; i++) {    /* loop through result set looking for a match */
-        if (tbl->relfilenode == atoi (PQgetvalue (res, i, PQfnumber (res, "relfilenode")))) {
-          found_match = 1;
-       break;
-        }
-      }
-      if (0 == found_match) {  /* then we didn't find this tbl_elem in the result set */
-        Dlelem *elem_to_remove = tbl_elem;
-        tbl_elem = DLGetSucc (tbl_elem);
-        remove_table_from_list (elem_to_remove);
-      }
-      else
-   tbl_elem = DLGetSucc (tbl_elem);
-    }  /* Done removing dropped tables from the table_list */
-
-    /* Then loop use result set as outer loop and
-       tbl_list as the inner loop to determine
-       what tables are new */
-    for (i = 0; i < t; i++)
-    {
-      tbl_elem = DLGetHead (dbi->table_list);
-      found_match = 0;
-      while (NULL != tbl_elem)
-      {
-        tbl = ((tbl_info *) DLE_VAL (tbl_elem));
-        if (tbl->relfilenode == atoi (PQgetvalue (res, i, PQfnumber (res, "relfilenode"))))
-        {
-          found_match = 1;
-       break;
-     }
-     tbl_elem = DLGetSucc (tbl_elem);
-      }
-      if (0 == found_match)    /*then we didn't find this result now in the tbl_list */
-      {
-        DLAddTail (dbi->table_list, DLNewElem (init_table_info (res, i, dbi)));
-     if (args->debug >= 1)
-        {
-       sprintf (logbuffer, "added table: %s.%s", dbi->dbname,
-          ((tbl_info *) DLE_VAL (DLGetTail (dbi->table_list)))->table_name);
-       log_entry (logbuffer);
-     }
-      }
-    }              /* end of for loop that adds tables */
-    fflush (LOGOUTPUT);
-    PQclear (res);
-    res = NULL;
-    if (args->debug >= 3) {
-      print_table_list (dbi->table_list);
-    }
-    if (disconnect)
-      db_disconnect (dbi);
-  }
+   int         disconnect = 0;
+   PGresult   *res = NULL;
+   tbl_info   *tbl = NULL;
+   Dlelem     *tbl_elem = DLGetHead(dbi->table_list);
+   int         i = 0,
+               t = 0,
+               found_match = 0;
+
+   if (NULL == dbi->conn)
+   {
+       dbi->conn = db_connect(dbi);
+       disconnect = 1;
+   }
+
+   if (NULL != dbi->conn)
+   {
+       /*
+        * Get a result set that has all the information we will need to
+        * both remove tables from the list that no longer exist and add
+        * tables to the list that are new
+        */
+       res = send_query(query_table_stats(dbi), dbi);
+       t = PQntuples(res);
+
+       /*
+        * First: use the tbl_list as the outer loop and the result set as
+        * the inner loop, this will determine what tables should be
+        * removed
+        */
+       while (NULL != tbl_elem)
+       {
+           tbl = ((tbl_info *) DLE_VAL(tbl_elem));
+           found_match = 0;
+
+           for (i = 0; i < t; i++)
+           {                   /* loop through result set looking for a
+                                * match */
+               if (tbl->relfilenode == atoi(PQgetvalue(res, i, PQfnumber(res, "relfilenode"))))
+               {
+                   found_match = 1;
+                   break;
+               }
+           }
+           if (0 == found_match)
+           {                   /* then we didn't find this tbl_elem in
+                                * the result set */
+               Dlelem     *elem_to_remove = tbl_elem;
+
+               tbl_elem = DLGetSucc(tbl_elem);
+               remove_table_from_list(elem_to_remove);
+           }
+           else
+               tbl_elem = DLGetSucc(tbl_elem);
+       }                       /* Done removing dropped tables from the
+                                * table_list */
+
+       /*
+        * Then loop use result set as outer loop and tbl_list as the
+        * inner loop to determine what tables are new
+        */
+       for (i = 0; i < t; i++)
+       {
+           tbl_elem = DLGetHead(dbi->table_list);
+           found_match = 0;
+           while (NULL != tbl_elem)
+           {
+               tbl = ((tbl_info *) DLE_VAL(tbl_elem));
+               if (tbl->relfilenode == atoi(PQgetvalue(res, i, PQfnumber(res, "relfilenode"))))
+               {
+                   found_match = 1;
+                   break;
+               }
+               tbl_elem = DLGetSucc(tbl_elem);
+           }
+           if (0 == found_match)       /* then we didn't find this result
+                                        * now in the tbl_list */
+           {
+               DLAddTail(dbi->table_list, DLNewElem(init_table_info(res, i, dbi)));
+               if (args->debug >= 1)
+               {
+                   sprintf(logbuffer, "added table: %s.%s", dbi->dbname,
+                           ((tbl_info *) DLE_VAL(DLGetTail(dbi->table_list)))->table_name);
+                   log_entry(logbuffer);
+               }
+           }
+       }                       /* end of for loop that adds tables */
+       fflush(LOGOUTPUT);
+       PQclear(res);
+       res = NULL;
+       if (args->debug >= 3)
+           print_table_list(dbi->table_list);
+       if (disconnect)
+           db_disconnect(dbi);
+   }
 }
 
 /* Free memory, and remove the node from the list */
 void
-remove_table_from_list (Dlelem * tbl_to_remove)
+remove_table_from_list(Dlelem *tbl_to_remove)
 {
-  tbl_info *tbl = ((tbl_info *) DLE_VAL (tbl_to_remove));
-
-  if (args->debug >= 1) {
-    sprintf (logbuffer, "Removing table: %s from list.", tbl->table_name);
-    log_entry (logbuffer);
-    fflush (LOGOUTPUT);
-  }
-  DLRemove (tbl_to_remove);
-
-  if (tbl->schema_name) {
-    free (tbl->schema_name);
-    tbl->schema_name = NULL;
-  }
-  if (tbl->table_name) {
-    free (tbl->table_name);
-    tbl->table_name = NULL;
-  }
-  if (tbl) {
-    free (tbl);
-    tbl = NULL;
-  }
-  DLFreeElem (tbl_to_remove);
+   tbl_info   *tbl = ((tbl_info *) DLE_VAL(tbl_to_remove));
+
+   if (args->debug >= 1)
+   {
+       sprintf(logbuffer, "Removing table: %s from list.", tbl->table_name);
+       log_entry(logbuffer);
+       fflush(LOGOUTPUT);
+   }
+   DLRemove(tbl_to_remove);
+
+   if (tbl->schema_name)
+   {
+       free(tbl->schema_name);
+       tbl->schema_name = NULL;
+   }
+   if (tbl->table_name)
+   {
+       free(tbl->table_name);
+       tbl->table_name = NULL;
+   }
+   if (tbl)
+   {
+       free(tbl);
+       tbl = NULL;
+   }
+   DLFreeElem(tbl_to_remove);
 }
 
 /* Free the entire table list */
 void
-free_tbl_list (Dllist * tbl_list)
+free_tbl_list(Dllist *tbl_list)
 {
-  Dlelem *tbl_elem = DLGetHead (tbl_list);
-  Dlelem *tbl_elem_to_remove = NULL;
-  while (NULL != tbl_elem) {
-    tbl_elem_to_remove = tbl_elem;
-    tbl_elem = DLGetSucc (tbl_elem);
-    remove_table_from_list (tbl_elem_to_remove);
-  }
-  DLFreeList (tbl_list);
+   Dlelem     *tbl_elem = DLGetHead(tbl_list);
+   Dlelem     *tbl_elem_to_remove = NULL;
+
+   while (NULL != tbl_elem)
+   {
+       tbl_elem_to_remove = tbl_elem;
+       tbl_elem = DLGetSucc(tbl_elem);
+       remove_table_from_list(tbl_elem_to_remove);
+   }
+   DLFreeList(tbl_list);
 }
 
 void
-print_table_list (Dllist * table_list)
+print_table_list(Dllist *table_list)
 {
-  Dlelem *table_elem = DLGetHead (table_list);
-  while (NULL != table_elem) {
-    print_table_info (((tbl_info *) DLE_VAL (table_elem)));
-    table_elem = DLGetSucc (table_elem);
-  }
+   Dlelem     *table_elem = DLGetHead(table_list);
+
+   while (NULL != table_elem)
+   {
+       print_table_info(((tbl_info *) DLE_VAL(table_elem)));
+       table_elem = DLGetSucc(table_elem);
+   }
 }
 
 void
-print_table_info (tbl_info * tbl)
+print_table_info(tbl_info * tbl)
 {
-  sprintf (logbuffer, "  table name:     %s.%s", tbl->dbi->dbname, tbl->table_name);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "     relfilenode: %i",tbl->relfilenode);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "     reltuples: %i;  relpages: %i", tbl->reltuples, tbl->relpages);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "     curr_analyze_count:  %li; cur_delete_count:   %li",
-      tbl->curr_analyze_count, tbl->curr_vacuum_count);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "     ins_at_last_analyze: %li; del_at_last_vacuum: %li",
-      tbl->CountAtLastAnalyze, tbl->CountAtLastVacuum);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "     insert_threshold:    %li; delete_threshold    %li",
-      tbl->analyze_threshold, tbl->vacuum_threshold);
-  log_entry (logbuffer);
-  fflush (LOGOUTPUT);
+   sprintf(logbuffer, "  table name:     %s.%s", tbl->dbi->dbname, tbl->table_name);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "     relfilenode: %i", tbl->relfilenode);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "     reltuples: %i;  relpages: %i", tbl->reltuples, tbl->relpages);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "     curr_analyze_count:  %li; cur_delete_count:   %li",
+           tbl->curr_analyze_count, tbl->curr_vacuum_count);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "     ins_at_last_analyze: %li; del_at_last_vacuum: %li",
+           tbl->CountAtLastAnalyze, tbl->CountAtLastVacuum);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "     insert_threshold:    %li; delete_threshold    %li",
+           tbl->analyze_threshold, tbl->vacuum_threshold);
+   log_entry(logbuffer);
+   fflush(LOGOUTPUT);
 }
 
 /* End of table Management Functions */
@@ -332,161 +370,188 @@ print_table_info (tbl_info * tbl)
 
 /* init_db_list() creates the db_list and initalizes template1 */
 Dllist *
-init_db_list ()
+init_db_list()
 {
-  Dllist *db_list = DLNewList ();
-  db_info *dbs = NULL;
-  PGresult *res = NULL;
-
-  DLAddHead (db_list, DLNewElem (init_dbinfo ((char *) "template1", 0, 0)));
-  if (NULL == DLGetHead (db_list)) {   /* Make sure init_dbinfo was successful */
-    log_entry ("init_db_list(): Error creating db_list for db: template1.");
-    fflush (LOGOUTPUT);
-    return NULL;
-  }
-
-  /* We do this just so we can set the proper oid for the template1 database */
-  dbs = ((db_info *) DLE_VAL (DLGetHead (db_list)));
-  dbs->conn = db_connect (dbs);
-
-  if (NULL != dbs->conn) {
-    res = send_query (FROZENOID_QUERY, dbs);
-    dbs->oid = atoi (PQgetvalue (res, 0, PQfnumber (res, "oid")));
-    dbs->age = atoi (PQgetvalue (res, 0, PQfnumber (res, "age")));
-    if (res)
-      PQclear (res);
-
-    if (args->debug >= 2) {
-      print_db_list (db_list, 0);
-    }
-  }
-  return db_list;
+   Dllist     *db_list = DLNewList();
+   db_info    *dbs = NULL;
+   PGresult   *res = NULL;
+
+   DLAddHead(db_list, DLNewElem(init_dbinfo((char *) "template1", 0, 0)));
+   if (NULL == DLGetHead(db_list))
+   {                           /* Make sure init_dbinfo was successful */
+       log_entry("init_db_list(): Error creating db_list for db: template1.");
+       fflush(LOGOUTPUT);
+       return NULL;
+   }
+
+   /*
+    * We do this just so we can set the proper oid for the template1
+    * database
+    */
+   dbs = ((db_info *) DLE_VAL(DLGetHead(db_list)));
+   dbs->conn = db_connect(dbs);
+
+   if (NULL != dbs->conn)
+   {
+       res = send_query(FROZENOID_QUERY, dbs);
+       dbs->oid = atoi(PQgetvalue(res, 0, PQfnumber(res, "oid")));
+       dbs->age = atoi(PQgetvalue(res, 0, PQfnumber(res, "age")));
+       if (res)
+           PQclear(res);
+
+       if (args->debug >= 2)
+           print_db_list(db_list, 0);
+   }
+   return db_list;
 }
 
 /* Simple function to create an instance of the dbinfo struct
-    Initalizes all the pointers and connects to the database  */
+   Initalizes all the pointers and connects to the database  */
 db_info *
-init_dbinfo (char *dbname, int oid, int age)
+init_dbinfo(char *dbname, int oid, int age)
 {
-  db_info *newdbinfo = (db_info *) malloc (sizeof (db_info));
-  newdbinfo->analyze_threshold = args->vacuum_base_threshold;
-  newdbinfo->vacuum_threshold = args->analyze_base_threshold;
-  newdbinfo->dbname = (char *) malloc (strlen (dbname) + 1);
-  strcpy (newdbinfo->dbname, dbname);
-  newdbinfo->username = NULL;
-  if (NULL != args->user) {
-    newdbinfo->username = (char *) malloc (strlen (args->user) + 1);
-    strcpy (newdbinfo->username, args->user);
-  }
-  newdbinfo->password = NULL;
-  if (NULL != args->password) {
-    newdbinfo->password = (char *) malloc (strlen (args->password) + 1);
-    strcpy (newdbinfo->password, args->password);
-  }
-  newdbinfo->oid = oid;
-  newdbinfo->age = age;
-  newdbinfo->table_list = DLNewList ();
-  newdbinfo->conn = NULL;
-
-  if (args->debug >= 2) {
-    print_table_list (newdbinfo->table_list);
-  }
-
-  return newdbinfo;
+   db_info    *newdbinfo = (db_info *) malloc(sizeof(db_info));
+
+   newdbinfo->analyze_threshold = args->vacuum_base_threshold;
+   newdbinfo->vacuum_threshold = args->analyze_base_threshold;
+   newdbinfo->dbname = (char *) malloc(strlen(dbname) + 1);
+   strcpy(newdbinfo->dbname, dbname);
+   newdbinfo->username = NULL;
+   if (NULL != args->user)
+   {
+       newdbinfo->username = (char *) malloc(strlen(args->user) + 1);
+       strcpy(newdbinfo->username, args->user);
+   }
+   newdbinfo->password = NULL;
+   if (NULL != args->password)
+   {
+       newdbinfo->password = (char *) malloc(strlen(args->password) + 1);
+       strcpy(newdbinfo->password, args->password);
+   }
+   newdbinfo->oid = oid;
+   newdbinfo->age = age;
+   newdbinfo->table_list = DLNewList();
+   newdbinfo->conn = NULL;
+
+   if (args->debug >= 2)
+       print_table_list(newdbinfo->table_list);
+
+   return newdbinfo;
 }
 
 /* Function adds and removes databases from the db_list as appropriate */
 void
-update_db_list (Dllist * db_list)
+update_db_list(Dllist *db_list)
 {
-  int disconnect = 0;
-  PGresult *res = NULL;
-  Dlelem *db_elem = DLGetHead (db_list);
-  db_info *dbi = NULL;
-  db_info *dbi_template1 = DLE_VAL (db_elem);
-  int i = 0, t = 0, found_match = 0;
-
-  if (args->debug >= 2) {
-    log_entry ("updating the database list");
-    fflush (LOGOUTPUT);
-  }
-
-  if (NULL == dbi_template1->conn) {
-    dbi_template1->conn = db_connect (dbi_template1);
-    disconnect = 1;
-  }
-
-  if (NULL != dbi_template1->conn) {
-    /* Get a result set that has all the information
-       we will need to both remove databasews from the list
-       that no longer exist and add databases to the list
-       that are new */
-    res = send_query (FROZENOID_QUERY2, dbi_template1);
-    t = PQntuples (res);
-
-    /* First: use the db_list as the outer loop and
-       the result set as the inner loop, this will
-       determine what databases should be removed */
-    while (NULL != db_elem) {
-      dbi = ((db_info *) DLE_VAL (db_elem));
-      found_match = 0;
-
-      for (i = 0; i < t; i++) {    /* loop through result set looking for a match */
-        if (dbi->oid == atoi (PQgetvalue (res, i, PQfnumber (res, "oid")))) {
-          found_match = 1;
-          /* update the dbi->age so that we ensure xid_wraparound won't happen */
-          dbi->age = atoi (PQgetvalue (res, i, PQfnumber (res, "age")));
-          break;
-        }
-      }
-      if (0 == found_match) {  /*then we didn't find this db_elem in the result set */
-     Dlelem *elem_to_remove = db_elem;
-     db_elem = DLGetSucc (db_elem);
-     remove_db_from_list (elem_to_remove);
-      }
-      else
-     db_elem = DLGetSucc (db_elem);
-    } /* Done removing dropped databases from the table_list */
-
-    /* Then loop use result set as outer loop and
-       db_list as the inner loop to determine
-       what databases are new */
-    for (i = 0; i < t; i++)
-    {
-      db_elem = DLGetHead (db_list);
-      found_match = 0;
-      while (NULL != db_elem)
-      {
-     dbi = ((db_info *) DLE_VAL (db_elem));
-     if (dbi->oid == atoi (PQgetvalue (res, i, PQfnumber (res, "oid"))))
-        {
-       found_match = 1;
-       break;
-     }
-     db_elem = DLGetSucc (db_elem);
-      }
-      if (0 == found_match)    /*then we didn't find this result now in the tbl_list */
-      {
-        DLAddTail (db_list, DLNewElem (init_dbinfo
-       (PQgetvalue(res, i, PQfnumber (res, "datname")),
-          atoi (PQgetvalue(res, i, PQfnumber (res, "oid"))),
-       atoi (PQgetvalue(res, i, PQfnumber (res, "age"))))));
-     if (args->debug >= 1)
-        {
-       sprintf (logbuffer, "added database: %s",((db_info *) DLE_VAL (DLGetTail (db_list)))->dbname);
-       log_entry (logbuffer);
-     }
-      }
-    }              /* end of for loop that adds tables */
-    fflush (LOGOUTPUT);
-    PQclear (res);
-    res = NULL;
-    if (args->debug >= 3) {
-      print_db_list (db_list, 0);
-    }
-    if (disconnect)
-      db_disconnect (dbi_template1);
-  }
+   int         disconnect = 0;
+   PGresult   *res = NULL;
+   Dlelem     *db_elem = DLGetHead(db_list);
+   db_info    *dbi = NULL;
+   db_info    *dbi_template1 = DLE_VAL(db_elem);
+   int         i = 0,
+               t = 0,
+               found_match = 0;
+
+   if (args->debug >= 2)
+   {
+       log_entry("updating the database list");
+       fflush(LOGOUTPUT);
+   }
+
+   if (NULL == dbi_template1->conn)
+   {
+       dbi_template1->conn = db_connect(dbi_template1);
+       disconnect = 1;
+   }
+
+   if (NULL != dbi_template1->conn)
+   {
+       /*
+        * Get a result set that has all the information we will need to
+        * both remove databasews from the list that no longer exist and
+        * add databases to the list that are new
+        */
+       res = send_query(FROZENOID_QUERY2, dbi_template1);
+       t = PQntuples(res);
+
+       /*
+        * First: use the db_list as the outer loop and the result set as
+        * the inner loop, this will determine what databases should be
+        * removed
+        */
+       while (NULL != db_elem)
+       {
+           dbi = ((db_info *) DLE_VAL(db_elem));
+           found_match = 0;
+
+           for (i = 0; i < t; i++)
+           {                   /* loop through result set looking for a
+                                * match */
+               if (dbi->oid == atoi(PQgetvalue(res, i, PQfnumber(res, "oid"))))
+               {
+                   found_match = 1;
+
+                   /*
+                    * update the dbi->age so that we ensure
+                    * xid_wraparound won't happen
+                    */
+                   dbi->age = atoi(PQgetvalue(res, i, PQfnumber(res, "age")));
+                   break;
+               }
+           }
+           if (0 == found_match)
+           {                   /* then we didn't find this db_elem in the
+                                * result set */
+               Dlelem     *elem_to_remove = db_elem;
+
+               db_elem = DLGetSucc(db_elem);
+               remove_db_from_list(elem_to_remove);
+           }
+           else
+               db_elem = DLGetSucc(db_elem);
+       }                       /* Done removing dropped databases from
+                                * the table_list */
+
+       /*
+        * Then loop use result set as outer loop and db_list as the inner
+        * loop to determine what databases are new
+        */
+       for (i = 0; i < t; i++)
+       {
+           db_elem = DLGetHead(db_list);
+           found_match = 0;
+           while (NULL != db_elem)
+           {
+               dbi = ((db_info *) DLE_VAL(db_elem));
+               if (dbi->oid == atoi(PQgetvalue(res, i, PQfnumber(res, "oid"))))
+               {
+                   found_match = 1;
+                   break;
+               }
+               db_elem = DLGetSucc(db_elem);
+           }
+           if (0 == found_match)       /* then we didn't find this result
+                                        * now in the tbl_list */
+           {
+               DLAddTail(db_list, DLNewElem(init_dbinfo
+                         (PQgetvalue(res, i, PQfnumber(res, "datname")),
+                        atoi(PQgetvalue(res, i, PQfnumber(res, "oid"))),
+                     atoi(PQgetvalue(res, i, PQfnumber(res, "age"))))));
+               if (args->debug >= 1)
+               {
+                   sprintf(logbuffer, "added database: %s", ((db_info *) DLE_VAL(DLGetTail(db_list)))->dbname);
+                   log_entry(logbuffer);
+               }
+           }
+       }                       /* end of for loop that adds tables */
+       fflush(LOGOUTPUT);
+       PQclear(res);
+       res = NULL;
+       if (args->debug >= 3)
+           print_db_list(db_list, 0);
+       if (disconnect)
+           db_disconnect(dbi_template1);
+   }
 }
 
 /* xid_wraparound_check
@@ -504,101 +569,116 @@ return 0 if nothing happened,
 return 1 if the database needed a database wide vacuum
 */
 int
-xid_wraparound_check (db_info * dbi)
+xid_wraparound_check(db_info * dbi)
 {
-  /* FIXME: should probably do something better here so that we don't vacuum all the
-     databases on the server at the same time.  We have 500million xacts to work with so
-     we should be able to spread the load of full database vacuums a bit */
-  if (1500000000 < dbi->age) {
-    PGresult *res = NULL;
-    res = send_query ("vacuum", dbi);
-    /* FIXME: Perhaps should add a check for PQ_COMMAND_OK */
-    PQclear (res);
-    return 1;
-  }
-  return 0;
+   /*
+    * FIXME: should probably do something better here so that we don't
+    * vacuum all the databases on the server at the same time.  We have
+    * 500million xacts to work with so we should be able to spread the
+    * load of full database vacuums a bit
+    */
+   if (1500000000 < dbi->age)
+   {
+       PGresult   *res = NULL;
+
+       res = send_query("vacuum", dbi);
+       /* FIXME: Perhaps should add a check for PQ_COMMAND_OK */
+       PQclear(res);
+       return 1;
+   }
+   return 0;
 }
 
 /* Close DB connection, free memory, and remove the node from the list */
 void
-remove_db_from_list (Dlelem * db_to_remove)
+remove_db_from_list(Dlelem *db_to_remove)
 {
-  db_info *dbi = ((db_info *) DLE_VAL (db_to_remove));
-
-  if (args->debug >= 1) {
-    sprintf (logbuffer, "Removing db: %s from list.", dbi->dbname);
-    log_entry (logbuffer);
-    fflush (LOGOUTPUT);
-  }
-  DLRemove (db_to_remove);
-  if (dbi->conn)
-    db_disconnect (dbi);
-  if (dbi->dbname) {
-    free (dbi->dbname);
-    dbi->dbname = NULL;
-  }
-  if (dbi->username) {
-    free (dbi->username);
-    dbi->username = NULL;
-  }
-  if (dbi->password) {
-    free (dbi->password);
-    dbi->password = NULL;
-  }
-  if (dbi->table_list) {
-    free_tbl_list (dbi->table_list);
-    dbi->table_list = NULL;
-  }
-  if (dbi) {
-    free (dbi);
-    dbi = NULL;
-  }
-  DLFreeElem (db_to_remove);
+   db_info    *dbi = ((db_info *) DLE_VAL(db_to_remove));
+
+   if (args->debug >= 1)
+   {
+       sprintf(logbuffer, "Removing db: %s from list.", dbi->dbname);
+       log_entry(logbuffer);
+       fflush(LOGOUTPUT);
+   }
+   DLRemove(db_to_remove);
+   if (dbi->conn)
+       db_disconnect(dbi);
+   if (dbi->dbname)
+   {
+       free(dbi->dbname);
+       dbi->dbname = NULL;
+   }
+   if (dbi->username)
+   {
+       free(dbi->username);
+       dbi->username = NULL;
+   }
+   if (dbi->password)
+   {
+       free(dbi->password);
+       dbi->password = NULL;
+   }
+   if (dbi->table_list)
+   {
+       free_tbl_list(dbi->table_list);
+       dbi->table_list = NULL;
+   }
+   if (dbi)
+   {
+       free(dbi);
+       dbi = NULL;
+   }
+   DLFreeElem(db_to_remove);
 }
 
 /* Function is called before program exit to free all memory
        mostly it's just to keep valgrind happy */
 void
-free_db_list (Dllist * db_list)
+free_db_list(Dllist *db_list)
 {
-  Dlelem *db_elem = DLGetHead (db_list);
-  Dlelem *db_elem_to_remove = NULL;
-  while (NULL != db_elem) {
-    db_elem_to_remove = db_elem;
-    db_elem = DLGetSucc (db_elem);
-    remove_db_from_list (db_elem_to_remove);
-    db_elem_to_remove = NULL;
-  }
-  DLFreeList (db_list);
+   Dlelem     *db_elem = DLGetHead(db_list);
+   Dlelem     *db_elem_to_remove = NULL;
+
+   while (NULL != db_elem)
+   {
+       db_elem_to_remove = db_elem;
+       db_elem = DLGetSucc(db_elem);
+       remove_db_from_list(db_elem_to_remove);
+       db_elem_to_remove = NULL;
+   }
+   DLFreeList(db_list);
 }
 
 void
-print_db_list (Dllist * db_list, int print_table_lists)
+print_db_list(Dllist *db_list, int print_table_lists)
 {
-  Dlelem *db_elem = DLGetHead (db_list);
-  while (NULL != db_elem) {
-    print_db_info (((db_info *) DLE_VAL (db_elem)), print_table_lists);
-    db_elem = DLGetSucc (db_elem);
-  }
+   Dlelem     *db_elem = DLGetHead(db_list);
+
+   while (NULL != db_elem)
+   {
+       print_db_info(((db_info *) DLE_VAL(db_elem)), print_table_lists);
+       db_elem = DLGetSucc(db_elem);
+   }
 }
 
 void
-print_db_info (db_info * dbi, int print_tbl_list)
+print_db_info(db_info * dbi, int print_tbl_list)
 {
-  sprintf (logbuffer, "dbname: %s Username %s Passwd %s", dbi->dbname,
-      dbi->username, dbi->password);
-  log_entry (logbuffer);
-  sprintf (logbuffer, " oid %i InsertThresh: %i  DeleteThresh: %i", dbi->oid,
-      dbi->analyze_threshold, dbi->vacuum_threshold);
-  log_entry (logbuffer);
-  if (NULL != dbi->conn)
-    log_entry (" conn is valid, we are connected");
-  else
-    log_entry (" conn is null, we are not connected.");
-
-  fflush (LOGOUTPUT);
-  if (0 < print_tbl_list)
-    print_table_list (dbi->table_list);
+   sprintf(logbuffer, "dbname: %s Username %s Passwd %s", dbi->dbname,
+           dbi->username, dbi->password);
+   log_entry(logbuffer);
+   sprintf(logbuffer, " oid %i InsertThresh: %i  DeleteThresh: %i", dbi->oid,
+           dbi->analyze_threshold, dbi->vacuum_threshold);
+   log_entry(logbuffer);
+   if (NULL != dbi->conn)
+       log_entry(" conn is valid, we are connected");
+   else
+       log_entry(" conn is null, we are not connected.");
+
+   fflush(LOGOUTPUT);
+   if (0 < print_tbl_list)
+       print_table_list(dbi->table_list);
 }
 
 /* End of DB List Management Function */
@@ -607,406 +687,475 @@ print_db_info (db_info * dbi, int print_tbl_list)
 
 
 char *
-query_table_stats (db_info * dbi)
+query_table_stats(db_info * dbi)
 {
-  if (!strcmp (dbi->dbname, "template1"))  /* Use template1 to monitor the system tables */
-    return (char *) TABLE_STATS_ALL;
-  else
-    return (char *) TABLE_STATS_USER;
+   if (!strcmp(dbi->dbname, "template1"))      /* Use template1 to
+                                                * monitor the system
+                                                * tables */
+       return (char *) TABLE_STATS_ALL;
+   else
+       return (char *) TABLE_STATS_USER;
 }
 
 /* Perhaps add some test to this function to make sure that the stats we need are available */
 PGconn *
-db_connect (db_info * dbi)
+db_connect(db_info * dbi)
 {
-  PGconn *db_conn =
-    PQsetdbLogin (args->host, args->port, NULL, NULL, dbi->dbname,
-         dbi->username, dbi->password);
-
-  if (CONNECTION_OK != PQstatus (db_conn)) {
-    sprintf (logbuffer, "Failed connection to database %s with error: %s.",
-        dbi->dbname, PQerrorMessage (db_conn));
-    log_entry (logbuffer);
-    fflush (LOGOUTPUT);
-    PQfinish (db_conn);
-    db_conn = NULL;
-  }
-  return db_conn;
-}              /* end of db_connect() */
+   PGconn     *db_conn =
+   PQsetdbLogin(args->host, args->port, NULL, NULL, dbi->dbname,
+                dbi->username, dbi->password);
+
+   if (CONNECTION_OK != PQstatus(db_conn))
+   {
+       sprintf(logbuffer, "Failed connection to database %s with error: %s.",
+               dbi->dbname, PQerrorMessage(db_conn));
+       log_entry(logbuffer);
+       fflush(LOGOUTPUT);
+       PQfinish(db_conn);
+       db_conn = NULL;
+   }
+   return db_conn;
+}  /* end of db_connect() */
 
 void
-db_disconnect (db_info * dbi)
+db_disconnect(db_info * dbi)
 {
-  if (NULL != dbi->conn) {
-    PQfinish (dbi->conn);
-    dbi->conn = NULL;
-  }
+   if (NULL != dbi->conn)
+   {
+       PQfinish(dbi->conn);
+       dbi->conn = NULL;
+   }
 }
 
 int
-check_stats_enabled (db_info * dbi)
+check_stats_enabled(db_info * dbi)
 {
-  PGresult *res = NULL;
-  int ret = 0;
-  res = send_query ("show stats_row_level", dbi);
-  ret =
-    strcmp ("on", PQgetvalue (res, 0, PQfnumber (res, "stats_row_level")));
-  PQclear (res);
-  return ret;
+   PGresult   *res = NULL;
+   int         ret = 0;
+
+   res = send_query("show stats_row_level", dbi);
+   ret =
+       strcmp("on", PQgetvalue(res, 0, PQfnumber(res, "stats_row_level")));
+   PQclear(res);
+   return ret;
 }
 
 PGresult *
-send_query (const char *query, db_info * dbi)
+send_query(const char *query, db_info * dbi)
 {
-  PGresult *res;
-
-  if (NULL == dbi->conn)
-    return NULL;
-
-  res = PQexec (dbi->conn, query);
-
-  if (!res) {
-    sprintf (logbuffer,
-        "Fatal error occured while sending query (%s) to database %s",
-        query, dbi->dbname);
-    log_entry (logbuffer);
-    sprintf (logbuffer, "The error is [%s]", PQresultErrorMessage (res));
-    log_entry (logbuffer);
-    fflush (LOGOUTPUT);
-    return NULL;
-  }
-  if (PQresultStatus (res) != PGRES_TUPLES_OK
-      && PQresultStatus (res) != PGRES_COMMAND_OK) {
-    sprintf (logbuffer,
-        "Can not refresh statistics information from the database %s.",
-        dbi->dbname);
-    log_entry (logbuffer);
-    sprintf (logbuffer, "The error is [%s]", PQresultErrorMessage (res));
-    log_entry (logbuffer);
-    fflush (LOGOUTPUT);
-    PQclear (res);
-    return NULL;
-  }
-  return res;
-}              /* End of send_query() */
+   PGresult   *res;
+
+   if (NULL == dbi->conn)
+       return NULL;
+
+   res = PQexec(dbi->conn, query);
+
+   if (!res)
+   {
+       sprintf(logbuffer,
+          "Fatal error occured while sending query (%s) to database %s",
+               query, dbi->dbname);
+       log_entry(logbuffer);
+       sprintf(logbuffer, "The error is [%s]", PQresultErrorMessage(res));
+       log_entry(logbuffer);
+       fflush(LOGOUTPUT);
+       return NULL;
+   }
+   if (PQresultStatus(res) != PGRES_TUPLES_OK
+       && PQresultStatus(res) != PGRES_COMMAND_OK)
+   {
+       sprintf(logbuffer,
+         "Can not refresh statistics information from the database %s.",
+               dbi->dbname);
+       log_entry(logbuffer);
+       sprintf(logbuffer, "The error is [%s]", PQresultErrorMessage(res));
+       log_entry(logbuffer);
+       fflush(LOGOUTPUT);
+       PQclear(res);
+       return NULL;
+   }
+   return res;
+}  /* End of send_query() */
 
 
 void
-free_cmd_args ()
+free_cmd_args()
 {
-  if (NULL != args) {
-    if (NULL != args->user)
-      free (args->user);
-    if (NULL != args->user)
-      free (args->password);
-    free (args);
-  }
+   if (NULL != args)
+   {
+       if (NULL != args->user)
+           free(args->user);
+       if (NULL != args->user)
+           free(args->password);
+       free(args);
+   }
 }
 
 cmd_args *
-get_cmd_args (int argc, char *argv[])
+get_cmd_args(int argc, char *argv[])
 {
-  int c;
-  args = (cmd_args *) malloc (sizeof (cmd_args));
-  args->sleep_base_value = SLEEPBASEVALUE;
-  args->sleep_scaling_factor = SLEEPSCALINGFACTOR;
-  args->vacuum_base_threshold = VACBASETHRESHOLD;
-  args->vacuum_scaling_factor = VACSCALINGFACTOR;
-  args->analyze_base_threshold = -1;
-  args->analyze_scaling_factor = -1;
-  args->debug = AUTOVACUUM_DEBUG;
-  args->daemonize = 0;
-
-  /* Fixme: Should add some sanity checking such as positive integer values etc */
-  while (-1 != (c = getopt (argc, argv, "s:S:v:V:a:A:d:U:P:H:L:p:hD"))) {
-    switch (c) {
-    case 's':
-      args->sleep_base_value = atoi (optarg);
-      break;
-    case 'S':
-      args->sleep_scaling_factor = atof (optarg);
-      break;
-    case 'v':
-      args->vacuum_base_threshold = atoi (optarg);
-      break;
-    case 'V':
-      args->vacuum_scaling_factor = atof (optarg);
-      break;
-    case 'a':
-      args->analyze_base_threshold = atoi (optarg);
-      break;
-    case 'A':
-      args->analyze_scaling_factor = atof (optarg);
-      break;
-    case 'D':
-      args->daemonize++;
-      break;
-    case 'd':
-      args->debug = atoi (optarg);
-      break;
-    case 'U':
-      args->user = optarg;
-      break;
-    case 'P':
-      args->password = optarg;
-      break;
-    case 'H':
-      args->host = optarg;
-      break;
-    case 'L':
-      args->logfile = optarg;
-      break;
-    case 'p':
-      args->port = optarg;
-      break;
-    case 'h':
-      usage();
-      exit (0);
-    default:
-      /* It's here that we know that things are invalid...
-    It is not forcibly an error to call usage */
-      fprintf (stderr, "Error: Invalid Command Line Options.\n");
-      usage();
-      exit (1);
-      break;
-    }
-    /* if values for insert thresholds are not specified,
-       then they default to 1/2 of the delete values */
-    if(-1 == args->analyze_base_threshold)
-      args->analyze_base_threshold = args->vacuum_base_threshold / 2;
-    if(-1 == args->analyze_scaling_factor)
-      args->analyze_scaling_factor = args->vacuum_scaling_factor / 2;
-  }
-  return args;
+   int         c;
+
+   args = (cmd_args *) malloc(sizeof(cmd_args));
+   args->sleep_base_value = SLEEPBASEVALUE;
+   args->sleep_scaling_factor = SLEEPSCALINGFACTOR;
+   args->vacuum_base_threshold = VACBASETHRESHOLD;
+   args->vacuum_scaling_factor = VACSCALINGFACTOR;
+   args->analyze_base_threshold = -1;
+   args->analyze_scaling_factor = -1;
+   args->debug = AUTOVACUUM_DEBUG;
+   args->daemonize = 0;
+
+   /*
+    * Fixme: Should add some sanity checking such as positive integer
+    * values etc
+    */
+   while (-1 != (c = getopt(argc, argv, "s:S:v:V:a:A:d:U:P:H:L:p:hD")))
+   {
+       switch (c)
+       {
+           case 's':
+               args->sleep_base_value = atoi(optarg);
+               break;
+           case 'S':
+               args->sleep_scaling_factor = atof(optarg);
+               break;
+           case 'v':
+               args->vacuum_base_threshold = atoi(optarg);
+               break;
+           case 'V':
+               args->vacuum_scaling_factor = atof(optarg);
+               break;
+           case 'a':
+               args->analyze_base_threshold = atoi(optarg);
+               break;
+           case 'A':
+               args->analyze_scaling_factor = atof(optarg);
+               break;
+           case 'D':
+               args->daemonize++;
+               break;
+           case 'd':
+               args->debug = atoi(optarg);
+               break;
+           case 'U':
+               args->user = optarg;
+               break;
+           case 'P':
+               args->password = optarg;
+               break;
+           case 'H':
+               args->host = optarg;
+               break;
+           case 'L':
+               args->logfile = optarg;
+               break;
+           case 'p':
+               args->port = optarg;
+               break;
+           case 'h':
+               usage();
+               exit(0);
+           default:
+
+               /*
+                * It's here that we know that things are invalid... It is
+                * not forcibly an error to call usage
+                */
+               fprintf(stderr, "Error: Invalid Command Line Options.\n");
+               usage();
+               exit(1);
+               break;
+       }
+
+       /*
+        * if values for insert thresholds are not specified, then they
+        * default to 1/2 of the delete values
+        */
+       if (-1 == args->analyze_base_threshold)
+           args->analyze_base_threshold = args->vacuum_base_threshold / 2;
+       if (-1 == args->analyze_scaling_factor)
+           args->analyze_scaling_factor = args->vacuum_scaling_factor / 2;
+   }
+   return args;
 }
 
-void usage()
+void
+usage()
 {
-  int i=0;
-  float f=0;
-  fprintf (stderr, "usage: pg_autovacuum \n");
-  fprintf (stderr, "   [-D] Daemonize (Detach from tty and run in the background)\n");
-  i=AUTOVACUUM_DEBUG;
-  fprintf (stderr, "   [-d] debug (debug level=0,1,2,3; default=%i)\n",i);
-
-  i=SLEEPBASEVALUE;
-  fprintf (stderr, "   [-s] sleep base value (default=%i)\n",i);
-  f=SLEEPSCALINGFACTOR;
-  fprintf (stderr, "   [-S] sleep scaling factor (default=%f)\n",f);
-
-  i=VACBASETHRESHOLD;
-  fprintf (stderr, "   [-v] vacuum base threshold (default=%i)\n",i);
-  f=VACSCALINGFACTOR;
-  fprintf (stderr, "   [-V] vacuum scaling factor (default=%f)\n",f);
-  i=i/2;
-  fprintf (stderr, "   [-a] analyze base threshold (default=%i)\n",i);
-  f=f/2;
-  fprintf (stderr, "   [-A] analyze scaling factor (default=%f)\n",f);
-
-  fprintf (stderr, "   [-L] logfile (default=none)\n");
-
-  fprintf (stderr, "   [-U] username (libpq default)\n");
-  fprintf (stderr, "   [-P] password (libpq default)\n");
-  fprintf (stderr, "   [-H] host (libpq default)\n");
-  fprintf (stderr, "   [-p] port (libpq default)\n");
-
-  fprintf (stderr, "   [-h] help (Show this output)\n");
+   int         i = 0;
+   float       f = 0;
+
+   fprintf(stderr, "usage: pg_autovacuum \n");
+   fprintf(stderr, "   [-D] Daemonize (Detach from tty and run in the background)\n");
+   i = AUTOVACUUM_DEBUG;
+   fprintf(stderr, "   [-d] debug (debug level=0,1,2,3; default=%i)\n", i);
+
+   i = SLEEPBASEVALUE;
+   fprintf(stderr, "   [-s] sleep base value (default=%i)\n", i);
+   f = SLEEPSCALINGFACTOR;
+   fprintf(stderr, "   [-S] sleep scaling factor (default=%f)\n", f);
+
+   i = VACBASETHRESHOLD;
+   fprintf(stderr, "   [-v] vacuum base threshold (default=%i)\n", i);
+   f = VACSCALINGFACTOR;
+   fprintf(stderr, "   [-V] vacuum scaling factor (default=%f)\n", f);
+   i = i / 2;
+   fprintf(stderr, "   [-a] analyze base threshold (default=%i)\n", i);
+   f = f / 2;
+   fprintf(stderr, "   [-A] analyze scaling factor (default=%f)\n", f);
+
+   fprintf(stderr, "   [-L] logfile (default=none)\n");
+
+   fprintf(stderr, "   [-U] username (libpq default)\n");
+   fprintf(stderr, "   [-P] password (libpq default)\n");
+   fprintf(stderr, "   [-H] host (libpq default)\n");
+   fprintf(stderr, "   [-p] port (libpq default)\n");
+
+   fprintf(stderr, "   [-h] help (Show this output)\n");
 }
 
 void
-print_cmd_args ()
+print_cmd_args()
 {
-  sprintf (logbuffer, "Printing command_args");
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->host=%s", (args->host) ? args->host : "(null)");
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->port=%s", (args->port) ? args->port : "(null)");
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->user=%s", (args->user) ? args->user : "(null)");
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->password=%s",(args->password) ? args->password : "(null)");
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->logfile=%s",(args->logfile) ? args->logfile : "(null)");
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->daemonize=%i",args->daemonize);
-  log_entry (logbuffer);
-
-  sprintf (logbuffer, "  args->sleep_base_value=%i", args->sleep_base_value);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->sleep_scaling_factor=%f",args->sleep_scaling_factor);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->vacuum_base_threshold=%i",args->vacuum_base_threshold);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->vacuum_scaling_factor=%f",args->vacuum_scaling_factor);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->analyze_base_threshold=%i",args->analyze_base_threshold);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->analyze_scaling_factor=%f",args->analyze_scaling_factor);
-  log_entry (logbuffer);
-  sprintf (logbuffer, "  args->debug=%i", args->debug);
-  log_entry (logbuffer);
-
-  fflush (LOGOUTPUT);
+   sprintf(logbuffer, "Printing command_args");
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->host=%s", (args->host) ? args->host : "(null)");
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->port=%s", (args->port) ? args->port : "(null)");
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->user=%s", (args->user) ? args->user : "(null)");
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->password=%s", (args->password) ? args->password : "(null)");
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->logfile=%s", (args->logfile) ? args->logfile : "(null)");
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->daemonize=%i", args->daemonize);
+   log_entry(logbuffer);
+
+   sprintf(logbuffer, "  args->sleep_base_value=%i", args->sleep_base_value);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->sleep_scaling_factor=%f", args->sleep_scaling_factor);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->vacuum_base_threshold=%i", args->vacuum_base_threshold);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->vacuum_scaling_factor=%f", args->vacuum_scaling_factor);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->analyze_base_threshold=%i", args->analyze_base_threshold);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->analyze_scaling_factor=%f", args->analyze_scaling_factor);
+   log_entry(logbuffer);
+   sprintf(logbuffer, "  args->debug=%i", args->debug);
+   log_entry(logbuffer);
+
+   fflush(LOGOUTPUT);
 }
 
 /* Beginning of AutoVacuum Main Program */
 int
-main (int argc, char *argv[])
+main(int argc, char *argv[])
 {
-  char buf[256];
-  int j = 0, loops = 0;
-/*  int numInserts, numDeletes, */
-  int sleep_secs;
-  Dllist *db_list;
-  Dlelem *db_elem, *tbl_elem;
-  db_info *dbs;
-  tbl_info *tbl;
-  PGresult *res=NULL;
-  long long diff = 0;
-  struct timeval now, then;
-
-  args = get_cmd_args (argc, argv);    /* Get Command Line Args and put them in the args struct */
-
-  /* Dameonize if requested */
-  if (1 == args->daemonize){ daemonize(); }
-
-  if (args->logfile) {
-    LOGOUTPUT = fopen (args->logfile, "a");
-    if (!LOGOUTPUT) {
-      fprintf (stderr, "Could not open log file - [%s]\n", args->logfile);
-      exit(-1);
-    }
-  }
-  else {
-    LOGOUTPUT = stderr;
-  }
-  if (args->debug >= 2) {
-    print_cmd_args ();
-  }
-
-  /* Init the db list with template1 */
-  db_list = init_db_list ();
-  if (NULL == db_list)
-    return 1;
-
-  if (0 != check_stats_enabled (((db_info *) DLE_VAL (DLGetHead (db_list))))) {
-    log_entry ("Error: GUC variable stats_row_level must be enabled.");
-    log_entry ("       Please fix the problems and try again.");
-    fflush (LOGOUTPUT);
-
-    exit (1);
-  }
-
-  gettimeofday (&then, 0); /* for use later to caluculate sleep time */
-
-  while (1) {          /* Main Loop */
-    db_elem = DLGetHead (db_list); /* Reset cur_db_node to the beginning of the db_list */
-
-    dbs = ((db_info *) DLE_VAL (db_elem)); /* get pointer to cur_db's db_info struct */
-    if (NULL == dbs->conn) {
-      dbs->conn = db_connect (dbs);
-      if (NULL == dbs->conn) { /* Serious problem: We can't connect to template1 */
-       log_entry ("Error: Cannot connect to template1, exiting.");
-       fflush (LOGOUTPUT);
-       fclose (LOGOUTPUT);
-       exit (1);
-      }
-    }
-
-    if (0 == (loops % UPDATE_INTERVAL))    /* Update the list if it's time */
-      update_db_list (db_list);    /* Add and remove databases from the list */
-
-    while (NULL != db_elem) {  /* Loop through databases in list */
-      dbs = ((db_info *) DLE_VAL (db_elem));   /* get pointer to cur_db's db_info struct */
-      if (NULL == dbs->conn)
-       dbs->conn = db_connect (dbs);
-
-      if (NULL != dbs->conn) {
-       if (0 == (loops % UPDATE_INTERVAL)) /* Update the list if it's time */
-           update_table_list (dbs);    /* Add and remove tables from the list */
-
-   if (0 == xid_wraparound_check (dbs));
-   {
-     res = send_query (query_table_stats (dbs), dbs);  /* Get an updated snapshot of this dbs table stats */
-     for (j = 0; j < PQntuples (res); j++) {   /* loop through result set */
-       tbl_elem = DLGetHead (dbs->table_list); /* Reset tbl_elem to top of dbs->table_list */
-       while (NULL != tbl_elem) {  /* Loop through tables in list */
-         tbl = ((tbl_info *) DLE_VAL (tbl_elem));  /* set tbl_info = current_table */
-         if (tbl->relfilenode == atoi (PQgetvalue(res, j, PQfnumber (res, "relfilenode")))) {
-         tbl->curr_analyze_count =
-           (atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_ins"))) +
-            atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_upd"))) +
-                 atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_del"))));
-         tbl->curr_vacuum_count =
-           (atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_del"))) +
-            atol (PQgetvalue (res, j, PQfnumber (res, "n_tup_upd"))));
-
-         /* Check numDeletes to see if we need to vacuum, if so:
-            Run vacuum analyze (adding analyze is small so we might as well)
-            Update table thresholds and related information
-            if numDeletes is not big enough for vacuum then check numInserts for analyze */
-         if ((tbl->curr_vacuum_count - tbl->CountAtLastVacuum) >= tbl->vacuum_threshold)
-              {
-           snprintf (buf, sizeof (buf), "vacuum analyze %s", tbl->table_name);
-           if (args->debug >= 1) {
-             sprintf (logbuffer, "Performing: %s", buf);
-             log_entry (logbuffer);
-             fflush (LOGOUTPUT);
-           }
-           send_query (buf, dbs);
-           update_table_thresholds (dbs, tbl, VACUUM_ANALYZE);
-           if (args->debug >= 2) {print_table_info (tbl);}
-         }
-         else if ((tbl->curr_analyze_count - tbl->CountAtLastAnalyze) >= tbl->analyze_threshold)
-              {
-           snprintf (buf, sizeof (buf), "analyze %s", tbl->table_name);
-           if (args->debug >= 1) {
-             sprintf (logbuffer, "Performing: %s", buf);
-             log_entry (logbuffer);
-             fflush (LOGOUTPUT);
-           }
-           send_query (buf, dbs);
-           update_table_thresholds (dbs, tbl, ANALYZE_ONLY);
-           if (args->debug >= 2) { print_table_info (tbl);  }
-         }
-       
-              break;       /* once we have found a match, no need to keep checking. */
-         }
-            /* Advance the table pointers for the next loop */
-         tbl_elem = DLGetSucc (tbl_elem);
-
-       }           /* end for table while loop */
-     }         /* end for j loop (tuples in PGresult) */
-   }           /* close of if(xid_wraparound_check()) */
-   /* Done working on this db, Clean up, then advance cur_db */
-   PQclear (res);
-   res = NULL;
-   db_disconnect (dbs);
-      }
-      db_elem = DLGetSucc (db_elem);   /* move on to next DB regardless */
-    }  /* end of db_list while loop */
-
-    /* Figure out how long to sleep etc ... */
-    gettimeofday (&now, 0);
-    diff = (now.tv_sec - then.tv_sec) * 1000000 + (now.tv_usec - then.tv_usec);
-
-    sleep_secs = args->sleep_base_value + args->sleep_scaling_factor * diff / 1000000;
-    loops++;
-    if (args->debug >= 2) {
-      sprintf (logbuffer,
-          "%i All DBs checked in: %lld usec, will sleep for %i secs.",
-          loops, diff, sleep_secs);
-      log_entry (logbuffer);
-    }
-
-    sleep (sleep_secs);        /* Larger Pause between outer loops */
-
-    gettimeofday (&then, 0);   /* Reset time counter */
-
-  } /* end of while loop */
-
-  /* program is exiting, this should never run, but is here to make compiler / valgrind happy */
-  free_db_list (db_list);
-  free_cmd_args ();
-  return EXIT_SUCCESS;
+   char        buf[256];
+   int         j = 0,
+               loops = 0;
+
+/* int numInserts, numDeletes, */
+   int         sleep_secs;
+   Dllist     *db_list;
+   Dlelem     *db_elem,
+              *tbl_elem;
+   db_info    *dbs;
+   tbl_info   *tbl;
+   PGresult   *res = NULL;
+   long long   diff = 0;
+   struct timeval now,
+               then;
+
+   args = get_cmd_args(argc, argv);    /* Get Command Line Args and put
+                                        * them in the args struct */
+
+   /* Dameonize if requested */
+   if (1 == args->daemonize)
+       daemonize();
+
+   if (args->logfile)
+   {
+       LOGOUTPUT = fopen(args->logfile, "a");
+       if (!LOGOUTPUT)
+       {
+           fprintf(stderr, "Could not open log file - [%s]\n", args->logfile);
+           exit(-1);
+       }
+   }
+   else
+       LOGOUTPUT = stderr;
+   if (args->debug >= 2)
+       print_cmd_args();
+
+   /* Init the db list with template1 */
+   db_list = init_db_list();
+   if (NULL == db_list)
+       return 1;
+
+   if (0 != check_stats_enabled(((db_info *) DLE_VAL(DLGetHead(db_list)))))
+   {
+       log_entry("Error: GUC variable stats_row_level must be enabled.");
+       log_entry("       Please fix the problems and try again.");
+       fflush(LOGOUTPUT);
+
+       exit(1);
+   }
+
+   gettimeofday(&then, 0);     /* for use later to caluculate sleep time */
+
+   while (1)
+   {                           /* Main Loop */
+       db_elem = DLGetHead(db_list);   /* Reset cur_db_node to the
+                                        * beginning of the db_list */
+
+       dbs = ((db_info *) DLE_VAL(db_elem));   /* get pointer to cur_db's
+                                                * db_info struct */
+       if (NULL == dbs->conn)
+       {
+           dbs->conn = db_connect(dbs);
+           if (NULL == dbs->conn)
+           {                   /* Serious problem: We can't connect to
+                                * template1 */
+               log_entry("Error: Cannot connect to template1, exiting.");
+               fflush(LOGOUTPUT);
+               fclose(LOGOUTPUT);
+               exit(1);
+           }
+       }
+
+       if (0 == (loops % UPDATE_INTERVAL))     /* Update the list if it's
+                                                * time */
+           update_db_list(db_list);    /* Add and remove databases from
+                                        * the list */
+
+       while (NULL != db_elem)
+       {                       /* Loop through databases in list */
+           dbs = ((db_info *) DLE_VAL(db_elem));       /* get pointer to
+                                                        * cur_db's db_info
+                                                        * struct */
+           if (NULL == dbs->conn)
+               dbs->conn = db_connect(dbs);
+
+           if (NULL != dbs->conn)
+           {
+               if (0 == (loops % UPDATE_INTERVAL))     /* Update the list if
+                                                        * it's time */
+                   update_table_list(dbs);     /* Add and remove tables
+                                                * from the list */
+
+               if (0 == xid_wraparound_check(dbs));
+               {
+                   res = send_query(query_table_stats(dbs), dbs);      /* Get an updated
+                                                                        * snapshot of this dbs
+                                                                        * table stats */
+                   for (j = 0; j < PQntuples(res); j++)
+                   {           /* loop through result set */
+                       tbl_elem = DLGetHead(dbs->table_list);  /* Reset tbl_elem to top
+                                                                * of dbs->table_list */
+                       while (NULL != tbl_elem)
+                       {       /* Loop through tables in list */
+                           tbl = ((tbl_info *) DLE_VAL(tbl_elem));     /* set tbl_info =
+                                                                        * current_table */
+                           if (tbl->relfilenode == atoi(PQgetvalue(res, j, PQfnumber(res, "relfilenode"))))
+                           {
+                               tbl->curr_analyze_count =
+                                   (atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_ins"))) +
+                                    atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_upd"))) +
+                                    atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_del"))));
+                               tbl->curr_vacuum_count =
+                                   (atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_del"))) +
+                                    atol(PQgetvalue(res, j, PQfnumber(res, "n_tup_upd"))));
+
+                               /*
+                                * Check numDeletes to see if we need to
+                                * vacuum, if so: Run vacuum analyze
+                                * (adding analyze is small so we might as
+                                * well) Update table thresholds and
+                                * related information if numDeletes is
+                                * not big enough for vacuum then check
+                                * numInserts for analyze
+                                */
+                               if ((tbl->curr_vacuum_count - tbl->CountAtLastVacuum) >= tbl->vacuum_threshold)
+                               {
+                                   snprintf(buf, sizeof(buf), "vacuum analyze %s", tbl->table_name);
+                                   if (args->debug >= 1)
+                                   {
+                                       sprintf(logbuffer, "Performing: %s", buf);
+                                       log_entry(logbuffer);
+                                       fflush(LOGOUTPUT);
+                                   }
+                                   send_query(buf, dbs);
+                                   update_table_thresholds(dbs, tbl, VACUUM_ANALYZE);
+                                   if (args->debug >= 2)
+                                       print_table_info(tbl);
+                               }
+                               else if ((tbl->curr_analyze_count - tbl->CountAtLastAnalyze) >= tbl->analyze_threshold)
+                               {
+                                   snprintf(buf, sizeof(buf), "analyze %s", tbl->table_name);
+                                   if (args->debug >= 1)
+                                   {
+                                       sprintf(logbuffer, "Performing: %s", buf);
+                                       log_entry(logbuffer);
+                                       fflush(LOGOUTPUT);
+                                   }
+                                   send_query(buf, dbs);
+                                   update_table_thresholds(dbs, tbl, ANALYZE_ONLY);
+                                   if (args->debug >= 2)
+                                       print_table_info(tbl);
+                               }
+
+                               break;  /* once we have found a match, no
+                                        * need to keep checking. */
+                           }
+
+                           /*
+                            * Advance the table pointers for the next
+                            * loop
+                            */
+                           tbl_elem = DLGetSucc(tbl_elem);
+
+                       }       /* end for table while loop */
+                   }           /* end for j loop (tuples in PGresult) */
+               }               /* close of if(xid_wraparound_check()) */
+               /* Done working on this db, Clean up, then advance cur_db */
+               PQclear(res);
+               res = NULL;
+               db_disconnect(dbs);
+           }
+           db_elem = DLGetSucc(db_elem);       /* move on to next DB
+                                                * regardless */
+       }                       /* end of db_list while loop */
+
+       /* Figure out how long to sleep etc ... */
+       gettimeofday(&now, 0);
+       diff = (now.tv_sec - then.tv_sec) * 1000000 + (now.tv_usec - then.tv_usec);
+
+       sleep_secs = args->sleep_base_value + args->sleep_scaling_factor * diff / 1000000;
+       loops++;
+       if (args->debug >= 2)
+       {
+           sprintf(logbuffer,
+            "%i All DBs checked in: %lld usec, will sleep for %i secs.",
+                   loops, diff, sleep_secs);
+           log_entry(logbuffer);
+       }
+
+       sleep(sleep_secs);      /* Larger Pause between outer loops */
+
+       gettimeofday(&then, 0); /* Reset time counter */
+
+   }                           /* end of while loop */
+
+   /*
+    * program is exiting, this should never run, but is here to make
+    * compiler / valgrind happy
+    */
+   free_db_list(db_list);
+   free_cmd_args();
+   return EXIT_SUCCESS;
 }
index ac97f63bec0515da64de5b1937170b141d086776..fbdaf699122ac7e4873f4f04d8cf70afa855265f 100644 (file)
 #include "/usr/include/pgsql/server/lib/dllist.h"
 */
 
-#define AUTOVACUUM_DEBUG    1
-#define VACBASETHRESHOLD    1000
-#define VACSCALINGFACTOR    2
-#define SLEEPBASEVALUE      300
-#define SLEEPSCALINGFACTOR  2
-#define UPDATE_INTERVAL     2
+#define AUTOVACUUM_DEBUG   1
+#define VACBASETHRESHOLD   1000
+#define VACSCALINGFACTOR   2
+#define SLEEPBASEVALUE     300
+#define SLEEPSCALINGFACTOR 2
+#define UPDATE_INTERVAL        2
 
 /* these two constants are used to tell update_table_stats what operation we just perfomred */
-#define VACUUM_ANALYZE      0
-#define ANALYZE_ONLY        1
+#define VACUUM_ANALYZE     0
+#define ANALYZE_ONLY       1
 
-#define TABLE_STATS_ALL     "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_all_tables b where a.relfilenode=b.relid"
-#define TABLE_STATS_USER    "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_user_tables b where a.relfilenode=b.relid"
+#define TABLE_STATS_ALL        "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_all_tables b where a.relfilenode=b.relid"
+#define TABLE_STATS_USER   "select a.relfilenode,a.relname,a.relnamespace,a.relpages,a.reltuples,b.schemaname,b.n_tup_ins,b.n_tup_upd,b.n_tup_del from pg_class a, pg_stat_user_tables b where a.relfilenode=b.relid"
 #define FRONTEND
 #define PAGES_QUERY "select relfilenode,reltuples,relpages from pg_class where relfilenode=%i"
 #define FROZENOID_QUERY "select oid,age(datfrozenxid) from pg_database where datname = 'template1'"
 /* define cmd_args stucture */
 struct cmdargs
 {
-  int vacuum_base_threshold, analyze_base_threshold, sleep_base_value, debug, daemonize;
-  float vacuum_scaling_factor, analyze_scaling_factor, sleep_scaling_factor;
-  char *user, *password, *host, *logfile, *port;
+   int         vacuum_base_threshold,
+               analyze_base_threshold,
+               sleep_base_value,
+               debug,
+               daemonize;
+   float       vacuum_scaling_factor,
+               analyze_scaling_factor,
+               sleep_scaling_factor;
+   char       *user,
+              *password,
+              *host,
+              *logfile,
+              *port;
 };
 typedef struct cmdargs cmd_args;
 
 /* define cmd_args as global so we can get to them everywhere */
-cmd_args *args;
+cmd_args   *args;
 
 /* Might need to add a time value for last time the whold database was vacuumed.
-    I think we need to guarantee this happens approx every 1Million TX's  */
+   I think we need to guarantee this happens approx every 1Million TX's  */
 struct dbinfo
 {
-  int oid, age;
-  int analyze_threshold, vacuum_threshold; /* Use these as defaults for table thresholds */
-  PGconn *conn;
-  char *dbname, *username, *password;
-  Dllist *table_list;
+   int         oid,
+               age;
+   int         analyze_threshold,
+               vacuum_threshold;       /* Use these as defaults for table
+                                        * thresholds */
+   PGconn     *conn;
+   char       *dbname,
+              *username,
+              *password;
+   Dllist     *table_list;
 };
 typedef struct dbinfo db_info;
 
 struct tableinfo
 {
-  char *schema_name, *table_name;
-  int  relfilenode, reltuples, relpages;
-  long analyze_threshold, vacuum_threshold;
-  long CountAtLastAnalyze; /* equal to: inserts + updates as of the last analyze or initial values at startup */
-  long CountAtLastVacuum;  /* equal to: deletes + updates as of the last vacuum or initial values at startup */
-  long curr_analyze_count, curr_vacuum_count; /* Latest values from stats system */
-  db_info *dbi; /* pointer to the database that this table belongs to */
+   char       *schema_name,
+              *table_name;
+   int         relfilenode,
+               reltuples,
+               relpages;
+   long        analyze_threshold,
+               vacuum_threshold;
+   long        CountAtLastAnalyze;     /* equal to: inserts + updates as
+                                        * of the last analyze or initial
+                                        * values at startup */
+   long        CountAtLastVacuum;      /* equal to: deletes + updates as
+                                        * of the last vacuum or initial
+                                        * values at startup */
+   long        curr_analyze_count,
+               curr_vacuum_count;      /* Latest values from stats system */
+   db_info    *dbi;            /* pointer to the database that this table
+                                * belongs to */
 };
 typedef struct tableinfo tbl_info;
 
 /* Functions for dealing with command line arguements */
-static cmd_args *get_cmd_args (int argc, char *argv[]);
-static void print_cmd_args (void);
-static void free_cmd_args (void);
-static void usage (void);
+static cmd_args *get_cmd_args(int argc, char *argv[]);
+static void print_cmd_args(void);
+static void free_cmd_args(void);
+static void usage(void);
 
 /* Functions for managing database lists */
-static Dllist *init_db_list (void);
-static db_info *init_dbinfo (char *dbname, int oid, int age);
-static void update_db_list (Dllist * db_list);
-static void remove_db_from_list (Dlelem * db_to_remove);
-static void print_db_info (db_info * dbi, int print_table_list);
-static void print_db_list (Dllist * db_list, int print_table_lists);
-static int xid_wraparound_check (db_info * dbi);
-static void free_db_list (Dllist * db_list);
+static Dllist *init_db_list(void);
+static db_info *init_dbinfo(char *dbname, int oid, int age);
+static void update_db_list(Dllist *db_list);
+static void remove_db_from_list(Dlelem *db_to_remove);
+static void print_db_info(db_info * dbi, int print_table_list);
+static void print_db_list(Dllist *db_list, int print_table_lists);
+static int xid_wraparound_check(db_info * dbi);
+static void free_db_list(Dllist *db_list);
 
 /* Functions for managing table lists */
-static tbl_info *init_table_info (PGresult * conn, int row, db_info *dbi);
-static void update_table_list (db_info * dbi);
-static void remove_table_from_list (Dlelem * tbl_to_remove);
-static void print_table_list (Dllist * tbl_node);
-static void print_table_info (tbl_info * tbl);
-static void update_table_thresholds (db_info * dbi, tbl_info * tbl, int vacuum_type);
-static void free_tbl_list (Dllist * tbl_list);
+static tbl_info *init_table_info(PGresult *conn, int row, db_info * dbi);
+static void update_table_list(db_info * dbi);
+static void remove_table_from_list(Dlelem *tbl_to_remove);
+static void print_table_list(Dllist *tbl_node);
+static void print_table_info(tbl_info * tbl);
+static void update_table_thresholds(db_info * dbi, tbl_info * tbl, int vacuum_type);
+static void free_tbl_list(Dllist *tbl_list);
 
 /* A few database helper functions */
-static int check_stats_enabled (db_info * dbi);
-static PGconn *db_connect (db_info * dbi);
-static void db_disconnect (db_info * dbi);
-static PGresult *send_query (const char *query, db_info * dbi);
-static char *query_table_stats (db_info * dbi);
+static int check_stats_enabled(db_info * dbi);
+static PGconn *db_connect(db_info * dbi);
+static void db_disconnect(db_info * dbi);
+static PGresult *send_query(const char *query, db_info * dbi);
+static char *query_table_stats(db_info * dbi);
 
 /* Other Generally needed Functions */
 static void daemonize(void);
-static void log_entry (const char *logentry);
+static void log_entry(const char *logentry);
index b6783c23efa36762997f8012343454a0644d7eac..09a71a586dcdfed31790ee66745c7fecf9e8e325 100644 (file)
@@ -1,7 +1,7 @@
 /* -------------------------------------------------------------------------
  * pg_dumplo
  *
- * $Header: /cvsroot/pgsql/contrib/pg_dumplo/Attic/main.c,v 1.16 2003/05/14 03:25:56 tgl Exp $
+ * $Header: /cvsroot/pgsql/contrib/pg_dumplo/Attic/main.c,v 1.17 2003/08/04 00:43:11 momjian Exp $
  *
  *                 Karel Zak 1999-2000
  * -------------------------------------------------------------------------
@@ -26,7 +26,7 @@
 
 #ifndef HAVE_GETOPT_LONG
 #include "getopt_long.h"
-int optreset;
+int            optreset;
 #endif
 
 char      *progname = NULL;
index 3253dab4b6249d4d3fb1128542a1c9dd436b45b0..ede1b02f6fd56bf63091bd5329014801a5c862b0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * $Header: /cvsroot/pgsql/contrib/pgbench/pgbench.c,v 1.25 2003/08/01 02:21:17 tgl Exp $
+ * $Header: /cvsroot/pgsql/contrib/pgbench/pgbench.c,v 1.26 2003/08/04 00:43:11 momjian Exp $
  *
  * pgbench: a simple TPC-B like benchmark program for PostgreSQL
  * written by Tatsuo Ishii
@@ -122,7 +122,7 @@ doConnect()
 {
    PGconn     *con;
    PGresult   *res;
+
    con = PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName,
                       login, pwd);
    if (con == NULL)
index 3e7915d8bb03de8ecba2b2bc97d12c3d7162602b..4b3dc593ceff57268a911774a2a655538f06cfde 100644 (file)
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $Id: openssl.c,v 1.11 2002/11/15 02:54:44 momjian Exp $
+ * $Id: openssl.c,v 1.12 2003/08/04 00:43:11 momjian Exp $
  */
 
 #include <postgres.h>
@@ -130,18 +130,19 @@ px_find_digest(const char *name, PX_MD ** res)
  * of functions does not allow enough flexibility
  * and forces some of the parameters (keylen,
  * padding) to SSL defaults.
- * 
+ *
  * So need to manage ciphers ourselves.
  */
 
-struct ossl_cipher {
-   int         (*init) (PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv);
-   int         (*encrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res);
-   int         (*decrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res);
+struct ossl_cipher
+{
+   int         (*init) (PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv);
+   int         (*encrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res);
+   int         (*decrypt) (PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res);
 
-   int block_size;
-   int max_key_size;
-   int stream_cipher;
+   int         block_size;
+   int         max_key_size;
+   int         stream_cipher;
 };
 
 typedef struct
@@ -224,7 +225,7 @@ static int
 bf_ecb_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res)
 {
    unsigned    bs = gen_ossl_block_size(c);
-   unsigned    i;
+   unsigned    i;
    ossldata   *od = c->ptr;
 
    for (i = 0; i < dlen / bs; i++)
@@ -288,13 +289,13 @@ static int
 ossl_des_init(PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv)
 {
    ossldata   *od = c->ptr;
-   des_cblock xkey;
+   des_cblock  xkey;
 
    memset(&xkey, 0, sizeof(xkey));
    memcpy(&xkey, key, klen > 8 ? 8 : klen);
    des_set_key(&xkey, od->u.des.key_schedule);
    memset(&xkey, 0, sizeof(xkey));
-   
+
    if (iv)
        memcpy(od->iv, iv, 8);
    else
@@ -304,53 +305,53 @@ ossl_des_init(PX_Cipher * c, const uint8 *key, unsigned klen, const uint8 *iv)
 
 static int
 ossl_des_ecb_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen,
-       uint8 *res)
+                    uint8 *res)
 {
    unsigned    bs = gen_ossl_block_size(c);
-   unsigned    i;
+   unsigned    i;
    ossldata   *od = c->ptr;
 
    for (i = 0; i < dlen / bs; i++)
-       des_ecb_encrypt((des_cblock*)(data + i * bs),
-               (des_cblock*)(res + i * bs),
-               od->u.des.key_schedule, 1);
+       des_ecb_encrypt((des_cblock *) (data + i * bs),
+                       (des_cblock *) (res + i * bs),
+                       od->u.des.key_schedule, 1);
    return 0;
 }
 
 static int
 ossl_des_ecb_decrypt(PX_Cipher * c, const uint8 *data, unsigned dlen,
-       uint8 *res)
+                    uint8 *res)
 {
    unsigned    bs = gen_ossl_block_size(c);
-   unsigned    i;
+   unsigned    i;
    ossldata   *od = c->ptr;
 
    for (i = 0; i < dlen / bs; i++)
-       des_ecb_encrypt((des_cblock*)(data + i * bs),
-               (des_cblock*)(res + i * bs),
-               od->u.des.key_schedule, 0);
+       des_ecb_encrypt((des_cblock *) (data + i * bs),
+                       (des_cblock *) (res + i * bs),
+                       od->u.des.key_schedule, 0);
    return 0;
 }
 
 static int
 ossl_des_cbc_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen,
-       uint8 *res)
+                    uint8 *res)
 {
    ossldata   *od = c->ptr;
 
    des_ncbc_encrypt(data, res, dlen, od->u.des.key_schedule,
-           (des_cblock*)od->iv, 1);
+                    (des_cblock *) od->iv, 1);
    return 0;
 }
 
 static int
 ossl_des_cbc_decrypt(PX_Cipher * c, const uint8 *data, unsigned dlen,
-       uint8 *res)
+                    uint8 *res)
 {
    ossldata   *od = c->ptr;
 
    des_ncbc_encrypt(data, res, dlen, od->u.des.key_schedule,
-           (des_cblock*)od->iv, 0);
+                    (des_cblock *) od->iv, 0);
    return 0;
 }
 
@@ -375,7 +376,7 @@ ossl_cast_ecb_encrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *re
 {
    unsigned    bs = gen_ossl_block_size(c);
    ossldata   *od = c->ptr;
-   const uint8    *end = data + dlen - bs;
+   const uint8 *end = data + dlen - bs;
 
    for (; data <= end; data += bs, res += bs)
        CAST_ecb_encrypt(data, res, &od->u.cast_key, CAST_ENCRYPT);
@@ -387,7 +388,7 @@ ossl_cast_ecb_decrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *re
 {
    unsigned    bs = gen_ossl_block_size(c);
    ossldata   *od = c->ptr;
-   const uint8    *end = data + dlen - bs;
+   const uint8 *end = data + dlen - bs;
 
    for (; data <= end; data += bs, res += bs)
        CAST_ecb_encrypt(data, res, &od->u.cast_key, CAST_DECRYPT);
@@ -429,37 +430,37 @@ static PX_Alias ossl_aliases[] = {
 
 static const struct ossl_cipher ossl_bf_cbc = {
    bf_init, bf_cbc_encrypt, bf_cbc_decrypt,
-   64/8, 448/8, 0
+   64 / 8, 448 / 8, 0
 };
 
 static const struct ossl_cipher ossl_bf_ecb = {
    bf_init, bf_ecb_encrypt, bf_ecb_decrypt,
-   64/8, 448/8, 0
+   64 / 8, 448 / 8, 0
 };
 
 static const struct ossl_cipher ossl_bf_cfb = {
    bf_init, bf_cfb64_encrypt, bf_cfb64_decrypt,
-   64/8, 448/8, 1
+   64 / 8, 448 / 8, 1
 };
 
 static const struct ossl_cipher ossl_des_ecb = {
    ossl_des_init, ossl_des_ecb_encrypt, ossl_des_ecb_decrypt,
-   64/8, 64/8, 0
+   64 / 8, 64 / 8, 0
 };
 
 static const struct ossl_cipher ossl_des_cbc = {
    ossl_des_init, ossl_des_cbc_encrypt, ossl_des_cbc_decrypt,
-   64/8, 64/8, 0
+   64 / 8, 64 / 8, 0
 };
 
 static const struct ossl_cipher ossl_cast_ecb = {
    ossl_cast_init, ossl_cast_ecb_encrypt, ossl_cast_ecb_decrypt,
-   64/8, 128/8, 0
+   64 / 8, 128 / 8, 0
 };
 
 static const struct ossl_cipher ossl_cast_cbc = {
    ossl_cast_init, ossl_cast_cbc_encrypt, ossl_cast_cbc_decrypt,
-   64/8, 128/8, 0
+   64 / 8, 128 / 8, 0
 };
 
 /*
@@ -467,7 +468,7 @@ static const struct ossl_cipher ossl_cast_cbc = {
  */
 static const struct
 {
-   const char     *name;
+   const char *name;
    const struct ossl_cipher *ciph;
 }  ossl_cipher_types[] =
 
@@ -510,8 +511,10 @@ px_find_cipher(const char *name, PX_Cipher ** res)
    const struct ossl_cipher *ossl_ciph = NULL;
 
    name = px_resolve_alias(ossl_aliases, name);
-   for (i = 0; ossl_cipher_types[i].name; i++) {
-       if (!strcmp(ossl_cipher_types[i].name, name)) {
+   for (i = 0; ossl_cipher_types[i].name; i++)
+   {
+       if (!strcmp(ossl_cipher_types[i].name, name))
+       {
            ossl_ciph = ossl_cipher_types[i].ciph;
            break;
        }
index de0d426f46213108d187e66ffc6a35f074ee17af..3abc6f12b10a788445da74a02d87d2a83549fedf 100644 (file)
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $Id: pgcrypto.c,v 1.13 2003/07/24 17:52:33 tgl Exp $
+ * $Id: pgcrypto.c,v 1.14 2003/08/04 00:43:11 momjian Exp $
  */
 
 #include <postgres.h>
@@ -241,7 +241,7 @@ pg_gen_salt_rounds(PG_FUNCTION_ARGS)
    if (len == 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-                errmsg("no such crypt algorithm or bad number of rounds")));
+            errmsg("no such crypt algorithm or bad number of rounds")));
 
    res = (text *) palloc(len + VARHDRSZ);
    VARATT_SIZEP(res) = len + VARHDRSZ;
index 110de6dff45d1ed9375bed0e62fb47b1122d3a4f..94160605dc7c5ac7205fdad1325c89740cc52829 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * $Header: /cvsroot/pgsql/contrib/pgstattuple/pgstattuple.c,v 1.11 2003/08/01 02:21:17 tgl Exp $
+ * $Header: /cvsroot/pgsql/contrib/pgstattuple/pgstattuple.c,v 1.12 2003/08/04 00:43:11 momjian Exp $
  *
  * Copyright (c) 2001,2002 Tatsuo Ishii
  *
@@ -221,5 +221,5 @@ pgstattuple_real(Relation rel)
        pfree(values[i]);
    pfree(values);
 
-   return(result);
+   return (result);
 }
index 31bd21b04eded5a2416fb89d21d824be146d2905..b6e0c6433167878d61751b5313357e5b353a337a 100644 (file)
@@ -73,8 +73,8 @@ autoinc(PG_FUNCTION_ARGS)
        if (SPI_gettypeid(tupdesc, attnum) != INT4OID)
            ereport(ERROR,
                    (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
-                    errmsg("attribute \"%s\" of \"%s\" must be type INT4",
-                            args[i], relname)));
+                  errmsg("attribute \"%s\" of \"%s\" must be type INT4",
+                         args[i], relname)));
 
        val = DatumGetInt32(SPI_getbinval(rettuple, tupdesc, attnum, &isnull));
 
index 6fa9c4c6f883e732f0481589ab3b13362345eba3..237b14d25c21adcf2efc1676a9d29bf442493044 100644 (file)
@@ -65,17 +65,17 @@ insert_username(PG_FUNCTION_ARGS)
    if (attnum < 0)
        ereport(ERROR,
                (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
-                errmsg("\"%s\" has no attribute \"%s\"", relname, args[0])));
+           errmsg("\"%s\" has no attribute \"%s\"", relname, args[0])));
 
    if (SPI_gettypeid(tupdesc, attnum) != TEXTOID)
        ereport(ERROR,
                (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
                 errmsg("attribute \"%s\" of \"%s\" must be type TEXT",
-                        args[0], relname)));
+                       args[0], relname)));
 
    /* create fields containing name */
    newval = DirectFunctionCall1(textin,
-                             CStringGetDatum(GetUserNameFromId(GetUserId())));
+                       CStringGetDatum(GetUserNameFromId(GetUserId())));
 
    /* construct new tuple */
    rettuple = SPI_modifytuple(rel, rettuple, 1, &attnum, &newval, NULL);
index 6d80bab55e685149c861ebf22eef0544a895148e..f3a97e1c81bb7dd4bb0c056914187701b3989ffa 100644 (file)
@@ -100,8 +100,8 @@ moddatetime(PG_FUNCTION_ARGS)
    if (SPI_gettypeid(tupdesc, attnum) != TIMESTAMPOID)
        ereport(ERROR,
                (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
-                errmsg("attribute \"%s\" of \"%s\" must be type TIMESTAMP",
-                        args[0], relname)));
+             errmsg("attribute \"%s\" of \"%s\" must be type TIMESTAMP",
+                    args[0], relname)));
 
 /* 1 is the number of items in the arrays attnum and newdt.
    attnum is the positional number of the field to be updated.
index c9baa9c249de5e075d6ffa6ba3028ecc8e8adab9..c409a269cac8f880efbb35ec06c2d3d56f91702d 100644 (file)
@@ -134,8 +134,8 @@ check_primary_key(PG_FUNCTION_ARGS)
        if (fnumber < 0)
            ereport(ERROR,
                    (errcode(ERRCODE_UNDEFINED_COLUMN),
-                    errmsg("there is no attribute \"%s\" in relation \"%s\"",
-                           args[i], SPI_getrelname(rel))));
+               errmsg("there is no attribute \"%s\" in relation \"%s\"",
+                      args[i], SPI_getrelname(rel))));
 
        /* Well, get binary (in internal format) value of column */
        kvals[i] = SPI_getbinval(tuple, tupdesc, fnumber, &isnull);
@@ -365,8 +365,8 @@ check_foreign_key(PG_FUNCTION_ARGS)
        if (fnumber < 0)
            ereport(ERROR,
                    (errcode(ERRCODE_UNDEFINED_COLUMN),
-                    errmsg("there is no attribute \"%s\" in relation \"%s\"",
-                           args[i], SPI_getrelname(rel))));
+               errmsg("there is no attribute \"%s\" in relation \"%s\"",
+                      args[i], SPI_getrelname(rel))));
 
        /* Well, get binary (in internal format) value of column */
        kvals[i] = SPI_getbinval(trigtuple, tupdesc, fnumber, &isnull);
@@ -591,7 +591,7 @@ check_foreign_key(PG_FUNCTION_ARGS)
                ereport(ERROR,
                        (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
                         errmsg("\"%s\": tuple is referenced in \"%s\"",
-                        trigger->tgname, relname)));
+                               trigger->tgname, relname)));
        }
        else
        {
index aa8d0a47b4637f95c283ddc08f66e85b2d0d7ced..8ffa56edc75fb696edc120abf091c495b1abf9b8 100644 (file)
@@ -6,11 +6,11 @@
 /* Modified by BÖJTHE Zoltán, Hungary, mailto:urdesobt@axelero.hu */
 
 #include "executor/spi.h"      /* this is what you need to work with SPI */
-#include "commands/trigger.h"      /* -"- and triggers */
+#include "commands/trigger.h"  /* -"- and triggers */
 #include "miscadmin.h"         /* for GetPgUserName() */
-#include <ctype.h>         /* tolower () */
+#include <ctype.h>             /* tolower () */
 
-#define ABSTIMEOID 702     /* it should be in pg_type.h */
+#define ABSTIMEOID 702         /* it should be in pg_type.h */
 
 /* AbsoluteTime currabstime(void); */
 Datum      timetravel(PG_FUNCTION_ARGS);
@@ -28,13 +28,13 @@ static int  nPlans = 0;
 
 typedef struct _TTOffList
 {
-    struct _TTOffList  *next;
-    char       name[1];
-} TTOffList;
+   struct _TTOffList *next;
+   char        name[1];
+}  TTOffList;
 
-static TTOffList TTOff = {NULL,{0}};
+static TTOffList TTOff = {NULL, {0}};
 
-static int findTTStatus(char *name);
+static int findTTStatus(char *name);
 static EPlan *find_plan(char *ident, EPlan ** eplan, int *nplans);
 
 /*
@@ -71,57 +71,57 @@ static EPlan *find_plan(char *ident, EPlan ** eplan, int *nplans);
 
 PG_FUNCTION_INFO_V1(timetravel);
 
-Datum                      /* have to return HeapTuple to Executor */
+Datum                          /* have to return HeapTuple to Executor */
 timetravel(PG_FUNCTION_ARGS)
 {
-   TriggerData *trigdata = (TriggerData *) fcinfo->context;
-   Trigger     *trigger;       /* to get trigger name */
-   int     argc;
-   char        **args;         /* arguments */
-   int     attnum[MaxAttrNum]; /* fnumbers of start/stop columns */
+   TriggerData *trigdata = (TriggerData *) fcinfo->context;
+   Trigger    *trigger;        /* to get trigger name */
+   int         argc;
+   char      **args;           /* arguments */
+   int         attnum[MaxAttrNum];     /* fnumbers of start/stop columns */
    Datum       oldtimeon,
-           oldtimeoff;
+               oldtimeoff;
    Datum       newtimeon,
-           newtimeoff,
-           newuser,
-           nulltext;
-   Datum       *cvals;         /* column values */
-   char        *cnulls;        /* column nulls */
-   char        *relname;       /* triggered relation name */
+               newtimeoff,
+               newuser,
+               nulltext;
+   Datum      *cvals;          /* column values */
+   char       *cnulls;         /* column nulls */
+   char       *relname;        /* triggered relation name */
    Relation    rel;            /* triggered relation */
    HeapTuple   trigtuple;
    HeapTuple   newtuple = NULL;
    HeapTuple   rettuple;
    TupleDesc   tupdesc;        /* tuple description */
-   int     natts;          /* # of attributes */
-   EPlan       *plan;          /* prepared plan */
+   int         natts;          /* # of attributes */
+   EPlan      *plan;           /* prepared plan */
    char        ident[2 * NAMEDATALEN];
    bool        isnull;         /* to know is some column NULL or not */
    bool        isinsert = false;
-   int     ret;
-   int     i;
+   int         ret;
+   int         i;
 
    /*
     * Some checks first...
     */
 
    /* Called by trigger manager ? */
-   if(!CALLED_AS_TRIGGER(fcinfo))
+   if (!CALLED_AS_TRIGGER(fcinfo))
        elog(ERROR, "timetravel: not fired by trigger manager");
 
    /* Should be called for ROW trigger */
-   if(TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
+   if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
        elog(ERROR, "timetravel: can't process STATEMENT events");
 
    /* Should be called BEFORE */
-   if(TRIGGER_FIRED_AFTER(trigdata->tg_event))
+   if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
        elog(ERROR, "timetravel: must be fired before event");
 
    /* INSERT ? */
-   if(TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
+   if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
        isinsert = true;
 
-   if(TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
+   if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        newtuple = trigdata->tg_newtuple;
 
    trigtuple = trigdata->tg_trigtuple;
@@ -130,7 +130,7 @@ timetravel(PG_FUNCTION_ARGS)
    relname = SPI_getrelname(rel);
 
    /* check if TT is OFF for this relation */
-   if(0==findTTStatus(relname))
+   if (0 == findTTStatus(relname))
    {
        /* OFF - nothing to do */
        pfree(relname);
@@ -140,7 +140,7 @@ timetravel(PG_FUNCTION_ARGS)
    trigger = trigdata->tg_trigger;
 
    argc = trigger->tgnargs;
-   if(argc != MinAttrNum && argc != MaxAttrNum)
+   if (argc != MinAttrNum && argc != MaxAttrNum)
        elog(ERROR, "timetravel (%s): invalid (!= %d or %d) number of arguments %d",
             relname, MinAttrNum, MaxAttrNum, trigger->tgnargs);
 
@@ -148,39 +148,39 @@ timetravel(PG_FUNCTION_ARGS)
    tupdesc = rel->rd_att;
    natts = tupdesc->natts;
 
-   for(i = 0 ; i < MinAttrNum ; i++)
+   for (i = 0; i < MinAttrNum; i++)
    {
        attnum[i] = SPI_fnumber(tupdesc, args[i]);
-       if(attnum[i] < 0)
+       if (attnum[i] < 0)
            elog(ERROR, "timetravel (%s): there is no attribute %s", relname, args[i]);
-       if(SPI_gettypeid(tupdesc, attnum[i]) != ABSTIMEOID)
+       if (SPI_gettypeid(tupdesc, attnum[i]) != ABSTIMEOID)
            elog(ERROR, "timetravel (%s): attribute %s must be of abstime type",
                 relname, args[i]);
    }
-   for( ; i < argc ; i++)
+   for (; i < argc; i++)
    {
        attnum[i] = SPI_fnumber(tupdesc, args[i]);
-       if(attnum[i] < 0)
+       if (attnum[i] < 0)
            elog(ERROR, "timetravel (%s): there is no attribute %s", relname, args[i]);
-       if(SPI_gettypeid(tupdesc, attnum[i]) != TEXTOID)
+       if (SPI_gettypeid(tupdesc, attnum[i]) != TEXTOID)
            elog(ERROR, "timetravel (%s): attribute %s must be of text type",
                 relname, args[i]);
    }
 
    /* create fields containing name */
-        newuser = DirectFunctionCall1(textin, CStringGetDatum(GetUserNameFromId(GetUserId())));
+   newuser = DirectFunctionCall1(textin, CStringGetDatum(GetUserNameFromId(GetUserId())));
 
-   nulltext = (Datum)NULL;
+   nulltext = (Datum) NULL;
 
-   if(isinsert)
-   { /* INSERT */
-       int chnattrs = 0;
-       int chattrs[MaxAttrNum];
-       Datum   newvals[MaxAttrNum];
-       char    newnulls[MaxAttrNum];
+   if (isinsert)
+   {                           /* INSERT */
+       int         chnattrs = 0;
+       int         chattrs[MaxAttrNum];
+       Datum       newvals[MaxAttrNum];
+       char        newnulls[MaxAttrNum];
 
        oldtimeon = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_on], &isnull);
-       if(isnull)
+       if (isnull)
        {
            newvals[chnattrs] = GetCurrentAbsoluteTime();
            newnulls[chnattrs] = ' ';
@@ -189,10 +189,10 @@ timetravel(PG_FUNCTION_ARGS)
        }
 
        oldtimeoff = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_off], &isnull);
-       if(isnull)
+       if (isnull)
        {
-           if((chnattrs == 0 && DatumGetInt32(oldtimeon) >= NOEND_ABSTIME) ||
-              (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) >= NOEND_ABSTIME))
+           if ((chnattrs == 0 && DatumGetInt32(oldtimeon) >= NOEND_ABSTIME) ||
+               (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) >= NOEND_ABSTIME))
                elog(ERROR, "timetravel (%s): %s is infinity", relname, args[a_time_on]);
            newvals[chnattrs] = NOEND_ABSTIME;
            newnulls[chnattrs] = ' ';
@@ -201,16 +201,16 @@ timetravel(PG_FUNCTION_ARGS)
        }
        else
        {
-           if((chnattrs == 0 && DatumGetInt32(oldtimeon) > DatumGetInt32(oldtimeoff)) ||
-              (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) > DatumGetInt32(oldtimeoff)))
+           if ((chnattrs == 0 && DatumGetInt32(oldtimeon) > DatumGetInt32(oldtimeoff)) ||
+               (chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) > DatumGetInt32(oldtimeoff)))
                elog(ERROR, "timetravel (%s): %s gt %s", relname, args[a_time_on], args[a_time_off]);
        }
 
        pfree(relname);
-       if(chnattrs <= 0)
+       if (chnattrs <= 0)
            return PointerGetDatum(trigtuple);
 
-       if(argc == MaxAttrNum)
+       if (argc == MaxAttrNum)
        {
            /* clear update_user value */
            newvals[chnattrs] = nulltext;
@@ -235,33 +235,34 @@ timetravel(PG_FUNCTION_ARGS)
 
 /* UPDATE/DELETE: */
    oldtimeon = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_on], &isnull);
-   if(isnull)
+   if (isnull)
        elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_on]);
 
    oldtimeoff = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_off], &isnull);
-   if(isnull)
+   if (isnull)
        elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_off]);
 
    /*
     * If DELETE/UPDATE of tuple with stop_date neq INFINITY then say
     * upper Executor to skip operation for this tuple
     */
-   if(newtuple != NULL)
-   { /* UPDATE */
+   if (newtuple != NULL)
+   {                           /* UPDATE */
        newtimeon = SPI_getbinval(newtuple, tupdesc, attnum[a_time_on], &isnull);
-       if(isnull)
+       if (isnull)
            elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_on]);
 
        newtimeoff = SPI_getbinval(newtuple, tupdesc, attnum[a_time_off], &isnull);
-       if(isnull)
+       if (isnull)
            elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_off]);
 
-       if(oldtimeon != newtimeon || oldtimeoff != newtimeoff)
+       if (oldtimeon != newtimeon || oldtimeoff != newtimeoff)
            elog(ERROR, "timetravel (%s): you can't change %s and/or %s columns (use set_timetravel)",
                 relname, args[a_time_on], args[a_time_off]);
    }
-   if(oldtimeoff != NOEND_ABSTIME)
-   { /* current record is a deleted/updated record */
+   if (oldtimeoff != NOEND_ABSTIME)
+   {                           /* current record is a deleted/updated
+                                * record */
        pfree(relname);
        return PointerGetDatum(NULL);
    }
@@ -269,27 +270,28 @@ timetravel(PG_FUNCTION_ARGS)
    newtimeoff = GetCurrentAbsoluteTime();
 
    /* Connect to SPI manager */
-   if((ret = SPI_connect()) < 0)
+   if ((ret = SPI_connect()) < 0)
        elog(ERROR, "timetravel (%s): SPI_connect returned %d", relname, ret);
 
    /* Fetch tuple values and nulls */
    cvals = (Datum *) palloc(natts * sizeof(Datum));
    cnulls = (char *) palloc(natts * sizeof(char));
-   for(i = 0; i < natts; i++)
+   for (i = 0; i < natts; i++)
    {
        cvals[i] = SPI_getbinval(trigtuple, tupdesc, i + 1, &isnull);
        cnulls[i] = (isnull) ? 'n' : ' ';
    }
 
    /* change date column(s) */
-   cvals[attnum[a_time_off] - 1] = newtimeoff; /* stop_date eq current date */
+   cvals[attnum[a_time_off] - 1] = newtimeoff; /* stop_date eq current
+                                                * date */
    cnulls[attnum[a_time_off] - 1] = ' ';
 
-   if(!newtuple)
-   { /* DELETE */
-       if(argc == MaxAttrNum)
+   if (!newtuple)
+   {                           /* DELETE */
+       if (argc == MaxAttrNum)
        {
-           cvals[attnum[a_del_user] - 1] = newuser;        /* set delete user */
+           cvals[attnum[a_del_user] - 1] = newuser;    /* set delete user */
            cnulls[attnum[a_del_user] - 1] = ' ';
        }
    }
@@ -302,11 +304,11 @@ timetravel(PG_FUNCTION_ARGS)
    plan = find_plan(ident, &Plans, &nPlans);
 
    /* if there is no plan ... */
-   if(plan->splan == NULL)
+   if (plan->splan == NULL)
    {
-       void    *pplan;
-       Oid *ctypes;
-       char    sql[8192];
+       void       *pplan;
+       Oid        *ctypes;
+       char        sql[8192];
 
        /* allocate ctypes for preparation */
        ctypes = (Oid *) palloc(natts * sizeof(Oid));
@@ -315,15 +317,15 @@ timetravel(PG_FUNCTION_ARGS)
         * Construct query: INSERT INTO _relation_ VALUES ($1, ...)
         */
        snprintf(sql, sizeof(sql), "INSERT INTO %s VALUES (", relname);
-       for(i = 1; i <= natts; i++)
+       for (i = 1; i <= natts; i++)
        {
            ctypes[i - 1] = SPI_gettypeid(tupdesc, i);
-           if(!(tupdesc->attrs[i - 1]->attisdropped))  /* skip dropped columns */
-               snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d%s",
-                   i, (i < natts) ? ", " : ")" );
+           if (!(tupdesc->attrs[i - 1]->attisdropped)) /* skip dropped columns */
+               snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d%s",
+                        i, (i < natts) ? ", " : ")");
 #if 0
-               snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d /* %d */ %s",
-                   i, ctypes[i-1], (i < natts) ? ", " : ")" );
+           snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "$%d /* %d */ %s",
+                    i, ctypes[i - 1], (i < natts) ? ", " : ")");
 #endif
        }
 
@@ -331,7 +333,7 @@ timetravel(PG_FUNCTION_ARGS)
 
        /* Prepare plan for query */
        pplan = SPI_prepare(sql, natts, ctypes);
-       if(pplan == NULL)
+       if (pplan == NULL)
            elog(ERROR, "timetravel (%s): SPI_prepare returned %d", relname, SPI_result);
 
        /*
@@ -340,7 +342,7 @@ timetravel(PG_FUNCTION_ARGS)
         * use.
         */
        pplan = SPI_saveplan(pplan);
-       if(pplan == NULL)
+       if (pplan == NULL)
            elog(ERROR, "timetravel (%s): SPI_saveplan returned %d", relname, SPI_result);
 
        plan->splan = pplan;
@@ -351,14 +353,14 @@ timetravel(PG_FUNCTION_ARGS)
     */
    ret = SPI_execp(plan->splan, cvals, cnulls, 0);
 
-   if(ret < 0)
+   if (ret < 0)
        elog(ERROR, "timetravel (%s): SPI_execp returned %d", relname, ret);
 
    /* Tuple to return to upper Executor ... */
-   if(newtuple)
-   { /* UPDATE */
-       int     chnattrs = 0;
-       int     chattrs[MaxAttrNum];
+   if (newtuple)
+   {                           /* UPDATE */
+       int         chnattrs = 0;
+       int         chattrs[MaxAttrNum];
        Datum       newvals[MaxAttrNum];
        char        newnulls[MaxAttrNum];
 
@@ -372,7 +374,7 @@ timetravel(PG_FUNCTION_ARGS)
        chattrs[chnattrs] = attnum[a_time_off];
        chnattrs++;
 
-       if(argc == MaxAttrNum)
+       if (argc == MaxAttrNum)
        {
            /* set update_user value */
            newvals[chnattrs] = newuser;
@@ -399,7 +401,8 @@ timetravel(PG_FUNCTION_ARGS)
         */
        /* SPI_pfree(tmptuple); */
    }
-   else                        /* DELETE case */
+   else
+/* DELETE case */
        rettuple = trigtuple;
 
    SPI_finish();               /* don't forget say Bye to SPI mgr */
@@ -417,23 +420,24 @@ PG_FUNCTION_INFO_V1(set_timetravel);
 Datum
 set_timetravel(PG_FUNCTION_ARGS)
 {
-        Name       relname = PG_GETARG_NAME(0);
-        int32      on = PG_GETARG_INT32(1);
-   char        *rname;
-   char        *d;
-   char        *s;
+   Name        relname = PG_GETARG_NAME(0);
+   int32       on = PG_GETARG_INT32(1);
+   char       *rname;
+   char       *d;
+   char       *s;
    int32       ret;
-   TTOffList   *p,*pp;
+   TTOffList  *p,
+              *pp;
 
-   for(pp = (p = &TTOff)->next; pp; pp=(p=pp)->next)
+   for (pp = (p = &TTOff)->next; pp; pp = (p = pp)->next)
    {
-       if(namestrcmp(relname, pp->name) == 0)
+       if (namestrcmp(relname, pp->name) == 0)
            break;
    }
-   if(pp)
+   if (pp)
    {
        /* OFF currently */
-       if(on != 0)
+       if (on != 0)
        {
            /* turn ON */
            p->next = pp->next;
@@ -444,20 +448,20 @@ set_timetravel(PG_FUNCTION_ARGS)
    else
    {
        /* ON currently */
-       if(on == 0)
+       if (on == 0)
        {
            /* turn OFF */
            s = rname = DatumGetCString(DirectFunctionCall1(nameout, NameGetDatum(relname)));
-           if(s)
+           if (s)
            {
-               pp = malloc(sizeof(TTOffList)+strlen(rname));
-               if(pp)
+               pp = malloc(sizeof(TTOffList) + strlen(rname));
+               if (pp)
                {
                    pp->next = NULL;
                    p->next = pp;
                    d = pp->name;
                    while (*s)
-                       *d++ = tolower((unsigned char)*s++);
+                       *d++ = tolower((unsigned char) *s++);
                    *d = '\0';
                }
                pfree(rname);
@@ -470,7 +474,7 @@ set_timetravel(PG_FUNCTION_ARGS)
 
 /*
  * get_timetravel (relname) --
- *  get timetravel status for specified relation (ON/OFF)
+ * get timetravel status for specified relation (ON/OFF)
  */
 PG_FUNCTION_INFO_V1(get_timetravel);
 
@@ -478,11 +482,11 @@ Datum
 get_timetravel(PG_FUNCTION_ARGS)
 {
    Name        relname = PG_GETARG_NAME(0);
-   TTOffList   *pp;
+   TTOffList  *pp;
 
-   for(pp = TTOff.next; pp; pp = pp->next)
+   for (pp = TTOff.next; pp; pp = pp->next)
    {
-       if(namestrcmp(relname, pp->name) == 0)
+       if (namestrcmp(relname, pp->name) == 0)
            PG_RETURN_INT32(0);
    }
    PG_RETURN_INT32(1);
@@ -491,9 +495,10 @@ get_timetravel(PG_FUNCTION_ARGS)
 static int
 findTTStatus(char *name)
 {
-   TTOffList* pp;
-   for(pp = TTOff.next; pp; pp = pp->next)
-       if(strcasecmp(name, pp->name) == 0)
+   TTOffList  *pp;
+
+   for (pp = TTOff.next; pp; pp = pp->next)
+       if (strcasecmp(name, pp->name) == 0)
            return 0;
    return 1;
 }
@@ -509,17 +514,17 @@ currabstime()
 static EPlan *
 find_plan(char *ident, EPlan ** eplan, int *nplans)
 {
-   EPlan   *newp;
-   int i;
+   EPlan      *newp;
+   int         i;
 
-   if(*nplans > 0)
+   if (*nplans > 0)
    {
-       for(i = 0; i < *nplans; i++)
+       for (i = 0; i < *nplans; i++)
        {
-           if(strcmp((*eplan)[i].ident, ident) == 0)
+           if (strcmp((*eplan)[i].ident, ident) == 0)
                break;
        }
-       if(i != *nplans)
+       if (i != *nplans)
            return (*eplan + i);
        *eplan = (EPlan *) realloc(*eplan, (i + 1) * sizeof(EPlan));
        newp = *eplan + i;
index d883793aace44c93129748c16dcd6ba48cb3513c..17a3a6a857978d1c88cec7e76bfc32ea3526ffee 100644 (file)
 
 #include "tablefunc.h"
 
-static int load_categories_hash(char *cats_sql, MemoryContext per_query_ctx);
+static int load_categories_hash(char *cats_sql, MemoryContext per_query_ctx);
 static Tuplestorestate *get_crosstab_tuplestore(char *sql,
-                                               int num_categories,
-                                               TupleDesc tupdesc,
-                                               MemoryContext per_query_ctx);
+                       int num_categories,
+                       TupleDesc tupdesc,
+                       MemoryContext per_query_ctx);
 static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial);
 static bool compatCrosstabTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2);
 static bool compatConnectbyTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2);
@@ -56,7 +56,7 @@ static TupleDesc make_crosstab_tupledesc(TupleDesc spi_tupdesc,
 static Tuplestorestate *connectby(char *relname,
          char *key_fld,
          char *parent_key_fld,
-           char *orderby_fld,
+         char *orderby_fld,
          char *branch_delim,
          char *start_with,
          int max_depth,
@@ -115,7 +115,7 @@ static HTAB *crosstab_HashTable;
 typedef struct crosstab_cat_desc
 {
    char       *catname;
-   int         attidx; /* zero based */
+   int         attidx;         /* zero based */
 }  crosstab_cat_desc;
 
 #define MAX_CATNAME_LEN            NAMEDATALEN
@@ -157,9 +157,9 @@ do { \
 /* hash table */
 typedef struct crosstab_hashent
 {
-   char                internal_catname[MAX_CATNAME_LEN];
-   crosstab_cat_desc  *catdesc;
-} crosstab_HashEnt;
+   char        internal_catname[MAX_CATNAME_LEN];
+   crosstab_cat_desc *catdesc;
+}  crosstab_HashEnt;
 
 /*
  * normal_rand - return requested number of random values
@@ -414,7 +414,7 @@ crosstab(PG_FUNCTION_ARGS)
                        (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                         errmsg("invalid source data SQL statement"),
                         errdetail("The provided SQL must return 3 " \
-                                  " columns; rowid, category, and values.")));
+                            " columns; rowid, category, and values.")));
        }
        else
        {
@@ -667,10 +667,10 @@ crosstab(PG_FUNCTION_ARGS)
 }
 
 /*
- * crosstab_hash - reimplement crosstab as materialized function and 
+ * crosstab_hash - reimplement crosstab as materialized function and
  * properly deal with missing values (i.e. don't pack remaining
  * values to the left)
- * 
+ *
  * crosstab - create a crosstab of rowids and values columns from a
  * SQL statement returning one rowid column, one category column,
  * and one value column.
@@ -705,13 +705,13 @@ PG_FUNCTION_INFO_V1(crosstab_hash);
 Datum
 crosstab_hash(PG_FUNCTION_ARGS)
 {
-   char               *sql = GET_STR(PG_GETARG_TEXT_P(0));
-   char               *cats_sql = GET_STR(PG_GETARG_TEXT_P(1));
-   ReturnSetInfo      *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
-   TupleDesc           tupdesc;
-   MemoryContext       per_query_ctx;
-   MemoryContext       oldcontext;
-   int                 num_categories;
+   char       *sql = GET_STR(PG_GETARG_TEXT_P(0));
+   char       *cats_sql = GET_STR(PG_GETARG_TEXT_P(1));
+   ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
+   TupleDesc   tupdesc;
+   MemoryContext per_query_ctx;
+   MemoryContext oldcontext;
+   int         num_categories;
 
    /* check to see if caller supports us returning a tuplestore */
    if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
@@ -729,9 +729,9 @@ crosstab_hash(PG_FUNCTION_ARGS)
    /*
     * Check to make sure we have a reasonable tuple descriptor
     *
-    * Note we will attempt to coerce the values into whatever
-    * the return attribute type is and depend on the "in"
-    * function to complain if needed.
+    * Note we will attempt to coerce the values into whatever the return
+    * attribute type is and depend on the "in" function to complain if
+    * needed.
     */
    if (tupdesc->natts < 2)
        ereport(ERROR,
@@ -770,19 +770,19 @@ crosstab_hash(PG_FUNCTION_ARGS)
 static int
 load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
 {
-   HASHCTL         ctl;
-   int             ret;
-   int             proc;
-   MemoryContext   SPIcontext;
-   int             num_categories = 0;
+   HASHCTL     ctl;
+   int         ret;
+   int         proc;
+   MemoryContext SPIcontext;
+   int         num_categories = 0;
 
    /* initialize the category hash table */
    ctl.keysize = MAX_CATNAME_LEN;
    ctl.entrysize = sizeof(crosstab_HashEnt);
 
    /*
-    * use INIT_CATS, defined above as a guess of how
-    * many hash table entries to create, initially
+    * use INIT_CATS, defined above as a guess of how many hash table
+    * entries to create, initially
     */
    crosstab_HashTable = hash_create("crosstab hash", INIT_CATS, &ctl, HASH_ELEM);
 
@@ -798,13 +798,13 @@ load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
    /* Check for qualifying tuples */
    if ((ret == SPI_OK_SELECT) && (proc > 0))
    {
-       SPITupleTable  *spi_tuptable = SPI_tuptable;
-       TupleDesc       spi_tupdesc = spi_tuptable->tupdesc;
-       int             i;
+       SPITupleTable *spi_tuptable = SPI_tuptable;
+       TupleDesc   spi_tupdesc = spi_tuptable->tupdesc;
+       int         i;
 
        /*
-        * The provided categories SQL query must always return one column:
-        * category - the label or identifier for each column
+        * The provided categories SQL query must always return one
+        * column: category - the label or identifier for each column
         */
        if (spi_tupdesc->natts != 1)
            ereport(ERROR,
@@ -814,9 +814,9 @@ load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
 
        for (i = 0; i < proc; i++)
        {
-           crosstab_cat_desc  *catdesc;
-           char               *catname;
-           HeapTuple           spi_tuple;
+           crosstab_cat_desc *catdesc;
+           char       *catname;
+           HeapTuple   spi_tuple;
 
            /* get the next sql result tuple */
            spi_tuple = spi_tuptable->vals[i];
@@ -862,13 +862,13 @@ get_crosstab_tuplestore(char *sql,
                        TupleDesc tupdesc,
                        MemoryContext per_query_ctx)
 {
-   Tuplestorestate    *tupstore;
-   AttInMetadata      *attinmeta = TupleDescGetAttInMetadata(tupdesc);
-   char              **values;
-   HeapTuple           tuple;
-   int                 ret;
-   int                 proc;
-   MemoryContext       SPIcontext;
+   Tuplestorestate *tupstore;
+   AttInMetadata *attinmeta = TupleDescGetAttInMetadata(tupdesc);
+   char      **values;
+   HeapTuple   tuple;
+   int         ret;
+   int         proc;
+   MemoryContext SPIcontext;
 
    /* initialize our tuplestore */
    tupstore = tuplestore_begin_heap(true, false, SortMem);
@@ -885,33 +885,36 @@ get_crosstab_tuplestore(char *sql,
    /* Check for qualifying tuples */
    if ((ret == SPI_OK_SELECT) && (proc > 0))
    {
-       SPITupleTable  *spi_tuptable = SPI_tuptable;
-       TupleDesc       spi_tupdesc = spi_tuptable->tupdesc;
-       int             ncols = spi_tupdesc->natts;
-       char           *rowid;
-       char           *lastrowid = NULL;
-       int             i, j;
-       int             result_ncols;
+       SPITupleTable *spi_tuptable = SPI_tuptable;
+       TupleDesc   spi_tupdesc = spi_tuptable->tupdesc;
+       int         ncols = spi_tupdesc->natts;
+       char       *rowid;
+       char       *lastrowid = NULL;
+       int         i,
+                   j;
+       int         result_ncols;
 
        /*
-        * The provided SQL query must always return at least three columns:
+        * The provided SQL query must always return at least three
+        * columns:
         *
         * 1. rowname   the label for each row - column 1 in the final result
-        * 2. category  the label for each value-column in the final result
-        * 3. value     the values used to populate the value-columns
-        * 
+        * 2. category  the label for each value-column in the final
+        * result 3. value     the values used to populate the
+        * value-columns
+        *
         * If there are more than three columns, the last two are taken as
-        * "category" and "values". The first column is taken as "rowname".
-        * Additional columns (2 thru N-2) are assumed the same for the same
-        * "rowname", and are copied into the result tuple from the first
-        * time we encounter a particular rowname.
+        * "category" and "values". The first column is taken as
+        * "rowname". Additional columns (2 thru N-2) are assumed the same
+        * for the same "rowname", and are copied into the result tuple
+        * from the first time we encounter a particular rowname.
         */
        if (ncols < 3)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("invalid source data SQL statement"),
                     errdetail("The provided SQL must return 3 " \
-                              " columns; rowid, category, and values.")));
+                            " columns; rowid, category, and values.")));
 
        result_ncols = (ncols - 2) + num_categories;
 
@@ -922,7 +925,7 @@ get_crosstab_tuplestore(char *sql,
                     errmsg("invalid return type"),
                     errdetail("query-specified return " \
                               "tuple has %d columns but crosstab " \
-                              "returns %d", tupdesc->natts, result_ncols)));
+                          "returns %d", tupdesc->natts, result_ncols)));
 
        /* allocate space */
        values = (char **) palloc(result_ncols * sizeof(char *));
@@ -932,9 +935,9 @@ get_crosstab_tuplestore(char *sql,
 
        for (i = 0; i < proc; i++)
        {
-           HeapTuple           spi_tuple;
-           crosstab_cat_desc  *catdesc;
-           char               *catname;
+           HeapTuple   spi_tuple;
+           crosstab_cat_desc *catdesc;
+           char       *catname;
 
            /* get the next sql result tuple */
            spi_tuple = spi_tuptable->vals[i];
@@ -958,7 +961,10 @@ get_crosstab_tuplestore(char *sql,
                 */
                if (lastrowid != NULL)
                {
-                   /* switch to appropriate context while storing the tuple */
+                   /*
+                    * switch to appropriate context while storing the
+                    * tuple
+                    */
                    SPIcontext = MemoryContextSwitchTo(per_query_ctx);
 
                    /* rowid changed, flush the previous output row */
@@ -984,7 +990,7 @@ get_crosstab_tuplestore(char *sql,
                crosstab_HashTableLookup(catname, catdesc);
 
                if (catdesc)
-                   values[catdesc->attidx + ncols - 2] = 
+                   values[catdesc->attidx + ncols - 2] =
                        SPI_getvalue(spi_tuple, spi_tupdesc, ncols);
            }
 
@@ -1026,29 +1032,29 @@ get_crosstab_tuplestore(char *sql,
  *
  *         keyid   parent_keyid pos
  *         ------+------------+--
- *         row1    NULL         0
- *         row2    row1         0
- *         row3    row1         0
- *         row4    row2         1
- *         row5    row2         0
- *         row6    row4         0
- *         row7    row3         0
- *         row8    row6         0
- *         row9    row5         0
+ *         row1    NULL         0
+ *         row2    row1         0
+ *         row3    row1         0
+ *         row4    row2         1
+ *         row5    row2         0
+ *         row6    row4         0
+ *         row7    row3         0
+ *         row8    row6         0
+ *         row9    row5         0
  *
  *
  * connectby(text relname, text keyid_fld, text parent_keyid_fld
- *            [, text orderby_fld], text start_with, int max_depth
- *            [, text branch_delim])
+ *           [, text orderby_fld], text start_with, int max_depth
+ *           [, text branch_delim])
  * connectby('foo', 'keyid', 'parent_keyid', 'pos', 'row2', 0, '~') returns:
  *
- *     keyid   parent_id   level    branch             serial
+ *     keyid   parent_id   level    branch             serial
  *     ------+-----------+--------+-----------------------
- *     row2    NULL          0       row2                1
- *     row5    row2          1       row2~row5           2
- *     row9    row5          2       row2~row5~row9      3
- *     row4    row2          1       row2~row4           4
- *     row6    row4          2       row2~row4~row6      5
+ *     row2    NULL          0       row2                1
+ *     row5    row2          1       row2~row5           2
+ *     row9    row5          2       row2~row5~row9      3
+ *     row4    row2          1       row2~row4           4
+ *     row6    row4          2       row2~row4~row6      5
  *     row8    row6          3       row2~row4~row6~row8 6
  *
  */
@@ -1114,7 +1120,7 @@ connectby_text(PG_FUNCTION_ARGS)
    rsinfo->setResult = connectby(relname,
                                  key_fld,
                                  parent_key_fld,
-                                   NULL,
+                                 NULL,
                                  branch_delim,
                                  start_with,
                                  max_depth,
@@ -1149,7 +1155,7 @@ connectby_text_serial(PG_FUNCTION_ARGS)
    char       *branch_delim = NULL;
    bool        show_branch = false;
    bool        show_serial = true;
-   
+
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    TupleDesc   tupdesc;
    AttInMetadata *attinmeta;
@@ -1192,7 +1198,7 @@ connectby_text_serial(PG_FUNCTION_ARGS)
    rsinfo->setResult = connectby(relname,
                                  key_fld,
                                  parent_key_fld,
-                                   orderby_fld,
+                                 orderby_fld,
                                  branch_delim,
                                  start_with,
                                  max_depth,
@@ -1222,12 +1228,12 @@ static Tuplestorestate *
 connectby(char *relname,
          char *key_fld,
          char *parent_key_fld,
-           char *orderby_fld,
+         char *orderby_fld,
          char *branch_delim,
          char *start_with,
          int max_depth,
          bool show_branch,
-           bool show_serial,
+         bool show_serial,
          MemoryContext per_query_ctx,
          AttInMetadata *attinmeta)
 {
@@ -1235,7 +1241,7 @@ connectby(char *relname,
    int         ret;
    MemoryContext oldcontext;
 
-   int serial = 1;
+   int         serial = 1;
 
    /* Connect to SPI manager */
    if ((ret = SPI_connect()) < 0)
@@ -1303,25 +1309,25 @@ build_tuplestore_recursively(char *key_fld,
    if (!show_serial)
    {
        appendStringInfo(sql, "SELECT %s, %s FROM %s WHERE %s = '%s' AND %s IS NOT NULL",
-                    key_fld,
-                    parent_key_fld,
-                    relname,
-                    parent_key_fld,
-                    start_with,
-                    key_fld);
-                    serial_column=0;
+                        key_fld,
+                        parent_key_fld,
+                        relname,
+                        parent_key_fld,
+                        start_with,
+                        key_fld);
+       serial_column = 0;
    }
    else
    {
        appendStringInfo(sql, "SELECT %s, %s FROM %s WHERE %s = '%s' AND %s IS NOT NULL ORDER BY %s",
-                    key_fld,
-                    parent_key_fld,
-                    relname,
-                    parent_key_fld,
-                    start_with,
-                    key_fld,
-                    orderby_fld);      
-                    serial_column=1;
+                        key_fld,
+                        parent_key_fld,
+                        relname,
+                        parent_key_fld,
+                        start_with,
+                        key_fld,
+                        orderby_fld);
+       serial_column = 1;
    }
 
    /* Retrieve the desired rows */
@@ -1371,8 +1377,8 @@ build_tuplestore_recursively(char *key_fld,
                ereport(ERROR,
                        (errcode(ERRCODE_SYNTAX_ERROR),
                         errmsg("invalid return type"),
-                        errdetail("Return and SQL tuple descriptions are " \
-                                  "incompatible.")));
+                    errdetail("Return and SQL tuple descriptions are " \
+                              "incompatible.")));
 
            /* root value is the one we initially start with */
            values[0] = start_with;
@@ -1395,7 +1401,7 @@ build_tuplestore_recursively(char *key_fld,
                if (show_branch)
                    values[4] = serial_str;
                else
-                   values[3] = serial_str;                 
+                   values[3] = serial_str;
            }
 
            /* construct the tuple */
@@ -1508,11 +1514,11 @@ build_tuplestore_recursively(char *key_fld,
 static void
 validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial)
 {
-   int serial_column=0;
+   int         serial_column = 0;
 
    if (show_serial)
-       serial_column=1;
-       
+       serial_column = 1;
+
    /* are there the correct number of columns */
    if (show_branch)
    {
@@ -1546,7 +1552,7 @@ validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial
                (errcode(ERRCODE_SYNTAX_ERROR),
                 errmsg("invalid return type"),
                 errdetail("Third column must be type %s.",
-                        format_type_be(INT4OID))));
+                          format_type_be(INT4OID))));
 
    /* check that the type of the fourth column is TEXT if applicable */
    if (show_branch && tupdesc->attrs[3]->atttypid != TEXTOID)
@@ -1554,7 +1560,7 @@ validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial
                (errcode(ERRCODE_SYNTAX_ERROR),
                 errmsg("invalid return type"),
                 errdetail("Fourth column must be type %s.",
-                        format_type_be(TEXTOID))));
+                          format_type_be(TEXTOID))));
 
    /* check that the type of the fifth column is INT4 */
    if (show_branch && show_serial && tupdesc->attrs[4]->atttypid != INT4OID)
@@ -1565,7 +1571,7 @@ validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial
    if (!show_branch && show_serial && tupdesc->attrs[3]->atttypid != INT4OID)
        elog(ERROR, "Query-specified return tuple not valid for Connectby: "
             "fourth column must be type %s", format_type_be(INT4OID));
-            
+
    /* OK, the tupdesc is valid for our purposes */
 }
 
@@ -1596,7 +1602,7 @@ compatConnectbyTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
                (errcode(ERRCODE_SYNTAX_ERROR),
                 errmsg("invalid return type"),
                 errdetail("SQL parent key field datatype does " \
-                          "not match return parent key field datatype.")));
+                       "not match return parent key field datatype.")));
 
    /* OK, the two tupdescs are compatible for our purposes */
    return true;
index 2455a72d8ddfdab883aa59c226d16f688e810b03..b827fd652d92759318f1ce71db29586188211dd1 100644 (file)
@@ -51,7 +51,8 @@ DICT      dicts[] = {
 #undef DICT_TABLE
 
 /* array for storing dictionary's objects (if needed) */
-void      *dictobjs[lengthof(dicts)];
+void      *dictobjs[
+                    lengthof(dicts)];
 
 #define STOPLEXEM  -2
 #define BYLOCALE   -1
@@ -175,7 +176,7 @@ lemmatize(char *word, int *len, int type)
        }
        else if (nd == BYLOCALE)
        {
-           continue; /* no dict for current locale */
+           continue;           /* no dict for current locale */
        }
        else
        {
index 917dced87fa0f683195c685f5bc44a7d391eb8ac..30062180076672a27d1fab34afdd8e19575ca56b 100644 (file)
@@ -4,80 +4,99 @@
 #include "ts_cfg.h"
 #include "dict.h"
 
-text* 
-char2text(char* in) {
+text *
+char2text(char *in)
+{
    return charl2text(in, strlen(in));
 }
 
-text* charl2text(char* in, int len) {
-   text *out=(text*)palloc(len+VARHDRSZ);
+text *
+charl2text(char *in, int len)
+{
+   text       *out = (text *) palloc(len + VARHDRSZ);
+
    memcpy(VARDATA(out), in, len);
-   VARATT_SIZEP(out) = len+VARHDRSZ;
+   VARATT_SIZEP(out) = len + VARHDRSZ;
    return out;
 }
 
-char   
-*text2char(text* in) {
-        char *out=palloc( VARSIZE(in) );
-        memcpy(out, VARDATA(in), VARSIZE(in)-VARHDRSZ);
-        out[ VARSIZE(in)-VARHDRSZ ] ='\0';
+char
+          *
+text2char(text *in)
+{
+   char       *out = palloc(VARSIZE(in));
+
+   memcpy(out, VARDATA(in), VARSIZE(in) - VARHDRSZ);
+   out[VARSIZE(in) - VARHDRSZ] = '\0';
    return out;
 }
 
-char    
-*pnstrdup(char* in, int len) {
-   char *out=palloc( len+1 );
+char
+          *
+pnstrdup(char *in, int len)
+{
+   char       *out = palloc(len + 1);
+
    memcpy(out, in, len);
-   out[len]='\0';
+   out[len] = '\0';
    return out;
 }
 
-text    
-*ptextdup(text* in) {
-   text *out=(text*)palloc( VARSIZE(in) );
-   memcpy(out,in,VARSIZE(in));
+text
+          *
+ptextdup(text *in)
+{
+   text       *out = (text *) palloc(VARSIZE(in));
+
+   memcpy(out, in, VARSIZE(in));
    return out;
 }
 
-text    
-*mtextdup(text* in) {
-   text *out=(text*)malloc( VARSIZE(in) );
-   if ( !out ) 
+text
+          *
+mtextdup(text *in)
+{
+   text       *out = (text *) malloc(VARSIZE(in));
+
+   if (!out)
        ts_error(ERROR, "No memory");
-   memcpy(out,in,VARSIZE(in));
+   memcpy(out, in, VARSIZE(in));
    return out;
 }
 
-void 
-ts_error(int state, const char *format, ...) {
-   va_list args;
-   int tlen = 128, len=0;
-   char    *buf;
-   
+void
+ts_error(int state, const char *format,...)
+{
+   va_list     args;
+   int         tlen = 128,
+               len = 0;
+   char       *buf;
+
    reset_cfg();
    reset_dict();
    reset_prs();
 
    va_start(args, format);
    buf = palloc(tlen);
-   len = vsnprintf(buf, tlen-1, format, args);
-   if ( len >= tlen ) {
-       tlen=len+1;
-       buf = repalloc( buf, tlen );
-       vsnprintf(buf, tlen-1, format, args);
+   len = vsnprintf(buf, tlen - 1, format, args);
+   if (len >= tlen)
+   {
+       tlen = len + 1;
+       buf = repalloc(buf, tlen);
+       vsnprintf(buf, tlen - 1, format, args);
    }
    va_end(args);
+
    /* ?? internal error ?? */
    elog(state, "%s", buf);
    pfree(buf);
 }
 
-int   
-text_cmp(text *a, text *b) {
-   if ( VARSIZE(a) == VARSIZE(b) )
-       return strncmp( VARDATA(a), VARDATA(b), VARSIZE(a)-VARHDRSZ );
-   return (int)VARSIZE(a) - (int)VARSIZE(b);
+int
+text_cmp(text *a, text *b)
+{
+   if (VARSIZE(a) == VARSIZE(b))
+       return strncmp(VARDATA(a), VARDATA(b), VARSIZE(a) - VARHDRSZ);
+   return (int) VARSIZE(a) - (int) VARSIZE(b);
 
 }
-
index 70313fa4d2473d2dc0f1352a33df4144b99be8a2..481f00405bba6fa274a36f600c820bdfb9d23e6e 100644 (file)
@@ -7,18 +7,18 @@
 #define PG_NARGS() (fcinfo->nargs)
 #endif
 
-text* char2text(char* in);
-text* charl2text(char* in, int len);
-char   *text2char(text* in);
-char   *pnstrdup(char* in, int len);
-text   *ptextdup(text* in);
-text   *mtextdup(text* in);
+text      *char2text(char *in);
+text      *charl2text(char *in, int len);
+char      *text2char(text *in);
+char      *pnstrdup(char *in, int len);
+text      *ptextdup(text *in);
+text      *mtextdup(text *in);
 
-int   text_cmp(text *a, text *b);
+int            text_cmp(text *a, text *b);
 
 #define NEXTVAL(x) ( (text*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) )
 #define ARRNELEMS(x)  ArrayGetNItems( ARR_NDIM(x), ARR_DIMS(x))
 
-void ts_error(int state, const char *format, ...);
+void       ts_error(int state, const char *format,...);
 
 #endif
index 8f4cad5c41754c7f6120c2ba9b39607228610368..9ceb78ffb8377bcd1eea1b6c9100ee47168fc6f9 100644 (file)
@@ -1,5 +1,5 @@
-/* 
- * interface functions to dictionary 
+/*
+ * interface functions to dictionary
  * Teodor Sigaev <teodor@sigaev.ru>
  */
 #include <errno.h>
 
 /*********top interface**********/
 
-static void *plan_getdict=NULL;
+static void *plan_getdict = NULL;
 
 void
-init_dict(Oid id, DictInfo *dict) {
-   Oid arg[1]={ OIDOID };
-   bool isnull;
-   Datum pars[1]={ ObjectIdGetDatum(id) };
-   int stat;
-
-   memset(dict,0,sizeof(DictInfo));
+init_dict(Oid id, DictInfo * dict)
+{
+   Oid         arg[1] = {OIDOID};
+   bool        isnull;
+   Datum       pars[1] = {ObjectIdGetDatum(id)};
+   int         stat;
+
+   memset(dict, 0, sizeof(DictInfo));
    SPI_connect();
-   if ( !plan_getdict ) {
-       plan_getdict = SPI_saveplan( SPI_prepare( "select dict_init, dict_initoption, dict_lexize from pg_ts_dict where oid = $1" , 1, arg ) );
-       if ( !plan_getdict ) 
+   if (!plan_getdict)
+   {
+       plan_getdict = SPI_saveplan(SPI_prepare("select dict_init, dict_initoption, dict_lexize from pg_ts_dict where oid = $1", 1, arg));
+       if (!plan_getdict)
            ts_error(ERROR, "SPI_prepare() failed");
    }
 
    stat = SPI_execp(plan_getdict, pars, " ", 1);
-   if ( stat < 0 )
-       ts_error (ERROR, "SPI_execp return %d", stat);
-   if ( SPI_processed > 0 ) {
-       Datum opt;
-       Oid oid=InvalidOid;
-       oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) );
-       if ( !(isnull || oid==InvalidOid) ) {
-           opt=SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull);
-           dict->dictionary=(void*)DatumGetPointer(OidFunctionCall1(oid, opt)); 
+   if (stat < 0)
+       ts_error(ERROR, "SPI_execp return %d", stat);
+   if (SPI_processed > 0)
+   {
+       Datum       opt;
+       Oid         oid = InvalidOid;
+
+       oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
+       if (!(isnull || oid == InvalidOid))
+       {
+           opt = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull);
+           dict->dictionary = (void *) DatumGetPointer(OidFunctionCall1(oid, opt));
        }
-       oid=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull) );
-       if ( isnull || oid==InvalidOid ) 
+       oid = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 3, &isnull));
+       if (isnull || oid == InvalidOid)
            ts_error(ERROR, "Null dict_lexize for dictonary %d", id);
        fmgr_info_cxt(oid, &(dict->lexize_info), TopMemoryContext);
-       dict->dict_id=id;
-   } else 
+       dict->dict_id = id;
+   }
+   else
        ts_error(ERROR, "No dictionary with id %d", id);
    SPI_finish();
 }
 
-typedef struct {
-   DictInfo    *last_dict;
-   int     len;
-   int     reallen;
-   DictInfo    *list;
+typedef struct
+{
+   DictInfo   *last_dict;
+   int         len;
+   int         reallen;
+   DictInfo   *list;
    SNMap       name2id_map;
-} DictList;
+}  DictList;
 
-static DictList DList = {NULL,0,0,NULL,{0,0,NULL}};
+static DictList DList = {NULL, 0, 0, NULL, {0, 0, NULL}};
 
 void
-reset_dict(void) {
-   freeSNMap( &(DList.name2id_map) );
+reset_dict(void)
+{
+   freeSNMap(&(DList.name2id_map));
    /* XXX need to free DList.list[*].dictionary */
-   if ( DList.list )
+   if (DList.list)
        free(DList.list);
-   memset(&DList,0,sizeof(DictList));
+   memset(&DList, 0, sizeof(DictList));
 }
 
 
 static int
-comparedict(const void *a, const void *b) {
-   return ((DictInfo*)a)->dict_id - ((DictInfo*)b)->dict_id;
+comparedict(const void *a, const void *b)
+{
+   return ((DictInfo *) a)->dict_id - ((DictInfo *) b)->dict_id;
 }
 
 DictInfo *
-finddict(Oid id) {
+finddict(Oid id)
+{
    /* last used dict */
-   if ( DList.last_dict && DList.last_dict->dict_id==id )
+   if (DList.last_dict && DList.last_dict->dict_id == id)
        return DList.last_dict;
 
 
    /* already used dict */
-   if (  DList.len != 0 ) {
-       DictInfo key;
-       key.dict_id=id;
+   if (DList.len != 0)
+   {
+       DictInfo    key;
+
+       key.dict_id = id;
        DList.last_dict = bsearch(&key, DList.list, DList.len, sizeof(DictInfo), comparedict);
-       if ( DList.last_dict != NULL )
+       if (DList.last_dict != NULL)
            return DList.last_dict;
    }
 
    /* last chance */
-   if ( DList.len==DList.reallen ) {
-       DictInfo *tmp;
-       int reallen = ( DList.reallen ) ? 2*DList.reallen : 16;
-       tmp=(DictInfo*)realloc(DList.list,sizeof(DictInfo)*reallen);
-       if ( !tmp ) 
-           ts_error(ERROR,"No memory");
-       DList.reallen=reallen;
-       DList.list=tmp;
+   if (DList.len == DList.reallen)
+   {
+       DictInfo   *tmp;
+       int         reallen = (DList.reallen) ? 2 * DList.reallen : 16;
+
+       tmp = (DictInfo *) realloc(DList.list, sizeof(DictInfo) * reallen);
+       if (!tmp)
+           ts_error(ERROR, "No memory");
+       DList.reallen = reallen;
+       DList.list = tmp;
    }
-   DList.last_dict=&(DList.list[DList.len]);
+   DList.last_dict = &(DList.list[DList.len]);
    init_dict(id, DList.last_dict);
 
    DList.len++;
    qsort(DList.list, DList.len, sizeof(DictInfo), comparedict);
-   return finddict(id); /* qsort changed order!! */;
+   return finddict(id); /* qsort changed order!! */ ;
 }
 
-static void *plan_name2id=NULL;
+static void *plan_name2id = NULL;
 
 Oid
-name2id_dict(text *name) {
-   Oid arg[1]={ TEXTOID };
-   bool isnull;
-   Datum pars[1]={ PointerGetDatum(name) };
-   int stat;
-   Oid id=findSNMap_t( &(DList.name2id_map), name );
-
-   if ( id ) 
+name2id_dict(text *name)
+{
+   Oid         arg[1] = {TEXTOID};
+   bool        isnull;
+   Datum       pars[1] = {PointerGetDatum(name)};
+   int         stat;
+   Oid         id = findSNMap_t(&(DList.name2id_map), name);
+
+   if (id)
        return id;
-   
+
    SPI_connect();
-   if ( !plan_name2id ) {
-       plan_name2id = SPI_saveplan( SPI_prepare( "select oid from pg_ts_dict where dict_name = $1" , 1, arg ) );
-       if ( !plan_name2id ) 
+   if (!plan_name2id)
+   {
+       plan_name2id = SPI_saveplan(SPI_prepare("select oid from pg_ts_dict where dict_name = $1", 1, arg));
+       if (!plan_name2id)
            ts_error(ERROR, "SPI_prepare() failed");
    }
 
    stat = SPI_execp(plan_name2id, pars, " ", 1);
-   if ( stat < 0 )
-       ts_error (ERROR, "SPI_execp return %d", stat);
-   if ( SPI_processed > 0 )
-       id=DatumGetObjectId( SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull) );
-   else  
+   if (stat < 0)
+       ts_error(ERROR, "SPI_execp return %d", stat);
+   if (SPI_processed > 0)
+       id = DatumGetObjectId(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
+   else
        ts_error(ERROR, "No dictionary with name '%s'", text2char(name));
    SPI_finish();
-   addSNMap_t( &(DList.name2id_map), name, id );
+   addSNMap_t(&(DList.name2id_map), name, id);
    return id;
 }
 
 
 /******sql-level interface******/
 PG_FUNCTION_INFO_V1(lexize);
-Datum lexize(PG_FUNCTION_ARGS);
+Datum      lexize(PG_FUNCTION_ARGS);
 
 Datum
-lexize(PG_FUNCTION_ARGS) {
-   text *in=PG_GETARG_TEXT_P(1);
-   DictInfo *dict = finddict( PG_GETARG_OID(0) );
-   char    **res, **ptr;
-   Datum   *da;
-   ArrayType    *a;
-
-
-   ptr = res = (char**)DatumGetPointer(
-       FunctionCall3(&(dict->lexize_info), 
-           PointerGetDatum(dict->dictionary),
-           PointerGetDatum(VARDATA(in)),
-           Int32GetDatum(VARSIZE(in)-VARHDRSZ)
-       )
-   );
+lexize(PG_FUNCTION_ARGS)
+{
+   text       *in = PG_GETARG_TEXT_P(1);
+   DictInfo   *dict = finddict(PG_GETARG_OID(0));
+   char      **res,
+             **ptr;
+   Datum      *da;
+   ArrayType  *a;
+
+
+   ptr = res = (char **) DatumGetPointer(
+                                     FunctionCall3(&(dict->lexize_info),
+                                      PointerGetDatum(dict->dictionary),
+                                           PointerGetDatum(VARDATA(in)),
+                                   Int32GetDatum(VARSIZE(in) - VARHDRSZ)
+                                                   )
+       );
    PG_FREE_IF_COPY(in, 1);
-   if ( !res ) {
-       if (PG_NARGS() > 2)  
+   if (!res)
+   {
+       if (PG_NARGS() > 2)
            PG_RETURN_POINTER(NULL);
        else
            PG_RETURN_NULL();
    }
 
-   while(*ptr) ptr++;
-   da = (Datum*)palloc(sizeof(Datum)*(ptr-res+1));
-   ptr=res;
-   while(*ptr) {
-       da[ ptr-res ] = PointerGetDatum( char2text(*ptr) );
+   while (*ptr)
+       ptr++;
+   da = (Datum *) palloc(sizeof(Datum) * (ptr - res + 1));
+   ptr = res;
+   while (*ptr)
+   {
+       da[ptr - res] = PointerGetDatum(char2text(*ptr));
        ptr++;
    }
 
    a = construct_array(
-       da,
-       ptr-res,
-       TEXTOID,
-       -1,
-       false,
-       'i'
-   );
-
-   ptr=res; 
-   while(*ptr) {
-       pfree( DatumGetPointer(da[ ptr-res ]) );
-       pfree( *ptr );
+                       da,
+                       ptr - res,
+                       TEXTOID,
+                       -1,
+                       false,
+                       'i'
+       );
+
+   ptr = res;
+   while (*ptr)
+   {
+       pfree(DatumGetPointer(da[ptr - res]));
+       pfree(*ptr);
        ptr++;
    }
    pfree(res);
    pfree(da);
-       
-   PG_RETURN_POINTER(a);   
+
+   PG_RETURN_POINTER(a);
 }
 
 PG_FUNCTION_INFO_V1(lexize_byname);
-Datum lexize_byname(PG_FUNCTION_ARGS);
-Datum 
-lexize_byname(PG_FUNCTION_ARGS) {
-   text *dictname=PG_GETARG_TEXT_P(0);
-   Datum res;
+Datum      lexize_byname(PG_FUNCTION_ARGS);
+Datum
+lexize_byname(PG_FUNCTION_ARGS)
+{
+   text       *dictname = PG_GETARG_TEXT_P(0);
+   Datum       res;
 
    strdup("simple");
-   res=DirectFunctionCall3(
-       lexize,
-       ObjectIdGetDatum(name2id_dict(dictname)),
-       PG_GETARG_DATUM(1),
-       (Datum)0
-   );
+   res = DirectFunctionCall3(
+                             lexize,
+                             ObjectIdGetDatum(name2id_dict(dictname)),
+                             PG_GETARG_DATUM(1),
+                             (Datum) 0
+       );
    PG_FREE_IF_COPY(dictname, 0);
-   if (res) 
-       PG_RETURN_DATUM(res); 
-   else 
+   if (res)
+       PG_RETURN_DATUM(res);
+   else
        PG_RETURN_NULL();
 }
 
-static Oid currect_dictionary_id=0;
+static Oid currect_dictionary_id = 0;
 
 PG_FUNCTION_INFO_V1(set_curdict);
-Datum set_curdict(PG_FUNCTION_ARGS);
+Datum      set_curdict(PG_FUNCTION_ARGS);
 Datum
-set_curdict(PG_FUNCTION_ARGS) {
+set_curdict(PG_FUNCTION_ARGS)
+{
    finddict(PG_GETARG_OID(0));
-   currect_dictionary_id=PG_GETARG_OID(0);
+   currect_dictionary_id = PG_GETARG_OID(0);
    PG_RETURN_VOID();
 }
 
 PG_FUNCTION_INFO_V1(set_curdict_byname);
-Datum set_curdict_byname(PG_FUNCTION_ARGS);
+Datum      set_curdict_byname(PG_FUNCTION_ARGS);
 Datum
-set_curdict_byname(PG_FUNCTION_ARGS) {
-   text *dictname=PG_GETARG_TEXT_P(0);
+set_curdict_byname(PG_FUNCTION_ARGS)
+{
+   text       *dictname = PG_GETARG_TEXT_P(0);
 
    DirectFunctionCall1(
-       set_curdict,
-       ObjectIdGetDatum( name2id_dict(dictname) )
-   );
+                       set_curdict,
+                       ObjectIdGetDatum(name2id_dict(dictname))
+       );
    PG_FREE_IF_COPY(dictname, 0);
    PG_RETURN_VOID();
 }
 
 PG_FUNCTION_INFO_V1(lexize_bycurrent);
-Datum lexize_bycurrent(PG_FUNCTION_ARGS);
-Datum 
-lexize_bycurrent(PG_FUNCTION_ARGS) {
-   Datum res;
-   if ( currect_dictionary_id == 0 )
+Datum      lexize_bycurrent(PG_FUNCTION_ARGS);
+Datum
+lexize_bycurrent(PG_FUNCTION_ARGS)
+{
+   Datum       res;
+
+   if (currect_dictionary_id == 0)
        ereport(ERROR,
                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                 errmsg("no currect dictionary"),
                 errhint("Execute select set_curdict().")));
 
    res = DirectFunctionCall3(
-       lexize,
-       ObjectIdGetDatum(currect_dictionary_id),
-       PG_GETARG_DATUM(0),
-       (Datum)0
-   );
-   if (res) 
+                             lexize,
+                             ObjectIdGetDatum(currect_dictionary_id),
+                             PG_GETARG_DATUM(0),
+                             (Datum) 0
+       );
+   if (res)
        PG_RETURN_DATUM(res);
-   else 
+   else
        PG_RETURN_NULL();
 }
-
-
index bbbbfc47a51d1ee8a2f15d8655054b6341da19f9..86ea42263e5069a201de18fa041f4b13952ecd66 100644 (file)
@@ -3,36 +3,39 @@
 #include "postgres.h"
 #include "fmgr.h"
 
-typedef struct {
-   int len;
-   char    **stop;
-   char*   (*wordop)(char*);
-} StopList;
-
-void sortstoplist(StopList *s);
-void freestoplist(StopList *s); 
-void readstoplist(text *in, StopList *s);
-bool searchstoplist(StopList *s, char *key);
-char* lowerstr(char *str);
-
-typedef struct {
-   Oid dict_id;
-   FmgrInfo lexize_info;
-   void *dictionary;
-} DictInfo;
-
-void init_dict(Oid id, DictInfo *dict);
-DictInfo* finddict(Oid id);
-Oid name2id_dict(text *name);
-void reset_dict(void);
+typedef struct
+{
+   int         len;
+   char      **stop;
+   char       *(*wordop) (char *);
+}  StopList;
+
+void       sortstoplist(StopList * s);
+void       freestoplist(StopList * s);
+void       readstoplist(text *in, StopList * s);
+bool       searchstoplist(StopList * s, char *key);
+char      *lowerstr(char *str);
+
+typedef struct
+{
+   Oid         dict_id;
+   FmgrInfo    lexize_info;
+   void       *dictionary;
+}  DictInfo;
+
+void       init_dict(Oid id, DictInfo * dict);
+DictInfo   *finddict(Oid id);
+Oid            name2id_dict(text *name);
+void       reset_dict(void);
 
 
 /* simple parser of cfg string */
-typedef struct {
-        char    *key;
-        char    *value;
-} Map;
+typedef struct
+{
+   char       *key;
+   char       *value;
+}  Map;
 
-void parse_cfgdict(text *in, Map **m);
+void       parse_cfgdict(text *in, Map ** m);
 
 #endif
index ead96106871bf746d7ed369f06df55becaef28ca..a8fb20453ba2125bed97bbadc0cfff28cef5112f 100644 (file)
@@ -1,5 +1,5 @@
-/* 
- * example of dictionary 
+/*
+ * example of dictionary
  * Teodor Sigaev <teodor@sigaev.ru>
  */
 #include <errno.h>
 #include "dict.h"
 #include "common.h"
 
-typedef struct {
+typedef struct
+{
    StopList    stoplist;
-} DictExample;
+}  DictExample;
 
 
 PG_FUNCTION_INFO_V1(dex_init);
-Datum dex_init(PG_FUNCTION_ARGS);
+Datum      dex_init(PG_FUNCTION_ARGS);
+
 PG_FUNCTION_INFO_V1(dex_lexize);
-Datum dex_lexize(PG_FUNCTION_ARGS);
+Datum      dex_lexize(PG_FUNCTION_ARGS);
 
-Datum 
-dex_init(PG_FUNCTION_ARGS) {
-   DictExample *d = (DictExample*)malloc( sizeof(DictExample) );
+Datum
+dex_init(PG_FUNCTION_ARGS)
+{
+   DictExample *d = (DictExample *) malloc(sizeof(DictExample));
 
-   if ( !d )
+   if (!d)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
-   memset(d,0,sizeof(DictExample));
+   memset(d, 0, sizeof(DictExample));
+
+   d->stoplist.wordop = lowerstr;
+
+   if (!PG_ARGISNULL(0) && PG_GETARG_POINTER(0) != NULL)
+   {
+       text       *in = PG_GETARG_TEXT_P(0);
 
-   d->stoplist.wordop=lowerstr;
-       
-   if ( !PG_ARGISNULL(0) && PG_GETARG_POINTER(0)!=NULL ) {
-       text       *in = PG_GETARG_TEXT_P(0);
        readstoplist(in, &(d->stoplist));
        sortstoplist(&(d->stoplist));
        PG_FREE_IF_COPY(in, 0);
@@ -44,18 +49,21 @@ dex_init(PG_FUNCTION_ARGS) {
 }
 
 Datum
-dex_lexize(PG_FUNCTION_ARGS) {
-   DictExample *d = (DictExample*)PG_GETARG_POINTER(0);
-   char       *in = (char*)PG_GETARG_POINTER(1);
-   char *txt = pnstrdup(in, PG_GETARG_INT32(2));
-   char    **res=palloc(sizeof(char*)*2);
+dex_lexize(PG_FUNCTION_ARGS)
+{
+   DictExample *d = (DictExample *) PG_GETARG_POINTER(0);
+   char       *in = (char *) PG_GETARG_POINTER(1);
+   char       *txt = pnstrdup(in, PG_GETARG_INT32(2));
+   char      **res = palloc(sizeof(char *) * 2);
 
-   if ( *txt=='\0' || searchstoplist(&(d->stoplist),txt) ) {
+   if (*txt == '\0' || searchstoplist(&(d->stoplist), txt))
+   {
        pfree(txt);
-       res[0]=NULL;
-   } else 
-       res[0]=txt;
-   res[1]=NULL;
+       res[0] = NULL;
+   }
+   else
+       res[0] = txt;
+   res[1] = NULL;
 
    PG_RETURN_POINTER(res);
 }
index c053adfad0b165228b818574b7f9fe598293a06a..e3a100fa0135c62c12d239046fe5220bd447d4fc 100644 (file)
@@ -1,4 +1,4 @@
-/* 
+/*
  * ISpell interface
  * Teodor Sigaev <teodor@sigaev.ru>
  */
 #include "common.h"
 #include "ispell/spell.h"
 
-typedef struct {
+typedef struct
+{
    StopList    stoplist;
    IspellDict  obj;
-} DictISpell;
+}  DictISpell;
 
 PG_FUNCTION_INFO_V1(spell_init);
-Datum spell_init(PG_FUNCTION_ARGS);
+Datum      spell_init(PG_FUNCTION_ARGS);
+
 PG_FUNCTION_INFO_V1(spell_lexize);
-Datum spell_lexize(PG_FUNCTION_ARGS);
+Datum      spell_lexize(PG_FUNCTION_ARGS);
 
 static void
-freeDictISpell(DictISpell  *d) {
+freeDictISpell(DictISpell * d)
+{
    FreeIspell(&(d->obj));
    freestoplist(&(d->stoplist));
    free(d);
 }
 
-Datum 
-spell_init(PG_FUNCTION_ARGS) {
-   DictISpell  *d;
-   Map *cfg, *pcfg;
-   text *in;
-   bool affloaded=false, dictloaded=false, stoploaded=false;
-
-   if ( PG_ARGISNULL(0) || PG_GETARG_POINTER(0)==NULL )
+Datum
+spell_init(PG_FUNCTION_ARGS)
+{
+   DictISpell *d;
+   Map        *cfg,
+              *pcfg;
+   text       *in;
+   bool        affloaded = false,
+               dictloaded = false,
+               stoploaded = false;
+
+   if (PG_ARGISNULL(0) || PG_GETARG_POINTER(0) == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_CONFIG_FILE_ERROR),
                 errmsg("ISpell confguration error")));
-   d = (DictISpell*)malloc( sizeof(DictISpell) );
-   if ( !d )
+
+   d = (DictISpell *) malloc(sizeof(DictISpell));
+   if (!d)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
-   memset(d,0,sizeof(DictISpell));
-   d->stoplist.wordop=lowerstr;
+   memset(d, 0, sizeof(DictISpell));
+   d->stoplist.wordop = lowerstr;
 
    in = PG_GETARG_TEXT_P(0);
-   parse_cfgdict(in,&cfg);
+   parse_cfgdict(in, &cfg);
    PG_FREE_IF_COPY(in, 0);
-   pcfg=cfg;
-   while(pcfg->key) {
-       if ( strcasecmp("DictFile", pcfg->key) == 0 ) {
-           if ( dictloaded ) {
+   pcfg = cfg;
+   while (pcfg->key)
+   {
+       if (strcasecmp("DictFile", pcfg->key) == 0)
+       {
+           if (dictloaded)
+           {
                freeDictISpell(d);
                ereport(ERROR,
-                       (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
-                        errmsg("dictionary already loaded")));
+                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                      errmsg("dictionary already loaded")));
            }
-           if ( ImportDictionary(&(d->obj), pcfg->value) ) {
+           if (ImportDictionary(&(d->obj), pcfg->value))
+           {
                freeDictISpell(d);
                ereport(ERROR,
                        (errcode(ERRCODE_CONFIG_FILE_ERROR),
                         errmsg("could not load dictionary file \"%s\"",
                                pcfg->value)));
            }
-           dictloaded=true;
-       } else if ( strcasecmp("AffFile", pcfg->key) == 0 ) {
-           if ( affloaded ) {
+           dictloaded = true;
+       }
+       else if (strcasecmp("AffFile", pcfg->key) == 0)
+       {
+           if (affloaded)
+           {
                freeDictISpell(d);
                ereport(ERROR,
-                       (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
-                        errmsg("affixes already loaded")));
+                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                      errmsg("affixes already loaded")));
            }
-           if ( ImportAffixes(&(d->obj), pcfg->value) ) {
+           if (ImportAffixes(&(d->obj), pcfg->value))
+           {
                freeDictISpell(d);
                ereport(ERROR,
                        (errcode(ERRCODE_CONFIG_FILE_ERROR),
                         errmsg("could not load affix file \"%s\"",
                                pcfg->value)));
            }
-           affloaded=true;
-       } else if ( strcasecmp("StopFile", pcfg->key) == 0 ) {
-           text *tmp=char2text(pcfg->value);
-           if ( stoploaded ) {
+           affloaded = true;
+       }
+       else if (strcasecmp("StopFile", pcfg->key) == 0)
+       {
+           text       *tmp = char2text(pcfg->value);
+
+           if (stoploaded)
+           {
                freeDictISpell(d);
                ereport(ERROR,
-                       (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
-                        errmsg("stop words already loaded")));
+                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                      errmsg("stop words already loaded")));
            }
            readstoplist(tmp, &(d->stoplist));
            sortstoplist(&(d->stoplist));
            pfree(tmp);
-           stoploaded=true;
-       } else {
+           stoploaded = true;
+       }
+       else
+       {
            freeDictISpell(d);
            ereport(ERROR,
                    (errcode(ERRCODE_SYNTAX_ERROR),
                     errmsg("unrecognized option: %s => %s",
-                            pcfg->key, pcfg->value)));
+                           pcfg->key, pcfg->value)));
        }
        pfree(pcfg->key);
        pfree(pcfg->value);
@@ -109,15 +130,20 @@ spell_init(PG_FUNCTION_ARGS) {
    }
    pfree(cfg);
 
-   if ( affloaded && dictloaded ) {
+   if (affloaded && dictloaded)
+   {
        SortDictionary(&(d->obj));
        SortAffixes(&(d->obj));
-   } else if ( !affloaded ) {
+   }
+   else if (!affloaded)
+   {
        freeDictISpell(d);
        ereport(ERROR,
                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                 errmsg("no affixes")));
-   } else {
+   }
+   else
+   {
        freeDictISpell(d);
        ereport(ERROR,
                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
@@ -128,37 +154,43 @@ spell_init(PG_FUNCTION_ARGS) {
 }
 
 Datum
-spell_lexize(PG_FUNCTION_ARGS) {
-   DictISpell *d = (DictISpell*)PG_GETARG_POINTER(0);
-   char       *in = (char*)PG_GETARG_POINTER(1);
-   char *txt;
-   char    **res;
-   char    **ptr, **cptr;
-
-   if ( !PG_GETARG_INT32(2) )
+spell_lexize(PG_FUNCTION_ARGS)
+{
+   DictISpell *d = (DictISpell *) PG_GETARG_POINTER(0);
+   char       *in = (char *) PG_GETARG_POINTER(1);
+   char       *txt;
+   char      **res;
+   char      **ptr,
+             **cptr;
+
+   if (!PG_GETARG_INT32(2))
        PG_RETURN_POINTER(NULL);
 
-   res=palloc(sizeof(char*)*2);
+   res = palloc(sizeof(char *) * 2);
    txt = pnstrdup(in, PG_GETARG_INT32(2));
-   res=NormalizeWord(&(d->obj), txt);
+   res = NormalizeWord(&(d->obj), txt);
    pfree(txt);
 
-   if ( res==NULL ) 
+   if (res == NULL)
        PG_RETURN_POINTER(NULL);
 
-   ptr=cptr=res;
-   while(*ptr) {
-       if ( searchstoplist(&(d->stoplist),*ptr) ) {
+   ptr = cptr = res;
+   while (*ptr)
+   {
+       if (searchstoplist(&(d->stoplist), *ptr))
+       {
            pfree(*ptr);
-           *ptr=NULL;
+           *ptr = NULL;
+           ptr++;
+       }
+       else
+       {
+           *cptr = *ptr;
+           cptr++;
            ptr++;
-       } else {
-           *cptr=*ptr;
-           cptr++; ptr++;
        }
    }
-   *cptr=NULL;
+   *cptr = NULL;
 
    PG_RETURN_POINTER(res);
 }
-
index 103d87d7f993783589053eded4ddecc2dc0af24b..51dba0444994e36eb8017aaa8c3b86287054151b 100644 (file)
@@ -1,6 +1,6 @@
-/* 
+/*
  * example of Snowball dictionary
- * http://snowball.tartarus.org/ 
+ * http://snowball.tartarus.org/
  * Teodor Sigaev <teodor@sigaev.ru>
  */
 #include <stdlib.h>
 #include "snowball/english_stem.h"
 #include "snowball/russian_stem.h"
 
-typedef struct {
+typedef struct
+{
    struct SN_env *z;
    StopList    stoplist;
-   int (*stem)(struct SN_env * z);
-} DictSnowball;
+   int         (*stem) (struct SN_env * z);
+}  DictSnowball;
 
 
 PG_FUNCTION_INFO_V1(snb_en_init);
-Datum snb_en_init(PG_FUNCTION_ARGS);
+Datum      snb_en_init(PG_FUNCTION_ARGS);
+
 PG_FUNCTION_INFO_V1(snb_ru_init);
-Datum snb_ru_init(PG_FUNCTION_ARGS);
+Datum      snb_ru_init(PG_FUNCTION_ARGS);
+
 PG_FUNCTION_INFO_V1(snb_lexize);
-Datum snb_lexize(PG_FUNCTION_ARGS);
+Datum      snb_lexize(PG_FUNCTION_ARGS);
 
-Datum 
-snb_en_init(PG_FUNCTION_ARGS) {
-   DictSnowball    *d = (DictSnowball*)malloc( sizeof(DictSnowball) );
+Datum
+snb_en_init(PG_FUNCTION_ARGS)
+{
+   DictSnowball *d = (DictSnowball *) malloc(sizeof(DictSnowball));
 
-   if ( !d )
+   if (!d)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
-   memset(d,0,sizeof(DictSnowball));
-   d->stoplist.wordop=lowerstr;
-       
-   if ( !PG_ARGISNULL(0) && PG_GETARG_POINTER(0)!=NULL ) {
-       text       *in = PG_GETARG_TEXT_P(0);
+   memset(d, 0, sizeof(DictSnowball));
+   d->stoplist.wordop = lowerstr;
+
+   if (!PG_ARGISNULL(0) && PG_GETARG_POINTER(0) != NULL)
+   {
+       text       *in = PG_GETARG_TEXT_P(0);
+
        readstoplist(in, &(d->stoplist));
        sortstoplist(&(d->stoplist));
        PG_FREE_IF_COPY(in, 0);
    }
 
    d->z = english_create_env();
-   if (!d->z) {
+   if (!d->z)
+   {
        freestoplist(&(d->stoplist));
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
    }
-   d->stem=english_stem;
+   d->stem = english_stem;
 
    PG_RETURN_POINTER(d);
 }
 
-Datum 
-snb_ru_init(PG_FUNCTION_ARGS) {
-   DictSnowball    *d = (DictSnowball*)malloc( sizeof(DictSnowball) );
+Datum
+snb_ru_init(PG_FUNCTION_ARGS)
+{
+   DictSnowball *d = (DictSnowball *) malloc(sizeof(DictSnowball));
 
-   if ( !d )
+   if (!d)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
-   memset(d,0,sizeof(DictSnowball));
-   d->stoplist.wordop=lowerstr;
-       
-   if ( !PG_ARGISNULL(0) && PG_GETARG_POINTER(0)!=NULL ) {
-       text       *in = PG_GETARG_TEXT_P(0);
+   memset(d, 0, sizeof(DictSnowball));
+   d->stoplist.wordop = lowerstr;
+
+   if (!PG_ARGISNULL(0) && PG_GETARG_POINTER(0) != NULL)
+   {
+       text       *in = PG_GETARG_TEXT_P(0);
+
        readstoplist(in, &(d->stoplist));
        sortstoplist(&(d->stoplist));
        PG_FREE_IF_COPY(in, 0);
    }
 
    d->z = russian_create_env();
-   if (!d->z) {
+   if (!d->z)
+   {
        freestoplist(&(d->stoplist));
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
    }
-   d->stem=russian_stem;
+   d->stem = russian_stem;
 
    PG_RETURN_POINTER(d);
 }
 
 Datum
-snb_lexize(PG_FUNCTION_ARGS) {
-   DictSnowball *d = (DictSnowball*)PG_GETARG_POINTER(0);
-   char       *in = (char*)PG_GETARG_POINTER(1);
-   char *txt = pnstrdup(in, PG_GETARG_INT32(2));
-   char    **res=palloc(sizeof(char*)*2);
-
-   if ( *txt=='\0' || searchstoplist(&(d->stoplist),txt) ) {
+snb_lexize(PG_FUNCTION_ARGS)
+{
+   DictSnowball *d = (DictSnowball *) PG_GETARG_POINTER(0);
+   char       *in = (char *) PG_GETARG_POINTER(1);
+   char       *txt = pnstrdup(in, PG_GETARG_INT32(2));
+   char      **res = palloc(sizeof(char *) * 2);
+
+   if (*txt == '\0' || searchstoplist(&(d->stoplist), txt))
+   {
        pfree(txt);
-       res[0]=NULL;
-   } else {
+       res[0] = NULL;
+   }
+   else
+   {
        SN_set_current(d->z, strlen(txt), txt);
-       (d->stem)(d->z);
-       if ( d->z->p && d->z->l ) {
-           txt=repalloc(txt, d->z->l+1);
-           memcpy( txt, d->z->p, d->z->l);
-           txt[d->z->l]='\0';
-       }   
-       res[0]=txt;
+       (d->stem) (d->z);
+       if (d->z->p && d->z->l)
+       {
+           txt = repalloc(txt, d->z->l + 1);
+           memcpy(txt, d->z->p, d->z->l);
+           txt[d->z->l] = '\0';
+       }
+       res[0] = txt;
    }
-   res[1]=NULL;
+   res[1] = NULL;
 
 
    PG_RETURN_POINTER(res);
 }
-
index 34f74cf0ff7cbd4039edde9b6464fbab5c542804..8364223be40e678e4f7751bf8b4ec2f8cc5735a0 100644 (file)
@@ -1,4 +1,4 @@
-/* 
+/*
  * ISpell interface
  * Teodor Sigaev <teodor@sigaev.ru>
  */
 #include "common.h"
 
 #define SYNBUFLEN  4096
-typedef struct {
-   char    *in;
-   char    *out;
-} Syn;
-
-typedef struct {
-   int len;
-   Syn *syn;   
-} DictSyn;
+typedef struct
+{
+   char       *in;
+   char       *out;
+}  Syn;
+
+typedef struct
+{
+   int         len;
+   Syn        *syn;
+}  DictSyn;
 
 PG_FUNCTION_INFO_V1(syn_init);
-Datum syn_init(PG_FUNCTION_ARGS);
+Datum      syn_init(PG_FUNCTION_ARGS);
+
 PG_FUNCTION_INFO_V1(syn_lexize);
-Datum syn_lexize(PG_FUNCTION_ARGS);
+Datum      syn_lexize(PG_FUNCTION_ARGS);
 
 static char *
-findwrd(char *in, char **end) {
-   char *start;
+findwrd(char *in, char **end)
+{
+   char       *start;
 
-   *end=NULL;
-   while(*in && isspace(*in))
+   *end = NULL;
+   while (*in && isspace(*in))
        in++;
 
-   if ( !in )
+   if (!in)
        return NULL;
-   start=in;
+   start = in;
 
-   while(*in && !isspace(*in))
+   while (*in && !isspace(*in))
        in++;
 
-   *end=in;
+   *end = in;
    return start;
 }
 
 static int
-compareSyn(const void *a, const void *b) {
-   return strcmp( ((Syn*)a)->in, ((Syn*)b)->in );
+compareSyn(const void *a, const void *b)
+{
+   return strcmp(((Syn *) a)->in, ((Syn *) b)->in);
 }
 
 
-Datum 
-syn_init(PG_FUNCTION_ARGS) {
-   text       *in;
-   DictSyn     *d;
-   int cur=0;
-   FILE    *fin;
-   char *filename;
-   char buf[SYNBUFLEN];
-   char *starti,*starto,*end=NULL;
-   int slen;
-
-   if ( PG_ARGISNULL(0) || PG_GETARG_POINTER(0)==NULL )
+Datum
+syn_init(PG_FUNCTION_ARGS)
+{
+   text       *in;
+   DictSyn    *d;
+   int         cur = 0;
+   FILE       *fin;
+   char       *filename;
+   char        buf[SYNBUFLEN];
+   char       *starti,
+              *starto,
+              *end = NULL;
+   int         slen;
+
+   if (PG_ARGISNULL(0) || PG_GETARG_POINTER(0) == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("NULL config")));
 
    in = PG_GETARG_TEXT_P(0);
-   if ( VARSIZE(in) - VARHDRSZ == 0 )
+   if (VARSIZE(in) - VARHDRSZ == 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("VOID config")));
 
-   filename=text2char(in);
+   filename = text2char(in);
    PG_FREE_IF_COPY(in, 0);
-   if ( (fin=fopen(filename,"r")) == NULL )
+   if ((fin = fopen(filename, "r")) == NULL)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("could not open file \"%s\": %m",
-                        filename)));
+                       filename)));
 
-   d = (DictSyn*)malloc( sizeof(DictSyn) );
-   if ( !d ) {
+   d = (DictSyn *) malloc(sizeof(DictSyn));
+   if (!d)
+   {
        fclose(fin);
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
    }
-   memset(d,0,sizeof(DictSyn));
+   memset(d, 0, sizeof(DictSyn));
 
-   while( fgets(buf,SYNBUFLEN,fin) ) {
-       slen = strlen(buf)-1;
+   while (fgets(buf, SYNBUFLEN, fin))
+   {
+       slen = strlen(buf) - 1;
        buf[slen] = '\0';
-       if ( *buf=='\0' ) continue;
-       if (cur==d->len) {
-           d->len = (d->len) ? 2*d->len : 16;
-           d->syn=(Syn*)realloc( d->syn, sizeof(Syn)*d->len );
-           if ( !d->syn ) {
+       if (*buf == '\0')
+           continue;
+       if (cur == d->len)
+       {
+           d->len = (d->len) ? 2 * d->len : 16;
+           d->syn = (Syn *) realloc(d->syn, sizeof(Syn) * d->len);
+           if (!d->syn)
+           {
                fclose(fin);
                ereport(ERROR,
                        (errcode(ERRCODE_OUT_OF_MEMORY),
@@ -107,64 +120,66 @@ syn_init(PG_FUNCTION_ARGS) {
            }
        }
 
-       starti=findwrd(buf,&end);
-       if ( !starti )
+       starti = findwrd(buf, &end);
+       if (!starti)
            continue;
-       *end='\0';
-       if ( end >= buf+slen )
+       *end = '\0';
+       if (end >= buf + slen)
            continue;
 
-       starto= findwrd(end+1, &end);
-       if ( !starto )
+       starto = findwrd(end + 1, &end);
+       if (!starto)
            continue;
-       *end='\0';
+       *end = '\0';
 
-       d->syn[cur].in=strdup(lowerstr(starti));
-       d->syn[cur].out=strdup(lowerstr(starto));
-       if ( !(d->syn[cur].in && d->syn[cur].out) ) {
+       d->syn[cur].in = strdup(lowerstr(starti));
+       d->syn[cur].out = strdup(lowerstr(starto));
+       if (!(d->syn[cur].in && d->syn[cur].out))
+       {
            fclose(fin);
            ereport(ERROR,
                    (errcode(ERRCODE_OUT_OF_MEMORY),
                     errmsg("out of memory")));
        }
 
-       cur++; 
+       cur++;
    }
-   
-   fclose(fin);    
-   
-   d->len=cur; 
-   if ( cur>1 )
-       qsort(d->syn, d->len, sizeof(Syn), compareSyn); 
+
+   fclose(fin);
+
+   d->len = cur;
+   if (cur > 1)
+       qsort(d->syn, d->len, sizeof(Syn), compareSyn);
 
    pfree(filename);
-        PG_RETURN_POINTER(d);
+   PG_RETURN_POINTER(d);
 }
 
 Datum
-syn_lexize(PG_FUNCTION_ARGS) {
-   DictSyn *d = (DictSyn*)PG_GETARG_POINTER(0);
-   char       *in = (char*)PG_GETARG_POINTER(1);
-   Syn key,*found;
-        char    **res=NULL;
-
-   if ( !PG_GETARG_INT32(2) )
+syn_lexize(PG_FUNCTION_ARGS)
+{
+   DictSyn    *d = (DictSyn *) PG_GETARG_POINTER(0);
+   char       *in = (char *) PG_GETARG_POINTER(1);
+   Syn         key,
+              *found;
+   char      **res = NULL;
+
+   if (!PG_GETARG_INT32(2))
        PG_RETURN_POINTER(NULL);
 
-   key.out=NULL;
-   key.in=lowerstr(pnstrdup(in, PG_GETARG_INT32(2)));
+   key.out = NULL;
+   key.in = lowerstr(pnstrdup(in, PG_GETARG_INT32(2)));
 
-   found=(Syn*)bsearch(&key, d->syn, d->len, sizeof(Syn), compareSyn);
+   found = (Syn *) bsearch(&key, d->syn, d->len, sizeof(Syn), compareSyn);
    pfree(key.in);
 
-   if ( !found ) 
+   if (!found)
        PG_RETURN_POINTER(NULL);
 
-   res=palloc(sizeof(char*)*2);
+   res = palloc(sizeof(char *) * 2);
 
-   res[0]=pstrdup(found->out);
-   res[1]=NULL;
+   res[0] = pstrdup(found->out);
+   res[1] = NULL;
 
-        PG_RETURN_POINTER(res);
+   PG_RETURN_POINTER(res);
 }
-
index c5ab2601496c0ffe0071cf03d1fab0b2c5635abc..45786cca6528c6785c9a29c5ff01828b2b2ae6a0 100644 (file)
 
 #define MAXNORMLEN 56
 
-#define STRNCASECMP(x,y)        (strncasecmp(x,y,strlen(y)))
+#define STRNCASECMP(x,y)       (strncasecmp(x,y,strlen(y)))
 
-static int cmpspell(const void *s1,const void *s2){
-   return(strcmp(((const SPELL*)s1)->word,((const SPELL*)s2)->word));
+static int
+cmpspell(const void *s1, const void *s2)
+{
+   return (strcmp(((const SPELL *) s1)->word, ((const SPELL *) s2)->word));
 }
 
-static void 
-strlower( char * str ) {
-   unsigned char *ptr = (unsigned char *)str;
-   while ( *ptr ) {
-       *ptr = tolower( *ptr );
+static void
+strlower(char *str)
+{
+   unsigned char *ptr = (unsigned char *) str;
+
+   while (*ptr)
+   {
+       *ptr = tolower(*ptr);
        ptr++;
    }
 }
 
 /* backward string compaire for suffix tree operations */
-static int 
-strbcmp(const char *s1, const char *s2) { 
-   int l1 = strlen(s1)-1, l2 = strlen(s2)-1;
-   while (l1 >= 0 && l2 >= 0) {
-       if (s1[l1] < s2[l2]) return -1;
-       if (s1[l1] > s2[l2]) return 1;
-       l1--; l2--;
+static int
+strbcmp(const char *s1, const char *s2)
+{
+   int         l1 = strlen(s1) - 1,
+               l2 = strlen(s2) - 1;
+
+   while (l1 >= 0 && l2 >= 0)
+   {
+       if (s1[l1] < s2[l2])
+           return -1;
+       if (s1[l1] > s2[l2])
+           return 1;
+       l1--;
+       l2--;
    }
-   if (l1 < l2) return -1;
-   if (l1 > l2) return 1;
+   if (l1 < l2)
+       return -1;
+   if (l1 > l2)
+       return 1;
 
    return 0;
 }
-static int 
-strbncmp(const char *s1, const char *s2, size_t count) { 
-   int l1 = strlen(s1) - 1, l2 = strlen(s2) - 1, l = count;
-   while (l1 >= 0 && l2 >= 0 && l > 0) {
-       if (s1[l1] < s2[l2]) return -1;
-       if (s1[l1] > s2[l2]) return 1;
+static int
+strbncmp(const char *s1, const char *s2, size_t count)
+{
+   int         l1 = strlen(s1) - 1,
+               l2 = strlen(s2) - 1,
+               l = count;
+
+   while (l1 >= 0 && l2 >= 0 && l > 0)
+   {
+       if (s1[l1] < s2[l2])
+           return -1;
+       if (s1[l1] > s2[l2])
+           return 1;
        l1--;
        l2--;
        l--;
    }
-   if (l == 0) return 0;
-   if (l1 < l2) return -1;
-   if (l1 > l2) return 1;
+   if (l == 0)
+       return 0;
+   if (l1 < l2)
+       return -1;
+   if (l1 > l2)
+       return 1;
    return 0;
 }
 
-static int 
-cmpaffix(const void *s1,const void *s2){
-   if (((const AFFIX*)s1)->type < ((const AFFIX*)s2)->type) return -1;
-   if (((const AFFIX*)s1)->type > ((const AFFIX*)s2)->type) return 1;
-   if (((const AFFIX*)s1)->type == 'p')
-       return(strcmp(((const AFFIX*)s1)->repl,((const AFFIX*)s2)->repl));
-   else 
-       return(strbcmp(((const AFFIX*)s1)->repl,((const AFFIX*)s2)->repl));
+static int
+cmpaffix(const void *s1, const void *s2)
+{
+   if (((const AFFIX *) s1)->type < ((const AFFIX *) s2)->type)
+       return -1;
+   if (((const AFFIX *) s1)->type > ((const AFFIX *) s2)->type)
+       return 1;
+   if (((const AFFIX *) s1)->type == 'p')
+       return (strcmp(((const AFFIX *) s1)->repl, ((const AFFIX *) s2)->repl));
+   else
+       return (strbcmp(((const AFFIX *) s1)->repl, ((const AFFIX *) s2)->repl));
 }
 
-int 
-AddSpell(IspellDict * Conf,const char * word,const char *flag){
-   if(Conf->nspell>=Conf->mspell){
-       if(Conf->mspell){
-           Conf->mspell+=1024*20;
-           Conf->Spell=(SPELL *)realloc(Conf->Spell,Conf->mspell*sizeof(SPELL));
-       }else{
-           Conf->mspell=1024*20;
-           Conf->Spell=(SPELL *)malloc(Conf->mspell*sizeof(SPELL));
+int
+AddSpell(IspellDict * Conf, const char *word, const char *flag)
+{
+   if (Conf->nspell >= Conf->mspell)
+   {
+       if (Conf->mspell)
+       {
+           Conf->mspell += 1024 * 20;
+           Conf->Spell = (SPELL *) realloc(Conf->Spell, Conf->mspell * sizeof(SPELL));
+       }
+       else
+       {
+           Conf->mspell = 1024 * 20;
+           Conf->Spell = (SPELL *) malloc(Conf->mspell * sizeof(SPELL));
        }
-       if ( Conf->Spell == NULL )
+       if (Conf->Spell == NULL)
            ereport(ERROR,
                    (errcode(ERRCODE_OUT_OF_MEMORY),
                     errmsg("out of memory")));
    }
-   Conf->Spell[Conf->nspell].word=strdup(word);
-   if ( !Conf->Spell[Conf->nspell].word ) 
+   Conf->Spell[Conf->nspell].word = strdup(word);
+   if (!Conf->Spell[Conf->nspell].word)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));
-   strncpy(Conf->Spell[Conf->nspell].flag,flag,10);
+   strncpy(Conf->Spell[Conf->nspell].flag, flag, 10);
    Conf->nspell++;
-   return(0);
+   return (0);
 }
 
 
-int 
-ImportDictionary(IspellDict * Conf,const char *filename){
-   unsigned char str[BUFSIZ];  
-   FILE *dict;
+int
+ImportDictionary(IspellDict * Conf, const char *filename)
+{
+   unsigned char str[BUFSIZ];
+   FILE       *dict;
 
-   if(!(dict=fopen(filename,"r")))return(1);
-   while(fgets(str,sizeof(str),dict)){
+   if (!(dict = fopen(filename, "r")))
+       return (1);
+   while (fgets(str, sizeof(str), dict))
+   {
        unsigned char *s;
        const unsigned char *flag;
 
-           flag = NULL;
-       if((s=strchr(str,'/'))){
-           *s=0;
-           s++;flag=s;
-           while(*s){
-               if (((*s>='A')&&(*s<='Z'))||((*s>='a')&&(*s<='z')))
+       flag = NULL;
+       if ((s = strchr(str, '/')))
+       {
+           *s = 0;
+           s++;
+           flag = s;
+           while (*s)
+           {
+               if (((*s >= 'A') && (*s <= 'Z')) || ((*s >= 'a') && (*s <= 'z')))
                    s++;
-               else {
-                   *s=0;
+               else
+               {
+                   *s = 0;
                    break;
                }
            }
-       }else{
-           flag="";
        }
+       else
+           flag = "";
        strlower(str);
        /* Dont load words if first letter is not required */
        /* It allows to optimize loading at  search time   */
-       s=str;
-       while(*s){
-           if(*s=='\r')*s=0;
-           if(*s=='\n')*s=0;
+       s = str;
+       while (*s)
+       {
+           if (*s == '\r')
+               *s = 0;
+           if (*s == '\n')
+               *s = 0;
            s++;
        }
-       AddSpell(Conf,str,flag);
+       AddSpell(Conf, str, flag);
    }
    fclose(dict);
-   return(0);
+   return (0);
 }
 
 
-static SPELL * 
-FindWord(IspellDict * Conf, const char *word, int affixflag) {
-   int l,c,r,resc,resl,resr, i;
+static SPELL *
+FindWord(IspellDict * Conf, const char *word, int affixflag)
+{
+   int         l,
+               c,
+               r,
+               resc,
+               resl,
+               resr,
+               i;
 
-   i = (int)(*word) & 255;
+   i = (int) (*word) & 255;
    l = Conf->SpellTree.Left[i];
    r = Conf->SpellTree.Right[i];
-   if (l == -1) return (NULL);
-   while(l<=r){
+   if (l == -1)
+       return (NULL);
+   while (l <= r)
+   {
        c = (l + r) >> 1;
        resc = strcmp(Conf->Spell[c].word, word);
-       if( (resc == 0) && 
-           ((affixflag == 0) || (strchr(Conf->Spell[c].flag, affixflag) != NULL)) ) {
-           return(&Conf->Spell[c]);
-       }
+       if ((resc == 0) &&
+           ((affixflag == 0) || (strchr(Conf->Spell[c].flag, affixflag) != NULL)))
+           return (&Conf->Spell[c]);
        resl = strcmp(Conf->Spell[l].word, word);
-       if( (resl == 0) && 
-           ((affixflag == 0) || (strchr(Conf->Spell[l].flag, affixflag) != NULL)) ) {
-           return(&Conf->Spell[l]);
-       }
+       if ((resl == 0) &&
+           ((affixflag == 0) || (strchr(Conf->Spell[l].flag, affixflag) != NULL)))
+           return (&Conf->Spell[l]);
        resr = strcmp(Conf->Spell[r].word, word);
-       if( (resr == 0) && 
-           ((affixflag == 0) || (strchr(Conf->Spell[r].flag, affixflag) != NULL)) ) {
-           return(&Conf->Spell[r]);
-       }
-       if(resc < 0){
+       if ((resr == 0) &&
+           ((affixflag == 0) || (strchr(Conf->Spell[r].flag, affixflag) != NULL)))
+           return (&Conf->Spell[r]);
+       if (resc < 0)
+       {
            l = c + 1;
            r--;
-       } else if(resc > 0){
+       }
+       else if (resc > 0)
+       {
            r = c - 1;
            l++;
-       } else {
+       }
+       else
+       {
            l++;
            r--;
        }
    }
-   return(NULL);
+   return (NULL);
 }
 
-int 
-AddAffix(IspellDict * Conf,int flag,const char *mask,const char *find,const char *repl,int type) {
-   if(Conf->naffixes>=Conf->maffixes){
-       if(Conf->maffixes){
-           Conf->maffixes+=16;
-           Conf->Affix = (AFFIX*)realloc((void*)Conf->Affix,Conf->maffixes*sizeof(AFFIX));
-       }else{
-           Conf->maffixes=16;
-           Conf->Affix = (AFFIX*)malloc(Conf->maffixes * sizeof(AFFIX));
+int
+AddAffix(IspellDict * Conf, int flag, const char *mask, const char *find, const char *repl, int type)
+{
+   if (Conf->naffixes >= Conf->maffixes)
+   {
+       if (Conf->maffixes)
+       {
+           Conf->maffixes += 16;
+           Conf->Affix = (AFFIX *) realloc((void *) Conf->Affix, Conf->maffixes * sizeof(AFFIX));
+       }
+       else
+       {
+           Conf->maffixes = 16;
+           Conf->Affix = (AFFIX *) malloc(Conf->maffixes * sizeof(AFFIX));
        }
-       if ( Conf->Affix == NULL ) 
+       if (Conf->Affix == NULL)
            ereport(ERROR,
                    (errcode(ERRCODE_OUT_OF_MEMORY),
                     errmsg("out of memory")));
    }
-   if (type=='s') {
-       sprintf(Conf->Affix[Conf->naffixes].mask,"%s$",mask);
-   } else {
-       sprintf(Conf->Affix[Conf->naffixes].mask,"^%s",mask);
-   }
+   if (type == 's')
+       sprintf(Conf->Affix[Conf->naffixes].mask, "%s$", mask);
+   else
+       sprintf(Conf->Affix[Conf->naffixes].mask, "^%s", mask);
    Conf->Affix[Conf->naffixes].compile = 1;
-   Conf->Affix[Conf->naffixes].flag=flag;
-   Conf->Affix[Conf->naffixes].type=type;
-   
-   strcpy(Conf->Affix[Conf->naffixes].find,find);
-   strcpy(Conf->Affix[Conf->naffixes].repl,repl);
-   Conf->Affix[Conf->naffixes].replen=strlen(repl);
+   Conf->Affix[Conf->naffixes].flag = flag;
+   Conf->Affix[Conf->naffixes].type = type;
+
+   strcpy(Conf->Affix[Conf->naffixes].find, find);
+   strcpy(Conf->Affix[Conf->naffixes].repl, repl);
+   Conf->Affix[Conf->naffixes].replen = strlen(repl);
    Conf->naffixes++;
-   return(0);
+   return (0);
 }
 
-static char * 
-remove_spaces(char *dist,char *src){
-char *d,*s;
-   d=dist;
-   s=src;
-   while(*s){
-       if(*s!=' '&&*s!='-'&&*s!='\t'){
-           *d=*s;
+static char *
+remove_spaces(char *dist, char *src)
+{
+   char       *d,
+              *s;
+
+   d = dist;
+   s = src;
+   while (*s)
+   {
+       if (*s != ' ' && *s != '-' && *s != '\t')
+       {
+           *d = *s;
            d++;
        }
        s++;
    }
-   *d=0;
-   return(dist);
+   *d = 0;
+   return (dist);
 }
 
 
-int 
-ImportAffixes(IspellDict * Conf,const char *filename){
+int
+ImportAffixes(IspellDict * Conf, const char *filename)
+{
    unsigned char str[BUFSIZ];
-   unsigned char flag=0;
-   unsigned char mask[BUFSIZ]="";
-   unsigned char find[BUFSIZ]="";
-   unsigned char repl[BUFSIZ]="";
+   unsigned char flag = 0;
+   unsigned char mask[BUFSIZ] = "";
+   unsigned char find[BUFSIZ] = "";
+   unsigned char repl[BUFSIZ] = "";
    unsigned char *s;
-   int i;
-   int suffixes=0;
-   int prefixes=0;
-   FILE *affix;
-
-   if(!(affix=fopen(filename,"r")))
-       return(1);
-
-   while(fgets(str,sizeof(str),affix)){
-       if(!STRNCASECMP(str,"suffixes")){
-           suffixes=1;
-           prefixes=0;
+   int         i;
+   int         suffixes = 0;
+   int         prefixes = 0;
+   FILE       *affix;
+
+   if (!(affix = fopen(filename, "r")))
+       return (1);
+
+   while (fgets(str, sizeof(str), affix))
+   {
+       if (!STRNCASECMP(str, "suffixes"))
+       {
+           suffixes = 1;
+           prefixes = 0;
            continue;
        }
-       if(!STRNCASECMP(str,"prefixes")){
-           suffixes=0;
-           prefixes=1;
+       if (!STRNCASECMP(str, "prefixes"))
+       {
+           suffixes = 0;
+           prefixes = 1;
            continue;
        }
-       if(!STRNCASECMP(str,"flag ")){
-           s=str+5;
-           while(strchr("* ",*s))
+       if (!STRNCASECMP(str, "flag "))
+       {
+           s = str + 5;
+           while (strchr("* ", *s))
                s++;
-           flag=*s;
+           flag = *s;
            continue;
        }
-       if((!suffixes)&&(!prefixes))continue;
-       if((s=strchr(str,'#')))*s=0;
-       if(!*str)continue;
+       if ((!suffixes) && (!prefixes))
+           continue;
+       if ((s = strchr(str, '#')))
+           *s = 0;
+       if (!*str)
+           continue;
        strlower(str);
-       strcpy(mask,"");
-       strcpy(find,"");
-       strcpy(repl,"");
-       i=sscanf(str,"%[^>\n]>%[^,\n],%[^\n]",mask,find,repl);
-       remove_spaces(str,repl);strcpy(repl,str);
-       remove_spaces(str,find);strcpy(find,str);
-       remove_spaces(str,mask);strcpy(mask,str);
-       switch(i){
+       strcpy(mask, "");
+       strcpy(find, "");
+       strcpy(repl, "");
+       i = sscanf(str, "%[^>\n]>%[^,\n],%[^\n]", mask, find, repl);
+       remove_spaces(str, repl);
+       strcpy(repl, str);
+       remove_spaces(str, find);
+       strcpy(find, str);
+       remove_spaces(str, mask);
+       strcpy(mask, str);
+       switch (i)
+       {
            case 3:
                break;
            case 2:
-               if(*find != '\0'){
-                   strcpy(repl,find);
-                   strcpy(find,"");
+               if (*find != '\0')
+               {
+                   strcpy(repl, find);
+                   strcpy(find, "");
                }
                break;
            default:
                continue;
        }
-       
-       AddAffix(Conf,(int)flag,mask,find,repl,suffixes?'s':'p');
-       
+
+       AddAffix(Conf, (int) flag, mask, find, repl, suffixes ? 's' : 'p');
+
    }
    fclose(affix);
-       
-   return(0);
+
+   return (0);
 }
 
-void 
-SortDictionary(IspellDict * Conf){
-  int  CurLet = -1, Let;size_t i;
+void
+SortDictionary(IspellDict * Conf)
+{
+   int         CurLet = -1,
+               Let;
+   size_t      i;
 
-        qsort((void*)Conf->Spell,Conf->nspell,sizeof(SPELL),cmpspell);
+   qsort((void *) Conf->Spell, Conf->nspell, sizeof(SPELL), cmpspell);
 
-   for(i = 0; i < 256 ; i++ )
+   for (i = 0; i < 256; i++)
        Conf->SpellTree.Left[i] = -1;
 
-   for(i = 0; i < Conf->nspell; i++) {
-     Let = (int)(*(Conf->Spell[i].word)) & 255;
-     if (CurLet != Let) {
-       Conf->SpellTree.Left[Let] = i;
-       CurLet = Let;
-     }
-     Conf->SpellTree.Right[Let] = i;
+   for (i = 0; i < Conf->nspell; i++)
+   {
+       Let = (int) (*(Conf->Spell[i].word)) & 255;
+       if (CurLet != Let)
+       {
+           Conf->SpellTree.Left[Let] = i;
+           CurLet = Let;
+       }
+       Conf->SpellTree.Right[Let] = i;
    }
 }
 
-void 
-SortAffixes(IspellDict * Conf) {
-  int   CurLetP = -1, CurLetS = -1, Let;
-  AFFIX *Affix; size_t i;
-  
-  if (Conf->naffixes > 1)
-    qsort((void*)Conf->Affix,Conf->naffixes,sizeof(AFFIX),cmpaffix);
-  for(i = 0; i < 256; i++) {
-      Conf->PrefixTree.Left[i] = Conf->PrefixTree.Right[i] = -1;
-      Conf->SuffixTree.Left[i] = Conf->SuffixTree.Right[i] = -1;
-  }
-
-  for(i = 0; i < Conf->naffixes; i++) {
-    Affix = &(((AFFIX*)Conf->Affix)[i]);
-    if(Affix->type == 'p') {
-      Let = (int)(*(Affix->repl)) & 255;
-      if (CurLetP != Let) {
-   Conf->PrefixTree.Left[Let] = i;
-   CurLetP = Let;
-      }
-      Conf->PrefixTree.Right[Let] = i;
-    } else {
-      Let = (Affix->replen) ? (int)(Affix->repl[Affix->replen-1]) & 255 : 0;
-      if (CurLetS != Let) {
-   Conf->SuffixTree.Left[Let] = i;
-   CurLetS = Let;
-      }
-      Conf->SuffixTree.Right[Let] = i;
-    }
-  }
+void
+SortAffixes(IspellDict * Conf)
+{
+   int         CurLetP = -1,
+               CurLetS = -1,
+               Let;
+   AFFIX      *Affix;
+   size_t      i;
+
+   if (Conf->naffixes > 1)
+       qsort((void *) Conf->Affix, Conf->naffixes, sizeof(AFFIX), cmpaffix);
+   for (i = 0; i < 256; i++)
+   {
+       Conf->PrefixTree.Left[i] = Conf->PrefixTree.Right[i] = -1;
+       Conf->SuffixTree.Left[i] = Conf->SuffixTree.Right[i] = -1;
+   }
+
+   for (i = 0; i < Conf->naffixes; i++)
+   {
+       Affix = &(((AFFIX *) Conf->Affix)[i]);
+       if (Affix->type == 'p')
+       {
+           Let = (int) (*(Affix->repl)) & 255;
+           if (CurLetP != Let)
+           {
+               Conf->PrefixTree.Left[Let] = i;
+               CurLetP = Let;
+           }
+           Conf->PrefixTree.Right[Let] = i;
+       }
+       else
+       {
+           Let = (Affix->replen) ? (int) (Affix->repl[Affix->replen - 1]) & 255 : 0;
+           if (CurLetS != Let)
+           {
+               Conf->SuffixTree.Left[Let] = i;
+               CurLetS = Let;
+           }
+           Conf->SuffixTree.Right[Let] = i;
+       }
+   }
 }
 
-static char * 
-CheckSuffix(const char *word, size_t len, AFFIX *Affix, int *res, IspellDict *Conf) {
-  regmatch_t subs[2]; /* workaround for apache&linux */
-  char newword[2*MAXNORMLEN] = "";
-  int err;
-  
-  *res = strbncmp(word, Affix->repl, Affix->replen);
-  if (*res < 0) {
-    return NULL;
-  }
-  if (*res > 0) {
-    return NULL;
-  }
-  strcpy(newword, word);
-  strcpy(newword+len-Affix->replen, Affix->find);
-
-  if (Affix->compile) {
-    err = regcomp(&(Affix->reg),Affix->mask,REG_EXTENDED|REG_ICASE|REG_NOSUB);
-    if(err){
-      /*regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE);*/
-      regfree(&(Affix->reg));
-      return(NULL);
-    }
-    Affix->compile = 0;
-  }
-  if(!(err=regexec(&(Affix->reg),newword,1,subs,0))){
-    if(FindWord(Conf, newword, Affix->flag))
-   return pstrdup(newword);    
-  }
-  return NULL;
+static char *
+CheckSuffix(const char *word, size_t len, AFFIX * Affix, int *res, IspellDict * Conf)
+{
+   regmatch_t  subs[2];        /* workaround for apache&linux */
+   char        newword[2 * MAXNORMLEN] = "";
+   int         err;
+
+   *res = strbncmp(word, Affix->repl, Affix->replen);
+   if (*res < 0)
+       return NULL;
+   if (*res > 0)
+       return NULL;
+   strcpy(newword, word);
+   strcpy(newword + len - Affix->replen, Affix->find);
+
+   if (Affix->compile)
+   {
+       err = regcomp(&(Affix->reg), Affix->mask, REG_EXTENDED | REG_ICASE | REG_NOSUB);
+       if (err)
+       {
+           /* regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE); */
+           regfree(&(Affix->reg));
+           return (NULL);
+       }
+       Affix->compile = 0;
+   }
+   if (!(err = regexec(&(Affix->reg), newword, 1, subs, 0)))
+   {
+       if (FindWord(Conf, newword, Affix->flag))
+           return pstrdup(newword);
+   }
+   return NULL;
 }
 
 #define NS 1
 #define MAX_NORM 512
-static int 
-CheckPrefix(const char *word, size_t len, AFFIX *Affix, IspellDict *Conf, int pi,
-       char **forms, char ***cur ) {
-  regmatch_t subs[NS*2];
-  char newword[2*MAXNORMLEN] = "";
-  int err, ls, res, lres;
-  size_t newlen;
-  AFFIX *CAffix = Conf->Affix;
-  
-  res = strncmp(word, Affix->repl, Affix->replen);
-  if (res != 0) {
-    return res;
-  }
-  strcpy(newword, Affix->find);
-  strcat(newword, word+Affix->replen);
-
-  if (Affix->compile) {
-    err = regcomp(&(Affix->reg),Affix->mask,REG_EXTENDED|REG_ICASE|REG_NOSUB);
-    if(err){
-      /*regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE);*/
-      regfree(&(Affix->reg));
-      return (0);
-    }
-    Affix->compile = 0;
-  }
-  if(!(err=regexec(&(Affix->reg),newword,1,subs,0))){
-    SPELL * curspell;
-
-    if((curspell=FindWord(Conf, newword, Affix->flag))){
-      if ((*cur - forms) < (MAX_NORM-1)) {
-   **cur =  pstrdup(newword);
-   (*cur)++; **cur = NULL;
-      }
-    } 
-    newlen = strlen(newword);
-    ls = Conf->SuffixTree.Left[pi];
-      if ( ls>=0 && ((*cur - forms) < (MAX_NORM-1)) ) {
-   **cur = CheckSuffix(newword, newlen, &CAffix[ls], &lres, Conf);
-   if (**cur) {
-     (*cur)++; **cur = NULL;
+static int
+CheckPrefix(const char *word, size_t len, AFFIX * Affix, IspellDict * Conf, int pi,
+           char **forms, char ***cur)
+{
+   regmatch_t  subs[NS * 2];
+   char        newword[2 * MAXNORMLEN] = "";
+   int         err,
+               ls,
+               res,
+               lres;
+   size_t      newlen;
+   AFFIX      *CAffix = Conf->Affix;
+
+   res = strncmp(word, Affix->repl, Affix->replen);
+   if (res != 0)
+       return res;
+   strcpy(newword, Affix->find);
+   strcat(newword, word + Affix->replen);
+
+   if (Affix->compile)
+   {
+       err = regcomp(&(Affix->reg), Affix->mask, REG_EXTENDED | REG_ICASE | REG_NOSUB);
+       if (err)
+       {
+           /* regerror(err, &(Affix->reg), regerrstr, ERRSTRSIZE); */
+           regfree(&(Affix->reg));
+           return (0);
+       }
+       Affix->compile = 0;
    }
-      }
-  }
-  return 0;
+   if (!(err = regexec(&(Affix->reg), newword, 1, subs, 0)))
+   {
+       SPELL      *curspell;
+
+       if ((curspell = FindWord(Conf, newword, Affix->flag)))
+       {
+           if ((*cur - forms) < (MAX_NORM - 1))
+           {
+               **cur = pstrdup(newword);
+               (*cur)++;
+               **cur = NULL;
+           }
+       }
+       newlen = strlen(newword);
+       ls = Conf->SuffixTree.Left[pi];
+       if (ls >= 0 && ((*cur - forms) < (MAX_NORM - 1)))
+       {
+           **cur = CheckSuffix(newword, newlen, &CAffix[ls], &lres, Conf);
+           if (**cur)
+           {
+               (*cur)++;
+               **cur = NULL;
+           }
+       }
+   }
+   return 0;
 }
 
 
-char ** 
-NormalizeWord(IspellDict * Conf,char *word){
+char     **
+NormalizeWord(IspellDict * Conf, char *word)
+{
 /*regmatch_t subs[NS];*/
-size_t len;
-char ** forms;
-char **cur;
-AFFIX * Affix;
-int ri, pi, ipi, lp, rp, cp, ls, rs;
-int lres, rres, cres = 0;
-  SPELL *spell;
-
-   len=strlen(word);
+   size_t      len;
+   char      **forms;
+   char      **cur;
+   AFFIX      *Affix;
+   int         ri,
+               pi,
+               ipi,
+               lp,
+               rp,
+               cp,
+               ls,
+               rs;
+   int         lres,
+               rres,
+               cres = 0;
+   SPELL      *spell;
+
+   len = strlen(word);
    if (len > MAXNORMLEN)
-       return(NULL);
+       return (NULL);
 
    strlower(word);
 
-   forms=(char **) palloc(MAX_NORM*sizeof(char **));
-   cur=forms;*cur=NULL;
+   forms = (char **) palloc(MAX_NORM * sizeof(char **));
+   cur = forms;
+   *cur = NULL;
 
-   ri = (int)(*word) & 255;
-   pi = (int)(word[strlen(word)-1]) & 255;
-   Affix=(AFFIX*)Conf->Affix;
+   ri = (int) (*word) & 255;
+   pi = (int) (word[strlen(word) - 1]) & 255;
+   Affix = (AFFIX *) Conf->Affix;
 
    /* Check that the word itself is normal form */
-   if((spell = FindWord(Conf, word, 0))){
-       *cur=pstrdup(word);
-       cur++;*cur=NULL;
+   if ((spell = FindWord(Conf, word, 0)))
+   {
+       *cur = pstrdup(word);
+       cur++;
+       *cur = NULL;
    }
 
    /* Find all other NORMAL forms of the 'word' */
 
-   for (ipi = 0; ipi <= pi; ipi += pi) {
-
-       /* check prefix */
-       lp = Conf->PrefixTree.Left[ri];
-       rp = Conf->PrefixTree.Right[ri];
-       while (lp >= 0 && lp <= rp) {
-         cp = (lp + rp) >> 1;
-         cres = 0;
-         if ((cur - forms) < (MAX_NORM-1)) {
-       cres = CheckPrefix(word, len, &Affix[cp], Conf, ipi, forms, &cur);
-         }
-         if ((lp < cp) && ((cur - forms) < (MAX_NORM-1)) ) {
-       lres = CheckPrefix(word, len, &Affix[lp], Conf, ipi, forms, &cur);
-         }
-         if ( (rp > cp) && ((cur - forms) < (MAX_NORM-1)) ) {
-       rres = CheckPrefix(word, len, &Affix[rp], Conf, ipi, forms, &cur);
-         }
-         if (cres < 0) {
-       rp = cp - 1;
-       lp++;
-         } else if (cres > 0) {
-       lp = cp + 1;
-       rp--;
-         } else {
-       lp++;
-       rp--;
-         }
-       }
-
-       /* check suffix */
-       ls = Conf->SuffixTree.Left[ipi];
-       rs = Conf->SuffixTree.Right[ipi];
-       while (ls >= 0 && ls <= rs) {
-         if (  ((cur - forms) < (MAX_NORM-1)) ) {
-       *cur = CheckSuffix(word, len, &Affix[ls], &lres, Conf);
-       if (*cur) {
-         cur++; *cur = NULL;
-       }
-         }
-         if ( (rs > ls) && ((cur - forms) < (MAX_NORM-1)) ) {
-       *cur = CheckSuffix(word, len, &Affix[rs], &rres, Conf);
-       if (*cur) {
-         cur++; *cur = NULL;
+   for (ipi = 0; ipi <= pi; ipi += pi)
+   {
+
+       /* check prefix */
+       lp = Conf->PrefixTree.Left[ri];
+       rp = Conf->PrefixTree.Right[ri];
+       while (lp >= 0 && lp <= rp)
+       {
+           cp = (lp + rp) >> 1;
+           cres = 0;
+           if ((cur - forms) < (MAX_NORM - 1))
+               cres = CheckPrefix(word, len, &Affix[cp], Conf, ipi, forms, &cur);
+           if ((lp < cp) && ((cur - forms) < (MAX_NORM - 1)))
+               lres = CheckPrefix(word, len, &Affix[lp], Conf, ipi, forms, &cur);
+           if ((rp > cp) && ((cur - forms) < (MAX_NORM - 1)))
+               rres = CheckPrefix(word, len, &Affix[rp], Conf, ipi, forms, &cur);
+           if (cres < 0)
+           {
+               rp = cp - 1;
+               lp++;
+           }
+           else if (cres > 0)
+           {
+               lp = cp + 1;
+               rp--;
+           }
+           else
+           {
+               lp++;
+               rp--;
+           }
        }
-         }
-         ls++;
-         rs--;
-       } /* end while */
-     
-   } /* for ipi */
-
-   if(cur==forms){
+
+       /* check suffix */
+       ls = Conf->SuffixTree.Left[ipi];
+       rs = Conf->SuffixTree.Right[ipi];
+       while (ls >= 0 && ls <= rs)
+       {
+           if (((cur - forms) < (MAX_NORM - 1)))
+           {
+               *cur = CheckSuffix(word, len, &Affix[ls], &lres, Conf);
+               if (*cur)
+               {
+                   cur++;
+                   *cur = NULL;
+               }
+           }
+           if ((rs > ls) && ((cur - forms) < (MAX_NORM - 1)))
+           {
+               *cur = CheckSuffix(word, len, &Affix[rs], &rres, Conf);
+               if (*cur)
+               {
+                   cur++;
+                   *cur = NULL;
+               }
+           }
+           ls++;
+           rs--;
+       }                       /* end while */
+
+   }                           /* for ipi */
+
+   if (cur == forms)
+   {
        pfree(forms);
-       return(NULL);
+       return (NULL);
    }
-   return(forms);
+   return (forms);
 }
 
-void 
-FreeIspell (IspellDict *Conf) {
-  int i;
-  AFFIX *Affix = (AFFIX *)Conf->Affix;
-
-  for (i = 0; i < Conf->naffixes; i++) {
-    if (Affix[i].compile == 0) {
-      regfree(&(Affix[i].reg));
-    }
-  }
-  for (i = 0; i < Conf->naffixes; i++) {
-   free( Conf->Spell[i].word );
-  }
-  free(Conf->Affix);
-  free(Conf->Spell);
-  memset( (void*)Conf, 0, sizeof(IspellDict) );
-  return;
+void
+FreeIspell(IspellDict * Conf)
+{
+   int         i;
+   AFFIX      *Affix = (AFFIX *) Conf->Affix;
+
+   for (i = 0; i < Conf->naffixes; i++)
+   {
+       if (Affix[i].compile == 0)
+           regfree(&(Affix[i].reg));
+   }
+   for (i = 0; i < Conf->naffixes; i++)
+       free(Conf->Spell[i].word);
+   free(Conf->Affix);
+   free(Conf->Spell);
+   memset((void *) Conf, 0, sizeof(IspellDict));
+   return;
 }
index 3034ca6709da85047f98e0f711c2f7fb361acd2e..baf5052f02689ea6307e85d56522061dc5b848dd 100644 (file)
@@ -4,48 +4,53 @@
 #include <sys/types.h>
 #include <regex.h>
 
-typedef struct spell_struct {
-        char * word; 
-        char flag[10];
-} SPELL;
-
-typedef struct aff_struct {   
-        char flag;
-        char type;
-        char mask[33];
-        char find[16];
-        char repl[16];
-        regex_t reg;
-        size_t replen;
-        char compile;
-} AFFIX;
-
-typedef struct Tree_struct {
-        int Left[256], Right[256];
-} Tree_struct;
-
-typedef struct {
-   int maffixes;
-   int naffixes;
-   AFFIX * Affix;
-
-   int nspell;
-   int mspell;
-   SPELL   *Spell;
-   Tree_struct SpellTree;
-   Tree_struct PrefixTree;
-   Tree_struct SuffixTree;
-
-} IspellDict;
-
-char ** NormalizeWord(IspellDict * Conf,char *word);
-int ImportAffixes(IspellDict * Conf, const char *filename);
-int ImportDictionary(IspellDict * Conf,const char *filename);
-
-int  AddSpell(IspellDict * Conf,const char * word,const char *flag);
-int  AddAffix(IspellDict * Conf,int flag,const char *mask,const char *find,const char *repl,int type);
-void SortDictionary(IspellDict * Conf);
-void SortAffixes(IspellDict * Conf);
-void FreeIspell (IspellDict *Conf);
+typedef struct spell_struct
+{
+   char       *word;
+   char        flag[10];
+}  SPELL;
+
+typedef struct aff_struct
+{
+   char        flag;
+   char        type;
+   char        mask[33];
+   char        find[16];
+   char        repl[16];
+   regex_t     reg;
+   size_t      replen;
+   char        compile;
+}  AFFIX;
+
+typedef struct Tree_struct
+{
+   int         Left[256],
+               Right[256];
+}  Tree_struct;
+
+typedef struct
+{
+   int         maffixes;
+   int         naffixes;
+   AFFIX      *Affix;
+
+   int         nspell;
+   int         mspell;
+   SPELL      *Spell;
+   Tree_struct SpellTree;
+   Tree_struct PrefixTree;
+   Tree_struct SuffixTree;
+
+}  IspellDict;
+
+char     **NormalizeWord(IspellDict * Conf, char *word);
+int            ImportAffixes(IspellDict * Conf, const char *filename);
+int            ImportDictionary(IspellDict * Conf, const char *filename);
+
+int            AddSpell(IspellDict * Conf, const char *word, const char *flag);
+int            AddAffix(IspellDict * Conf, int flag, const char *mask, const char *find, const char *repl, int type);
+void       SortDictionary(IspellDict * Conf);
+void       SortAffixes(IspellDict * Conf);
+void       FreeIspell(IspellDict * Conf);
 
 #endif
index 783cf43ceb7e6fcaee58751c0f40314231c1bf16..6b553e4525671721cc27e00652b92603ceba1881 100644 (file)
@@ -1,5 +1,5 @@
-/* 
- * Simple config parser 
+/*
+ * Simple config parser
  * Teodor Sigaev <teodor@sigaev.ru>
  */
 #include <stdlib.h>
 #define CS_WAITEQ  2
 #define CS_WAITVALUE   3
 #define CS_INVALUE 4
-#define CS_IN2VALUE    5
+#define CS_IN2VALUE 5
 #define CS_WAITDELIM   6
 #define CS_INESC   7
 #define CS_IN2ESC  8
 
 static char *
-nstrdup(char *ptr, int len) {
-   char *res=palloc(len+1), *cptr;
-   memcpy(res,ptr,len);
-   res[len]='\0';
+nstrdup(char *ptr, int len)
+{
+   char       *res = palloc(len + 1),
+              *cptr;
+
+   memcpy(res, ptr, len);
+   res[len] = '\0';
    cptr = ptr = res;
-   while(*ptr) {
-       if ( *ptr == '\\' ) 
+   while (*ptr)
+   {
+       if (*ptr == '\\')
            ptr++;
-       *cptr=*ptr; ptr++; cptr++;
+       *cptr = *ptr;
+       ptr++;
+       cptr++;
    }
-   *cptr='\0';
+   *cptr = '\0';
 
    return res;
 }
 
 void
-parse_cfgdict(text *in, Map **m) {
-   Map *mptr;
-   char *ptr=VARDATA(in), *begin=NULL;
-   char num=0;
-   int state=CS_WAITKEY;
+parse_cfgdict(text *in, Map ** m)
+{
+   Map        *mptr;
+   char       *ptr = VARDATA(in),
+              *begin = NULL;
+   char        num = 0;
+   int         state = CS_WAITKEY;
 
-   while( ptr-VARDATA(in) < VARSIZE(in) - VARHDRSZ ) {
-       if ( *ptr==',' ) num++;
+   while (ptr - VARDATA(in) < VARSIZE(in) - VARHDRSZ)
+   {
+       if (*ptr == ',')
+           num++;
        ptr++;
    }
 
-   *m=mptr=(Map*)palloc( sizeof(Map)*(num+2) );
-   memset(mptr, 0, sizeof(Map)*(num+2) );
-   ptr=VARDATA(in);